text:
@class RACSignal;

@interface PFUser (RACExtensions)

/// Makes a request to log in a user with specified credentials.
///
/// This method will also cache the user locally so that calls to
/// userFromCurrentUser will use the latest logged in user.
///
/// @see +logInWithUsernameInBackground:password:
///
/// @param username The username of the user.
/// @param password The password of the user.
/// @return A signal that sends the successfully logged in PFUser.
+ (RACSignal *)rac_logInWithUsername:(NSString *)username password:(NSString *)password;

/// Send a password reset request for a specified email.
///
/// If a user account exists with that email, an email will be sent to that
/// address with instructions on how to reset their password.
///
/// @see +logInWithUsernameInBackground:password:
///
/// @param email Email of the account to send a reset password request.
/// @return A signal that completes on success.
+ (RACSignal *)rac_requestPasswordResetForEmail:(NSString *)email;

/// Signs up the user.
///
/// Make sure that password and username are set. This will also enforce that
/// the username isn't already taken.
///
/// @see +signUpInBackgroundWithBlock:
///
/// @return A signal that completes on successful sign-up.
- (RACSignal *)rac_signUp;

@end


text:
package com.doctor.ganymed_ssh2;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
 *
 * @author doctor
 *
 * @time 2015年8月5日 下午2:14:16
 *
 * @see https://github.com/northern-bites/ganymed-ssh2/blob/master/examples/Basic.java
 *
 */
public class Basic {

	/**
	 * 如果出现:Password authentication fails, I get "Authentication method password
	 * not supported by the server at this stage
	 *
	 * 请查看:ssh配置文件: /ect/ssh/sshd_config , 找到配置: "PasswordAuthentication" 被设为 "no" .
	 * changed it to "PasswordAuthentication yes"
	 *
	 *
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		String hostname = "127.0.0.1";
		String username = "doctor";
		String passwd = "xxx";
		Connection connection = new Connection(hostname);
		connection.connect();

		boolean authenticateWithPassword = connection.authenticateWithPassword(username, passwd);
		if (!authenticateWithPassword) {
			throw new RuntimeException("authenticateWithPassword failed");
		}

		Session session = connection.openSession();
		session.execCommand("pwd  ; date ;echo hello doctor");
		InputStream streamGobbler = new StreamGobbler(session.getStdout());

		String result = IOUtils.toString(streamGobbler, StandardCharsets.UTF_8);
		System.out.println("result:" + result);
		System.out.println("ExitStatus:" + session.getExitStatus());

		session.close();
		connection.close();

	}

}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var usecontent = require('dust-usecontent-helper');
var message = require('dust-message-helper');
var iferr = require('iferr');

module.exports = function(dust, debug, options, loader) {
    options = options || {};

    debug("registering");

    // Default to true, but since it imposes some complexity and lack of clarity,
    // about where things come from in the templates, allow it to be disabled.
    var autoloadTemplateContent = options.autoloadTemplateContent == null || options.autoloadTemplateContent;

    debug("will autoload template content? %j", autoloadTemplateContent);

    usecontent.withLoader(loader).registerWith(dust);

    // The message helper is the main user surface from the template side.
    message.registerWith(dust, { enableMetadata: options.enableMetadata });

    // Here's where the dirty bit of auto-wrapping templates with the content
    // load is triggered.
    if (autoloadTemplateContent) {
        wrapOnLoad(dust, loader, debug);
    }
};

function hackGibson(ctx, content, bundle) {
    var oldShiftBlocks = ctx.shiftBlocks;
    var oldPush = ctx.push;

    // Alter the context to wrap each block shifted, so content will be
    // present even in blocks rendered from other templates like layouts.
    ctx.shiftBlocks = function(locals) {
        return oldShiftBlocks.call(this, objMap(locals, function (l) {
            return wrapBlock(l, content, bundle);
        }));
    };

    // Alter the context to apply this same alteration to each context
    // pushed below this one, maintaining this hack for all future
    // context pushes.
    ctx.push = function(/* head, idx, len */) {
        var newCtx = oldPush.apply(this, arguments);
        hackGibson(newCtx, content, bundle);
        return newCtx;
    };
}

function wrapBlock(block, content, bundle) {
    // Return a block that re-pushes the content, and then passes to
    // the original block. This makes sure the content is associated
    // with the auto-loaded content bundle, not coming from the calling
    // context, which could be a different template and have the wrong
    // content loaded.
    return function (chunk, ctx) {
        ctx = ctx.push({intl: { messages: content, bundle: bundle }});
        return block(chunk, ctx);
    };
}

function objMap(obj, fn) {
    var n = {};
    Object.keys(obj).forEach(function (e) {
        n[e] = fn(obj[e]);
    });
    return n;
}

// This is where the magic lies. To get a hook on templates and wrap them with
// javascript that is aware of the template's name
function wrapOnLoad(dust, loader, debug) {
    var oldOnLoad = dust.onLoad;

    if (!oldOnLoad) {
        throw new Error("dust.onLoad must be configured to use automatic content loading");
    }

    debug("wrapping onLoad function to support content autoloading");

    dust.onLoad = function(name, options, cb) {

        var ourLoader = iferr(cb, function (srcOrTemplate) {
            debug("got template %s", srcOrTemplate);

            var tmpl = getTemplate(srcOrTemplate);
            if (!tmpl) {
                debug("Compiling template '%s'", name);
                tmpl = dust.loadSource(dust.compile(srcOrTemplate, name));
            }

            if (tmpl.loadsDefaultContent) {
                newTmpl = tmpl;
            } else {
                debug("wrapping template '%s' to look up default content", tmpl.templateName);
                var newTmpl = function (chunk, ctx) {
                    return chunk.map(function (chunk) {
                        var bundle = tmpl.templateName + '.properties';

                        loader(ctx, bundle, function (err, content) {
                            if (err) {
                                chunk.setError(err);
                            } else {
                                hackGibson(ctx, content, bundle);
                                dust.helpers.useContent(chunk, ctx, { block: tmpl }, { bundle: bundle }).end();
                            }
                        });
                    });
                };
                newTmpl.templateName = tmpl.templateName;
                newTmpl.loadsDefaultContent = true;
                newTmpl.__dustBody = true;
            }

            if (dust.config.cache) {
                // This actually replaces the template registered by
                // compiling and loading above.
                dust.cache[tmpl.templateName] = newTmpl;
            }

            cb(null, newTmpl);
        });

        debug("calling old onLoad to get template '%s'", name);
        if (oldOnLoad.length === 2) {
            return oldOnLoad.call(this, name, ourLoader);
        } else {
            return oldOnLoad.call(this, name, options, ourLoader);
        }
    };

    /**
     * Extracts a template function (body_0) from whatever is passed.
     *
     * This is an extract of the same function from the dustjs source.
     *
     *  nameOrTemplate Could be:
     *   - the name of a template to load from cache
     *   - a CommonJS-compiled template (a function with a `template` property)
     *   - a template function
     * returns a template function, if found
     */
    function getTemplate(nameOrTemplate) {
        if(!nameOrTemplate) {
            return null;
        }
        if(typeof nameOrTemplate === 'function' && nameOrTemplate.template) {
            // Sugar away CommonJS module templates
            return nameOrTemplate.template;
        }
        if(dust.isTemplateFn(nameOrTemplate)) {
            // Template functions passed directly
            return nameOrTemplate;
        }
    }
}


text:
package main

import (
	"github.com/kuangyh/saw/table"
)

func main() {
	table.Verify()
}


text:
class AppointmentsController < ApplicationController

  # Require authorization before invoking any of this controller's actions:
  before_filter :authorize

  # Default action.
  #
  # == Params:
  #
  # - <tt>:date_from_lookup</tt>, <tt>:date_to_lookup</tt> =>
  #   The date range for which the analysis must be performed.
  #
  # - <tt>:date_schedule</tt> || <tt>:curr_date</tt> =>
  #   The current date inside the week to be displayed. This is used only if no other range is supplied.
  #
  def index
# DEBUG
#    logger.debug( "\r\n\r\n---[ #{controller_name()}.index ] ---" )
#    logger.debug( "Params: #{params.inspect()}" )
    ap = AppParameter.get_parameter_row_for( :appointments )
    @max_view_height = ap.get_view_height()

    if ( params[:date_from_lookup].blank? && params[:date_schedule].blank? && params[:curr_date].blank? )
                                                    # Having the parameters, apply the resolution and the radius backwards:
      start_date = DateTime.now.strftime( ap.get_filtering_resolution )
                                                    # Set the (default) parameters for the scope configuration: (actual used value will be stored inside component_session[])
      @filtering_date_start  = ( Date.parse( start_date ) - ap.get_filtering_radius ).strftime( AGEX_FILTER_DATE_FORMAT_SQL )
      @filtering_date_end    = ( Date.parse( start_date ) + ap.get_filtering_radius ).strftime( AGEX_FILTER_DATE_FORMAT_SQL )
    else
      begin
        curr_date = Date.parse params[:date_from_lookup] || params[:date_schedule] || params[:curr_date]
      rescue
        logger.warn("**[W]** - #{controller_name()}.index(): Warning: invalid date specified as paramaters! (params=#{params.inspect})")
        curr_date = Date.today
      end
                                                    # Compute actual date range for the SQL data extraction query:
      @filtering_date_start = Schedule.get_week_start( curr_date ).strftime( AGEX_FILTER_DATE_FORMAT_SQL )
      @filtering_date_end = params[:date_to_lookup] || Schedule.get_week_end( curr_date ).strftime( AGEX_FILTER_DATE_FORMAT_SQL )
      # [20130212] We must use the AGEX_FILTER_DATE_FORMAT_SQL for the filtering dates used by
      # the custom Netzke component for the date filtering, because the result text from the
      # method Schedule.get_week_start/end_for_mysql_param() uses a DateTime instance instead of a simple Date
      # (used inside the FilteringDateRangePanel)
    end

# DEBUG
#    logger.debug( "@filtering_date_start: #{@filtering_date_start.inspect()}" )
#    logger.debug( "@filtering_date_end:   #{@filtering_date_end.inspect()}" )
    @context_title = I18n.t(:appointments_list, {:scope=>[:patient]})
  end
  # ---------------------------------------------------------------------------

  # Issues the receipt, updating also all associated Appointment instances.
  #
  # Since version 2.5 this action works for creating both single and multi-appointment receipts.
  #
  # The transaction will fall back for multi-appointment receipts if *any* of the selected appointments
  # has already an issued receipt associated with it.
  #
  # ==Params:
  # - +id+ => Appointment ID for which the Receipt must be issued.
  # - +ids+ => either an Array of Appointment IDs or a String of IDs concatenated by ',', for which the Receipt must be issued. Used only when params[:id] is not specified
  # - +date_receipt+ : chosen Date for the receipt; can be +nil+ to use the current date.
  # - +patient_id+   : Patient id chosen for the receipt. When missing Appointment.patient_id will be used, assuming either one of :id or :ids parameters are specified and valid.
  #
  def issue_receipt
    return if request.xhr?                          # (This is not supposed to be used with an Ajax call)
# DEBUG
    logger.debug "\r\n!! ----- AppointmentsController::issue_receipt() -----"
    logger.debug "issue_receipt: params #{params.inspect}"
                                                    # Parse params:
    id_list = []
                                                    # Collect all the Appointment IDs we have to process into a single array:
    if params[:id].to_i > 0                         # Single-appointment Receipt, typical case
      id_list << params[:id]

    elsif params[:data]                             # Multi-appointment Receipt, typical case
      id_list = ActiveSupport::JSON.decode( params[:data] )

    elsif params[:ids].instance_of?( Array )        # (Backward-compatibility case)
      id_list = params[:ids]

    elsif params[:ids].instance_of?( String )       # (Backward-compatibility case)
      id_list = params[:ids].split(',').compact.uniq.sort
    end

    is_ok = (id_list.size > 0)                      # set OK status depending on whether we have any IDs for retrieval or not
    msg = '-- Unexpected error condition! --'       # set a default flash msg to enhance the scope of the variable
                                                    # Get an array of all the rows to be updated
    appointments = nil
    begin
      appointments = Appointment.where( :id => id_list )
    rescue
      raise ArgumentError, "AppointmentsController::issue_receipt(): no valid ID(s) found inside data parameter!", caller
    end
# DEBUG
    logger.debug "AppointmentsController::issue_receipt(): id list: #{id_list.inspect}"

    if is_ok && (appointments.size > 0)             # Any valid row instances found and ready to be processed? Prepare data for the creation of a new receipt:
      params_hash = {
        :patient_id => appointments[0].patient_id,
        :date_receipt => appointments[0].date_receipt,
        :receipt_description => appointments[0].receipt_description
      }
      receipt = Receipt.new( params_hash )
      receipt.additional_notes = ""
                                                    # Init collected values:
      receipt.price = 0
      appointments_list = []
      payed_appointments = []
      all_is_payed = true
                                                    # Compute collect price and "all_is_payed" flag
      appointments.each { |appointment|
        receipt.additional_notes += appointment.additional_notes + "\r\n" if appointment.additional_notes
        receipt.price += appointment.price
        all_is_payed = all_is_payed && appointment.is_payed
        payed_appointments << appointment.get_date_schedule if appointment.is_payed
        appointments_list << appointment.get_date_schedule
      }
      receipt.is_payed = all_is_payed
      receipt.notes = "#{I18n.t(:appointments_payed, {:scope=>[:receipt]})}: #{payed_appointments.join(", ")}" if payed_appointments.size > 0
      receipt.additional_notes = receipt.additional_notes +
                                 "\r\n#{I18n.t(:invoiced_appointments, {:scope=>[:receipt]})}: #{appointments_list.join(", ")}" if appointments_list.size > 1
                                                    # Preset additional values
      receipt.preset_default_values()
# DEBUG
      logger.debug "AppointmentsController::issue_receipt(): receipt: #{receipt.inspect}"

      begin
        ActiveRecord::Base.transaction do           # ----- START TRANSACTION -----
          if receipt.save                           # Receipt save (possibly) sucessful?...
            appointments.each do |appointment|      # ...Iterate on all appointments:
              if !appointment.is_receipt_issued?    # Update currently processed appointment instance:
                appointment.receipt_id = receipt.id # No receipt issued yet? (This should be the norm) => Update receipt ID
                unless appointment.save
                  log_error("in issue_receipt() during appointment update - APPOINTMENT: " << appointment.inspect)
                  msg = I18n.t(:something_went_wrong)
                  log_info('Rolling back transaction...')
                  is_ok = false
                  raise ActiveRecord::Rollback
                end
              else
                log_error("issue_receipt(): Receipt already issued! - APPOINTMENT: #{appointment.inspect}\r\nSome of the selected IDs had already an issued Receipt and this should (normally) never occur when the standard selection view is used.")
                msg = I18n.t(:something_went_wrong)
                log_info('Rolling back transaction...')
                is_ok = false
                raise ActiveRecord::Rollback
              end
            end                                     # (end of loop)
          else                                      # Receipt save failure!
            log_error( "in issue_receipt() during receipt save - RECEIPT: " << receipt.inspect )
            msg = I18n.t(:something_went_wrong)
            log_info('Rolling back transaction...')
            is_ok = false
            raise ActiveRecord::Rollback
          end
        end

      rescue                                        # ----- END TRANSACTION -----
        is_ok = false
        log_error('executing transaction rollback...')
        msg ||= $!.to_s
        msg = "#{msg} #{I18n.t(:transaction_cancelled)}"
      end
                                                    # Set an O-K message only if everything went as expected:
      msg = I18n.t(:new_receipt_issued, {:scope=>[:receipt]}) + " (#{receipt.get_receipt_header()})" if is_ok
    else                                            # Appointment instance list was empty?
      if ! is_ok                                    # User didn't select anything:
        msg = I18n.t(:no_selection_receipt_not_issued, {:scope=>[:receipt]})
      else                                          # Something was selected, but nothing was retrieved:
        log_error( "issue_receipt(): An error as occurred while retrieving some of the selected appointment data:\r\nEmpty appointment instance list - PARAMS: " << params.inspect )
        msg = I18n.t(:something_went_wrong)
      end
    end
                                                    # Set the flash message and set the redirect:
    flash[:notice] = msg
    redirect_to( (appointments.size == 0) || (! is_ok) ? week_plan_path() : receipts_path() )
  end
  # ---------------------------------------------------------------------------

  # Outputs a detailed report using the selected rows IDs specified as parameter.
  #
  # == Params:
  # - <tt>:type</tt> => the extension of the file to be created; one among: 'pdf', 'odt', 'txt', 'full.csv', 'simple.csv'
  #   (default: 'pdf')
  # - <tt>:data</tt> (*required*) => a JSON-encoded array of Appointment IDs to be retrieved and processed
  #
  def report_detail
#    logger.debug "\r\n!! ----- report_detail -----"
#    logger.debug "report_detail: params #{params.inspect}"
                                                    # Parse params:
    id_list = ActiveSupport::JSON.decode( params[:data] ) if params[:data]
    unless id_list.kind_of?(Array)
      raise ArgumentError, "report_detail(): invalid or missing data parameter!", caller
    end
    return if id_list.size < 1
# DEBUG
#    logger.debug "report_detail(): id list: #{id_list.inspect}"
                                                    # Retrieve the receipt rows from the ID list:
    records = nil
    begin
      records = Appointment.where( :id => id_list )
    rescue
      raise ArgumentError, "report_detail(): no valid ID(s) found inside data parameter!", caller
    end
    return if records.nil?
# DEBUG
#    logger.debug "report_detail(): records class: #{records.class}"
#    logger.debug "report_detail(): records found: #{records.size}"

    filetype    = params[:type] || 'csv'
    separator   = params[:separator] || ';'         # (This plus the following params are used only during data exports)

    report_title = "#{I18n.t( :appointments, {:scope=>[:appointment]} )} #{records.first.get_date_schedule} ... #{records.last.get_date_schedule}"
    report_base_name = "#{I18n.t( :appointments, {:scope=>[:appointment]} )}-#{records.first.get_compacted_date_schedule}_#{records.last.get_compacted_date_schedule}"
                                                    # == DATA Collection ==
    detail_data  = []
    records.each { |row|
      detail_data << row.to_a_s(
        Appointment.report_detail_symbols(),
        Appointment::CONVERTED_FLOAT2STRING_FIXED_PRECISION,
        8
      )
    }
    ruport_table = Ruport::Data::Table.new(
      :column_names => Appointment.report_detail_symbols(),
      :data => detail_data
    )
    localize_ruport_table_column_names( ruport_table, :appointment )
                                                    # == OPTIONS setup + RENDERING phase ==
    filename = create_unique_filename( report_base_name ) + ".#{filetype}"

    if ( filetype == 'csv' )                        # --- CSV ---
      data = ''
      data << ruport_table.as( :csv, :format_options => {:col_sep => separator}, :ignore_table_width => true )
      data << "\r\n"
# DEBUG
#        puts data
      send_data( data, :type => "text/#{filetype}", :filename => filename )
      # -------------------------------------------
    else
      flash[:error] = I18n.t( :unsupported_output_format )
      redirect_to_index
    end
  end
  # ---------------------------------------------------------------------------

end


text:
// Code generated by main. DO NOT EDIT.

package k3s

import (
	"context"
	"time"

	clientset "github.com/rancher/k3s/pkg/generated/clientset/versioned"
	scheme "github.com/rancher/k3s/pkg/generated/clientset/versioned/scheme"
	informers "github.com/rancher/k3s/pkg/generated/informers/externalversions"
	"github.com/rancher/wrangler/pkg/generic"
	"github.com/rancher/wrangler/pkg/schemes"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/rest"
)

func init() {
	scheme.AddToScheme(schemes.All)
}

type Factory struct {
	synced            bool
	informerFactory   informers.SharedInformerFactory
	clientset         clientset.Interface
	controllerManager *generic.ControllerManager
	threadiness       map[schema.GroupVersionKind]int
}

func NewFactoryFromConfigOrDie(config *rest.Config) *Factory {
	f, err := NewFactoryFromConfig(config)
	if err != nil {
		panic(err)
	}
	return f
}

func NewFactoryFromConfig(config *rest.Config) (*Factory, error) {
	return NewFactoryFromConfigWithOptions(config, nil)
}

func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) {
	return NewFactoryFromConfigWithOptions(config, &FactoryOptions{
		Namespace: namespace,
	})
}

type FactoryOptions struct {
	Namespace string
	Resync    time.Duration
}

func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) {
	if opts == nil {
		opts = &FactoryOptions{}
	}

	cs, err := clientset.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	resync := opts.Resync
	if resync == 0 {
		resync = 2 * time.Hour
	}

	if opts.Namespace == "" {
		informerFactory := informers.NewSharedInformerFactory(cs, resync)
		return NewFactory(cs, informerFactory), nil
	}

	informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace))
	return NewFactory(cs, informerFactory), nil
}

func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory {
	return &Factory{
		threadiness:       map[schema.GroupVersionKind]int{},
		controllerManager: &generic.ControllerManager{},
		clientset:         clientset,
		informerFactory:   informerFactory,
	}
}

func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller {
	return c.controllerManager.Controllers()
}

func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) {
	c.threadiness[gvk] = threadiness
}

func (c *Factory) Sync(ctx context.Context) error {
	c.informerFactory.Start(ctx.Done())
	c.informerFactory.WaitForCacheSync(ctx.Done())
	return nil
}

func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error {
	if err := c.Sync(ctx); err != nil {
		return err
	}

	return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness)
}

func (c *Factory) K3s() Interface {
	return New(c.controllerManager, c.informerFactory.K3s(), c.clientset)
}


text:
namespace OwinCompression
{
    using Microsoft.Owin;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    // TODO: Use generic OWIN context, not specifically Microsoft.Owin

    public class ResponseCompressionMiddleware : OwinMiddleware
    {
        private const string AcceptEncodingHeader = "Accept-Encoding";
        private const string ContentEncodingHeader = "Content-Encoding";
        private static readonly List<KeyValuePair<string, bool>> _defaultMimeTypeCompressions;
        private static readonly Dictionary<string, ResponseCompressions> _supportedCompressions;
        private readonly List<KeyValuePair<string, bool>> _mimeTypeCompressions;

        static ResponseCompressionMiddleware()
        {
            Interlocked.Exchange(ref _supportedCompressions, GetSupportedCompressions());
            Interlocked.Exchange(ref _defaultMimeTypeCompressions, GetSupportedContentTypes());
        }

        public ResponseCompressionMiddleware(OwinMiddleware next)
            : this(next, null)
        {
        }

        public ResponseCompressionMiddleware(OwinMiddleware next, IEnumerable<string> mimeTypes)
            : base(next)
        {
            if (mimeTypes == null)
            {
                this._mimeTypeCompressions = _defaultMimeTypeCompressions;
            }
            else
            {
                this._mimeTypeCompressions = mimeTypes.Select(mt => new KeyValuePair<string, bool>(mt, true)).ToList();
            }
        }

        public async override Task Invoke(IOwinContext context)
        {
            var compression = GetCompression(context.Request.Headers);

            var compressionStream = GetCompressionStreamBuilder(context, compression);

            if (compression == ResponseCompressions.None || compressionStream == null)
            {
                // Unsupported or no compression
                //  Invoke next & quick exit
                await Next.Invoke(context);
                return;
            }

            await InvokeRequestAndCompressStream(context, compressionStream);
        }

        private static ResponseCompressions GetCompression(IHeaderDictionary headers)
        {
            if (!headers.ContainsKey(AcceptEncodingHeader))
                return ResponseCompressions.None;

            var encodingsAccepted = headers[AcceptEncodingHeader]
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Trim());

            var firstEncoding = encodingsAccepted
                .FirstOrDefault(e => _supportedCompressions.ContainsKey(e)); ;

            return _supportedCompressions[firstEncoding ?? string.Empty];
        }

        private static Func<Stream, Stream> GetCompressionStreamBuilder(IOwinContext context, ResponseCompressions compression)
        {
            var compressionStream = default(Func<Stream, Stream>);

            switch (compression)
            {
                // Get a compression stream, but we require the underlying stream
                //  to remain open after compression
                case ResponseCompressions.Gzip:
                    compressionStream = s => new GZipStream(s, CompressionMode.Compress, true);
                    break;

                case ResponseCompressions.Deflate:
                    compressionStream = s => new DeflateStream(s, CompressionMode.Compress, true);
                    break;

                default:
                    return null;
            }

            var compressionHeader = compression.ToString().ToLower();
            context.Response.Headers.AppendValues(ContentEncodingHeader, compressionHeader);

            return compressionStream;
        }

        private static Dictionary<string, ResponseCompressions> GetSupportedCompressions()
        {
            var dict = Enum.GetValues(typeof(ResponseCompressions)).OfType<ResponseCompressions>()
                .ToDictionary(s => s == ResponseCompressions.None ? string.Empty : s.ToString().ToLower(), s => s);

            return dict;
        }

        private static List<KeyValuePair<string, bool>> GetSupportedContentTypes()
        {
            // TODO : this really should be from a configuration file
            // Which Mimetypes actually support compression?
            var mimetypes = new Dictionary<string, bool> {
                {"text/*", true },
                {"message/*", true },
                {"application/javascript",true },
                {"application/json",true },
                {"*/*", false }
            };

            return mimetypes.ToList();
        }

        private async Task InvokeRequestAndCompressStream(IOwinContext context, Func<Stream, Stream> compression)
        {
            // ref the response stream for use copying later
            var stream = context.Response.Body;
            using (var buffer = new MemoryStream())
            {
                // replace the current response body for the duration of the request
                //  so we can use the memory stream buffer
                context.Response.Body = buffer;
                await Next.Invoke(context);
                context.Response.Body = stream;

                // MimeType doesn't support compression.
                //  Copy stream to output & quick exit
                if (!MimeTypeCompressionIsSupported(context.Response.ContentType))
                {
                    buffer.Seek(0, SeekOrigin.Begin);
                    await buffer.CopyToAsync(stream);

                    return;
                }

                using (var compressedBuffer = new MemoryStream())
                {
                    // get a compression buffer & copy the "fake" response stream
                    //  to another "fake", using the compression stream
                    using (var compressionStream = compression(compressedBuffer))
                    {
                        buffer.Seek(0, SeekOrigin.Begin);
                        await buffer.CopyToAsync(compressionStream);
                    }

                    // we need the new "fake" stream to update the contentLength,
                    //  because we cannot query the HttpResponse for a length (NotSupportedException)
                    context.Response.ContentLength = compressedBuffer.Length;
                    compressedBuffer.Seek(0, SeekOrigin.Begin);
                    await compressedBuffer.CopyToAsync(stream);
                }
            }
        }

        private bool IsMatch(string contentMimeType, string mimeTypeExpression)
        {
            if (!mimeTypeExpression.Contains("*"))
            {
                return contentMimeType.Equals(mimeTypeExpression, StringComparison.InvariantCultureIgnoreCase);
            }

            var rxExpression = mimeTypeExpression.Replace("*", ".*").Replace("/", "\\/");

            return System.Text.RegularExpressions.Regex.IsMatch(contentMimeType, rxExpression);
        }

        private bool MimeTypeCompressionIsSupported(string contentType)
        {
            var contentMimeType = contentType.Split(';')[0];
            foreach (var mimeType in _mimeTypeCompressions)
            {
                if (IsMatch(contentMimeType, mimeType.Key))
                {
                    return mimeType.Value;
                }
            }

            return false;
        }
    }
}


text:
import { Component, OnInit, Input, Output, EventEmitter, AfterViewInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

import { IAddFileFormConfig, AddFileFormConfig, AddFileFormType } from '../../../models/view/add-file-config.model';

import 'codemirror/mode/yaml/yaml';
import { IPackageConfig } from '../../../models/domain/package-config.model';

declare let jQuery: any;

/**
 * This class represents the lazy loaded DashboardComponent.
 */
@Component({
    moduleId: module.id,
    selector: 'fix-yaml-config',
    templateUrl: 'yaml-config.component.html',
    styleUrls: ['yaml-config.component.css']
})
export class YamlConfigComponent implements AfterViewInit, OnInit {

    configEditor: any = { lineNumbers: true, mode: 'text/x-yaml' };

    contentFile = '';

    @Input() packageConfig: IPackageConfig;
    @Output() packageConfigChange: EventEmitter<IPackageConfig>;

    constructor() {
        console.log();
    }

    ngOnInit(): void {
        console.log('tototototototo');
    }

    ngAfterViewInit(): void {
        jQuery('.selecttemplate').selectpicker();
        jQuery('.selectplateform').selectpicker();
    }

}


text:
quack.core.genericObj = function(attr) {
	//constructor
	this.id = attr.id || "defaultID"; //can replace this with a random ID
	this.type = attr.type | "generic";
	this.parent = undefined;
	this.children = [];

	//this.position = new quack.math.vector3(0, 0, 0);
	//set position
	if (attr.position === undefined) {
		this.position = new quack.math.vector3(0, 0, 0);
	}
	else if (!(attr.position instanceof quack.math.vector3)){
		this.position = new quack.math.vector3(attr.position.x, attr.position.y, attr.position.z);
	}
	else {
		this.position = attr.position;
	}

	//set lookAt
	if (attr.lookAt === undefined) {
		this.lookAt = new quack.math.vector3(0, 0, 0);
	}
	else if (!(attr.lookAt instanceof quack.math.vector3)){
		this.lookAt = new quack.math.vector3(attr.lookAt.x, attr.lookAt.y, attr.lookAt.z);
	}
	else {
		this.lookAt = attr.lookAt;
	}

	this.up = new quack.math.vector3(0, 1, 0);
	//this.lookAt = new quack.math.vector3(0, 0, 0);
	this.scale = new quack.math.vector3(1, 1, 1);
	this.modelMatrix = new quack.math.matrix4();

	this.setPosition = function(x, y ,z) {
		this.position.set(x, y ,z);

		return this;
	};

	this.setUp = function(x, y, z) {
		this.up.set(x, y, z);

		return this;
	};

	this.setLookAt = function(x, y, z) {
		this.lookAt.set(x, y, z);

		return this;
	};

	this.append = function(obj) {
		this.children.push(obj);

		return this;
	};
};


text:
smart-buffer  [![Build Status](https://travis-ci.org/JoshGlazebrook/smart-buffer.svg?branch=master)](https://travis-ci.org/JoshGlazebrook/smart-buffer)  [![Coverage Status](https://coveralls.io/repos/github/JoshGlazebrook/smart-buffer/badge.svg?branch=master)](https://coveralls.io/github/JoshGlazebrook/smart-buffer?branch=master)
=============

smart-buffer is a light Buffer wrapper that takes away the need to keep track of what position to read and write data to and from the underlying Buffer. It also adds null terminating string operations and **grows** as you add more data.

![stats](https://nodei.co/npm/smart-buffer.png?downloads=true&downloadRank=true&stars=true "stats")

### What it's useful for:

I created smart-buffer because I wanted to simplify the process of using Buffer for building and reading network packets to send over a socket. Rather than having to keep track of which position I need to write a UInt16 to after adding a string of variable length, I simply don't have to.

Key Features:
* Proxies all of the Buffer write and read functions.
* Keeps track of read and write positions for you.
* Grows the internal Buffer as you add data to it.
* Useful string operations. (Null terminating strings)
* Allows for inserting values at specific points in the internal Buffer.
* Built in TypeScript
* Type Definitions Provided

Requirements:
* Node v4.0+ is supported at this time.  (Versions prior to 2.0 will work on node 0.10)

#### Note:
smart-buffer can be used for writing to an underlying buffer as well as reading from it. It however does not function correctly if you're mixing both read and write operations with each other.

## Breaking Changes with 2.0
The latest version (2.0+) is written in TypeScript, and are compiled to ES6 Javascript. This means the earliest Node.js it supports will be 4.x (in strict mode.) If you're using version 6 and above it will work without any issues. From an API standpoint, 2.0 is backwards compatible. The only difference is SmartBuffer is not exported directly as the root module.

## Breaking Changes with 3.0
Starting with 3.0, if any of the readIntXXXX() methods are called and the requested data is larger than the bounds of the internally managed valid buffer data, an exception will now be thrown.

## Installing:

`npm install smart-buffer`

or

`yarn add smart-buffer`

Note: The published NPM package includes the built javascript library.
If you cloned this repo and wish to build the library manually use:

`tsc -p ./`

## Using smart-buffer

### Example

Say you were building a packet that had to conform to the following protocol:

`[PacketType:2][PacketLength:2][Data:XX]`

To build this packet using the vanilla Buffer class, you would have to count up the length of the data payload beforehand. You would also need to keep track of the current "cursor" position in your Buffer so you write everything in the right places. With smart-buffer you don't have to do either of those things.

```javascript
// 1.x (javascript)
var SmartBuffer = require('smart-buffer');

// 1.x (typescript)
import SmartBuffer = require('smart-buffer');

// 2.x+ (javascript)
const SmartBuffer = require('smart-buffer').SmartBuffer;

// 2.x+ (typescript)
import { SmartBuffer, SmartBufferOptions} from 'smart-buffer';

function createLoginPacket(username, password, age, country) {
    let packet = new SmartBuffer();
    packet.writeUInt16LE(0x0060); // Login Packet Type/ID
    packet.writeStringNT(username);
    packet.writeStringNT(password);
    packet.writeUInt8(age);
    packet.writeStringNT(country);
    packet.writeUInt16LE(packet.length - 2, 2);

    return packet.toBuffer();
}
```
With the above function, you now can do this:
```javascript
let login = createLoginPacket("Josh", "secret123", 22, "United States");

// <Buffer 60 00 1e 00 4a 6f 73 68 00 73 65 63 72 65 74 31 32 33 00 16 55 6e 69 74 65 64 20 53 74 61 74 65 73 00>
```
Notice that the `[PacketLength:2]` part of the packet was inserted after we had added everything else, and as shown in the Buffer dump above, is in the correct location along with everything else.

Reading back the packet we created above is just as easy:
```javascript

let reader = SmartBuffer.fromBuffer(login);

let logininfo = {
    packetType: reader.readUInt16LE(),
    packetLength: reader.readUInt16LE(),
    username: reader.readStringNT(),
    password: reader.readStringNT(),
    age: reader.readUInt8(),
    country: reader.readStringNT()
};

/*
{
    packetType: 96, (0x0060)
    packetLength: 30,
    username: 'Josh',
    password: 'secret123',
    age: 22,
    country: 'United States'
};
*/
```

# Api Reference:

### Constructing a smart-buffer

smart-buffer has a few different ways to construct an instance. Starting with version 2.0, the following factory methods are preffered.

```javascript
let SmartBuffer = require('smart-buffer');

// Creating SmartBuffer from existing Buffer
let buff = SmartBuffer.fromBuffer(buffer); // Creates instance from buffer. (Uses default utf8 encoding)
let buff = SmartBuffer.fromBuffer(buffer, 'ascii'); // Creates instance from buffer with ascii encoding for Strings.

// Creating SmartBuffer with specified internal Buffer size.
let buff = SmartBuffer.fromSize(1024); // Creates instance with internal Buffer size of 1024.
let buff = SmartBuffer.fromSize(1024, 'utf8'); // Creates instance with intenral Buffer size of 1024, and utf8 encoding.

// Creating SmartBuffer with options object. This one specifies size and encoding.
let buff = SmartBuffer.fromOptions({
    size: 1024,
    encoding: 'ascii'
});

// Creating SmartBuffer with options object. This one specified an existing Buffer.
let buff = SmartBuffer.fromOptions({
    buff: buffer
});

// Just want a regular SmartBuffer with all default options?
let buff = new SmartBuffer();
```

## Backwards Compatibility:

All constructors used prior to 2.0 still are supported. However it's not recommended to use these.

```javascript
let writer = new SmartBuffer();               // Defaults to utf8, 4096 length internal Buffer.
let writer = new SmartBuffer(1024);           // Defaults to utf8, 1024 length internal Buffer.
let writer = new SmartBuffer('ascii');         // Sets to ascii encoding, 4096 length internal buffer.
let writer = new SmartBuffer(1024, 'ascii');  // Sets to ascii encoding, 1024 length internal buffer.
```

## Reading Data

smart-buffer supports all of the common read functions you will find in the vanilla Buffer class. The only difference is, you do not need to specify which location to start reading from. This is possible because as you read data out of a smart-buffer, it automatically progresses an internal read offset/position to know where to pick up from on the next read.

## Reading Numeric Values

When numeric values, you simply need to call the function you want, and the data is returned.

Supported Operations:
* readInt8
* readInt16BE
* readInt16LE
* readInt32BE
* readInt32LE
* readUInt8
* readUInt16BE
* readUInt16LE
* readUInt32BE
* readUInt32LE
* readFloatBE
* readFloatLE
* readDoubleBE
* readDoubleLE

```javascript
let reader = new SmartBuffer(somebuffer);
let num = reader.readInt8();
```

## Reading String Values

When reading String values, you can either choose to read a null terminated string, or a string of a specified length.

### SmartBuffer.readStringNT( [encoding] )
> `String` **String encoding to use**  - Defaults to the encoding set in the constructor.

returns `String`

> Note: When readStringNT is called and there is no null character found, smart-buffer will read to the end of the internal Buffer.

### SmartBuffer.readString( [length] )
### SmartBuffer.readString( [encoding] )
### SmartBuffer.readString( [length], [encoding] )
> `Number` **Length of the string to read**

> `String` **String encoding to use** - Defaults to the encoding set in the constructor, or utf8.

returns `String`

> Note: When readString is called without a specified length, smart-buffer will read to the end of the internal Buffer.

## Reading Buffer Values

### SmartBuffer.readBuffer( length )
> `Number` **Length of data to read into a Buffer**

returns `Buffer`

> Note: This function uses `slice` to retrieve the Buffer.

### SmartBuffer.readBufferNT()

returns `Buffer`

> Note: This reads the next sequence of bytes in the buffer until a null (0x00) value is found. (Null terminated buffer)
> Note: This function uses `slice` to retrieve the Buffer.

## Writing Data

smart-buffer supports all of the common write functions you will find in the vanilla Buffer class. The only difference is, you do not need to specify which location to write to in your Buffer by default. You do however have the option of **inserting** a piece of data into your smart-buffer at a given location.

## Writing Numeric Values

For numeric values, you simply need to call the function you want, and the data is written at the end of the internal Buffer's current write position. You can specify a offset/position to **insert** the given value at, but keep in mind this does not override data at the given position. This feature also does not work properly when inserting a value beyond the current internal length of the smart-buffer (length being the .length property of the smart-buffer instance you're writing to)

Supported Operations:
* writeInt8
* writeInt16BE
* writeInt16LE
* writeInt32BE
* writeInt32LE
* writeUInt8
* writeUInt16BE
* writeUInt16LE
* writeUInt32BE
* writeUInt32LE
* writeFloatBE
* writeFloatLE
* writeDoubleBE
* writeDoubleLE

The following signature is the same for all the above functions:

### SmartBuffer.writeInt8( value, [offset] )
> `Number` **A valid Int8 number**

> `Number` **The position to insert this value at**

returns this

> Note: All write operations return `this` to allow for chaining.

## Writing String Values

When reading String values, you can either choose to write a null terminated string, or a non null terminated string.

### SmartBuffer.writeStringNT( value, [offset], [encoding] )
### SmartBuffer.writeStringNT( value, [offset] )
### SmartBuffer.writeStringNT( value, [encoding] )
> `String` **String value to write**

> `Number` **The position to insert this String at**

> `String` **The String encoding to use.** - Defaults to the encoding set in the constructor, or utf8.

returns this

### SmartBuffer.writeString( value, [offset], [encoding] )
### SmartBuffer.writeString( value, [offset] )
### SmartBuffer.writeString( value, [encoding] )
> `String` **String value to write**

> `Number` **The position to insert this String at**

> `String` **The String encoding to use** - Defaults to the encoding set in the constructor, or utf8.

returns this

## Writing Buffer Values

### SmartBuffer.writeBuffer( value, [offset] )
> `Buffer` **Buffer value to write**

> `Number` **The position to insert this Buffer's content at**

returns this

### SmartBuffer.writeBufferNT( value, [offset] )
> `Buffer` **Buffer value to write**

> `Number` **The position to insert this Buffer's content at**

returns this

## Utility Functions

### SmartBuffer.clear()
Resets the SmartBuffer to its default state where it can be reused for reading or writing.

### SmartBuffer.remaining()

returns `Number` The amount of data left to read based on the current read Position.

### SmartBuffer.skip( value )
> `Number` **The amount of bytes to skip ahead**

Skips the read position ahead by the given value.

returns this

### SmartBuffer.rewind( value )
> `Number` **The amount of bytes to reward backwards**

Rewinds the read position backwards by the given value.

returns this

### SmartBuffer.moveTo( position )
> `Number` **The point to skip the read position to**

Moves the read position to the given point.
returns this

### SmartBuffer.toBuffer()

returns `Buffer` A Buffer containing the contents of the internal Buffer.

> Note: This uses the slice function.

### SmartBuffer.toString( [encoding] )
> `String` **The String encoding to use** - Defaults to the encoding set in the constructor, or utf8.

returns `String` The internal Buffer in String representation.

## Properties

### SmartBuffer.length

returns `Number` **The length of the data that is being tracked in the internal Buffer** - Does NOT return the absolute length of the internal Buffer being written to.

## License

This work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License).


text:
package message

import (
	"strings"
)

type MessageType int

const (
	UNKNOWN         MessageType = 1
	ERROR_MESSAGE   MessageType = 2
	INFO_MESSAGE    MessageType = 3
	WARNING_MESSAGE MessageType = 4
)

var messageTypeStrings = map[MessageType]string{
	UNKNOWN:         "Unknown",
	ERROR_MESSAGE:   "Error",
	INFO_MESSAGE:    "Information",
	WARNING_MESSAGE: "Warning",
}

var messageTypeVariations = map[string]MessageType{
	"error":       ERROR_MESSAGE,
	"err":         ERROR_MESSAGE,
	"info":        INFO_MESSAGE,
	"information": INFO_MESSAGE,
	"warning":     WARNING_MESSAGE,
	"warn":        WARNING_MESSAGE,
}

func Lookup(messageType string) MessageType {
	messageType = strings.ToLower(messageType)

	for variation, possibleMessageType := range messageTypeVariations {
		if variation == messageType {
			return possibleMessageType
		}
	}

	return UNKNOWN
}

func (this MessageType) String() string {
	return messageTypeStrings[this]
}


text:
package org.onosproject.net.intent.impl;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.net.intent.IntentData;
import org.onosproject.net.intent.IntentEvent;
import org.onosproject.net.intent.IntentListener;
import org.onosproject.net.intent.IntentService;
import org.onosproject.net.intent.IntentStore;
import org.onosproject.net.intent.Key;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;

import java.util.Dictionary;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.onlab.util.Tools.get;
import static org.onlab.util.Tools.groupedThreads;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * This component cleans up intents that have encountered errors or otherwise
 * stalled during installation or withdrawal.
 * <p>
 * It periodically polls (based on configured period) for pending and CORRUPT
 * intents from the store and retries. It also listens for CORRUPT event
 * notifications, which signify errors in processing, and retries.
 * </p>
 */
@Component(immediate = true)
public class IntentCleanup implements Runnable, IntentListener {

    private static final Logger log = getLogger(IntentCleanup.class);

    private static final int DEFAULT_PERIOD = 5; //seconds
    private static final int DEFAULT_THRESHOLD = 5; //tries

    @Property(name = "enabled", boolValue = true,
              label = "Enables/disables the intent cleanup component")
    private boolean enabled = true;

    @Property(name = "period", intValue = DEFAULT_PERIOD,
              label = "Frequency in ms between cleanup runs")
    protected int period = DEFAULT_PERIOD;
    private long periodMs;

    @Property(name = "retryThreshold", intValue = DEFAULT_THRESHOLD,
            label = "Number of times to retry CORRUPT intent without delay")
    protected int retryThreshold = DEFAULT_THRESHOLD;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected IntentService service;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected IntentStore store;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected ComponentConfigService cfgService;

    private ExecutorService executor;
    private Timer timer;
    private TimerTask timerTask;

    @Activate
    public void activate() {
        cfgService.registerProperties(getClass());
        executor = newSingleThreadExecutor(groupedThreads("onos/intent", "cleanup", log));
        timer = new Timer("onos-intent-cleanup-timer");
        service.addListener(this);
        adjustRate();
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        cfgService.unregisterProperties(getClass(), false);
        service.removeListener(this);
        timer.cancel();
        timerTask = null;
        executor.shutdown();
        log.info("Stopped");
    }

    @Modified
    public void modified(ComponentContext context) {
        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();

        int newPeriod;
        boolean newEnabled;
        try {
            String s = get(properties, "period");
            newPeriod = isNullOrEmpty(s) ? period : Integer.parseInt(s.trim());

            s = get(properties, "retryThreshold");
            retryThreshold = isNullOrEmpty(s) ? retryThreshold : Integer.parseInt(s.trim());

            s = get(properties, "enabled");
            newEnabled = isNullOrEmpty(s) ? enabled : Boolean.parseBoolean(s.trim());
        } catch (NumberFormatException e) {
            log.warn(e.getMessage());
            newPeriod = period;
            newEnabled = enabled;
        }

        // Any change in the following parameters implies hard restart
        if (newPeriod != period || enabled != newEnabled) {
            period = newPeriod;
            enabled = newEnabled;
            adjustRate();
        }

        log.info("Settings: enabled={}, period={}, retryThreshold={}",
                 enabled, period, retryThreshold);
    }

    protected void adjustRate() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }

        if (enabled) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    executor.execute(IntentCleanup.this);
                }
            };

            periodMs = period * 1_000; //convert to ms
            timer.scheduleAtFixedRate(timerTask, periodMs, periodMs);
        }
    }

    @Override
    public void run() {
        try {
            cleanup();
        } catch (Exception e) {
            log.warn("Caught exception during Intent cleanup", e);
        }
    }

    private void resubmitCorrupt(IntentData intentData, boolean checkThreshold) {
        if (checkThreshold && intentData.errorCount() >= retryThreshold) {
            return; // threshold met or exceeded
        }

        switch (intentData.request()) {
            case INSTALL_REQ:
                service.submit(intentData.intent());
                break;
            case WITHDRAW_REQ:
                service.withdraw(intentData.intent());
                break;
            default:
                log.warn("Trying to resubmit corrupt/failed intent {} in state {} with request {}",
                         intentData.key(), intentData.state(), intentData.request());
                break;
        }
    }

    private void resubmitPendingRequest(IntentData intentData) {
        switch (intentData.request()) {
            case INSTALL_REQ:
                service.submit(intentData.intent());
                break;
            case WITHDRAW_REQ:
                service.withdraw(intentData.intent());
                break;
            case PURGE_REQ:
                service.purge(intentData.intent());
                break;
            default:
                log.warn("Failed to resubmit pending intent {} in state {} with request {}",
                         intentData.key(), intentData.state(), intentData.request());
                break;
        }
    }

    /**
     * Iterates through corrupt, failed and pending intents and
     * re-submit/withdraw appropriately.
     */
    private void cleanup() {
        int corruptCount = 0, failedCount = 0, stuckCount = 0, pendingCount = 0;

        for (IntentData intentData : store.getIntentData(true, periodMs)) {
            switch (intentData.state()) {
                case FAILED:
                    resubmitCorrupt(intentData, false);
                    failedCount++;
                    break;
                case CORRUPT:
                    resubmitCorrupt(intentData, false);
                    corruptCount++;
                    break;
                case INSTALLING: //FALLTHROUGH
                case WITHDRAWING:
                    resubmitPendingRequest(intentData);
                    stuckCount++;
                    break;
                default:
                    //NOOP
                    break;
            }
        }

        for (IntentData intentData : store.getPendingData(true, periodMs)) {
            resubmitPendingRequest(intentData);
            stuckCount++;
        }

        if (corruptCount + failedCount + stuckCount + pendingCount > 0) {
            log.debug("Intent cleanup ran and resubmitted {} corrupt, {} failed, {} stuck, and {} pending intents",
                    corruptCount, failedCount, stuckCount, pendingCount);
        }
    }

    @Override
    public void event(IntentEvent event) {
        // this is the fast path for CORRUPT intents, retry on event notification.
        //TODO we might consider using the timer to back off for subsequent retries
        if (enabled && event.type() == IntentEvent.Type.CORRUPT) {
            Key key = event.subject().key();
            if (store.isMaster(key)) {
                IntentData data = store.getIntentData(event.subject().key());
                resubmitCorrupt(data, true);
            }
        }
    }
}


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;

namespace WebAddressbookTests
{
    [TestFixture]
    public class ContactRemovalTests : AuthTestBase
    {
        [Test]
        public void ContactRemovalTest()
        {
            app.Contacts.ChekingContract();

            List<ContactData> oldContacts = ContactData.GetAll();
            ContactData toBeRemoved = oldContacts[0];

            app.Contacts.ConRemove(toBeRemoved);

            Assert.AreEqual(oldContacts.Count - 1, app.Contacts.GetContactCount());

            List<ContactData> newContacts = ContactData.GetAll();
            oldContacts.RemoveAt(0);
            Assert.AreEqual(oldContacts, newContacts);

            foreach(ContactData contact in newContacts)
            {
                Assert.AreNotEqual(contact.Id, toBeRemoved.Id);
            }
        }
    }
}


text:
package com.xplus.commons.thread.senior.volatiledemo;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 演示实现原子特性,最终结果是10000
 */
public class VolatileAtomicImpl extends Thread {

  private static AtomicInteger count = new AtomicInteger(0);

  private static void addCount() {
    for (int i = 0; i < 1000; i++) {
      count.incrementAndGet();
    }
    try {
      Thread.sleep(new Random().nextInt(10));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(count);
  }

  @Override
  public void run() {
    addCount();
  }

  public static void main(String[] args) {
    VolatileAtomicImpl [] arr = new VolatileAtomicImpl[10];
    int num = 10;
    for (int i = 0; i < num; i++) {
      arr[i] = new VolatileAtomicImpl();
    }

    for (int i = 0; i < num; i++) {
      arr[i].start();
    }

  }

}


text:
export default function reducer(state={
    id: null,
    name: null,
    email: null,
    type: null,
    photos: null,
    fetching: false,
    fetched: false,
    error: null,
  }, action) {

    switch (action.type) {
      case "FETCH_USER": {
        return {...state, fetching: true}
      }
      case "FETCH_USER_REJECTED": {
        return {...state, fetching: false, error: action.payload}
      }
      case "FETCH_USER_FULFILLED": {
        return {
          ...state,
          fetching: false,
          fetched: true,
          user: action.payload,
        }
      }
      case "SET_USER_NAME": {
        return {
          ...state,
          ...state.user, name: action.payload,
        }
      }
      case "SET_USER_EMAIL": {
        return {
          ...state,
          ...state.user, email: action.payload,
        }
      }
      case "SET_USER_TYPE": {
        return {
          ...state,
          ...state.user, type: action.payload,
        }
      }
      case "SET_USER_PARAMS": {
        if(action.payload || action.payload.type != 'guest'){
          return {
            ...state,
            ...state.user, type: action.payload.type, name: action.payload.name, email: action.payload.email, photos: action.payload.photos, id: action.payload.id,
          }
        }else{
          return {
            ...state,
            ...state.user, type: 'guest', name: 'guest', email: 'guest@guest.com', id: '0',
          }
        }
      }
    }
    return state
}


text:
package LeetCodePerformancePractice;

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

public class _094BinaryTreeInorderTraversal {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x) { val = x; }
	}
	static List<Integer> output;
	public List<Integer> inorderTraversal(TreeNode root) {
		output=new ArrayList<>();
		inorder(root);
		return output;
	}
	private void inorder(TreeNode root) {
		if(root!=null)
		{
			inorder(root.left);
			output.add(root.val);
			inorder(root.right);
		}
	}

}


text:
package org.yaml.snakeyaml.types;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

/**
 * @see http://yaml.org/type/str.html
 */
public class StrTagTest extends AbstractTest {
    private String getData(String data, String key) {
        return (String) getMapValue(data, key);
    }

    public void testString() throws IOException {
        assertEquals("abcd", getData("string: abcd", "string"));
    }

    public void testStringShorthand() throws IOException {
        assertEquals("abcd", getData("string: !!str abcd", "string"));
    }

    public void testStringTag() throws IOException {
        assertEquals("abcd", getData("string: !<tag:yaml.org,2002:str> abcd", "string"));
    }

    public void testUnicode() throws IOException {
        // escaped 8-bit unicode character (u-umlaut):
        assertEquals("\u00fc", load("\"\\xfc\""));
        assertEquals("\\xfc", load("\\xfc"));

        // 2 escaped 8-bit unicode characters (u-umlaut following by e-grave):
        assertEquals("\u00fc\u00e8", load("\"\\xfc\\xe8\""));

        // escaped 16-bit unicode character (em dash):
        assertEquals("\u2014", load("\"\\u2014\""));

        // UTF-32 encoding is explicitly not supported
        assertEquals("\\U2014AAAA", load("'\\U2014AAAA'"));

        // (and I don't have a surrogate pair handy at the moment)
        // raw unicode characters in the stream (em dash)
        assertEquals("\u2014", load("\u2014"));
    }

    /**
     * @see http://code.google.com/p/jvyamlb/issues/detail?id=6
     */
    @SuppressWarnings("unchecked")
    public void testIssueId6() {
        Map<String, String> map = (Map<String, String>) load("---\ntest: |-\n \"Test\r\r (* error here)\"");
        assertEquals("\"Test\n\n(* error here)\"", map.get("test"));
    }

    public void testStrDump() {
        assertEquals("abc\n", dump("abc"));
    }

    public void testUnicodeDump() {
        assertEquals("\\u263a\n", dump("\\u263a"));
        assertEquals("The leading zero must be preserved.", "\\u063a\n", dump("\\u063a"));
    }

    public void testStringIntOut() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("number", "1");
        String output = dump(map);
        assertTrue(output, output.contains("number: '1'"));
    }

    public void testStringFloatOut() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("number", "1.1");
        String output = dump(map);
        assertTrue(output, output.contains("number: '1.1'"));
    }

    public void testStringBoolOut() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("number", "True");
        String output = dump(map);
        assertTrue(output, output.contains("number: 'True'"));
    }

    public void testEmitLongString() throws IOException {
        String str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String output = dump(str);
        assertEquals(str + "\n", output);
    }

    public void testEmitLongStringWithCR() throws IOException {
        String str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n";
        String output = dump(str);
        assertEquals("'" + str + "\n  '\n", output);
    }

    public void testEmitDoubleQuoted() throws IOException {
        String str = "\"xx\"";
        String output = dump(str);
        assertEquals("'" + str + "'\n", output);
    }

    public void testEmitEndOfLine() throws IOException {
        String str = "xxxxxxx\n";
        String output = dump(str);
        assertEquals("'" + str + "\n  '\n", output);
    }

    public void testDumpUtf16() throws IOException {
        String str = "xxx";
        assertEquals(3, str.toString().length());
        Yaml yaml = new Yaml();
        Charset charset = Charset.forName("UTF-16");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(stream, charset);
        yaml.dump(str, writer);
        assertEquals(str + "\n", stream.toString("UTF-16"));
        assertEquals("Must include BOM: " + stream.toString(), (1 + 3 + 1) * 2, stream.toString()
                .length());
    }
}


text:
package org.apache.camel.component.telegram.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Represents a Game.
 *
 * @see
 * https://core.telegram.org/bots/api#inlinequeryresultgame
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InlineQueryResultGame extends InlineQueryResult {

    private static final String TYPE = "game";

    @JsonProperty("game_short_name")
    private String gameShortName;

    public InlineQueryResultGame() {
        super(TYPE);
    }

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

    public static final class Builder {
        private String id;
        private InlineKeyboardMarkup replyMarkup;
        private String gameShortName;

        private Builder() {
        }

        public Builder id(String id) {
            this.id = id;
            return this;
        }

        public Builder replyMarkup(InlineKeyboardMarkup replyMarkup) {
            this.replyMarkup = replyMarkup;
            return this;
        }

        public Builder gameShortName(String gameShortName) {
            this.gameShortName = gameShortName;
            return this;
        }

        public InlineQueryResultGame build() {
            InlineQueryResultGame inlineQueryResultGame = new InlineQueryResultGame();
            inlineQueryResultGame.setType(TYPE);
            inlineQueryResultGame.setId(id);
            inlineQueryResultGame.setReplyMarkup(replyMarkup);
            inlineQueryResultGame.gameShortName = this.gameShortName;
            return inlineQueryResultGame;
        }

        public String getId() {
            return id;
        }

        public InlineKeyboardMarkup getReplyMarkup() {
            return replyMarkup;
        }

        public String getGameShortName() {
            return gameShortName;
        }

        public void setId(String id) {
            this.id = id;
        }

        public void setReplyMarkup(InlineKeyboardMarkup replyMarkup) {
            this.replyMarkup = replyMarkup;
        }

        public void setGameShortName(String gameShortName) {
            this.gameShortName = gameShortName;
        }
    }
}


text:
/* */
(function(process) {
  'use strict';
  var CallbackQueue = require("./CallbackQueue");
  var PooledClass = require("./PooledClass");
  var ReactPerf = require("./ReactPerf");
  var ReactReconciler = require("./ReactReconciler");
  var Transaction = require("./Transaction");
  var assign = require("./Object.assign");
  var invariant = require("fbjs/lib/invariant");
  var dirtyComponents = [];
  var asapCallbackQueue = CallbackQueue.getPooled();
  var asapEnqueued = false;
  var batchingStrategy = null;
  function ensureInjected() {
    !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined;
  }
  var NESTED_UPDATES = {
    initialize: function() {
      this.dirtyComponentsLength = dirtyComponents.length;
    },
    close: function() {
      if (this.dirtyComponentsLength !== dirtyComponents.length) {
        dirtyComponents.splice(0, this.dirtyComponentsLength);
        flushBatchedUpdates();
      } else {
        dirtyComponents.length = 0;
      }
    }
  };
  var UPDATE_QUEUEING = {
    initialize: function() {
      this.callbackQueue.reset();
    },
    close: function() {
      this.callbackQueue.notifyAll();
    }
  };
  var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
  function ReactUpdatesFlushTransaction() {
    this.reinitializeTransaction();
    this.dirtyComponentsLength = null;
    this.callbackQueue = CallbackQueue.getPooled();
    this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(false);
  }
  assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
    getTransactionWrappers: function() {
      return TRANSACTION_WRAPPERS;
    },
    destructor: function() {
      this.dirtyComponentsLength = null;
      CallbackQueue.release(this.callbackQueue);
      this.callbackQueue = null;
      ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
      this.reconcileTransaction = null;
    },
    perform: function(method, scope, a) {
      return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
    }
  });
  PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
  function batchedUpdates(callback, a, b, c, d, e) {
    ensureInjected();
    batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
  }
  function mountOrderComparator(c1, c2) {
    return c1._mountOrder - c2._mountOrder;
  }
  function runBatchedUpdates(transaction) {
    var len = transaction.dirtyComponentsLength;
    !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined;
    dirtyComponents.sort(mountOrderComparator);
    for (var i = 0; i < len; i++) {
      var component = dirtyComponents[i];
      var callbacks = component._pendingCallbacks;
      component._pendingCallbacks = null;
      ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction);
      if (callbacks) {
        for (var j = 0; j < callbacks.length; j++) {
          transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
        }
      }
    }
  }
  var flushBatchedUpdates = function() {
    while (dirtyComponents.length || asapEnqueued) {
      if (dirtyComponents.length) {
        var transaction = ReactUpdatesFlushTransaction.getPooled();
        transaction.perform(runBatchedUpdates, null, transaction);
        ReactUpdatesFlushTransaction.release(transaction);
      }
      if (asapEnqueued) {
        asapEnqueued = false;
        var queue = asapCallbackQueue;
        asapCallbackQueue = CallbackQueue.getPooled();
        queue.notifyAll();
        CallbackQueue.release(queue);
      }
    }
  };
  flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates);
  function enqueueUpdate(component) {
    ensureInjected();
    if (!batchingStrategy.isBatchingUpdates) {
      batchingStrategy.batchedUpdates(enqueueUpdate, component);
      return;
    }
    dirtyComponents.push(component);
  }
  function asap(callback, context) {
    !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined;
    asapCallbackQueue.enqueue(callback, context);
    asapEnqueued = true;
  }
  var ReactUpdatesInjection = {
    injectReconcileTransaction: function(ReconcileTransaction) {
      !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined;
      ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
    },
    injectBatchingStrategy: function(_batchingStrategy) {
      !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined;
      !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined;
      !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined;
      batchingStrategy = _batchingStrategy;
    }
  };
  var ReactUpdates = {
    ReactReconcileTransaction: null,
    batchedUpdates: batchedUpdates,
    enqueueUpdate: enqueueUpdate,
    flushBatchedUpdates: flushBatchedUpdates,
    injection: ReactUpdatesInjection,
    asap: asap
  };
  module.exports = ReactUpdates;
})(require("process"));


text:
package org.apache.giraph.metrics;

/**
 * Pair of value with host it came from.
 *
 * @param <T> types of value (either long or double)
 */
public class ValueWithHostname<T extends Number> {
  /** long value we're holding */
  private T value;
  /** host associated with value */
  private String hostname;

  /**
   * Create with initial value
   *
   * @param value initial value to use
   */
  public ValueWithHostname(T value) {
    this.value = value;
    this.hostname = null;
  }

  /**
   * @return value
   */
  public T getValue() {
    return value;
  }

  /**
   * @return String hostname
   */
  public String getHostname() {
    return hostname;
  }

  /**
   * Check if there is any hostname. Used as a flag that we have any data.
   *
   * @return true if hostname is set
   */
  public boolean hasHostname() {
    return hostname != null;
  }

  /**
   * Set value and partition together.
   * @param value value to use.
   * @param hostname String host it came from.
   */
  public void set(T value, String hostname) {
    this.value = value;
    this.hostname = hostname;
  }
}


text:
import xs from 'xstream';
import { div, nav, a, h3, p, ul, li, h1, h2, i, footer, header, main, svg, g, path, img, map, area, use, span } from '@cycle/dom'
import { merge, prop, equals } from 'ramda';

import { Check } from '../components/Check'
import dropRepeats from 'xstream/extra/dropRepeats'
import { compoundSVG, targetSVG, ligandSVG, diseaseSVG, correlationSVG, settingsSVG } from '../svg'

const appear = {
    style: {
        opacity: '0',
        transition: 'opacity 4s',
        delayed: { opacity: '1' },
        destroy: { opacity: '0' }
    }
}

function Home(sources) {

    const checkProps$ = sources.onion.state$
        .compose(dropRepeats((x, y) => equals(x.settings, y.settings)))
        .map(state => merge(state.settings.form, state.settings.api))
    const CheckSink = Check(merge(sources, { props: checkProps$ }))

    const makeLink = (path, label, selector) => {
        return li(".home-menu .row",
                div(selector,
                    [
                        a(".home-menu", { props: { href: path } }, label),
                        span(".extraText",
                            span(".tooltiptext")
                        )
                    ]
                )
            )
    }

    const vdom$ = xs.combine(CheckSink.DOM)
        .map(([check]) => div([
            // div({ style: { 'z-index': -1, height: '100%', overflow: 'hidden', position: 'absolute', opacity: 0.08, 'text-align': 'center', width: '100%' } },
            //     Array(60).fill().map(_ => div({ style: { width: '25%', display: 'inline-block' } }, [logoSVG]))),
            div('.row .transparent', [
                h2('.title .col .l6 .m8 .s10 offset-l3 .offset-m2 .offset-s1', { style: { 'vertical-align': 'top' } }, [
                    span('.main', 'Welcome to ComPass'),
                    // div({ style: { display: 'inline-block', width: '200px', 'vertical-align': '-40%' } }, [logoSVG]),
                    span('.spacer',' '),
                    span('.check', check),
                ]),
                p('.introduction .col .l6 .m8 .s10 offset-l3 .offset-m2 .offset-s1  .flow-text', [
                    'This application is the interface with L1000 data.'
                ]),
                div('.row', []),
                div('.col .l6 .m8 .s10 offset-l3 .offset-m2 .offset-s1 .center-align', appear, [
                    ul('.left', [
                        makeLink('/compound', span(['Compound', ' ', compoundSVG]), '.compound'),
                        makeLink('/genetic', span(['Genetic', ' ', targetSVG]), '.genetic'),
                        makeLink('/ligand', span(['Ligand', ' ', ligandSVG]), '.ligand'),
                        makeLink('/disease', span(['Disease', ' ', diseaseSVG]), '.disease'),
                        makeLink('/correlation', span(['Correlation', ' ', correlationSVG]), '.correlation'),
                        makeLink('/settings', span(['Settings', ' ', settingsSVG]), '.settings'),
                    ]),
                ]),
                div('.row', []),
                p('.afterword .col .l6 .m8 .s10 offset-l3 .offset-m2 .offset-s1  .flow-text', [
                    'You can click on one of the workflows above to start it.',
                    ' Alternatively, you can initiate ghost mode in the settings.'
                ]),
            ])
        ]));

    return {
        DOM: vdom$,
        HTTP: CheckSink.HTTP,
        onion: CheckSink.onion,
        alert: CheckSink.alert,
        popup: CheckSink.popup
    };
}

export default Home


text:
>gist of the blog on python interpreter from http://akaptur.com/

## Functions and objects
```python
>>> a = "hello"
```
>What exactly happens when i press enter after typing in this code?? :unamused:

Four steps happen when that line of code is to be excuted: lexing,parsing,compiling and interpreting.
__**Lexing**__ is breaking of the code you just typed into tokens. The __**parser**__ takes these tokens and
generates a structure that shows their relationship to each other(Abstarct syntax tree).The __**compiler**__ then takes
the AST and turns it into code objects. Then the __**interpreter**__ takes each of these code objects and executes the code
it represnts.

Note: Function objects, Code objects and bytecode are all different things.

### Function Objects
Function objects are the "function objects". Functions are first-class objects (In short, first class objects means it is same as other objects, there no exclusive restrictions on how we can use them) in python, like a list is an object or an isntance of ```MyObject``` is an object.

```python
>>> def  foo(a):
...     x= 3
...
>>> foo
<function foo at 0x02261B30>
```

In the above example, we are not invoking foo(There is difference between ```foo()``` and ```foo```). We can pass ```foo``` as
an argument, or we can bind it to another name(```function_name = foo```).

### Code Objects

```python
>>> def  foo(a):
...     x= 3
...
>>> foo
<function foo at 0x02261B30>
>>> foo.func_code
<code object foo at 02216C80, file "<stdin>", line 1>
```
As you can see, code object is an attribute of the function object. Function object has lot of other attributes too.
A code object is generated by the python compiler and interpreted by the interpreter. It contains information that the interpreter
needs to interpret. Let's look at the attributes of the code object.
```python
>>> dir(foo.func_code)
['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__
__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__',
__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
_sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_c
e', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', '
_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
```
>dir() is an in-built python function, which tries to give some info about the object like the attributes in that module
namespace.

Even i don't understand a bunch of that stuff, but the blog post which i am referring to asks us to look at three attributes.
```python
>>> foo.func_code.co_varnames
('a', 'x')
>>> foo.func_code.co_consts
(None, 3)
>>> foo.func_code.co_argcount
1
```
By looking at these above arguments, we can make out that the code object gives the information needed by an interpreter to understand
a piece of code or a code block. But so far, we haven't seen any instructions on how to execute a code block. Well, that information is given by the *bytecode*.

###Bytecode
Bytecode is an attribute of the code object. Here is what an bytecode looks like:
```python
>>> foo.func_code.co_code
'd\x01\x00}\x01\x00d\x00\x00S'
```
What's going on here? :confused:

So what is *bytecode*? Well, it's just a series of bytes(duh!). Most of them are not so printable. So let's take ```ord``` of each byte to see the integer of each byte
```python
>>> [ord(b) for b in foo.func_code.co_code
[100, 1, 0, 125, 1, 0, 100, 0, 0, 83]
```
The interpreter loops through each of these bytes, look up what it should do and do that thing. Bytecode doesn't include any python objects,references to objects or anything like that. One way to understand what these numbers mean to interpreter is to look through the CPython interpreter file (```ceval.c```).
####Disassembling bytecode
We will be using ```dis``` module to look at the disassembling bytecode. Disassembling means taking a series of byte codes and print out something human readable. We'll use ```dis.dis()``` function to analyze the code objects of our function ```foo()```. These are nothing but a series of stack operations for the interpreter to do.

```python
>>> def foo(a):
...  x=3
...  return 3
...
>>> import dis
>>> dis.dis(foo.func_code)
  2           0 LOAD_CONST               1 (3)
              3 STORE_FAST               1 (x)

  3           6 LOAD_CONST               1 (3)
              9 RETURN_VALUE
```
>You can see ```dis.dis(foo)``` also doing the same thing. It's just convenience.
The  numbers in the left-hand side are the line numbers in the original code. The second column is the offset into the bytecode. The middle column shows the name of the bytes, which are clearly for human interpretation. The interpreter doesn't benefit from these names.

The last two columns give information about the instructions's argument,only if there is an argument. Fourth column shows the argument
index and the last column is the argument itself. If you look at our function ```foo(a)```, we are passing arg ```a``` but we have never used ```a```, we have used a second argument ```x```. That is what the fourth column shows, the argument index 0 is for ```a``` and 1 is for ```x```.


text:
package org.opennms.newts.rest;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import com.fasterxml.jackson.annotation.JsonProperty;

public class GraphiteConfig {

    @JsonProperty("enabled")
    private boolean m_enabled = false;

    @Min(value = 1024)
    @Max(value = 65535)
    @JsonProperty("port")
    private int m_port = 2003;

    public boolean isEnabled() {
        return m_enabled;
    }

    public int getPort() {
        return m_port;
    }

}


text:
<ion-view title="Adopt A Pet">
  <ion-content has-tabs="true">
    <form ng-submit="addSwim()">

        Swim title
        <input type="text" ng-model="swim.title">

        Laps
        <input type="text" ng-model="swim.laps">

      <button class="button button-positive button-block" type=submit>Add Swim</button>

  </ion-content>
</ion-view>


text:
{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE RecordWildCards      #-}
{-# LANGUAGE TemplateHaskell      #-}
{-# LANGUAGE TypeFamilies         #-}
{-# LANGUAGE TypeSynonymInstances #-}

module Physics.Demo.IOWorld where

import           Control.Lens               (makeLenses, view, (%~), (&), (.~),
                                             (^.), _1)
import           Control.Monad
import           Control.Monad.IO.Class
import           Control.Monad.Reader
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Maybe
import qualified Data.Vector.Unboxed        as V

import           Linear.Matrix              (M33)
import           Linear.V2

import           EasySDL.Draw
import           GameLoop
import qualified SDL.Event                  as E
import qualified SDL.Input.Keyboard         as K
import qualified SDL.Input.Keyboard.Codes   as KC
import qualified SDL.Time                   as T
import qualified SDL.Video.Renderer         as R

import qualified Physics.Broadphase.Aabb    as B
import qualified Physics.Broadphase.Grid    as G
import           Physics.Contact
import           Physics.Contact.ConvexHull
import           Physics.Contact.Types      (ContactBehavior (..))
import qualified Physics.Contact.Types      as C
import           Physics.Demo.Scenes
import           Physics.Draw
import           Physics.Draw.Canonical
import qualified Physics.Draw.Opt           as D
import           Physics.Engine
import qualified Physics.Engine.Main        as OM
import           Physics.Scenes.Scene
import qualified Physics.Solvers.Contact    as S
import           Physics.World

import           Utils.Descending
import           Utils.Utils

type DemoM = ReaderT OM.EngineConfig (StateT (OM.EngineState () RealWorld) IO)

convertEngineT :: OM.EngineST () RealWorld a -> DemoM a
convertEngineT action =
  ReaderT (\config -> StateT (stToIO . runStateT (runReaderT action config)))

runDemo :: Scene RealWorld () -> DemoM a -> IO a
runDemo scene@Scene{..} action = do
  eState <- liftIO . stToIO $ OM.initEngine scene
  evalStateT (runReaderT action eConfig) eState
  where eConfig = OM.EngineConfig 0.01 _scContactBeh

resetEngine :: Scene RealWorld () -> DemoM ()
resetEngine scene =
  convertEngineT $ OM.changeScene scene

drawWorld :: R.Renderer -> M33 Double -> DemoM ()
drawWorld r vt = do
  world <- demoWorld
  liftIO $ D.drawWorld r vt world

demoWorld :: DemoM (World RealWorld ())
demoWorld = view _1 <$> get

worldContacts :: DemoM [Contact]
worldContacts = do
  world <- demoWorld
  keys <- lifty $ G.culledKeys <$> G.toGrid OM.gridAxes world
  contacts_ <- lifty $ S.prepareFrame keys world
  let contacts :: Descending C.Contact
      contacts = fmap (flipExtractUnsafe . snd) contacts_
  return . _descList $ toCanonical <$> contacts

lifty :: (MonadIO m) => ST RealWorld a -> m a
lifty = liftIO . stToIO

worldAabbs :: DemoM [Aabb]
worldAabbs = do
  world <- demoWorld
  aabbs <- lifty $ B.toAabbs world
  return $ toCanonical . snd <$> V.toList aabbs

debugEngineState :: DemoM String
debugEngineState = return "<insert debug trace here>"

updateWorld :: DemoM ()
updateWorld = void . convertEngineT $ OM.updateWorld

data DemoState =
  DemoState { _demoFinished      :: Bool
            , _demoSceneIndex    :: Int
            , _demoDrawDebug     :: Bool
            , _demoPrintDebug    :: Bool
            , _demoViewTransform :: M33 Double
            }
makeLenses ''DemoState

getViewTransform :: V2 Double -> V2 Double -> M33 Double
getViewTransform window scale = fst $ viewTransform window scale (V2 0 0)

initialState :: Int -> M33 Double -> DemoState
initialState i = DemoState False i True False

nextInitialState :: DemoState -> Int -> DemoM DemoState
nextInitialState DemoState{..} i = do
  scene <- lifty $ scenes i
  resetEngine scene
  return $ initialState i _demoViewTransform
    & demoDrawDebug .~ _demoDrawDebug
    & demoPrintDebug .~ _demoPrintDebug

timeStep :: Num a => a
timeStep = 10

renderWorld :: R.Renderer -> DemoState -> DemoM ()
renderWorld r DemoState{..} = do
  liftIO $ setColor r black
  drawWorld r _demoViewTransform

renderContacts :: R.Renderer -> DemoState -> DemoM ()
renderContacts r DemoState{..} = do
  liftIO $ setColor r pink
  contacts <- worldContacts
  liftIO $ mapM_ (drawContact r . transform _demoViewTransform) contacts

renderAabbs :: R.Renderer -> DemoState -> DemoM ()
renderAabbs r DemoState{..} = do
  liftIO $ setColor r silver
  aabbs <- worldAabbs
  liftIO $ mapM_ (drawAabb r . transform _demoViewTransform) aabbs

demoStep :: R.Renderer -> DemoState -> DemoM DemoState
demoStep r s0@DemoState {..} = do
  events <- liftIO E.pollEvents
  liftIO $ clearScreen r
  renderWorld r s0
  when (s0 ^. demoDrawDebug) $ do
    renderContacts r s0
    renderAabbs r s0
  when (s0 ^. demoPrintDebug) $ do
    debug <- debugEngineState
    liftIO $ print debug
  s1 <- foldM handleEvent s0 events
  updateWorld
  liftIO $ R.present r
  return s1

handleEvent :: DemoState -> E.Event -> DemoM DemoState
handleEvent s0 (E.Event _ E.QuitEvent) =
  return s0 { _demoFinished = True }
handleEvent s0 (E.Event _ (E.KeyboardEvent (E.KeyboardEventData _ motion _ key)))
  | motion == E.Pressed =
    handleKeypress s0 (K.keysymScancode key) (K.keysymModifier key)
  | otherwise = return s0
handleEvent s0 _ = return s0

handleKeypress :: DemoState
               -> K.Scancode
               -> K.KeyModifier
               -> DemoM DemoState
handleKeypress state KC.ScancodeR _ =
  nextInitialState state (state ^. demoSceneIndex)
handleKeypress state KC.ScancodeN km
  | K.keyModifierLeftShift km || K.keyModifierRightShift km =
    nextInitialState state $
    (state ^. demoSceneIndex - 1)
    `posMod` sceneCount
  | otherwise =
    nextInitialState state $
    (state ^. demoSceneIndex + 1)
    `mod` sceneCount
handleKeypress state KC.ScancodeD _ =
  return $ state & demoDrawDebug %~ not
handleKeypress state KC.ScancodeP _ =
  return $ state & demoPrintDebug %~ not
handleKeypress state _ _ = return state

demoMain :: V2 Double -> V2 Double -> R.Renderer -> IO ()
demoMain window scale r = do
  t0 <- T.ticks
  let demo = timedRunUntil t0 timeStep (initialState 0 $ getViewTransform window scale) _demoFinished (\s _ -> demoStep r s)
  scene <- lifty $ scenes 0
  runDemo scene demo


text:
<?php
	include_once("../../../database/mcat_db.php");
	include_once("../../../lib/session_manager.php");
	include_once("../../../lib/new-email.php");
	include_once("../../../lib/utils.php");

	session_start();

	$objDB = new CMcatDB();

	$user_id = CSessionManager::Get(CSessionManager::STR_USER_ID);
	$timezone = $_POST['time_zone'];

	$pan_no = $_POST['pan_no'];
	if(!empty($pan_no))
	{
		$objDB->SetUserPANNumber($pan_no,$user_id);
	}

	$balance = $_SESSION['balance'];

	$encash_pnts = 0;

	if($balance > CConfig::MAX_ENCASH_PNTS)
	{
		$encash_pnts = CConfig::MAX_ENCASH_PNTS;
		$balance = $balance - $encash_pnts;
	}
	else
	{
		$remaining = $balance%5;
		$encash_pnts = $balance - $remaining;
		$balance = $remaining;
	}

	$objDB->UpdateContribBalance($balance, $user_id);
	$objDB->InsertContribEncashRequest($user_id,$timezone,$_SERVER['REMOTE_ADDR'],$encash_pnts,0);

	$contrib_email = $objDB->GetUserEmail($user_id);
	$contrib_name = $objDB->GetUserName($user_id);

	$objMail = new CEMail(CConfig::OEI_FINANCE, $objDB->GetPasswordFromOfficialEMail(CConfig::OEI_FINANCE));
	$objMail->PrepAndSendEncashPointsRequestMail($contrib_email, $contrib_name, $encash_pnts);
	//CEMail::PrepAndSendEncashPointsRequestMail($contrib_email, $contrib_name, $encash_pnts);

	unset($_SESSION['balance']);

	CUtils::Redirect("../encash_points.php?encashed=1");
?>


text:
const test = require('tape')
const today = require('./')

test('should return an object with values', function (t) {
  t.plan(5)

  const date = today()

  t.equal(typeof date, 'object')
  t.equal(typeof date.year, 'string')
  t.equal(typeof date.month, 'string')
  t.equal(typeof date.day, 'string')
  t.equal(typeof date.date, 'string')
})