text:
/*************************************************************************/
/*  renderer_scene_environment_rd.h                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef RENDERING_SERVER_SCENE_ENVIRONMENT_RD_H
#define RENDERING_SERVER_SCENE_ENVIRONMENT_RD_H

#include "servers/rendering/renderer_scene_render.h"
#include "servers/rendering/rendering_device.h"

class RendererSceneEnvironmentRD {
private:
	static uint64_t auto_exposure_counter;

public:
	// BG
	RS::EnvironmentBG background = RS::ENV_BG_CLEAR_COLOR;
	RID sky;
	float sky_custom_fov = 0.0;
	Basis sky_orientation;
	Color bg_color;
	float bg_energy = 1.0;
	int canvas_max_layer = 0;
	RS::EnvironmentAmbientSource ambient_source = RS::ENV_AMBIENT_SOURCE_BG;
	Color ambient_light;
	float ambient_light_energy = 1.0;
	float ambient_sky_contribution = 1.0;
	RS::EnvironmentReflectionSource reflection_source = RS::ENV_REFLECTION_SOURCE_BG;
	Color ao_color;

	/// Tonemap

	RS::EnvironmentToneMapper tone_mapper;
	float exposure = 1.0;
	float white = 1.0;
	bool auto_exposure = false;
	float min_luminance = 0.2;
	float max_luminance = 8.0;
	float auto_exp_speed = 0.2;
	float auto_exp_scale = 0.5;
	uint64_t auto_exposure_version = 0;

	// Fog
	bool fog_enabled = false;
	Color fog_light_color = Color(0.5, 0.6, 0.7);
	float fog_light_energy = 1.0;
	float fog_sun_scatter = 0.0;
	float fog_density = 0.001;
	float fog_height = 0.0;
	float fog_height_density = 0.0; //can be negative to invert effect
	float fog_aerial_perspective = 0.0;

	/// Volumetric Fog
	///
	bool volumetric_fog_enabled = false;
	float volumetric_fog_density = 0.01;
	Color volumetric_fog_light = Color(0, 0, 0);
	float volumetric_fog_light_energy = 0.0;
	float volumetric_fog_length = 64.0;
	float volumetric_fog_detail_spread = 2.0;
	float volumetric_fog_gi_inject = 0.0;
	bool volumetric_fog_temporal_reprojection = true;
	float volumetric_fog_temporal_reprojection_amount = 0.9;

	/// Glow

	bool glow_enabled = false;
	Vector<float> glow_levels;
	float glow_intensity = 0.8;
	float glow_strength = 1.0;
	float glow_bloom = 0.0;
	float glow_mix = 0.01;
	RS::EnvironmentGlowBlendMode glow_blend_mode = RS::ENV_GLOW_BLEND_MODE_SOFTLIGHT;
	float glow_hdr_bleed_threshold = 1.0;
	float glow_hdr_luminance_cap = 12.0;
	float glow_hdr_bleed_scale = 2.0;

	/// SSAO

	bool ssao_enabled = false;
	float ssao_radius = 1.0;
	float ssao_intensity = 2.0;
	float ssao_power = 1.5;
	float ssao_detail = 0.5;
	float ssao_horizon = 0.06;
	float ssao_sharpness = 0.98;
	float ssao_direct_light_affect = 0.0;
	float ssao_ao_channel_affect = 0.0;

	/// SSR
	///
	bool ssr_enabled = false;
	int ssr_max_steps = 64;
	float ssr_fade_in = 0.15;
	float ssr_fade_out = 2.0;
	float ssr_depth_tolerance = 0.2;

	/// SDFGI
	bool sdfgi_enabled = false;
	RS::EnvironmentSDFGICascades sdfgi_cascades;
	float sdfgi_min_cell_size = 0.2;
	bool sdfgi_use_occlusion = false;
	float sdfgi_bounce_feedback = 0.0;
	bool sdfgi_read_sky_light = false;
	float sdfgi_energy = 1.0;
	float sdfgi_normal_bias = 1.1;
	float sdfgi_probe_bias = 1.1;
	RS::EnvironmentSDFGIYScale sdfgi_y_scale = RS::ENV_SDFGI_Y_SCALE_DISABLED;

	/// Adjustments

	bool adjustments_enabled = false;
	float adjustments_brightness = 1.0f;
	float adjustments_contrast = 1.0f;
	float adjustments_saturation = 1.0f;
	bool use_1d_color_correction = false;
	RID color_correction = RID();

	void set_ambient_light(const Color &p_color, RS::EnvironmentAmbientSource p_ambient, float p_energy, float p_sky_contribution, RS::EnvironmentReflectionSource p_reflection_source, const Color &p_ao_color);
	void set_tonemap(RS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale);
	void set_glow(bool p_enable, Vector<float> p_levels, float p_intensity, float p_strength, float p_mix, float p_bloom_threshold, RS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap);
	void set_sdfgi(bool p_enable, RS::EnvironmentSDFGICascades p_cascades, float p_min_cell_size, RS::EnvironmentSDFGIYScale p_y_scale, bool p_use_occlusion, float p_bounce_feedback, bool p_read_sky, float p_energy, float p_normal_bias, float p_probe_bias);
	void set_fog(bool p_enable, const Color &p_light_color, float p_light_energy, float p_sun_scatter, float p_density, float p_height, float p_height_density, float p_fog_aerial_perspective);
	void set_volumetric_fog(bool p_enable, float p_density, const Color &p_light, float p_light_energy, float p_length, float p_detail_spread, float p_gi_inject, bool p_temporal_reprojection, float p_temporal_reprojection_amount);
	void set_ssr(bool p_enable, int p_max_steps, float p_fade_int, float p_fade_out, float p_depth_tolerance);
	void set_ssao(bool p_enable, float p_radius, float p_intensity, float p_power, float p_detail, float p_horizon, float p_sharpness, float p_light_affect, float p_ao_channel_affect);
};

#endif /* !RENDERING_SERVER_SCENE_ENVIRONMENT_RD_H */


text:
import {expect} from 'chai';
import {spec} from 'modules/conversantBidAdapter';
import * as utils from 'src/utils';

var Adapter = require('modules/conversantBidAdapter');
var bidManager = require('src/bidmanager');

describe('Conversant adapter tests', function() {
  const siteId = '108060';

  const bidRequests = [
    {
      bidder: 'conversant',
      params: {
        site_id: siteId,
        position: 1,
        tag_id: 'tagid-1',
        secure: false,
        bidfloor: 0.5
      },
      placementCode: 'pcode000',
      transactionId: 'tx000',
      sizes: [[300, 250]],
      bidId: 'bid000',
      bidderRequestId: '117d765b87bed38',
      requestId: 'req000'
    }, {
      bidder: 'conversant',
      params: {
        site_id: siteId,
        secure: false
      },
      placementCode: 'pcode001',
      transactionId: 'tx001',
      sizes: [[468, 60]],
      bidId: 'bid001',
      bidderRequestId: '117d765b87bed38',
      requestId: 'req000'
    }, {
      bidder: 'conversant',
      params: {
        site_id: siteId,
        position: 2,
        tag_id: '',
        secure: false
      },
      placementCode: 'pcode002',
      transactionId: 'tx002',
      sizes: [[300, 600], [160, 600]],
      bidId: 'bid002',
      bidderRequestId: '117d765b87bed38',
      requestId: 'req000'
    }, {
      bidder: 'conversant',
      params: {
        site_id: siteId,
        api: [2],
        protocols: [1, 2],
        mimes: ['video/mp4', 'video/x-flv'],
        maxduration: 30
      },
      mediaTypes: {
        video: {
          context: 'instream'
        }
      },
      placementCode: 'pcode003',
      transactionId: 'tx003',
      sizes: [640, 480],
      bidId: 'bid003',
      bidderRequestId: '117d765b87bed38',
      requestId: 'req000'
    }];

  const bidResponses = {
    body: {
      id: 'req000',
      seatbid: [{
        bid: [{
          nurl: 'notify000',
          adm: 'markup000',
          crid: '1000',
          impid: 'bid000',
          price: 0.99,
          w: 300,
          h: 250,
          adomain: ['https://example.com'],
          id: 'bid000'
        }, {
          impid: 'bid001',
          price: 0.00000,
          id: 'bid001'
        }, {
          nurl: 'notify002',
          adm: 'markup002',
          crid: '1002',
          impid: 'bid002',
          price: 2.99,
          w: 300,
          h: 600,
          adomain: ['https://example.com'],
          id: 'bid002'
        }, {
          nurl: 'notify003',
          adm: 'markup003',
          crid: '1003',
          impid: 'bid003',
          price: 3.99,
          adomain: ['https://example.com'],
          id: 'bid003'
        }]
      }]
    },
    headers: {}};

  it('Verify basic properties', function() {
    expect(spec.code).to.equal('conversant');
    expect(spec.aliases).to.be.an('array').with.lengthOf(1);
    expect(spec.aliases[0]).to.equal('cnvr');
    expect(spec.supportedMediaTypes).to.be.an('array').with.lengthOf(1);
    expect(spec.supportedMediaTypes[0]).to.equal('video');
  });

  it('Verify user syncs', function() {
    expect(spec.getUserSyncs({})).to.be.undefined;
    expect(spec.getUserSyncs({iframeEnabled: true})).to.be.undefined;
    expect(spec.getUserSyncs({pixelEnabled: false})).to.be.undefined;

    const syncs = spec.getUserSyncs({pixelEnabled: true});
    expect(syncs).to.be.an('array').with.lengthOf(1);
    expect(syncs[0].type).to.equal('image');
    expect(syncs[0].url).to.equal('//media.msg.dotomi.com/w/user.sync');
  });

  it('Verify isBidRequestValid', function() {
    expect(spec.isBidRequestValid({})).to.be.false;
    expect(spec.isBidRequestValid({params: {}})).to.be.false;
    expect(spec.isBidRequestValid({params: {site_id: '123'}})).to.be.true;
    expect(spec.isBidRequestValid(bidRequests[0])).to.be.true;
    expect(spec.isBidRequestValid(bidRequests[1])).to.be.true;
    expect(spec.isBidRequestValid(bidRequests[2])).to.be.true;
    expect(spec.isBidRequestValid(bidRequests[3])).to.be.true;

    const simpleVideo = JSON.parse(JSON.stringify(bidRequests[3]));
    simpleVideo.params.site_id = 123;
    expect(spec.isBidRequestValid(simpleVideo)).to.be.false;
    simpleVideo.params.site_id = siteId;
    simpleVideo.params.mimes = [1, 2, 3];
    expect(spec.isBidRequestValid(simpleVideo)).to.be.false;
    simpleVideo.params.mimes = 'bad type';
    expect(spec.isBidRequestValid(simpleVideo)).to.be.false;
    delete simpleVideo.params.mimes;
    expect(spec.isBidRequestValid(simpleVideo)).to.be.true;
  });

  it('Verify buildRequest', function() {
    const request = spec.buildRequests(bidRequests);
    expect(request.method).to.equal('POST');
    expect(request.url).to.equal('//media.msg.dotomi.com/s2s/header/24');
    const payload = request.data;

    expect(payload).to.have.property('id', 'req000');
    expect(payload).to.have.property('at', 1);
    expect(payload).to.have.property('imp');
    expect(payload.imp).to.be.an('array').with.lengthOf(4);

    expect(payload.imp[0]).to.have.property('id', 'bid000');
    expect(payload.imp[0]).to.have.property('secure', 0);
    expect(payload.imp[0]).to.have.property('bidfloor', 0.5);
    expect(payload.imp[0]).to.have.property('displaymanager', 'Prebid.js');
    expect(payload.imp[0]).to.have.property('displaymanagerver').that.matches(/^\d+\.\d+\.\d+$/);
    expect(payload.imp[0]).to.have.property('tagid', 'tagid-1');
    expect(payload.imp[0]).to.have.property('banner');
    expect(payload.imp[0].banner).to.have.property('pos', 1);
    expect(payload.imp[0].banner).to.have.property('format');
    expect(payload.imp[0].banner.format).to.deep.equal([{w: 300, h: 250}]);
    expect(payload.imp[0]).to.not.have.property('video');

    expect(payload.imp[1]).to.have.property('id', 'bid001');
    expect(payload.imp[1]).to.have.property('secure', 0);
    expect(payload.imp[1]).to.have.property('bidfloor', 0);
    expect(payload.imp[1]).to.have.property('displaymanager', 'Prebid.js');
    expect(payload.imp[0]).to.have.property('displaymanagerver').that.matches(/^\d+\.\d+\.\d+$/);
    expect(payload.imp[1]).to.not.have.property('tagid');
    expect(payload.imp[1]).to.have.property('banner');
    expect(payload.imp[1].banner).to.not.have.property('pos');
    expect(payload.imp[1].banner).to.have.property('format');
    expect(payload.imp[1].banner.format).to.deep.equal([{w: 468, h: 60}]);

    expect(payload.imp[2]).to.have.property('id', 'bid002');
    expect(payload.imp[2]).to.have.property('secure', 0);
    expect(payload.imp[2]).to.have.property('bidfloor', 0);
    expect(payload.imp[2]).to.have.property('displaymanager', 'Prebid.js');
    expect(payload.imp[0]).to.have.property('displaymanagerver').that.matches(/^\d+\.\d+\.\d+$/);
    expect(payload.imp[2]).to.have.property('banner');
    expect(payload.imp[2].banner).to.have.property('pos', 2);
    expect(payload.imp[2].banner).to.have.property('format');
    expect(payload.imp[2].banner.format).to.deep.equal([{w: 300, h: 600}, {w: 160, h: 600}]);

    expect(payload.imp[3]).to.have.property('id', 'bid003');
    expect(payload.imp[3]).to.have.property('secure', 0);
    expect(payload.imp[3]).to.have.property('bidfloor', 0);
    expect(payload.imp[3]).to.have.property('displaymanager', 'Prebid.js');
    expect(payload.imp[0]).to.have.property('displaymanagerver').that.matches(/^\d+\.\d+\.\d+$/);
    expect(payload.imp[3]).to.not.have.property('tagid');
    expect(payload.imp[3]).to.have.property('video');
    expect(payload.imp[3].video).to.not.have.property('pos');
    expect(payload.imp[3].video).to.have.property('w', 640);
    expect(payload.imp[3].video).to.have.property('h', 480);
    expect(payload.imp[3].video).to.have.property('mimes');
    expect(payload.imp[3].video.mimes).to.deep.equal(['video/mp4', 'video/x-flv']);
    expect(payload.imp[3].video).to.have.property('protocols');
    expect(payload.imp[3].video.protocols).to.deep.equal([1, 2]);
    expect(payload.imp[3].video).to.have.property('api');
    expect(payload.imp[3].video.api).to.deep.equal([2]);
    expect(payload.imp[3].video).to.have.property('maxduration', 30);
    expect(payload.imp[3]).to.not.have.property('banner');

    expect(payload).to.have.property('site');
    expect(payload.site).to.have.property('id', siteId);
    expect(payload.site).to.have.property('mobile').that.is.oneOf([0, 1]);
    const loc = utils.getTopWindowLocation();
    const page = loc.href;
    expect(payload.site).to.have.property('page', page);

    expect(payload).to.have.property('device');
    expect(payload.device).to.have.property('w', screen.width);
    expect(payload.device).to.have.property('h', screen.height);
    expect(payload.device).to.have.property('dnt').that.is.oneOf([0, 1]);
    expect(payload.device).to.have.property('ua', navigator.userAgent);
  });

  it('Verify interpretResponse', function() {
    const request = spec.buildRequests(bidRequests);
    const response = spec.interpretResponse(bidResponses, request);
    expect(response).to.be.an('array').with.lengthOf(3);

    let bid = response[0];
    expect(bid).to.have.property('requestId', 'bid000');
    expect(bid).to.have.property('currency', 'USD');
    expect(bid).to.have.property('cpm', 0.99);
    expect(bid).to.have.property('creativeId', '1000');
    expect(bid).to.have.property('width', 300);
    expect(bid).to.have.property('height', 250);
    expect(bid).to.have.property('ad', 'markup000');
    expect(bid).to.have.property('ttl', 300);
    expect(bid).to.have.property('netRevenue', true);

    // There is no bid001 because cpm is $0

    bid = response[1];
    expect(bid).to.have.property('requestId', 'bid002');
    expect(bid).to.have.property('currency', 'USD');
    expect(bid).to.have.property('cpm', 2.99);
    expect(bid).to.have.property('creativeId', '1002');
    expect(bid).to.have.property('width', 300);
    expect(bid).to.have.property('height', 600);
    expect(bid).to.have.property('ad', 'markup002');
    expect(bid).to.have.property('ttl', 300);
    expect(bid).to.have.property('netRevenue', true);

    bid = response[2];
    expect(bid).to.have.property('requestId', 'bid003');
    expect(bid).to.have.property('currency', 'USD');
    expect(bid).to.have.property('cpm', 3.99);
    expect(bid).to.have.property('creativeId', '1003');
    expect(bid).to.have.property('width', 640);
    expect(bid).to.have.property('height', 480);
    expect(bid).to.have.property('vastUrl', 'markup003');
    expect(bid).to.have.property('mediaType', 'video');
    expect(bid).to.have.property('ttl', 300);
    expect(bid).to.have.property('netRevenue', true);
  });

  it('Verify handling of bad responses', function() {
    let response = spec.interpretResponse({}, {});
    expect(response).to.be.an('array').with.lengthOf(0);
    response = spec.interpretResponse({id: '123'}, {});
    expect(response).to.be.an('array').with.lengthOf(0);
    response = spec.interpretResponse({id: '123', seatbid: []}, {});
    expect(response).to.be.an('array').with.lengthOf(0);
  });
})

redpajama_set_name: RedPajamaGithub


text:
create extension postgis^

-- begin CRUISESAMPLE_PORT
create table CRUISESAMPLE_PORT (
    ID uuid,
    VERSION integer not null,
    CREATE_TS timestamp,
    CREATED_BY varchar(50),
    UPDATE_TS timestamp,
    UPDATED_BY varchar(50),
    DELETE_TS timestamp,
    DELETED_BY varchar(50),
    --
    NAME varchar(255) not null,
    LOCATION geometry not null,
    --
    primary key (ID)
)^
-- end CRUISESAMPLE_PORT
-- begin CRUISESAMPLE_ROUTE
create table CRUISESAMPLE_ROUTE (
    ID uuid,
    VERSION integer not null,
    CREATE_TS timestamp,
    CREATED_BY varchar(50),
    UPDATE_TS timestamp,
    UPDATED_BY varchar(50),
    DELETE_TS timestamp,
    DELETED_BY varchar(50),
    --
    NAME varchar(255) not null,
    --
    primary key (ID)
)^
-- end CRUISESAMPLE_ROUTE
-- begin CRUISESAMPLE_WAYPOINT
create table CRUISESAMPLE_WAYPOINT (
    ID uuid,
    VERSION integer not null,
    CREATE_TS timestamp,
    CREATED_BY varchar(50),
    UPDATE_TS timestamp,
    UPDATED_BY varchar(50),
    DELETE_TS timestamp,
    DELETED_BY varchar(50),
    --
    POINT geometry not null,
    ETA timestamp,
    ROUTE_ID uuid,
    --
    primary key (ID)
)^
-- end CRUISESAMPLE_WAYPOINT
-- begin CRUISESAMPLE_STOP
create table CRUISESAMPLE_STOP (
    ID uuid,
    VERSION integer not null,
    CREATE_TS timestamp,
    CREATED_BY varchar(50),
    UPDATE_TS timestamp,
    UPDATED_BY varchar(50),
    DELETE_TS timestamp,
    DELETED_BY varchar(50),
    --
    ORDER_ integer not null,
    PORT_ID uuid not null,
    --
    primary key (ID)
)^
-- end CRUISESAMPLE_STOP
-- begin CRUISESAMPLE_ROUTE_STOP_LINK
create table CRUISESAMPLE_ROUTE_STOP_LINK (
    ROUTE_ID uuid,
    STOP_ID uuid,
    primary key (ROUTE_ID, STOP_ID)
)^
-- end CRUISESAMPLE_ROUTE_STOP_LINK


text:
package fi.vincit.multiusertest.configuration;

import fi.vincit.multiusertest.test.AbstractMultiUserConfig;
import fi.vincit.multiusertest.util.LoginRole;
import fi.vincit.multiusertest.util.SecurityUtil;
import fi.vincit.multiusertest.util.User;
import org.junit.After;

import java.util.HashMap;
import java.util.Map;

public class InitProducerBeforeTestConfiguredTest extends AbstractMultiUserConfig<User, User.Role> {

    private static Map<String, User> users = new HashMap<>();

    private static boolean producerCreated = false;

    public static void setProducerCreated(boolean producerCreated) {
        InitProducerBeforeTestConfiguredTest.producerCreated = producerCreated;
    }

    @Override
    public void loginWithUser(User user) {
        SecurityUtil.logInUser(user);
    }

    @After
    public void tearDown() {
        SecurityUtil.clear();
    }

    @Override
    public User createUser(String username, String firstName, String lastName, User.Role userRole, LoginRole loginRole) {
        User user = new User(username, userRole);
        users.put(username, user);
        return user;
    }

    @Override
    public void logInAs(LoginRole role) {
        if (role == LoginRole.PRODUCER) {
            if (!producerCreated) {
                throw new AssertionError("No produced created before logInAs call");
            }
        } else {
            super.logInAs(role);
        }
    }

    @Override
    public User.Role stringToRole(String role) {
        return User.Role.valueOf(role);
    }

    @Override
    public User getUserByUsername(String username) {
        return users.get(username);
    }
}


text:
import Controller from '@ember/controller';
import { task, timeout } from 'ember-concurrency';

export default Controller.extend({
  membersCollapsed: true,
  repertoryCollapsed: true,
  imageCollapsed: true,
  whichChoice: true,
  autosave: task(function* (property, value){
    this.model.entry.set(property, value);
    yield timeout(1000);
    try {
      yield this.model.entry.save();
      this.flashMessages.success("Saved");
    } catch(e) {
      e.errors.forEach((error) => {
        this.flashMessages.danger(error.detail);
      })
    }
  }).restartable(),
});


text:
#ifndef TA_UTIL_FORMAT_PRINTF_AGENT_H
#define TA_UTIL_FORMAT_PRINTF_AGENT_H

#include <stdio.h>
#include "common/agent.h"

/********************************************************************/
/**                       Helper Functions                         **/
/********************************************************************/

int vasprintfDotsShell( char ** ptr  ,           const char * format, ... );
int vdprintfDotsShell ( int fd       ,           const char * format, ... );
int vfprintfDotsShell ( FILE * stream,           const char * format, ... );
int vprintfDotsShell  (                          const char * format, ... );
int vsnprintfDotsShell( char * s     , size_t n, const char * format, ... );
int vsprintfDotsShell ( char * s     ,           const char * format, ... );

/********************************************************************/
/**                      Agent Initialization                      **/
/********************************************************************/

void register_util_format_printf_commands(void);

#endif


text:
  #define PROTOBUF_USE_EXCEPTIONS 1
#elif defined(__EXCEPTIONS)
  #define PROTOBUF_USE_EXCEPTIONS 1
#else
  #define PROTOBUF_USE_EXCEPTIONS 0
#endif
#endif

#if PROTOBUF_USE_EXCEPTIONS
#include <exception>
#endif
#if defined(__APPLE__)
#include <TargetConditionals.h>  // for TARGET_OS_IPHONE
#endif

#if defined(__ANDROID__) || defined(GOOGLE_PROTOBUF_OS_ANDROID) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE) || defined(GOOGLE_PROTOBUF_OS_IPHONE)
#include <pthread.h>
#endif

#include <google/protobuf/port_def.inc>

namespace std {}

namespace google {
namespace protobuf {
namespace internal {

// Some of these constants are macros rather than const ints so that they can
// be used in #if directives.

// The current version, represented as a single integer to make comparison
// easier:  major * 10^6 + minor * 10^3 + micro
#define GOOGLE_PROTOBUF_VERSION 3019001

// A suffix string for alpha, beta or rc releases. Empty for stable releases.
#define GOOGLE_PROTOBUF_VERSION_SUFFIX ""

// The minimum header version which works with the current version of
// the library.  This constant should only be used by protoc's C++ code
// generator.
static const int kMinHeaderVersionForLibrary = 3019000;

// The minimum protoc version which works with the current version of the
// headers.
#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3019000

// The minimum header version which works with the current version of
// protoc.  This constant should only be used in VerifyVersion().
static const int kMinHeaderVersionForProtoc = 3019000;

// Verifies that the headers and libraries are compatible.  Use the macro
// below to call this.
void PROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion,
                                   const char* filename);

// Converts a numeric version number to a string.
std::string PROTOBUF_EXPORT VersionString(int version);

}  // namespace internal

// Place this macro in your main() function (or somewhere before you attempt
// to use the protobuf library) to verify that the version you link against
// matches the headers you compiled against.  If a version mismatch is
// detected, the process will abort.
#define GOOGLE_PROTOBUF_VERIFY_VERSION                                    \
  ::google::protobuf::internal::VerifyVersion(                            \
    GOOGLE_PROTOBUF_VERSION, GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION,         \
    __FILE__)

// ===================================================================
// from google3/util/utf8/public/unilib.h

namespace internal {

// Checks if the buffer contains structurally-valid UTF-8.  Implemented in
// structurally_valid.cc.
PROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len);

inline bool IsStructurallyValidUTF8(StringPiece str) {
  return IsStructurallyValidUTF8(str.data(), static_cast<int>(str.length()));
}

// Returns initial number of bytes of structurally valid UTF-8.
PROTOBUF_EXPORT int UTF8SpnStructurallyValid(StringPiece str);

// Coerce UTF-8 byte string in src_str to be
// a structurally-valid equal-length string by selectively
// overwriting illegal bytes with replace_char (typically ' ' or '?').
// replace_char must be legal printable 7-bit Ascii 0x20..0x7e.
// src_str is read-only.
//
// Returns pointer to output buffer, src_str.data() if no changes were made,
//  or idst if some bytes were changed. idst is allocated by the caller
//  and must be at least as big as src_str
//
// Optimized for: all structurally valid and no byte copying is done.
//
PROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid(StringPiece str, char* dst,
                                                    char replace_char);

}  // namespace internal

// This lives in message_lite.h now, but we leave this here for any users that
// #include common.h and not message_lite.h.
PROTOBUF_EXPORT void ShutdownProtobufLibrary();

namespace internal {

// Strongly references the given variable such that the linker will be forced
// to pull in this variable's translation unit.
template <typename T>
void StrongReference(const T& var) {
  auto volatile unused = &var;
  (void)&unused;  // Use address to avoid an extra load of "unused".
}

}  // namespace internal

#if PROTOBUF_USE_EXCEPTIONS
class FatalException : public std::exception {
 public:
  FatalException(const char* filename, int line, const std::string& message)
      : filename_(filename), line_(line), message_(message) {}
  virtual ~FatalException() throw();

  const char* what() const throw() override;

  const char* filename() const { return filename_; }
  int line() const { return line_; }
  const std::string& message() const { return message_; }

 private:
  const char* filename_;
  const int line_;
  const std::string message_;
};
#endif

// This is at the end of the file instead of the beginning to work around a bug
// in some versions of MSVC.
using std::string;

}  // namespace protobuf
}  // namespace google

#include <google/protobuf/port_undef.inc>

#endif  // GOOGLE_PROTOBUF_COMMON_H__


text:
import m from 'mithril';

/**
 * produces a bootstrap 'form-group row' with a 'label' and a input[type=?] or a textarea
 * @param initialNode
 * @returns {{view: (function(*))}}
 * @constructor
 */
function FormInputRadioCheckBox(initialNode) {

    let enabled = true;

    return {
        view: function (vnode) {
            if (!vnode.attrs.inputs || !Array.isArray(vnode.attrs.inputs) || vnode.attrs.inputs.length === 0) {
                throw Error("FormInputRadio component must have an 'inputs' attribute which must be an array with at least one entry!");
            }
            if (vnode.attrs.type !== undefined && vnode.attrs.type !== 'radio' && vnode.attrs.type !== 'checkbox') {
                throw Error("FormInputRadio component only supports 'radio' and 'checkbox' types. The default is 'radio'.");
            }
            enabled = vnode.attrs.enabled !== undefined ? vnode.attrs.enabled : true;
            return m("fieldset.form-group", {
                "data-tooltip": vnode.attrs["data-tooltip"] ? vnode.attrs["data-tooltip"] : "",
                "data-tooltip-y": vnode.attrs["data-tooltip-y"] ? vnode.attrs["data-tooltip-y"] : ""
            }, [
                m("div.row", [
                    // backwards compaitibility must ensure no legend attr means it displays ...
                    !vnode.attrs.hideLegend || (!!vnode.attrs.hideLegend && vnode.attrs.hideLegend == false) ?
                        m("legend", {
                            class: "col-sm-3 col-form-label pt-0"
                        }, vnode.attrs.label ? vnode.attrs.label : "") :
                        [],
                    m("div", {class: "col-sm-9"}, [
                        vnode.attrs.inputs.map(function (item) {
                            return m("div.form-check", [
                                m("input.form-check-input", {
                                    type: vnode.attrs.type === undefined ? 'radio' : vnode.attrs.type,
                                    id: item.id,
                                    required: !!item.required,
                                    disabled: !enabled,
                                    onchange: function(e) {
                                        if (enabled) {
                                            item.onchange(this);
                                        } else {
                                            e.redraw = false;
                                        }
                                    },
                                    value: item.value,
                                    checked: item.checked

                                }),
                                m("label.form-check-label", {for: item.id}, item.label)
                            ])
                        }),
                        (vnode.attrs.required ?
                            m("div", {class: "invalid-feedback"}, vnode.attrs.invalidFeedback ? vnode.attrs.invalidFeedback : "Please provide a value")
                            : "")
                    ])
                ])
            ])
        }
    }
}

export default FormInputRadioCheckBox;


text:
module Hive
    ( module Hive.Board
    , module Hive.Coord
    , Board
    , Unit(..)
    , Player(..)
    , Move(..)
    , isValidMove
    , Point
    )
where

import Prelude hiding (lookup)
import Data.List.Split (chunksOf)
import Data.Ix (range)
import Data.Maybe (catMaybes)

import Hive.Board
import Hive.Coord

data Unit = Beetle (Maybe Unit) | Ant | Spider | Grasshopper | Queen deriving (Eq, Show)

data Player = PlayerWhite | PlayerBlack deriving (Eq, Show)

type Point = AxialCoord
type Field = (Player, Unit)
data Move = MoveFromTo Point Point | MoveInsert Point Field

type Board = HexBoard Field

isValidMove :: Move -> Board -> Bool
isValidMove (MoveInsert p (owner, unit)) board = isNextToFriendButNotEnemy ||
                                                 isFirstMoveInGame ||
                                                 isValidSecondMoveInGame
    where
        isNextToFriendButNotEnemy = numberOfFriendFields >= 1 && numberOfEnemyFields == 0
        isFirstMoveInGame = numberOfFieldsOnBoard == 0
        isValidSecondMoveInGame = numberOfFieldsOnBoard == 1 && numberOfFriendFields == 0 && isNextToEnemy
        isNextToEnemy = numberOfEnemyFields >= 1
        numberOfFriendFields = numberOfFields owner
        numberOfEnemyFields = numberOfFields $ playerCounterpart owner
        numberOfFields player = length . filter ((== player) . fst) $ neighbours p board
        numberOfFieldsOnBoard = size board

isValidMove (MoveFromTo _ _) board = undefined

playerCounterpart :: Player -> Player
playerCounterpart PlayerBlack = PlayerWhite
playerCounterpart PlayerWhite = PlayerBlack

toString :: Board -> String
toString board = unlines . chunksOf 10 . map fieldToChar $ range (AxialCoord (0, 0), AxialCoord (9, 9))
    where
        fieldToChar :: Point -> Char
        fieldToChar point = case lookup point board of
            Just (_, unit) -> unitToChar unit
            Nothing -> '.'

unitToChar :: Unit -> Char
unitToChar (Beetle _) = 'B'
unitToChar Ant = 'A'
unitToChar Spider = 'S'
unitToChar Grasshopper = 'G'
unitToChar Queen = 'Q'


text:
set(PACKAGE_VERSION_EXACT False)
set(PACKAGE_VERSION_COMPATIBLE False)
if("${PACKAGE_FIND_VERSION}" STREQUAL "")
  set(PACKAGE_VERSION_COMPATIBLE TRUE)
  return()
endif()

if("${PACKAGE_FIND_VERSION}" VERSION_EQUAL "")
  set(PACKAGE_VERSION_EXACT True)
  set(PACKAGE_VERSION_COMPATIBLE True)
endif()

if("${PACKAGE_FIND_VERSION}" VERSION_LESS "")
  set(PACKAGE_VERSION_COMPATIBLE True)
endif()


text:
<?php
/**
 * File : UEditorAction.php
 * Author : David
 * Date : 2017/03/18
 * Remark : Null
 */
namespace diwait\ueditor;

use Yii;
use yii\base\Action;
use yii\helpers\ArrayHelper;
use yii\helpers\BaseHtml;
use yii\web\Response;
use yii\web\UploadedFile;

class UEditorAction extends Action
{
    public $config = [];
    private $filepath;
    private $stateInfo; //上传状态信息,
    private $stateMap = [ //上传状态映射表,国际化用户需考虑此处数据的国际化
        "SUCCESS", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上传",
        "没有文件被上传",
        "上传文件为空",
        "ERROR_TMP_FILE"           => "临时文件错误",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
        "ERROR_SIZE_EXCEED"        => "文件大小超出网站限制",
        "ERROR_TYPE_NOT_ALLOWED"   => "文件类型不允许",
        "ERROR_CREATE_DIR"         => "目录创建失败",
        "ERROR_DIR_NOT_WRITEABLE"  => "目录没有写权限",
        "ERROR_FILE_MOVE"          => "文件保存时出错",
        "ERROR_FILE_NOT_FOUND"     => "找不到上传文件",
        "ERROR_WRITE_CONTENT"      => "写入文件内容错误",
        "ERROR_UNKNOWN"            => "未知错误",
        "ERROR_DEAD_LINK"          => "链接不可用",
        "ERROR_HTTP_LINK"          => "链接不是http链接",
        "ERROR_HTTP_CONTENTTYPE"   => "链接contentType不正确"
    ];

    /**
     * 文件保存规则参数如下:
     * imagePathFormat
     * filePathFormat
     * videoPathFormat
     * scrawlPathFormat
     */
    public function init()
    {
        // close csrf
        Yii::$app->request->enableCsrfValidation = false;
        // 默认设置
        $_config = require(__DIR__ . '/config.php');

        // 添加图片默认root路径与访问网址
        $this->config['imageRoot'] = isset($this->config['imageRoot']) ? $this->config['imageRoot'] : Yii::getAlias('@webroot');
        $this->config['imageUrl'] = isset($this->config['imageUrl']) ? $this->config['imageUrl'] : $this->nowUrl();
        $this->config['scrawlRoot'] = isset($this->config['scrawlRoot']) ? $this->config['scrawlRoot'] : Yii::getAlias('@webroot');
        $this->config['scrawlUrl'] = isset($this->config['scrawlUrl']) ? $this->config['scrawlUrl'] : $this->nowUrl();
        $this->config['videoRoot'] = isset($this->config['videoRoot']) ? $this->config['videoRoot'] : Yii::getAlias('@webroot');
        $this->config['videoUrl'] = isset($this->config['videoUrl']) ? $this->config['videoUrl'] : $this->nowUrl();
        $this->config['fileRoot'] = isset($this->config['fileRoot']) ? $this->config['fileRoot'] : Yii::getAlias('@webroot');
        $this->config['fileUrl'] = isset($this->config['fileUrl']) ? $this->config['fileUrl'] : $this->nowUrl();

        $this->config = ArrayHelper::merge($_config, $this->config);
        parent::init();
    }

    public function run()
    {
        if (Yii::$app->request->get('callback', false)) {
            Yii::$app->response->format = Response::FORMAT_JSONP;
        } else {
            Yii::$app->response->format = Response::FORMAT_JSON;
        }

        $result = '';
        switch (Yii::$app->request->get('action')) {
            // 获取后端配置
            case 'config' :
                $result = $this->config;
                break;
            // 上传图片
            case 'uploadimage':
            // 上传涂鸦
            case 'uploadscrawl':
            // 上传视频
            case 'uploadvideo':
            // 上传文件
            case 'uploadfile':
                $result = $this->actionUpload();
                break;
            // 获取文件列表
            case 'listfile' :
                $allowFiles =  $this->config['fileManagerAllowFiles'];
                $listSize =  $this->config['fileManagerListSize'];
                $path =  $this->config['fileManagerListPath'];
                $result = $this->getLists($allowFiles, $listSize, $path, $this->config['fileRoot'], $this->config['fileUrl']);
                break;
            // 获取图片列表
            case 'listimage' :
                $allowFiles =  $this->config['imageManagerAllowFiles'];
                $listSize =  $this->config['imageManagerListSize'];
                $path =  $this->config['imageManagerListPath'];
                $result = $this->getLists($allowFiles, $listSize, $path, $this->config['imageRoot'], $this->config['imageUrl']);
                break;
        }
        return $result;
    }

    /**
     * 上传处理
     * @return bool|string
     */
    protected function actionUpload()
    {
        $status = false;
        switch (Yii::$app->request->get('action')) {
            case 'uploadimage' :
                $status = $this->uploadImage();
                break;
            case 'uploadscrawl' :
                $status = $this->uploadScrawl();
                break;
            case 'uploadfile' :
                $status = $this->uploadFile();
                break;
            case 'uploadvideo' :
                $status = $this->uploadVideo();
                break;
        }
        return $status ? $this->getFileInfo() : $status;
    }

    /**
     * 上传图片
     * @return string
     */
    protected function uploadImage()
    {
        $model = new \diwait\ueditor\UploadImageModel();
        $model->webRoot = $this->config['imageRoot'];
        $model->path = $this->config['imagePathFormat'];
        // 上传文件字段名称
        $FullfieldName = $this->config['imageFieldName'];
        $fieldName = str_replace([BaseHtml::getAttributeName($FullfieldName), '[', ']'], [''], $FullfieldName);
        $model->rulesVal = [
            [$fieldName, 'file', 'skipOnEmpty' => false, 'extensions' => $this->dealExtensions($this->config['imageAllowFiles']), 'uploadRequired' => '请上传文件', 'wrongExtension' => '请上传格式为' . $this->dealExtensions($this->config['imageAllowFiles']) . '的图片']
        ];

        if (Yii::$app->request->isPost) {
            $model->$fieldName = UploadedFile::getInstance($model, $fieldName);
            if ($result = $model->upload()) {
                if ($result !== null) {
                    $this->stateInfo = $this->stateMap[0];
                    $this->filepath = $this->config['imageUrl'] . $result;
                    return true;
                }
                return false;
            } else {
                $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
                return false;
            }
        } else {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return false;
        }
    }

    /**
     * 上传涂鸦
     * @return bool
     */
    protected function uploadScrawl()
    {
        if ($base64Data = Yii::$app->request->post('imgFile')) {
            $model = new UploadScrawlModel();
            $model->webRoot = $this->config['scrawlRoot'];
            $model->path = $this->config['scrawlPathFormat'];
            $result = $model->upload($base64Data);

            if ($result !== null && file_exists($this->config['scrawlRoot'] . $result)) {
                $this->stateInfo = $this->stateMap[0];
                $this->filepath = $this->config['scrawlUrl'] . $result;
                return true;
            } else {
                $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
                return false;
            }
        } else {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
            return false;
        }
    }

    /**
     * 上传附件
     * @return string
     */
    protected function uploadFile()
    {
        $model = new \diwait\ueditor\UploadFileModel();
        $model->webRoot = $this->config['fileRoot'];
        $model->path = $this->config['filePathFormat'];

        // 上传文件字段名称
        $FullfieldName = $this->config['fileFieldName'];
        $fieldName = str_replace([BaseHtml::getAttributeName($FullfieldName), '[', ']'], [''], $FullfieldName);
        $model->rulesVal = [
            [$fieldName, 'file', 'skipOnEmpty' => false, 'extensions' => $this->dealExtensions($this->config['fileAllowFiles']), 'uploadRequired' => '请上传文件', 'wrongExtension' => '请上传格式为' . $this->dealExtensions($this->config['fileAllowFiles']) . '的文件', 'checkExtensionByMimeType' => false]
        ];

        if (Yii::$app->request->isPost) {
            $model->$fieldName = UploadedFile::getInstance($model, $fieldName);
            if ($result = $model->upload()) {
                if ($result !== null) {
                    $this->stateInfo = $this->stateMap[0];
                    $this->filepath = $this->config['fileUrl'] . $result;
                    return true;
                }
                return false;
            } else {
                $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
                return false;
            }
        } else {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return false;
        }
    }

    /**
     * 上传视频
     * @return string
     */
    protected function uploadVideo()
    {
        $model = new \diwait\ueditor\UploadVideoModel();
        $model->webRoot = $this->config['videoRoot'];
        $model->path = $this->config['videoPathFormat'];

        // 上传文件字段名称
        $FullfieldName = $this->config['videoFieldName'];
        $fieldName = str_replace([BaseHtml::getAttributeName($FullfieldName), '[', ']'], [''], $FullfieldName);
        $model->rulesVal = [
            [$fieldName, 'file', 'skipOnEmpty' => false, 'extensions' => $this->dealExtensions($this->config['videoAllowFiles']), 'uploadRequired' => '请上传文件', 'wrongExtension' => '请上传格式为' . $this->dealExtensions($this->config['videoAllowFiles']) . '的视频', 'checkExtensionByMimeType' => false]
        ];

        if (Yii::$app->request->isPost) {
            $model->$fieldName = UploadedFile::getInstance($model, $fieldName);
            if ($result = $model->upload()) {
                if ($result !== null) {
                    $this->stateInfo = $this->stateMap[0];
                    $this->filepath = $this->config['videoUrl'] . $result;
                    return true;
                }
                return false;
            } else {
                $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
                return false;
            }
        } else {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return false;
        }
    }

    /**
     * 获取文件列表
     * @param $allowFiles
     * @param $listSize
     * @param $path
     * @param $webRoot
     * @return string
     */
    protected function getLists($allowFiles, $listSize, $path, $webRoot, $webUrl)
    {
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        // 获取参数
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        // 获取文件列表
        $path = $webRoot . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = $this->getfiles($path, $webRoot, $webUrl, $allowFiles);
        if (! count($files)) {
            return [
                "state" => "no match file",
                "list" => [],
                "start" => $start,
                "total" => count($files)
            ];
        }

        // 获取指定范围的列表
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }

        // 返回数据
        return [
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ];
    }

    /**
     * 处理扩展名前的点符号
     * @param $extensions
     * @return mixed
     */
    protected function dealExtensions($extensions)
    {
        return str_replace('.', '', implode(',', $extensions));
    }

    /**
     * 上传错误检查
     * @param $errCode
     * @return string
     */
    protected function getStateInfo($errCode)
    {
        return ! $this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
    }

    /**
     * 获取当前域名
     * @return mixed
     */
    protected function nowUrl()
    {
        return $this->isHttps() ? 'https://' . $_SERVER['SERVER_NAME'] : 'http://' . $_SERVER['SERVER_NAME'];
    }

    /**
     * 判断是否Https
     * @return bool
     */
    protected function isHttps()
    {
        if (! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            return true;
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            return true;
        } elseif (! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            return true;
        }

        return false;
    }

    /**
     * 返回文件上传信息
     * @return array
     */
    public function getFileInfo()
    {
        return array(
            "state"    => $this->stateInfo,
            "url"      => $this->filepath
        );
    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    protected function getfiles($path, $webRoot, $webUrl, $allowFiles, &$files = [])
    {
        if (! is_dir($path)) { return null; };
        if (substr($path, strlen($path) - 1) != '/') { $path .= '/'; }
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    self::getfiles($path2, $webRoot, $webUrl, $allowFiles, $files);
                } else {
                    if (preg_match("/\\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = [
                            'url'=> $webUrl . substr($path2, strlen($webRoot)),
                            'mtime'=> filemtime($path2)
                        ];
                    }
                }
            }
        }
        return $files;
    }
}


text:
<?php

	// this document formats a tumblr 'link' post

	// prin the url and title
	if(isset($post->title)) {
		echo '
 url.'">'.$post->title.'
';
	}

	// print the description text
	if(isset($post->description)) {
		echo $post->description;
	}
?>


text:
/**

\class ODTask
\brief ODTask is an abstract class that outlines the methods that will be used to
support On-Demand background loading of files.  These ODTasks are generally meant to be run
in a background thread.

*//*******************************************************************/

#include "ODTask.h"
#include "ODManager.h"
#include "../WaveTrack.h"
#include "../Project.h"
//temporarilly commented out till it is added to all projects
//#include "../Profiler.h"

DEFINE_EVENT_TYPE(EVT_ODTASK_COMPLETE)

/// Constructs an ODTask
ODTask::ODTask()
{

   static int sTaskNumber=0;
   mPercentComplete=0;
   mDoingTask=false;
   mTerminate = false;
   mNeedsODUpdate=false;
   mIsRunning = false;

   mTaskNumber=sTaskNumber++;

   mDemandSample=0;
}

//outside code must ensure this task is not scheduled again.
void ODTask::TerminateAndBlock()
{
   //one mutex pair for the value of mTerminate
   mTerminateMutex.Lock();
   mTerminate=true;
   //release all data the derived class may have allocated
   mTerminateMutex.Unlock();

   //and one mutex pair for the exit of the function
   mBlockUntilTerminateMutex.Lock();
//TODO lock mTerminate?
   mBlockUntilTerminateMutex.Unlock();

   //wait till we are out of doSome() to terminate.
   Terminate();
}

///Do a modular part of the task.  For example, if the task is to load the entire file, load one BlockFile.
///Relies on DoSomeInternal(), which is the subclasses must implement.
///@param amountWork the percent amount of the total job to do.  1.0 represents the entire job.  the default of 0.0
/// will do the smallest unit of work possible
void ODTask::DoSome(float amountWork)
{
   SetIsRunning(true);
   mBlockUntilTerminateMutex.Lock();

//   printf("%s %i subtask starting on new thread with priority\n", GetTaskName(),GetTaskNumber());

   mDoingTask=mTaskStarted=true;

   float workUntil = amountWork+PercentComplete();

   //check periodically to see if we should exit.
   mTerminateMutex.Lock();
   if(mTerminate)
   {
      mTerminateMutex.Unlock();
      SetIsRunning(false);
      mBlockUntilTerminateMutex.Unlock();
      return;
   }
   mTerminateMutex.Unlock();

   Update();

   if(UsesCustomWorkUntilPercentage())
      workUntil = ComputeNextWorkUntilPercentageComplete();

   if(workUntil<PercentComplete())
      workUntil = PercentComplete();

   //Do Some of the task.

   mTerminateMutex.Lock();
   while(PercentComplete() < workUntil && PercentComplete() < 1.0 && !mTerminate)
   {
      wxThread::This()->Yield();
      //release within the loop so we can cut the number of iterations short

      DoSomeInternal(); //keep the terminate mutex on so we don't remo
      mTerminateMutex.Unlock();
      //check to see if ondemand has been called
      if(GetNeedsODUpdate() && PercentComplete() < 1.0)
         ODUpdate();

      //But add the mutex lock back before we check the value again.
      mTerminateMutex.Lock();
   }
   mTerminateMutex.Unlock();
   mDoingTask=false;

   mTerminateMutex.Lock();
   //if it is not done, put it back onto the ODManager queue.
   if(PercentComplete() < 1.0&& !mTerminate)
   {
      ODManager::Instance()->AddTask(this);

      //we did a bit of progress - we should allow a resave.
      AudacityProject::AllProjectsDeleteLock();
      for(unsigned i=0; i<gAudacityProjects.GetCount(); i++)
      {
         if(IsTaskAssociatedWithProject(gAudacityProjects[i]))
         {
            //mark the changes so that the project can be resaved.
            gAudacityProjects[i]->GetUndoManager()->SetODChangesFlag();
            break;
         }
      }
      AudacityProject::AllProjectsDeleteUnlock();

//      printf("%s %i is %f done\n", GetTaskName(),GetTaskNumber(),PercentComplete());
   }
   else
   {
      //for profiling, uncomment and look in audacity.app/exe's folder for AudacityProfile.txt
      //static int tempLog =0;
      //if(++tempLog % 5==0)
         //END_TASK_PROFILING("On Demand Drag and Drop 5 80 mb files into audacity, 5 wavs per task");
      //END_TASK_PROFILING("On Demand open an 80 mb wav stereo file");

      wxCommandEvent event( EVT_ODTASK_COMPLETE );
      AudacityProject::AllProjectsDeleteLock();

      for(unsigned i=0; i<gAudacityProjects.GetCount(); i++)
      {
         if(IsTaskAssociatedWithProject(gAudacityProjects[i]))
         {
            //this assumes tasks are only associated with one project.
            gAudacityProjects[i]->AddPendingEvent( event );
            //mark the changes so that the project can be resaved.
            gAudacityProjects[i]->GetUndoManager()->SetODChangesFlag();
            break;
         }
      }
      AudacityProject::AllProjectsDeleteUnlock();

//      printf("%s %i complete\n", GetTaskName(),GetTaskNumber());
   }
   mTerminateMutex.Unlock();
   SetIsRunning(false);
   mBlockUntilTerminateMutex.Unlock();
}

bool ODTask::IsTaskAssociatedWithProject(AudacityProject* proj)
{
   TrackList *tracks = proj->GetTracks();
   TrackListIterator iter1(tracks);
   Track *tr = iter1.First();

   while (tr)
   {
      //go over all tracks in the project
      if (tr->GetKind() == Track::Wave)
      {
         //look inside our task's track list for one that matches this projects one.
         mWaveTrackMutex.Lock();
         for(int i=0;i<(int)mWaveTracks.size();i++)
         {
            if(mWaveTracks[i]==tr)
            {
               //if we find one, then the project is associated with us;return true
               mWaveTrackMutex.Unlock();
               return true;
            }
         }
         mWaveTrackMutex.Unlock();
      }
      tr = iter1.Next();
   }

   return false;

}

void ODTask::ODUpdate()
{
   Update();
   ResetNeedsODUpdate();
}

void ODTask::SetIsRunning(bool value)
{
   mIsRunningMutex.Lock();
   mIsRunning=value;
   mIsRunningMutex.Unlock();
}

bool ODTask::IsRunning()
{
   bool ret;
   mIsRunningMutex.Lock();
   ret= mIsRunning;
   mIsRunningMutex.Unlock();
   return ret;
}

sampleCount ODTask::GetDemandSample()
{
   sampleCount retval;
   mDemandSampleMutex.Lock();
   retval = mDemandSample;
   mDemandSampleMutex.Unlock();
   return retval;
}

void ODTask::SetDemandSample(sampleCount sample)
{

   mDemandSampleMutex.Lock();
   mDemandSample=sample;
   mDemandSampleMutex.Unlock();
}

///return the amount of the task that has been completed.  0.0 to 1.0
float ODTask::PercentComplete()
{
   mPercentCompleteMutex.Lock();
   float ret = mPercentComplete;
   mPercentCompleteMutex.Unlock();
   return ret;
}

///return
bool ODTask::IsComplete()
{
   return PercentComplete() >= 1.0 && !IsRunning();
}

WaveTrack* ODTask::GetWaveTrack(int i)
{
   WaveTrack* track = NULL;
   mWaveTrackMutex.Lock();
   if(i<(int)mWaveTracks.size())
      track = mWaveTracks[i];
   mWaveTrackMutex.Unlock();
   return track;
}

///Sets the wavetrack that will be analyzed for ODPCMAliasBlockFiles that will
///have their summaries computed and written to disk.
void ODTask::AddWaveTrack(WaveTrack* track)
{
   mWaveTracks.push_back(track);
}

int ODTask::GetNumWaveTracks()
{
   int num;
   mWaveTrackMutex.Lock();
   num = (int)mWaveTracks.size();
   mWaveTrackMutex.Unlock();
   return num;
}

void ODTask::SetNeedsODUpdate()
{
   mNeedsODUpdateMutex.Lock();
   mNeedsODUpdate=true;
   mNeedsODUpdateMutex.Unlock();
}
bool ODTask::GetNeedsODUpdate()
{
   bool ret;
   mNeedsODUpdateMutex.Lock();
   ret=mNeedsODUpdate;
   mNeedsODUpdateMutex.Unlock();
   return ret;
}

void ODTask::ResetNeedsODUpdate()
{
   mNeedsODUpdateMutex.Lock();
   mNeedsODUpdate=false;
   mNeedsODUpdateMutex.Unlock();
}

///does an od update and then recalculates the data.
void ODTask::RecalculatePercentComplete()
{
   if(GetNeedsODUpdate())
   {
      ODUpdate();
      CalculatePercentComplete();
   }
}

///changes the tasks associated with this Waveform to process the task from a different point in the track
///@param track the track to update
///@param seconds the point in the track from which the tasks associated with track should begin processing from.
void ODTask::DemandTrackUpdate(WaveTrack* track, double seconds)
{
   bool demandSampleChanged=false;
   mWaveTrackMutex.Lock();
   for(size_t i=0;i<mWaveTracks.size();i++)
   {
      if(track == mWaveTracks[i])
      {
         sampleCount newDemandSample = (sampleCount)(seconds * track->GetRate());
         demandSampleChanged = newDemandSample != GetDemandSample();
         SetDemandSample(newDemandSample);
         break;
      }
   }
   mWaveTrackMutex.Unlock();

   if(demandSampleChanged)
      SetNeedsODUpdate();

}

void ODTask::StopUsingWaveTrack(WaveTrack* track)
{
   mWaveTrackMutex.Lock();
   for(size_t i=0;i<mWaveTracks.size();i++)
   {
      if(mWaveTracks[i] == track)
         mWaveTracks[i]=NULL;
   }
   mWaveTrackMutex.Unlock();
}

///Replaces all instances to a wavetrack with a new one, effectively transferring the task.
void ODTask::ReplaceWaveTrack(WaveTrack* oldTrack,WaveTrack* newTrack)
{
   mWaveTrackMutex.Lock();
   for(size_t i=0;i<mWaveTracks.size();i++)
   {
      if(oldTrack == mWaveTracks[i])
      {
         mWaveTracks[i] = newTrack;
      }
   }
   mWaveTrackMutex.Unlock();
}


text:
import React from 'react'
import PropTypes from 'prop-types'

import { compose, bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import { Row, Col, Icon, Alert, Form, Input, Button, message } from 'antd'
const { TextArea } = Input
const FormItem = Form.Item
const connectForm = Form.create()

import { layout, feedback, rules, disableSubmit } from '../../../../util/form'
import api from '../../../../services'

@compose(
  connect(
    state => ({
      id: state.db.proposal.body && state.db.proposal.body._id,
      proposal: state.db.proposal._id,
      body: state.db.proposal.body
      //  Direct accessing subdoc props that may not exist === crash
    }),
    dispatch => ({ api: bindActionCreators(api, dispatch) })
  ),
  connectForm
)
class ProjectPlan extends React.Component {
  static propTypes = {
    id: PropTypes.string,
    form: PropTypes.object,
    api: PropTypes.object,
    proposal: PropTypes.string,
    body: PropTypes.object
  }
  impactFields = [
    {
      field: 'overview.impact.academic',
      title: 'Academic Experience',
      subtitle: 'How will this project enrich a student's learning environment and experience?'
    }, {
      field: 'overview.impact.research',
      title: 'Research Involvement',
      subtitle: 'Can this project be used for scholarly research?'
    }, {
      field: 'overview.impact.career',
      title: 'Career Development',
      subtitle: 'Can this technology be used to further a student's career?'
    }
  ]
  projectFields = [
    {
      title: 'State Analysis',
      subtitle: 'Tell us about...',
      current: {
        field: 'plan.state.current',
        title: 'Current State',
        subtitle: 'Describe the resources currently available, and how students utilize these resources.'
      },
      future: {
        field: 'plan.state.future',
        title: 'Future State',
        subtitle: 'Describe the new resources being made available to students, including any advantages over current technology.'
      }
    },
    {
      title: 'Service Availability',
      subtitle: 'What sort of technology is currently available, and how will this change?',
      current: {
        field: 'plan.availability.current',
        title: 'Current Availability',
        subtitle: 'How many students use these resources per quarter? Include any restrictions that are involved, including hours of operations, mandatory training, and associations with organizations'
      },
      future: {
        field: 'plan.availability.future',
        title: 'Future Availability',
        subtitle: 'How will students be able to use the proposed resources? Include any restrictions that are involved, including hours of operations, mandatory training, and associations with organizations.'
      }
    },
    {
      title: 'Student Outreach',
      subtitle: 'Student technology is great, but we also need to connect with the community. How are you working to make sure students are aware of these resources?',
      current: {
        field: 'plan.outreach.current',
        title: 'Prior Efforts',
        subtitle: 'Describe efforts to receive departmental funding and community endorsements for this project and similar initiatives.'
      },
      future: {
        field: 'plan.outreach.future',
        title: 'Outreach Strategy',
        subtitle: 'If approved, how will you reach out to the student community and inform them about this resource.'
      }
    },
    {
      title: 'Implementation Strategy',
      subtitle: 'What sort of support have you gathered?',
      current: {
        field: 'plan.strategy.current',
        title: 'Organizational Backing',
        subtitle: 'What sort of resources will your organization make available to ensure the success of this project?'
      },
      future: {
        field: 'plan.strategy.future',
        title: 'Implementation Strategy',
        subtitle: 'Briefly describe the implementation process, and include a timeline if possible.'
      }
    },
    {
      title: 'Risk Assessment',
      subtitle: 'How are we accounting for scenarios such as abuse, theft, or negigent use of technology?',
      current: {
        field: 'plan.risk.current',
        title: 'Current Risks',
        subtitle: 'Are there any current concerns regarding privacy or security? Have you scoped out insurance for the proposed technology?'
      },
      future: {
        field: 'plan.risk.future',
        title: 'Proposed Mitigations',
        subtitle: 'If approved, how will you secure the systems and technology for this project.'
      }
    }
  ]
  componentDidMount () {
    const { form, body } = this.props
    if (body) {
      const { overview, plan } = body
      form.setFieldsValue({ overview, plan })
    } else {
      console.log('placeholder')
      // form.validateFields()
    }
  }
  handleSubmit = (e) => {
    e.preventDefault()
    let { form, api, id, proposal } = this.props
    const values = form.getFieldsValue()
    const project = { proposal, ...values }
    const params = {
      id,
      transform: proposal => ({ proposal }),
      update: ({ proposal: (prev, next) => {
        let change = Object.assign({}, prev)
        change.body = next
        return change
      }})
    }
    params.id
    ? api.patch('project', project, params)
    .then(message.success('Proposal Body updated!', 10))
    .catch(err => {
      message.warning('Proposal Body failed to update - Unexpected client error', 10)
      console.warn(err)
    })
    : api.post('project', project, params)
    .then(message.success('Saved your new plan!', 10))
    .catch(err => {
      message.warning('Proposal Body failed to update - Unexpected client error', 10)
      console.warn(err)
    })
  }

  render (
    { impactFields, projectFields } = this,
    { form, body } = this.props
  ) {
    return (

        <Form onSubmit={this.handleSubmit}>
          <Alert type='info' banner
            message='Project Plan Format'
            description='We are using a traditional project plan format for our proposals going forward. The committee has decided on this because it covers the questions traditionally addressed in Q&A, and ensures that proposals are comprehensive, covering the full lifecycle of the project. We understand that a lot of these questions may not apply directly to all cases, so for those fields, feel free to write "N/A".'
          />

Overview

          <FormItem label='Abstract' {...layout} hasFeedback={feedback(form, 'overview.abstract')}>
            {form.getFieldDecorator('overview.abstract', rules.required)(
              <TextArea rows={6} />
            )}
          </FormItem>
          <FormItem label='Objectives' {...layout} hasFeedback={feedback(form, 'overview.objectives')}>
            {form.getFieldDecorator('overview.objectives', rules.required)(
              <TextArea rows={4} />
            )}
          </FormItem>
          <FormItem label='Core Justification' {...layout} hasFeedback={feedback(form, 'overview.justification')}>
            {form.getFieldDecorator('overview.justification', rules.required)(
              <TextArea rows={4} />
            )}
          </FormItem>

Impact

          <Row gutter={32}>
            {impactFields.map((impact, i) => (
              <Col key={i} className='gutter-row' xs={24} md={8}>

{impact.title}

{impact.subtitle}

                <FormItem hasFeedback={feedback(form, impact.field)}>
                  {form.getFieldDecorator(impact.field, rules.required)(
                    <TextArea rows={3} />
                  )}
                </FormItem>
              </Col>
            ))}
          </Row>

Project Plan

          {projectFields.map((area, i) => (

{area.title}

{area.subtitle}

              <Row gutter={32}>
                <Col className='gutter-row' xs={24} md={12} >

{area.current.title}

                  {area.current.subtitle}
                  <FormItem hasFeedback={feedback(form, area.current.field)}>
                    {form.getFieldDecorator(area.current.field, rules.required)(
                      <TextArea rows={4} />
                    )}
                  </FormItem>
                </Col>
                <Col className='gutter-row' xs={24} md={12} >

{area.future.title}

                  {area.future.subtitle}
                  <FormItem hasFeedback={feedback(form, area.future.field)}>
                    {form.getFieldDecorator(area.future.field, rules.required)(
                      <TextArea rows={4} />
                    )}
                  </FormItem>
                </Col>
              </Row>

          ))}
          <FormItem>
            <Button size='large' type='primary'
              onMouseEnter={() => form.validateFields()}
              htmlType='submit' disabled={disableSubmit(form)}
              style={{ width: '100%' }}
              ><Icon type='cloud-upload-o' />Update</Button>
          </FormItem>
        </Form>

    )
  }
}

export default ProjectPlan


text:
/*
 __COMMENT_HEADING__
 */

#import "__CLASS_PREFIX__ApplicationFactory.h"

@implementation __CLASS_PREFIX__ApplicationFactory

@end


text:
<?php

namespace PhRest\Auth;

use \JWT,

    \Phalcon\Security,
    \PhRest\Config\Local;

/**
 * Class Session
 * @package PhRest\Auth
 */
class Session {

    /**
     * @var string
     */
    private $algorithm;

    /**
     * @var string
     */
    private $salt;

    /**
     * @return string
     */
    public function getAlgorithm() {
        return $this->algorithm;
    }

    /**
     * @param string $algorithm
     * @return $this
     */
    public function setAlgorithm($algorithm) {
        $this->algorithm = $algorithm;
        return $this;
    }

    /**
     * @return string
     */
    public function getSalt() {
        return $this->salt;
    }

    /**
     * @param string $salt
     * @return $this
     */
    public function setSalt($salt) {
        $this->salt = $salt;
        return $this;
    }

    /**
     * @param string $algorithm
     * @param string $salt
     */
    public function __construct($algorithm = 'HS256', $salt = null) {
        if (is_null($salt)) {
            $salt = Local::get()->getSecurity()->getSalt();
        }

        $this
            ->setAlgorithm($algorithm)
            ->setSalt($salt);
    }

    /**
     * @param array $token
     * @return string
     */
    public function encode(array $token) {
        return JWT::encode($token, $this->getSalt());
    }

    /**
     * @param string $token
     * @return array
     */
    public function decode($token) {
        return JWT::decode($token, $this->getSalt(), [$this->getAlgorithm()]);
    }

    /**
     * @param array $user
     * @param integer $expiration
     * @return array
     */
    public static function create($user, $expiration) {
        $iat = time();

        return [
            'sub' => $user,
            'iat' => $iat,
            'exp' => $iat + $expiration
        ];
    }

}


text:
<!DOCTYPE hmtl>
<!--
This page toggles focus on an input field on click events and is used to test
that focus gain spawns the keyboard and focus loss hides it.
-->
<html>
  <head>
    <style>
      html, body {
        height: 100%;
        margin: 0;
      }
      #divtoclick {
        min-height: 100%;
      }
    </style>
  </head>
  <script>
    var focused = false;
    function toggleFocusOnClick() {
      if (focused) {
        document.getElementById("input").blur();
      } else {
        document.getElementById("input").focus();
      }
      focused = !focused;
    }
  </script>
  <body>
    <div id="divtoclick" onclick="toggleFocusOnClick()">
      <input id="input"></input>
    </div>
  </body>
</html>


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

import io.airlift.slice.Slice;
import io.trino.spi.TrinoException;
import io.trino.spi.function.Description;
import io.trino.spi.function.LiteralParameters;
import io.trino.spi.function.ScalarFunction;
import io.trino.spi.function.SqlType;

import java.math.BigDecimal;
import java.math.BigInteger;

import static io.trino.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static io.trino.spi.StandardErrorCode.NUMERIC_VALUE_OUT_OF_RANGE;
import static io.trino.spi.type.Decimals.encodeUnscaledValue;
import static java.lang.Character.isDigit;
import static java.lang.String.format;

public final class DataSizeFunctions
{
    private DataSizeFunctions() {}

    @Description("Converts data size string to bytes")
    @ScalarFunction(value = "parse_data_size", alias = "parse_presto_data_size")
    @LiteralParameters("x")
    @SqlType("decimal(38,0)")
    public static Slice parsePrestoDataSize(@SqlType("varchar(x)") Slice input)
    {
        String dataSize = input.toStringUtf8();

        int valueLength = 0;
        for (int i = 0; i < dataSize.length(); i++) {
            char c = dataSize.charAt(i);
            if (isDigit(c) || c == '.') {
                valueLength++;
            }
            else {
                break;
            }
        }

        if (valueLength == 0) {
            throw invalidDataSize(dataSize);
        }

        BigDecimal value = parseValue(dataSize.substring(0, valueLength), dataSize);
        Unit unit = Unit.parse(dataSize.substring(valueLength), dataSize);
        BigInteger bytes = value.multiply(unit.getFactor()).toBigInteger();
        try {
            return encodeUnscaledValue(bytes);
        }
        catch (ArithmeticException e) {
            throw new TrinoException(NUMERIC_VALUE_OUT_OF_RANGE, format("Value out of range: '%s' ('%sB')", dataSize, bytes));
        }
    }

    private static BigDecimal parseValue(String value, String dataSize)
    {
        try {
            return new BigDecimal(value);
        }
        catch (NumberFormatException e) {
            throw invalidDataSize(dataSize);
        }
    }

    private static TrinoException invalidDataSize(String dataSize)
    {
        return new TrinoException(INVALID_FUNCTION_ARGUMENT, format("Invalid data size: '%s'", dataSize));
    }

    private enum Unit
    {
        BYTE(BigDecimal.ONE),
        KILOBYTE(new BigDecimal(1L << 10)),
        MEGABYTE(new BigDecimal(1L << 20)),
        GIGABYTE(new BigDecimal(1L << 30)),
        TERABYTE(new BigDecimal(1L << 40)),
        PETABYTE(new BigDecimal(1L << 50)),
        EXABYTE(new BigDecimal(1L << 60)),
        ZETTABYTE(new BigDecimal(1L << 60).multiply(new BigDecimal(1L << 10))),
        YOTTABYTE(new BigDecimal(1L << 60).multiply(new BigDecimal(1L << 20)));

        private final BigDecimal factor;

        Unit(BigDecimal factor)
        {
            this.factor = factor;
        }

        public BigDecimal getFactor()
        {
            return factor;
        }

        public static Unit parse(String unitString, String dataSize)
        {
            switch (unitString) {
                case "B":
                    return BYTE;
                case "kB":
                    return KILOBYTE;
                case "MB":
                    return MEGABYTE;
                case "GB":
                    return GIGABYTE;
                case "TB":
                    return TERABYTE;
                case "PB":
                    return PETABYTE;
                case "EB":
                    return EXABYTE;
                case "ZB":
                    return ZETTABYTE;
                case "YB":
                    return YOTTABYTE;
                default:
                    throw invalidDataSize(dataSize);
            }
        }
    }
}


text:
package org.elasticsearch.repositories.s3;

import com.amazonaws.AmazonClientException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AbstractAmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.Streams;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentMap;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

class MockAmazonS3 extends AbstractAmazonS3 {

    private final ConcurrentMap<String, byte[]> blobs;
    private final String bucket;
    private final boolean serverSideEncryption;
    private final String cannedACL;
    private final String storageClass;

    MockAmazonS3(final ConcurrentMap<String, byte[]> blobs,
                 final String bucket,
                 final boolean serverSideEncryption,
                 final String cannedACL,
                 final String storageClass) {
        this.blobs = Objects.requireNonNull(blobs);
        this.bucket = Objects.requireNonNull(bucket);
        this.serverSideEncryption = serverSideEncryption;
        this.cannedACL = cannedACL;
        this.storageClass = storageClass;
    }

    @Override
    public boolean doesObjectExist(final String bucketName, final String objectName) throws SdkClientException {
        assertThat(bucketName, equalTo(bucket));
        return blobs.containsKey(objectName);
    }

    @Override
    public PutObjectResult putObject(final PutObjectRequest request) throws AmazonClientException {
        assertThat(request.getBucketName(), equalTo(bucket));
        assertThat(request.getMetadata().getSSEAlgorithm(), serverSideEncryption ? equalTo("AES256") : nullValue());
        assertThat(request.getCannedAcl(), notNullValue());
        assertThat(request.getCannedAcl().toString(), cannedACL != null ? equalTo(cannedACL) : equalTo("private"));
        assertThat(request.getStorageClass(), storageClass != null ? equalTo(storageClass) : equalTo("STANDARD"));

        final String blobName = request.getKey();
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            Streams.copy(request.getInputStream(), out);
            blobs.put(blobName, out.toByteArray());
        } catch (IOException e) {
            throw new AmazonClientException(e);
        }
        return new PutObjectResult();
    }

    @Override
    public S3Object getObject(final GetObjectRequest request) throws AmazonClientException {
        assertThat(request.getBucketName(), equalTo(bucket));

        final String blobName = request.getKey();
        final byte[] content = blobs.get(blobName);
        if (content == null) {
            AmazonS3Exception exception = new AmazonS3Exception("[" + blobName + "] does not exist.");
            exception.setStatusCode(404);
            throw exception;
        }

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(content.length);

        S3Object s3Object = new S3Object();
        s3Object.setObjectContent(new S3ObjectInputStream(new ByteArrayInputStream(content), null, false));
        s3Object.setKey(blobName);
        s3Object.setObjectMetadata(metadata);

        return s3Object;
    }

    @Override
    public ObjectListing listObjects(final ListObjectsRequest request) throws AmazonClientException {
        assertThat(request.getBucketName(), equalTo(bucket));

        final ObjectListing listing = new ObjectListing();
        listing.setBucketName(request.getBucketName());
        listing.setPrefix(request.getPrefix());

        for (Map.Entry<String, byte[]> blob : blobs.entrySet()) {
            if (Strings.isEmpty(request.getPrefix()) || blob.getKey().startsWith(request.getPrefix())) {
                S3ObjectSummary summary = new S3ObjectSummary();
                summary.setBucketName(request.getBucketName());
                summary.setKey(blob.getKey());
                summary.setSize(blob.getValue().length);
                listing.getObjectSummaries().add(summary);
            }
        }
        return listing;
    }

    @Override
    public void deleteObject(final DeleteObjectRequest request) throws AmazonClientException {
        assertThat(request.getBucketName(), equalTo(bucket));
        blobs.remove(request.getKey());
    }

    @Override
    public void shutdown() {
        // TODO check close
    }

    @Override
    public DeleteObjectsResult deleteObjects(DeleteObjectsRequest request) throws SdkClientException {
        assertThat(request.getBucketName(), equalTo(bucket));

        final List<DeleteObjectsResult.DeletedObject> deletions = new ArrayList<>();
        for (DeleteObjectsRequest.KeyVersion key : request.getKeys()) {
            if (blobs.remove(key.getKey()) == null) {
                AmazonS3Exception exception = new AmazonS3Exception("[" + key + "] does not exist.");
                exception.setStatusCode(404);
                throw exception;
            } else {
                DeleteObjectsResult.DeletedObject deletion = new DeleteObjectsResult.DeletedObject();
                deletion.setKey(key.getKey());
                deletions.add(deletion);
            }
        }
        return new DeleteObjectsResult(deletions);
    }
}


text:
package net.authorize.sample.RecurringBilling;

import net.authorize.Environment;
import net.authorize.api.contract.v1.*;
import net.authorize.api.controller.base.ApiOperationBase;
import net.authorize.api.controller.ARBUpdateSubscriptionController;

public class UpdateSubscription {

    public static ANetApiResponse run(String apiLoginId, String transactionKey, String subscriptionId) {
        //Common code to set for all requests
        ApiOperationBase.setEnvironment(Environment.SANDBOX);
        MerchantAuthenticationType merchantAuthenticationType  = new MerchantAuthenticationType() ;
        merchantAuthenticationType.setName(apiLoginId);
        merchantAuthenticationType.setTransactionKey(transactionKey);
        ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);

        // Populate the payment data
        PaymentType paymentType = new PaymentType();
        CreditCardType creditCard = new CreditCardType();
        creditCard.setCardNumber("4111111111111111");
        creditCard.setExpirationDate("1230");
        paymentType.setCreditCard(creditCard);

        //set profile information
		CustomerProfileIdType profile = new CustomerProfileIdType();
		profile.setCustomerProfileId("121212");
		profile.setCustomerPaymentProfileId("131313");
		profile.setCustomerAddressId("141414");

        ARBSubscriptionType arbSubscriptionType = new ARBSubscriptionType();
        arbSubscriptionType.setPayment(paymentType);
        //to update profile
        //arbSubscriptionType.setProfile(profile);

        // Make the API Request
        ARBUpdateSubscriptionRequest apiRequest = new ARBUpdateSubscriptionRequest();
        apiRequest.setSubscriptionId(subscriptionId);
        apiRequest.setSubscription(arbSubscriptionType);
        ARBUpdateSubscriptionController controller = new ARBUpdateSubscriptionController(apiRequest);
        controller.execute();
        ARBUpdateSubscriptionResponse response = controller.getApiResponse();
        if (response!=null) {

             if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {

                System.out.println(response.getMessages().getMessage().get(0).getCode());
                System.out.println(response.getMessages().getMessage().get(0).getText());
            }
            else
            {
                System.out.println("Failed to update Subscription:  " + response.getMessages().getResultCode());
            }
        }
		return response;
    }
}


text:
package com.intellij.util;

import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.List;

/**
 * @author Alexander Koshevoy
 */
public abstract class AbstractPathMapper implements PathMapper {

  @Nullable
  public static String convertToLocal(@NotNull String remotePath, @NotNull Iterable<? extends PathMappingSettings.PathMapping> mappings) {
    PathMappingSettings.BestMappingSelector selector = new PathMappingSettings.BestMappingSelector();
    for (PathMappingSettings.PathMapping mapping : mappings) {
      if (mapping.canReplaceRemote(remotePath)) {
        selector.consider(mapping, mapping.getRemoteLen());
      }
    }
    if (selector.get() != null) {
      //noinspection ConstantConditions
      return selector.get().mapToLocal(remotePath);
    }
    return null;
  }

  @Nullable
  public static String convertToRemote(@NotNull String localPath, @NotNull Collection<? extends PathMappingSettings.PathMapping> pathMappings) {
    PathMappingSettings.BestMappingSelector selector = new PathMappingSettings.BestMappingSelector();
    for (PathMappingSettings.PathMapping mapping : pathMappings) {
      if (mapping != null && mapping.canReplaceLocal(localPath)) {
        selector.consider(mapping, mapping.getLocalLen());
      }
    }

    if (selector.get() != null) {
      //noinspection ConstantConditions
      return selector.get().mapToRemote(localPath);
    }
    return null;
  }

  @NotNull
  @Override
  public final List<String> convertToRemote(@NotNull Collection<String> paths) {
    List<String> result = ContainerUtil.newArrayList();
    for (String p : paths) {
      result.add(convertToRemote(p));
    }
    return result;
  }

  @Override
  public final boolean canReplaceRemote(@NotNull String remotePath) {
    for (PathMappingSettings.PathMapping mapping : getAvailablePathMappings()) {
      if (mapping.canReplaceRemote(remotePath)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public final boolean canReplaceLocal(@NotNull String localPath) {
    for (PathMappingSettings.PathMapping mapping : getAvailablePathMappings()) {
      if (mapping.canReplaceLocal(localPath)) {
        return true;
      }
    }
    return false;
  }

  @NotNull
  protected abstract Collection<PathMappingSettings.PathMapping> getAvailablePathMappings();
}


text:
CKEDITOR.plugins.setLang( 'embedbase', 'ug', {
	pathName: 'ۋاسىتە ئوبيېكتى',
	title: 'سىڭدۈرمە ۋاسىتە',
	button: 'Insert Media Embed', // MISSING
	unsupportedUrlGiven: 'The specified URL is not supported.', // MISSING
	unsupportedUrl: 'The URL {url} is not supported by Media Embed.', // MISSING
	fetchingFailedGiven: 'Failed to fetch content for the given URL.', // MISSING
	fetchingFailed: 'Failed to fetch content for {url}.', // MISSING
	fetchingOne: 'Fetching oEmbed response...', // MISSING
	fetchingMany: 'Fetching oEmbed responses, {current} of {max} done...' // MISSING
} );


text:
package org.apache.nifi.security.util.crypto;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.nifi.components.AllowableValue;
import org.bouncycastle.crypto.digests.Blake2bDigest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class provides a generic service for cryptographic hashing.
 * <p>
 * See also:
 * * {@link HashAlgorithm}
 */
public class HashService {
    private static final Logger logger = LoggerFactory.getLogger(HashService.class);
    private static final int BUFFER_SIZE = 8192;
    private static final String UTF_16_DESCRIPTION = "This character set normally decodes using an optional BOM at the beginning of the data but encodes by inserting a BE BOM. " +
        "For hashing, it will be replaced with UTF-16BE. ";

    /**
     * Returns an array of {@link AllowableValue} elements for each {@link HashAlgorithm}. The
     * complete {@code description} is built from the digest length, safety warnings, etc. See
     * {@link HashAlgorithm#buildAllowableValueDescription()}.
     *
     * @return an ordered {@code AllowableValue[]} containing the values
     */
    public static AllowableValue[] buildHashAlgorithmAllowableValues() {
        final HashAlgorithm[] hashAlgorithms = HashAlgorithm.values();
        List<AllowableValue> allowableValues = new ArrayList<>(hashAlgorithms.length);
        for (HashAlgorithm algorithm : hashAlgorithms) {
            allowableValues.add(new AllowableValue(algorithm.getName(), algorithm.getName(), algorithm.buildAllowableValueDescription()));
        }

        return allowableValues.toArray(new AllowableValue[0]);
    }

    /**
     * Returns an array of {@link AllowableValue} elements for each {@link Charset}. Only the charsets in {@link StandardCharsets} are returned to be consistent across JVM instances.
     *
     * @return an ordered {@code AllowableValue[]} containing the values
     */
    public static AllowableValue[] buildCharacterSetAllowableValues() {
        final List<Charset> charsets = getSupportedCharsets();
        return charsets.stream().map(cs ->
                 new AllowableValue(cs.name(),
                         cs.displayName(),
                         cs == StandardCharsets.UTF_16 ? UTF_16_DESCRIPTION : cs.displayName())
        ).toArray(AllowableValue[]::new);
    }

    /**
     * Returns a {@link List} of supported {@link Charset}s on this platform. This is not a complete
     * list, as only the charsets in {@link StandardCharsets} are returned to be consistent across
     * JVM instances.
     *
     * @return the list of charsets
     */
    public static List<Charset> getSupportedCharsets() {
        return Arrays.asList(StandardCharsets.US_ASCII,
                StandardCharsets.ISO_8859_1,
                StandardCharsets.UTF_8,
                StandardCharsets.UTF_16BE,
                StandardCharsets.UTF_16LE,
                StandardCharsets.UTF_16);
    }

    /**
     * Returns the hash of the specified value. This method uses an {@link java.io.InputStream} to perform the operation in a streaming manner for large inputs.
     *
     * @param algorithm the hash algorithm to use
     * @param value     the value to hash (cannot be {@code null} but can be an empty stream)
     * @return the hash value in hex
     */
    public static String hashValueStreaming(HashAlgorithm algorithm, InputStream value) throws IOException {
        if (algorithm == null) {
            throw new IllegalArgumentException("The hash algorithm cannot be null");
        }
        if (value == null) {
            throw new IllegalArgumentException("The value cannot be null");
        }
        // The Blake2 algorithms are instantiated differently and rely on BouncyCastle
        if (algorithm.isBlake2()) {
            return Hex.encodeHexString(blake2HashStreaming(algorithm, value));
        } else {
            return Hex.encodeHexString(traditionalHashStreaming(algorithm, value));
        }
    }

    /**
     * Returns the hex-encoded hash of the specified value.
     *
     * @param algorithm the hash algorithm to use
     * @param value     the value to hash (cannot be {@code null} but can be an empty String)
     * @param charset   the charset to use
     * @return the hash value in hex
     */
    public static String hashValue(HashAlgorithm algorithm, String value, Charset charset) {
        byte[] rawHash = hashValueRaw(algorithm, value, charset);
        return Hex.encodeHexString(rawHash);
    }

    /**
     * Returns the hex-encoded hash of the specified value. The default charset ({@code StandardCharsets.UTF_8}) is used.
     *
     * @param algorithm the hash algorithm to use
     * @param value     the value to hash (cannot be {@code null} but can be an empty String)
     * @return the hash value in hex
     */
    public static String hashValue(HashAlgorithm algorithm, String value) {
        return hashValue(algorithm, value, StandardCharsets.UTF_8);
    }

    /**
     * Returns the raw {@code byte[]} hash of the specified value.
     *
     * @param algorithm the hash algorithm to use
     * @param value     the value to hash (cannot be {@code null} but can be an empty String)
     * @param charset   the charset to use
     * @return the hash value in bytes
     */
    public static byte[] hashValueRaw(HashAlgorithm algorithm, String value, Charset charset) {
        if (value == null) {
            throw new IllegalArgumentException("The value cannot be null");
        }
        /** See the note on {@link HashServiceTest#testHashValueShouldHandleUTF16BOMIssue()} */
        if (charset == StandardCharsets.UTF_16) {
            logger.warn("The charset provided was UTF-16, but Java will insert a Big Endian BOM in the decoded message before hashing, so switching to UTF-16BE");
            charset = StandardCharsets.UTF_16BE;
        }
        return hashValueRaw(algorithm, value.getBytes(charset));
    }

    /**
     * Returns the raw {@code byte[]} hash of the specified value. The default charset ({@code StandardCharsets.UTF_8}) is used.
     *
     * @param algorithm the hash algorithm to use
     * @param value     the value to hash (cannot be {@code null} but can be an empty String)
     * @return the hash value in bytes
     */
    public static byte[] hashValueRaw(HashAlgorithm algorithm, String value) {
        return hashValueRaw(algorithm, value, StandardCharsets.UTF_8);
    }

    /**
     * Returns the raw {@code byte[]} hash of the specified value.
     *
     * @param algorithm the hash algorithm to use
     * @param value     the value to hash
     * @return the hash value in bytes
     */
    public static byte[] hashValueRaw(HashAlgorithm algorithm, byte[] value) {
        if (algorithm == null) {
            throw new IllegalArgumentException("The hash algorithm cannot be null");
        }
        if (value == null) {
            throw new IllegalArgumentException("The value cannot be null");
        }
        if (algorithm.isBlake2()) {
            return blake2Hash(algorithm, value);
        } else {
            return traditionalHash(algorithm, value);
        }
    }

    private static byte[] traditionalHash(HashAlgorithm algorithm, byte[] value) {
        return DigestUtils.getDigest(algorithm.getName()).digest(value);
    }

    private static byte[] traditionalHashStreaming(HashAlgorithm algorithm, InputStream value) throws IOException {
        MessageDigest digest = DigestUtils.getDigest(algorithm.getName());
        // DigestInputStream digestInputStream = new DigestInputStream(value, digest);
        return DigestUtils.digest(digest, value);
    }

    private static byte[] blake2Hash(HashAlgorithm algorithm, byte[] value) {
        int digestLengthBytes = algorithm.getDigestBytesLength();
        Blake2bDigest blake2bDigest = new Blake2bDigest(digestLengthBytes * 8);
        byte[] rawHash = new byte[blake2bDigest.getDigestSize()];
        blake2bDigest.update(value, 0, value.length);
        blake2bDigest.doFinal(rawHash, 0);
        return rawHash;
    }

    private static byte[] blake2HashStreaming(HashAlgorithm algorithm, InputStream value) throws IOException {
        int digestLengthBytes = algorithm.getDigestBytesLength();
        Blake2bDigest blake2bDigest = new Blake2bDigest(digestLengthBytes * 8);
        byte[] rawHash = new byte[blake2bDigest.getDigestSize()];

        final byte[] buffer = new byte[BUFFER_SIZE];
        int read = value.read(buffer, 0, BUFFER_SIZE);

        while (read > -1) {
            blake2bDigest.update(buffer, 0, read);
            read = value.read(buffer, 0, BUFFER_SIZE);
        }

        blake2bDigest.doFinal(rawHash, 0);
        return rawHash;
    }
}