text:
package com.allspeak.audiocapture;

import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;

import com.allspeak.ENUMS;
import com.allspeak.ERRORS;
import android.media.AudioRecord;
import android.media.AudioFormat;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.AudioManager;

import android.os.Process;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.allspeak.utility.Messaging;
import com.allspeak.audiocapture.AudioInputCapture;

public class AudioPlayback extends Thread
{

    private int channelConfigIN                 = AudioFormat.CHANNEL_IN_MONO;
    private int channelConfigOUT                = AudioFormat.CHANNEL_OUT_MONO;
    private int audioFormat                     = AudioFormat.ENCODING_PCM_16BIT;
    private int sampleRateInHz                  = 8000;
    private int nTotalReadBytes                 = 0;
    private static float fNormalizationFactor   = (float)32767.0;

    // For the recording buffer
    private int minBufferSize                   = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfigIN, audioFormat);

    // Used for reading from the AudioRecord buffer
    private int readBufferSize                  = minBufferSize;

    private AudioRecord mRecorder               = null;
    private AudioTrack mAudioTrack              = null;
    private AudioTrack mAudioManager            = null;

    private Handler mStatusCallback             = null;   // destination handler of status messages
    private Handler mResultCallback             = null;   // destination handler of data result
    private Handler mCommandCallback            = null;   // destination handler of output command
    private CallbackContext mWlCb               = null;   // access to web layer
    //==========================================================================================================
    public AudioPlayback()
    {
        mRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, sampleRateInHz, channelConfigIN, audioFormat, minBufferSize);
    }

    public AudioPlayback(int sampleRate, int bufferSizeInBytes, int channels, String format, int audioSource)
    {
        sampleRateInHz      = sampleRate;
        switch (channels) {
            case 2:
                channelConfigIN     = AudioFormat.CHANNEL_IN_STEREO;
                channelConfigOUT    = AudioFormat.CHANNEL_OUT_STEREO;
                break;
            case 1:
            default:
                channelConfigIN = AudioFormat.CHANNEL_IN_MONO;
                channelConfigOUT = AudioFormat.CHANNEL_OUT_MONO;
                break;
        }
        if(format == "PCM_8BIT")    audioFormat = AudioFormat.ENCODING_PCM_8BIT;
        else                        audioFormat = AudioFormat.ENCODING_PCM_16BIT;

        readBufferSize = bufferSizeInBytes;

        // Get the minimum recording buffer size for the specified configuration
        minBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfigIN, audioFormat);

        // Ensure that the given recordingBufferSize isn't lower than the minimum buffer size allowed for the current configuration
        if (readBufferSize < minBufferSize) readBufferSize = minBufferSize;

        mRecorder       = new AudioRecord(audioSource, sampleRateInHz, channelConfigIN, audioFormat, minBufferSize);
        mAudioTrack     = new AudioTrack(AudioManager.STREAM_VOICE_CALL, sampleRateInHz, channelConfigOUT, audioFormat, minBufferSize, AudioTrack.MODE_STREAM);
    }
    //==========================================================================================================

    public void setHandler(Handler handler)
    {
        mStatusCallback     = handler;
        mCommandCallback    = handler;
        mResultCallback     = handler;
    }

    public void setHandler(Handler scb, Handler ccb, Handler rcb)
    {
        mStatusCallback     = scb;
        mCommandCallback    = ccb;
        mResultCallback     = rcb;
    }

    public void setWlCb(CallbackContext wlcb)
    {
        mWlCb = wlcb;
    }
    //==========================================================================================================

    public void setPlayBackPercVol(int newperc)
    {
        float max       = mAudioTrack.getMaxVolume();
        float newgain   = (newperc*max)/100;
        mAudioTrack.setVolume(newgain);
    }

    @Override
    public void run()
    {
        Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
        short[] audioBuffer  = new short[readBufferSize];

        synchronized(this)
        {
            mRecorder.startRecording();
            mAudioTrack.setPlaybackRate(sampleRateInHz);
            mAudioTrack.play();
            Messaging.sendMessageToHandler(mStatusCallback, ENUMS.CAPTURE_STATUS_STARTED, "", "");

            while (!isInterrupted())
            {
                try
                {
                    int numReadBytes = mRecorder.read(audioBuffer, 0, readBufferSize);
                    mAudioTrack.write(audioBuffer, 0, audioBuffer.length);
                    if (numReadBytes > 0)
                    {
                        float[] normalizedData  = AudioInputCapture.normalizeAudio(audioBuffer, fNormalizationFactor);
                        float rms               = AudioInputCapture.getAudioLevels(normalizedData);
                        float decibels          = AudioInputCapture.getDecibelFromAmplitude(rms);

                        JSONObject info = new JSONObject();
                        info.put("data_type", ENUMS.CAPTURE_DATADEST_JS_DB);
                        info.put("type", ENUMS.CAPTURE_RESULT);
                        info.put("decibels", Float.toString(decibels));
                        Messaging.sendUpdate2Web(mWlCb, info, true);
                    }
                }
                catch(Exception ex)
                {
                    Messaging.sendMessageToHandler(mStatusCallback, ERRORS.CAPTURE_ERROR, "error", ex.toString());
                    break;
                }
            }
            if (mRecorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING)
            {
                mRecorder.stop();
                mAudioTrack.stop();
            }
            Messaging.sendMessageToHandler(mStatusCallback, ENUMS.CAPTURE_STATUS_STOPPED, "stop", Integer.toString(nTotalReadBytes));
            mRecorder.release();
            mRecorder = null;
            mAudioTrack.release();
            mAudioTrack = null;
        }
    }
    //==========================================================================================================
}


text:
<!DOCTYPE>

    <title>Microscope</title>
    <link href='http://fonts.googleapis.com/css?family=IM+Fell+DW+Pica:400,400italic' rel='stylesheet' type='text/css'>
    <link href="style.css" rel="stylesheet" />

Microscope

Loading...

Microscope is a game created by John Turesson as a submission for the game competition Ludum Dare #31 in 2014.

The source to the game can be downloaded from here.

Credit goes to gamerendering.com for the radial blur shader, Hivenfour for the SeamlessLoop JavaScript audio player, Mr.Doob for the three.js JavaScript renderer and flipcode.com for the distance approximation algorithm.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Sun</title>

    <link rel="stylesheet" href="demos.css">

<canvas id="mainCanvas" width="500" height="500"></canvas>

Loading...


text:
IF(NOT DEFINED CMAKE_INSTALL_PREFIX)
  SET(CMAKE_INSTALL_PREFIX "/usr/local")
ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX)
STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  IF(BUILD_TYPE)
    STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  ELSE(BUILD_TYPE)
    SET(CMAKE_INSTALL_CONFIG_NAME "Release")
  ENDIF(BUILD_TYPE)
  MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)

# Set the component getting installed.
IF(NOT CMAKE_INSTALL_COMPONENT)
  IF(COMPONENT)
    MESSAGE(STATUS "Install component: \"${COMPONENT}\"")
    SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  ELSE(COMPONENT)
    SET(CMAKE_INSTALL_COMPONENT)
  ENDIF(COMPONENT)
ENDIF(NOT CMAKE_INSTALL_COMPONENT)

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE EXECUTABLE FILES "/home/olfrik/Projects/seqan/src/sandbox/olfrik/apps/t1SeqA2/CMakeFiles/CMakeRelink.dir/t1SeqA2")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/doc/t1SeqA2" TYPE FILE FILES
    "/home/olfrik/Projects/seqan/src/sandbox/olfrik/apps/t1SeqA2/LICENSE"
    "/home/olfrik/Projects/seqan/src/sandbox/olfrik/apps/t1SeqA2/README"
    )
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")


text:
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentationCommentFormatting;
using Microsoft.CodeAnalysis.Editor.SignatureHelp;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp
{
    [ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.CSharp)]
    internal partial class InvocationExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider
    {
        public override bool IsTriggerCharacter(char ch)
        {
            return ch == '(' || ch == ',';
        }

        public override bool IsRetriggerCharacter(char ch)
        {
            return ch == ')';
        }

        private bool TryGetInvocationExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InvocationExpressionSyntax expression)
        {
            if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression))
            {
                return false;
            }

            return expression.ArgumentList != null;
        }

        private bool IsTriggerToken(SyntaxToken token)
        {
            return !token.IsKind(SyntaxKind.None) &&
                token.ValueText.Length == 1 &&
                IsTriggerCharacter(token.ValueText[0]) &&
                token.Parent is ArgumentListSyntax &&
                token.Parent.Parent is InvocationExpressionSyntax;
        }

        private static bool IsArgumentListToken(InvocationExpressionSyntax expression, SyntaxToken token)
        {
            return expression.ArgumentList.Span.Contains(token.SpanStart) &&
                token != expression.ArgumentList.CloseParenToken;
        }

        protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            InvocationExpressionSyntax invocationExpression;
            if (!TryGetInvocationExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out invocationExpression))
            {
                return null;
            }

            var semanticModel = await document.GetSemanticModelForNodeAsync(invocationExpression, cancellationToken).ConfigureAwait(false);
            var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
            if (within == null)
            {
                return null;
            }

            // get the regular signature help items
            var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>();
            var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken)
                                           .OfType<IMethodSymbol>()
                                           .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation);

            // try to bind to the actual method
            var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken);
            var matchedMethodSymbol = symbolInfo.Symbol as IMethodSymbol;

            // if the symbol could be bound, replace that item in the symbol list
            if (matchedMethodSymbol != null && matchedMethodSymbol.IsGenericMethod)
            {
                methodGroup = methodGroup.Select(m => matchedMethodSymbol.OriginalDefinition == m ? matchedMethodSymbol : m);
            }

            methodGroup = methodGroup.Sort(symbolDisplayService, semanticModel, invocationExpression.SpanStart);

            var expressionType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type as INamedTypeSymbol;

            var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>();
            var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>();

            var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList);
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();

            if (methodGroup.Any())
            {
                return CreateSignatureHelpItems(
                    GetMethodGroupItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, methodGroup, cancellationToken),
                    textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken));
            }
            else if (expressionType != null && expressionType.TypeKind == TypeKind.Delegate)
            {
                return CreateSignatureHelpItems(
                    GetDelegateInvokeItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, expressionType, cancellationToken),
                    textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken));
            }
            else
            {
                return null;
            }
        }

        public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
        {
            InvocationExpressionSyntax expression;
            if (TryGetInvocationExpression(
                    root,
                    position,
                    syntaxFacts,
                    SignatureHelpTriggerReason.InvokeSignatureHelpCommand,
                    cancellationToken,
                    out expression) &&
                currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start)
            {
                return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position);
            }

            return null;
        }
    }
}


text:
#import "NSObject.h"

@interface CNFInternalSettingsUtilities : NSObject
{
}

+ (void)setIDSEnvironment:(id)arg1;
+ (id)IDSEnvironment;
+ (void)setCurrentInternalSettingsBundle:(id)arg1;
+ (id)currentInternalSettingsBundle;
+ (void)signOutAllAccounts;
+ (void)nukeKeychain;
+ (void)killEverything;
+ (void)killMobileSMS;
+ (void)killMobilePhone;
+ (void)killFaceTime;
+ (void)killMediaServerd;
+ (void)syncImagentLogSettings;
+ (void)killImavagent;
+ (void)killImagent;
+ (void)setViceroyLoggingEnabled:(_Bool)arg1;
+ (_Bool)isViceroyLoggingEnabled;

@end


text:
require 'spec_helper'

provider_class = Puppet::Type.type(:oneview_fcoe_network).provider(:c7000)

describe provider_class, integration: true do
  let(:resource) do
    Puppet::Type.type(:oneview_fcoe_network).new(
      name: 'fcoe',
      ensure: 'present',
      data:
          {
            'name' => 'OneViewSDK Test FC Network',
            'connectionTemplateUri' => nil,
            'vlanId'                => '300',
            'type'                  => 'fcoe-network'
          }
    )
  end

  let(:provider) { resource.provider }

  let(:instance) { provider.class.instances.first }

  before(:each) do
    provider.exists?
  end

  it 'should be an instance of the provider Ruby' do
    expect(provider).to be_an_instance_of Puppet::Type.type(:oneview_fcoe_network).provider(:c7000)
  end

  context 'given the min parameters' do
    it 'exists? should return false at first' do
      expect(provider.exists?).not_to be
    end

    it 'should create a new network' do
      expect(provider.create).to be
    end
  end

  context 'given the search parameters' do
    let(:resource) do
      Puppet::Type.type(:oneview_fcoe_network).new(
        name: 'fcoe',
        ensure: 'present',
        data:
            {
              'name' => 'OneViewSDK Test FC Network'
            }
      )
    end

    before(:each) do
      provider.exists?
    end

    it 'exists? should find a network' do
      expect(provider.exists?).to be
    end

    it 'should return that no network was found' do
      expect(provider.found).to be
    end

    it 'should run destroy' do
      expect(provider.destroy).to be
    end
  end
end


text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use app\common\Utility;

/* @var $this yii\web\View */
/* @var $model app\modules\work\models\WorkType */
/* @var $form yii\widgets\ActiveForm */
?>
<?php

 $changeattribute='';
$this->registerJs(
   '$("document").ready(function(){
        $("#new_work-type").on("pjax:end", function() {
            $.pjax.reload({container:"#work-types"});  //Reload GridView
        });
    });'
);
?>

        Form for creating WorkType

    <?php $form = ActiveForm::begin([
    'layout' => 'horizontal',
    'fieldConfig' => [
        'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
        'horizontalCssClasses' => [
            'label' => 'col-sm-4',
            'offset' => 'col-sm-offset-4',
            'wrapper' => 'col-sm-8',
            'error' => '',
            'hint' => '',
        ],
    ],
]); ?>

    <?= $model->showForm($form,"category") ?>

    <?= $model->showForm($form,"name_hi") ?>

    <?= $model->showForm($form,"name_en") ?>

<?php
/*
try {
$x= Utility::rules()["app\modules\work\models\WorkType"][$changeattribute];
} catch (Exception $e) {$x=null;}
$modelArray=Yii::$app->request->post("WorkType");
		if ($x && $model && array_key_exists($changeattribute,$modelArray) && array_key_exists($modelArray[$changeattribute],$x))
		{
			$attribute_value=$modelArray[$changeattribute];

			foreach ($x[$attribute_value]["show"] as $field)
			{

				echo "
\n";

				echo $model->showForm($form,$field);
				echo "
";

			}
		}
**/
?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
using System;
using System.Collections.Generic;
using eidss.model.Enums;
using eidss.model.Reports.TH;

namespace eidss.webclient.Models.Reports
{
    //[Serializable]
    //public class NumberOfCasesDeathsMonthTHWebModel : NumberOfCasesDeathsMonthTHModel
    //{
    //    public NumberOfCasesDeathsMonthTHWebModel()
    //    {
    //        Diagnoses.AddSelectAllItem = true;
    //    }

    //    public NumberOfCasesDeathsMonthTHWebModel
    //        (string lang,
    //            int year,
    //            string[] diagnoses,
    //            string[] regions,
    //            string[] zones,
    //            long? caseClassification,
    //            long? organizationId, List<PersonalDataGroup> forbiddenGroups, bool useArchive)
    //        : base(lang, year, diagnoses, regions, zones, caseClassification, organizationId, forbiddenGroups, useArchive)
    //    {
    //        Diagnoses.AddSelectAllItem = true;
    //    }

    //    public string Diagnoses_CheckedItems { get; set; }
    //    public string ZoneFilter_CheckedItems { get; set; }
    //    public string RegionFilter_CheckedItems { get; set; }

    //    public NumberOfCasesDeathsMonthTHModel ConvertToBaseModel()
    //    {
    //        var baseModel = new NumberOfCasesDeathsMonthTHModel(Language, Year,
    //            Diagnoses.CheckedItems,
    //            Regions.CheckedItems,
    //            Zones.CheckedItems,
    //            CaseClassification,
    //            OrganizationId, ForbiddenGroups, UseArchive);
    //        return baseModel;
    //    }
    //}
}


text:
package soa.study.ws.rs.spring;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {

	@RequestMapping(value = "/hello/{msg}", method = RequestMethod.GET)
	@ResponseBody
	public Greeting echo(@PathVariable String msg) {

		Greeting greeting = new Greeting();
		greeting.setName(HelloWorldController.class.getName());
		greeting.setAge("version1");
		greeting.setMsg(msg);
		return greeting;
	}

	@RequestMapping(value = "/post/entry", method = RequestMethod.POST//
	, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Greeting entry(@RequestBody Greeting greeting) {

		greeting.setMsg("Hello World");
		return greeting;
	}

}


text:
package collector

import (
	"context"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/go-kit/log"
	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
	"github.com/smartystreets/goconvey/convey"
)

func TestScrapeBinlogSize(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("error opening a stub database connection: %s", err)
	}
	defer db.Close()

	mock.ExpectQuery(logbinQuery).WillReturnRows(sqlmock.NewRows([]string{""}).AddRow(1))

	columns := []string{"Log_name", "File_size"}
	rows := sqlmock.NewRows(columns).
		AddRow("centos6-bin.000001", "1813").
		AddRow("centos6-bin.000002", "120").
		AddRow("centos6-bin.000444", "573009")
	mock.ExpectQuery(sanitizeQuery(binlogQuery)).WillReturnRows(rows)

	ch := make(chan prometheus.Metric)
	go func() {
		if err = (ScrapeBinlogSize{}).Scrape(context.Background(), db, ch, log.NewNopLogger()); err != nil {
			t.Errorf("error calling function on test: %s", err)
		}
		close(ch)
	}()

	counterExpected := []MetricResult{
		{labels: labelMap{}, value: 574942, metricType: dto.MetricType_GAUGE},
		{labels: labelMap{}, value: 3, metricType: dto.MetricType_GAUGE},
		{labels: labelMap{}, value: 444, metricType: dto.MetricType_GAUGE},
	}
	convey.Convey("Metrics comparison", t, func() {
		for _, expect := range counterExpected {
			got := readMetric(<-ch)
			convey.So(got, convey.ShouldResemble, expect)
		}
	})

	// Ensure all SQL queries were executed
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled exceptions: %s", err)
	}
}


text:
<?php

use Znck\Attach\Contracts\AttachmentContract;

if (!function_exists('attach_url')) {
    /**
     * Generate url for attachment.
     *
     * @param AttachmentContract $attachment
     * @param string|null $var
     * @param array $params
     * @param bool|null $sign
     *
     * @return null|string
     */
    function attach_url($attachment, string $var = null, $params = [], bool $sign = null)
    {
        if (!($attachment instanceof AttachmentContract)) {
            return null;
        }

        return app(Znck\Attach\Contracts\UrlGeneratorContract::class)->url($attachment, $var, $params, $sign);
    }
}


text:
using System;

namespace Odachi.Validation
{
	/// <summary>
	/// Validation state builder.
	/// </summary>
	public class Validator
	{
		public Validator()
		{
			State = new ValidationState();
		}
		public Validator(ValidationState state)
		{
			State = state ?? throw new ArgumentNullException(nameof(state));
		}

		public ValidationState State { get; }

		public bool HasWarnings => State.HasWarnings;

		public bool HasErrors => State.HasErrors;

		public Validator Message(ValidationMessage message)
		{
			State.Add(message);

			return this;
		}

		public Validator Warning(string key, string message)
		{
			State.Add(new ValidationMessage()
			{
				Key = key,
				Severity = ValidationSeverity.Warning,
				Text = message,
			});

			return this;
		}

		public Validator Error(string key, string message)
		{
			State.Add(new ValidationMessage()
			{
				Key = key,
				Severity = ValidationSeverity.Error,
				Text = message,
			});

			return this;
		}
	}
}


text:
namespace glslang {

//
// Base class for parse helpers.
// This just has version-related information and checking.
// This class should be sufficient for preprocessing.
//
class TParseVersions {
public:
    TParseVersions(TIntermediate& interm, int version, EProfile profile,
                   const SpvVersion& spvVersion, EShLanguage language, TInfoSink& infoSink,
                   bool forwardCompatible, EShMessages messages)
        : infoSink(infoSink), version(version), profile(profile), language(language),
          spvVersion(spvVersion), forwardCompatible(forwardCompatible),
          intermediate(interm), messages(messages), numErrors(0), currentScanner(0) { }
    virtual ~TParseVersions() { }
    virtual void initializeExtensionBehavior();
    virtual void requireProfile(const TSourceLoc&, int queryProfiles, const char* featureDesc);
    virtual void profileRequires(const TSourceLoc&, int queryProfiles, int minVersion, int numExtensions, const char* const extensions[], const char* featureDesc);
    virtual void profileRequires(const TSourceLoc&, int queryProfiles, int minVersion, const char* const extension, const char* featureDesc);
    virtual void requireStage(const TSourceLoc&, EShLanguageMask, const char* featureDesc);
    virtual void requireStage(const TSourceLoc&, EShLanguage, const char* featureDesc);
    virtual void checkDeprecated(const TSourceLoc&, int queryProfiles, int depVersion, const char* featureDesc);
    virtual void requireNotRemoved(const TSourceLoc&, int queryProfiles, int removedVersion, const char* featureDesc);
    virtual void unimplemented(const TSourceLoc&, const char* featureDesc);
    virtual void requireExtensions(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
    virtual void ppRequireExtensions(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
    virtual TExtensionBehavior getExtensionBehavior(const char*);
    virtual bool extensionTurnedOn(const char* const extension);
    virtual bool extensionsTurnedOn(int numExtensions, const char* const extensions[]);
    virtual void updateExtensionBehavior(int line, const char* const extension, const char* behavior);
    virtual void fullIntegerCheck(const TSourceLoc&, const char* op);
    virtual void doubleCheck(const TSourceLoc&, const char* op);
    virtual void float16Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void float16ScalarVectorCheck(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual bool float16Arithmetic();
    virtual void requireFloat16Arithmetic(const TSourceLoc& loc, const char* op, const char* featureDesc);
    virtual void int16ScalarVectorCheck(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual bool int16Arithmetic();
    virtual void requireInt16Arithmetic(const TSourceLoc& loc, const char* op, const char* featureDesc);
    virtual void int8ScalarVectorCheck(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual bool int8Arithmetic();
    virtual void requireInt8Arithmetic(const TSourceLoc& loc, const char* op, const char* featureDesc);
#ifdef AMD_EXTENSIONS
    virtual void float16OpaqueCheck(const TSourceLoc&, const char* op, bool builtIn = false);
#endif
    virtual void int64Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void explicitInt8Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void explicitInt16Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void explicitInt32Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void explicitFloat32Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void explicitFloat64Check(const TSourceLoc&, const char* op, bool builtIn = false);
    virtual void spvRemoved(const TSourceLoc&, const char* op);
    virtual void vulkanRemoved(const TSourceLoc&, const char* op);
    virtual void requireVulkan(const TSourceLoc&, const char* op);
    virtual void requireSpv(const TSourceLoc&, const char* op);
    virtual bool checkExtensionsRequested(const TSourceLoc&, int numExtensions, const char* const extensions[], const char* featureDesc);
    virtual void updateExtensionBehavior(const char* const extension, TExtensionBehavior);
    virtual void checkExtensionStage(const TSourceLoc&, const char* const extension);
    virtual void fcoopmatCheck(const TSourceLoc&, const char* op, bool builtIn = false);

    virtual void C_DECL error(const TSourceLoc&, const char* szReason, const char* szToken,
        const char* szExtraInfoFormat, ...) = 0;
    virtual void C_DECL  warn(const TSourceLoc&, const char* szReason, const char* szToken,
        const char* szExtraInfoFormat, ...) = 0;
    virtual void C_DECL ppError(const TSourceLoc&, const char* szReason, const char* szToken,
        const char* szExtraInfoFormat, ...) = 0;
    virtual void C_DECL ppWarn(const TSourceLoc&, const char* szReason, const char* szToken,
        const char* szExtraInfoFormat, ...) = 0;

    void addError() { ++numErrors; }
    int getNumErrors() const { return numErrors; }

    void setScanner(TInputScanner* scanner) { currentScanner = scanner; }
    TInputScanner* getScanner() const { return currentScanner; }
    const TSourceLoc& getCurrentLoc() const { return currentScanner->getSourceLoc(); }
    void setCurrentLine(int line) { currentScanner->setLine(line); }
    void setCurrentColumn(int col) { currentScanner->setColumn(col); }
    void setCurrentSourceName(const char* name) { currentScanner->setFile(name); }
    void setCurrentString(int string) { currentScanner->setString(string); }

    void getPreamble(std::string&);
    bool relaxedErrors()    const { return (messages & EShMsgRelaxedErrors) != 0; }
    bool suppressWarnings() const { return (messages & EShMsgSuppressWarnings) != 0; }
    bool isReadingHLSL()    const { return (messages & EShMsgReadHlsl) == EShMsgReadHlsl; }
    bool hlslEnable16BitTypes() const { return (messages & EShMsgHlslEnable16BitTypes) != 0; }
    bool hlslDX9Compatible() const { return (messages & EShMsgHlslDX9Compatible) != 0; }

    TInfoSink& infoSink;

    // compilation mode
    int version;                 // version, updated by #version in the shader
    EProfile profile;            // the declared profile in the shader (core by default)
    EShLanguage language;        // really the stage
    SpvVersion spvVersion;
    bool forwardCompatible;      // true if errors are to be given for use of deprecated features
    TIntermediate& intermediate; // helper for making and hooking up pieces of the parse tree

protected:
    TMap<TString, TExtensionBehavior> extensionBehavior;    // for each extension string, what its current behavior is set to
    EShMessages messages;        // errors/warnings/rule-sets
    int numErrors;               // number of compile-time errors encountered
    TInputScanner* currentScanner;

private:
    explicit TParseVersions(const TParseVersions&);
    TParseVersions& operator=(const TParseVersions&);
};

} // end namespace glslang

#endif // _PARSE_VERSIONS_INCLUDED_


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

/**
 * This is PID 1 inside the sandbox environment and runs in a separate user,
 * mount, UTS, IPC and PID namespace.
 */

#include "src/main/tools/linux-sandbox-pid1.h"

#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <math.h>
#include <mntent.h>
#include <net/if.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <string>

#ifndef MS_REC
// Some systems do not define MS_REC in sys/mount.h. We might be able to grab it
// from linux/fs.h instead (cf. #2667).
#include <linux/fs.h>
#endif

#ifndef TEMP_FAILURE_RETRY
// Some C standard libraries like musl do not define this macro, so we'll
// include our own version for compatibility.
#define TEMP_FAILURE_RETRY(exp)            \
  ({                                       \
    decltype(exp) _rc;                     \
    do {                                   \
      _rc = (exp);                         \
    } while (_rc == -1 && errno == EINTR); \
    _rc;                                   \
  })
#endif  // TEMP_FAILURE_RETRY

#include "src/main/tools/linux-sandbox-options.h"
#include "src/main/tools/linux-sandbox.h"
#include "src/main/tools/logging.h"
#include "src/main/tools/process-tools.h"

static int global_child_pid;

static void SetupSelfDestruction(int *sync_pipe) {
  // We could also poll() on the pipe fd to find out when the parent goes away,
  // and rely on SIGCHLD interrupting that otherwise. That might require us to
  // install some trivial handler for SIGCHLD. Using O_ASYNC to turn the pipe
  // close into SIGIO may also work. Another option is signalfd, although that's
  // almost as obscure as this prctl.
  if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0) {
    DIE("prctl");
  }

  // Switch to a new process group, otherwise our process group will still refer
  // to the outer PID namespace. We might then accidentally kill our parent by a
  // call to e.g. `kill(0, sig)`.
  if (setpgid(0, 0) < 0) {
    DIE("setpgid");
  }

  // Verify that the parent still lives.
  char buf = 0;
  if (close(sync_pipe[0]) < 0) {
    DIE("close");
  }
  if (write(sync_pipe[1], &buf, 1) < 0) {
    DIE("write");
  }
  if (close(sync_pipe[1]) < 0) {
    DIE("close");
  }
}

static void SetupMountNamespace() {
  // Fully isolate our mount namespace private from outside events, so that
  // mounts in the outside environment do not affect our sandbox.
  if (mount(nullptr, "/", nullptr, MS_REC | MS_PRIVATE, nullptr) < 0) {
    DIE("mount");
  }
}

static void WriteFile(const std::string &filename, const char *fmt, ...) {
  FILE *stream = fopen(filename.c_str(), "w");
  if (stream == nullptr) {
    DIE("fopen(%s)", filename.c_str());
  }

  va_list ap;
  va_start(ap, fmt);
  int r = vfprintf(stream, fmt, ap);
  va_end(ap);

  if (r < 0) {
    DIE("vfprintf");
  }

  if (fclose(stream) != 0) {
    DIE("fclose(%s)", filename.c_str());
  }
}

static void SetupUserNamespace() {
  // Disable needs for CAP_SETGID.
  struct stat sb;
  if (stat("/proc/self/setgroups", &sb) == 0) {
    WriteFile("/proc/self/setgroups", "deny");
  } else {
    // Ignore ENOENT, because older Linux versions do not have this file (but
    // also do not require writing to it).
    if (errno != ENOENT) {
      DIE("stat(/proc/self/setgroups");
    }
  }

  int inner_uid, inner_gid;
  if (opt.fake_root) {
    // Change our username to 'root'.
    inner_uid = 0;
    inner_gid = 0;
  } else if (opt.fake_username) {
    // Change our username to 'nobody'.
    struct passwd *pwd = getpwnam("nobody");
    if (pwd == nullptr) {
      DIE("unable to find passwd entry for user nobody")
    }

    inner_uid = pwd->pw_uid;
    inner_gid = pwd->pw_gid;
  } else {
    // Do not change the username inside the sandbox.
    inner_uid = global_outer_uid;
    inner_gid = global_outer_gid;
  }

  WriteFile("/proc/self/uid_map", "%d %d 1\n", inner_uid, global_outer_uid);
  WriteFile("/proc/self/gid_map", "%d %d 1\n", inner_gid, global_outer_gid);
}

static void SetupUtsNamespace() {
  if (sethostname("localhost", 9) < 0) {
    DIE("sethostname");
  }

  if (setdomainname("localdomain", 11) < 0) {
    DIE("setdomainname");
  }
}

static void MountFilesystems() {
  for (const std::string &tmpfs_dir : opt.tmpfs_dirs) {
    PRINT_DEBUG("tmpfs: %s", tmpfs_dir.c_str());
    if (mount("tmpfs", tmpfs_dir.c_str(), "tmpfs",
              MS_NOSUID | MS_NODEV | MS_NOATIME, nullptr) < 0) {
      DIE("mount(tmpfs, %s, tmpfs, MS_NOSUID | MS_NODEV | MS_NOATIME, nullptr)",
          tmpfs_dir.c_str());
    }
  }

  // Make sure that our working directory is a mount point. The easiest way to
  // do this is by bind-mounting it upon itself.
  PRINT_DEBUG("working dir: %s", opt.working_dir.c_str());

  // An attempt to mount the sandbox in tmpfs will always fail, so this block is
  // slightly redundant with the next mount() check, but dumping the mount()
  // syscall is incredibly cryptic, so we explicitly check against and warn
  // about attempts to use tmpfs.
  for (const std::string &tmpfs_dir : opt.tmpfs_dirs) {
    if (opt.working_dir.find(tmpfs_dir) == 0) {
      DIE("The sandbox working directory cannot be below a path where we mount "
          "tmpfs (you requested mounting %s in %s). Is your --output_base= "
          "below one of your --sandbox_tmpfs_path values?",
          opt.working_dir.c_str(), tmpfs_dir.c_str());
    }
  }

  if (mount(opt.working_dir.c_str(), opt.working_dir.c_str(), nullptr, MS_BIND,
            nullptr) < 0) {
    DIE("mount(%s, %s, nullptr, MS_BIND, nullptr)", opt.working_dir.c_str(),
        opt.working_dir.c_str());
  }

  for (size_t i = 0; i < opt.bind_mount_sources.size(); i++) {
    const std::string &source = opt.bind_mount_sources.at(i);
    const std::string &target = opt.bind_mount_targets.at(i);
    PRINT_DEBUG("bind mount: %s -> %s", source.c_str(), target.c_str());
    if (mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr) < 0) {
      DIE("mount(%s, %s, nullptr, MS_BIND, nullptr)", source.c_str(),
          target.c_str());
    }
  }

  for (const std::string &writable_file : opt.writable_files) {
    PRINT_DEBUG("writable: %s", writable_file.c_str());
    if (mount(writable_file.c_str(), writable_file.c_str(), nullptr,
              MS_BIND | MS_REC, nullptr) < 0) {
      DIE("mount(%s, %s, nullptr, MS_BIND | MS_REC, nullptr)",
          writable_file.c_str(), writable_file.c_str());
    }
  }
}

// We later remount everything read-only, except the paths for which this method
// returns true.
static bool ShouldBeWritable(const std::string &mnt_dir) {
  if (mnt_dir == opt.working_dir) {
    return true;
  }

  for (const std::string &writable_file : opt.writable_files) {
    if (mnt_dir == writable_file) {
      return true;
    }
  }

  for (const std::string &tmpfs_dir : opt.tmpfs_dirs) {
    if (mnt_dir == tmpfs_dir) {
      return true;
    }
  }

  return false;
}

// Makes the whole filesystem read-only, except for the paths for which
// ShouldBeWritable returns true.
static void MakeFilesystemMostlyReadOnly() {
  FILE *mounts = setmntent("/proc/self/mounts", "r");
  if (mounts == nullptr) {
    DIE("setmntent");
  }

  struct mntent *ent;
  while ((ent = getmntent(mounts)) != nullptr) {
    int mountFlags = MS_BIND | MS_REMOUNT;

    // MS_REMOUNT does not allow us to change certain flags. This means, we have
    // to first read them out and then pass them in back again. There seems to
    // be no better way than this (an API for just getting the mount flags of a
    // mount entry as a bitmask would be great).
    if (hasmntopt(ent, "nodev") != nullptr) {
      mountFlags |= MS_NODEV;
    }
    if (hasmntopt(ent, "noexec") != nullptr) {
      mountFlags |= MS_NOEXEC;
    }
    if (hasmntopt(ent, "nosuid") != nullptr) {
      mountFlags |= MS_NOSUID;
    }
    if (hasmntopt(ent, "noatime") != nullptr) {
      mountFlags |= MS_NOATIME;
    }
    if (hasmntopt(ent, "nodiratime") != nullptr) {
      mountFlags |= MS_NODIRATIME;
    }
    if (hasmntopt(ent, "relatime") != nullptr) {
      mountFlags |= MS_RELATIME;
    }

    if (!ShouldBeWritable(ent->mnt_dir)) {
      mountFlags |= MS_RDONLY;
    }

    PRINT_DEBUG("remount %s: %s", (mountFlags & MS_RDONLY) ? "ro" : "rw",
                ent->mnt_dir);
    if (mount(nullptr, ent->mnt_dir, nullptr, mountFlags, nullptr) < 0) {
      // If we get EACCES or EPERM, this might be a mount-point for which we
      // don't have read access. Not much we can do about this, but it also
      // won't do any harm, so let's go on. The same goes for EINVAL or ENOENT,
      // which are fired in case a later mount overlaps an earlier mount, e.g.
      // consider the case of /proc, /proc/sys/fs/binfmt_misc and /proc, with
      // the latter /proc being the one that an outer sandbox has mounted on
      // top of its parent /proc. In that case, we're not allowed to remount
      // /proc/sys/fs/binfmt_misc, because it is hidden. If we get ESTALE, the
      // mount is a broken NFS mount. In the ideal case, the user would either
      // fix or remove that mount, but in cases where that's not possible, we
      // should just ignore it.
      switch (errno) {
        case EACCES:
        case EPERM:
        case EINVAL:
        case ENOENT:
        case ESTALE:
          PRINT_DEBUG(
              "remount(nullptr, %s, nullptr, %d, nullptr) failure (%m) ignored",
              ent->mnt_dir, mountFlags);
          break;
        default:
          DIE("remount(nullptr, %s, nullptr, %d, nullptr)", ent->mnt_dir,
              mountFlags);
      }
    }
  }

  endmntent(mounts);
}

static void MountProc() {
  // Mount a new proc on top of the old one, because the old one still refers to
  // our parent PID namespace.
  if (mount("/proc", "/proc", "proc", MS_NODEV | MS_NOEXEC | MS_NOSUID,
            nullptr) < 0) {
    DIE("mount");
  }
}

static void SetupNetworking() {
  // When running in a separate network namespace, enable the loopback interface
  // because some application may want to use it.
  if (opt.create_netns) {
    int fd;
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
      DIE("socket");
    }

    struct ifreq ifr = {};
    strncpy(ifr.ifr_name, "lo", IF_NAMESIZE);

    // Verify that name is valid.
    if (if_nametoindex(ifr.ifr_name) == 0) {
      DIE("if_nametoindex");
    }

    // Enable the interface.
    ifr.ifr_flags |= IFF_UP;
    if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
      DIE("ioctl");
    }

    if (close(fd) < 0) {
      DIE("close");
    }
  }
}

static void EnterSandbox() {
  if (chdir(opt.working_dir.c_str()) < 0) {
    DIE("chdir(%s)", opt.working_dir.c_str());
  }
}

static void ForwardSignal(int signum) {
  PRINT_DEBUG("ForwardSignal(%d)", signum);
  kill(-global_child_pid, signum);
}

static void SpawnChild() {
  PRINT_DEBUG("calling fork...");
  global_child_pid = fork();

  if (global_child_pid < 0) {
    DIE("fork()");
  } else if (global_child_pid == 0) {
    // Put the child into its own process group.
    if (setpgid(0, 0) < 0) {
      DIE("setpgid");
    }

    // Try to assign our terminal to the child process.
    if (tcsetpgrp(STDIN_FILENO, getpgrp()) < 0 && errno != ENOTTY) {
      DIE("tcsetpgrp")
    }

    // Unblock all signals, restore default handlers.
    ClearSignalMask();

    // Force umask to include read and execute for everyone, to make output
    // permissions predictable.
    umask(022);

    // argv[] passed to execve() must be a null-terminated array.
    opt.args.push_back(nullptr);

    if (execvp(opt.args[0], opt.args.data()) < 0) {
      DIE("execvp(%s, %p)", opt.args[0], opt.args.data());
    }
  } else {
    PRINT_DEBUG("child started with PID %d", global_child_pid);
  }
}

static int WaitForChild() {
  while (true) {
    // Wait for some process to exit. This includes reparented processes in our
    // PID namespace.
    int status;
    const pid_t pid = TEMP_FAILURE_RETRY(wait(&status));

    if (pid < 0) {
      // We don't expect any errors besides EINTR. In particular, ECHILD should
      // be impossible because we haven't yet seen global_child_pid exit.
      DIE("wait");
    }

    PRINT_DEBUG("wait returned pid=%d, status=0x%02x", pid, status);

    // If this isn't our child's PID, there's nothing further to do; we've
    // successfully reaped a zombie.
    if (pid != global_child_pid) {
      continue;
    }

    // If the child exited due to a signal, log that fact and exit with the same
    // status.
    if (WIFSIGNALED(status)) {
      const int signal = WTERMSIG(status);
      PRINT_DEBUG("child exited due to signal %d", WTERMSIG(status));
      return 128 + signal;
    }

    // Otherwise it must have exited normally.
    const int exit_code = WEXITSTATUS(status);
    PRINT_DEBUG("child exited normally with code %d", exit_code);
    return exit_code;
  }
}

int Pid1Main(void *sync_pipe_param) {
  PRINT_DEBUG("Pid1Main started");

  if (getpid() != 1) {
    DIE("Using PID namespaces, but we are not PID 1");
  }

  // Start with default signal handlers and an empty signal mask.
  ClearSignalMask();

  SetupSelfDestruction(reinterpret_cast<int *>(sync_pipe_param));

  // Sandbox ourselves.
  SetupMountNamespace();
  SetupUserNamespace();
  if (opt.fake_hostname) {
    SetupUtsNamespace();
  }
  MountFilesystems();
  MakeFilesystemMostlyReadOnly();
  MountProc();
  SetupNetworking();
  EnterSandbox();

  // Ignore terminal signals; we hand off the terminal to the child in
  // SpawnChild below.
  IgnoreSignal(SIGTTIN);
  IgnoreSignal(SIGTTOU);

  // Fork the child process.
  SpawnChild();

  // Forward requests to shut down gracefully to the child.
  InstallSignalHandler(SIGTERM, ForwardSignal);

  // Note that there's no need to kill any remaining descendant processes; they
  // are in our PID namespace and the kernel will send them SIGKILL
  // automatically once we exit.
  return WaitForChild();
}


text:
require 'bundler/setup'
require 'test/unit'
require 'pp'
require 'logger'
require 'mocha'
require 'shoulda'
require 'active_record'
require 'active_model'
require 'restclient'
require 'multitenancy'
require 'database_cleaner'

ROOT = File.expand_path("../..", __FILE__)
$:.unshift(ROOT + "/lib")

config = YAML::load(IO.read(File.join(File.dirname(__FILE__), 'database.yml')))
ActiveRecord::Base.logger = Logger.new(File.join(File.dirname(__FILE__), "debug.log"))
ActiveRecord::Base.configurations[:db1] = config[ENV['DB1'] || 'db1']
ActiveRecord::Base.configurations[:db2] = config[ENV['DB2'] || 'db2']
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[:db1])

class ActiveSupport::TestCase

  setup do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
    DatabaseCleaner.start
  end

  teardown do
    DatabaseCleaner.clean
  end
end


text:
package com.sicdlib.dto.entity;

import javax.persistence.*;
import java.sql.Timestamp;

/**
 * Created by init on 2017/5/24.
 */
@Entity
@Table(name = "bbs_china_comment", schema = "socialmind", catalog = "")
public class BbsChinaCommentEntity {
    private String commentId;
    private String postId;
    private String authorId;
    private String authorName;
    private Integer priseNum;
    private String dateTime;
    private String floor;
    private String content;
    private Timestamp timeStamp;
    private String id;

    @Basic
    @Column(name = "comment_id")
    public String getCommentId() {
        return commentId;
    }

    public void setCommentId(String commentId) {
        this.commentId = commentId;
    }

    @Basic
    @Column(name = "post_id")
    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    @Basic
    @Column(name = "author_id")
    public String getAuthorId() {
        return authorId;
    }

    public void setAuthorId(String authorId) {
        this.authorId = authorId;
    }

    @Basic
    @Column(name = "author_name")
    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    @Basic
    @Column(name = "prise_num")
    public Integer getPriseNum() {
        return priseNum;
    }

    public void setPriseNum(Integer priseNum) {
        this.priseNum = priseNum;
    }

    @Basic
    @Column(name = "date_time")
    public String getDateTime() {
        return dateTime;
    }

    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }

    @Basic
    @Column(name = "floor")
    public String getFloor() {
        return floor;
    }

    public void setFloor(String floor) {
        this.floor = floor;
    }

    @Basic
    @Column(name = "content")
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Basic
    @Column(name = "time_stamp")
    public Timestamp getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(Timestamp timeStamp) {
        this.timeStamp = timeStamp;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        BbsChinaCommentEntity that = (BbsChinaCommentEntity) o;

        if (commentId != null ? !commentId.equals(that.commentId) : that.commentId != null) return false;
        if (postId != null ? !postId.equals(that.postId) : that.postId != null) return false;
        if (authorId != null ? !authorId.equals(that.authorId) : that.authorId != null) return false;
        if (authorName != null ? !authorName.equals(that.authorName) : that.authorName != null) return false;
        if (priseNum != null ? !priseNum.equals(that.priseNum) : that.priseNum != null) return false;
        if (dateTime != null ? !dateTime.equals(that.dateTime) : that.dateTime != null) return false;
        if (floor != null ? !floor.equals(that.floor) : that.floor != null) return false;
        if (content != null ? !content.equals(that.content) : that.content != null) return false;
        if (timeStamp != null ? !timeStamp.equals(that.timeStamp) : that.timeStamp != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = commentId != null ? commentId.hashCode() : 0;
        result = 31 * result + (postId != null ? postId.hashCode() : 0);
        result = 31 * result + (authorId != null ? authorId.hashCode() : 0);
        result = 31 * result + (authorName != null ? authorName.hashCode() : 0);
        result = 31 * result + (priseNum != null ? priseNum.hashCode() : 0);
        result = 31 * result + (dateTime != null ? dateTime.hashCode() : 0);
        result = 31 * result + (floor != null ? floor.hashCode() : 0);
        result = 31 * result + (content != null ? content.hashCode() : 0);
        result = 31 * result + (timeStamp != null ? timeStamp.hashCode() : 0);
        return result;
    }

    @Id
    @Column(name = "id")
    public String getId() {
        return id;
    }

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


text:
define([
        '../ThirdParty/measureText',
        './Color',
        './defaultValue',
        './defined',
        './DeveloperError'
    ], function(
        measureText,
        Color,
        defaultValue,
        defined,
        DeveloperError) {
    'use strict';

    var imageSmoothingEnabledName;

    /**
     * Writes the given text into a new canvas.  The canvas will be sized to fit the text.
     * If text is blank, returns undefined.
     *
     * @param {String} text The text to write.
     * @param {Object} [options] Object with the following properties:
     * @param {String} [options.font='10px sans-serif'] The CSS font to use.
     * @param {String} [options.textBaseline='bottom'] The baseline of the text.
     * @param {Boolean} [options.fill=true] Whether to fill the text.
     * @param {Boolean} [options.stroke=false] Whether to stroke the text.
     * @param {Color} [options.fillColor=Color.WHITE] The fill color.
     * @param {Color} [options.strokeColor=Color.BLACK] The stroke color.
     * @param {Number} [options.strokeWidth=1] The stroke width.
     * @param {Color} [options.backgroundColor=Color.TRANSPARENT] The background color of the canvas.
     * @param {Number} [options.padding=0] The pixel size of the padding to add around the text.
     * @returns {Canvas} A new canvas with the given text drawn into it.  The dimensions object
     *                   from measureText will also be added to the returned canvas. If text is
     *                   blank, returns undefined.
     * @exports writeTextToCanvas
     */
    function writeTextToCanvas(text, options) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(text)) {
            throw new DeveloperError('text is required.');
        }
        //>>includeEnd('debug');
        if (text === '') {
            return undefined;
        }

        options = defaultValue(options, defaultValue.EMPTY_OBJECT);
        var font = defaultValue(options.font, '10px sans-serif');
        var stroke = defaultValue(options.stroke, false);
        var fill = defaultValue(options.fill, true);
        var strokeWidth = defaultValue(options.strokeWidth, 1);
        var backgroundColor = defaultValue(options.backgroundColor, Color.TRANSPARENT);
        var padding = defaultValue(options.padding, 0);
        var doublePadding = padding * 2.0;

        var canvas = document.createElement('canvas');
        canvas.width = 1;
        canvas.height = 1;
        canvas.style.font = font;

        var context2D = canvas.getContext('2d');

        if (!defined(imageSmoothingEnabledName)) {
            if (defined(context2D.imageSmoothingEnabled)) {
                imageSmoothingEnabledName = 'imageSmoothingEnabled';
            } else if (defined(context2D.mozImageSmoothingEnabled)) {
                imageSmoothingEnabledName = 'mozImageSmoothingEnabled';
            } else if (defined(context2D.webkitImageSmoothingEnabled)) {
                imageSmoothingEnabledName = 'webkitImageSmoothingEnabled';
            } else if (defined(context2D.msImageSmoothingEnabled)) {
                imageSmoothingEnabledName = 'msImageSmoothingEnabled';
            }
        }

        context2D.font = font;
        context2D.lineJoin = 'round';
        context2D.lineWidth = strokeWidth;
        context2D[imageSmoothingEnabledName] = false;

        // textBaseline needs to be set before the measureText call. It won't work otherwise.
        // It's magic.
        context2D.textBaseline = defaultValue(options.textBaseline, 'bottom');

        // in order for measureText to calculate style, the canvas has to be
        // (temporarily) added to the DOM.
        canvas.style.visibility = 'hidden';
        document.body.appendChild(canvas);

        var dimensions = measureText(context2D, text, stroke, fill);
        canvas.dimensions = dimensions;

        document.body.removeChild(canvas);
        canvas.style.visibility = '';

        //Some characters, such as the letter j, have a non-zero starting position.
        //This value is used for kerning later, but we need to take it into account
        //now in order to draw the text completely on the canvas
        var x = -dimensions.bounds.minx;

        //Expand the width to include the starting position.
        var width = Math.ceil(dimensions.width) + x + doublePadding;

        //While the height of the letter is correct, we need to adjust
        //where we start drawing it so that letters like j and y properly dip
        //below the line.
        var height = dimensions.height + doublePadding;
        var baseline = height - dimensions.ascent + doublePadding;
        var y = height - baseline + doublePadding;

        canvas.width = width;
        canvas.height = height;

        // Properties must be explicitly set again after changing width and height
        context2D.font = font;
        context2D.lineJoin = 'round';
        context2D.lineWidth = strokeWidth;
        context2D[imageSmoothingEnabledName] = false;

        // Draw background
        if (backgroundColor !== Color.TRANSPARENT) {
            context2D.fillStyle = backgroundColor.toCssColorString();
            context2D.fillRect(0, 0, canvas.width, canvas.height);
        }

        if (stroke) {
            var strokeColor = defaultValue(options.strokeColor, Color.BLACK);
            context2D.strokeStyle = strokeColor.toCssColorString();
            context2D.strokeText(text, x + padding, y);
        }

        if (fill) {
            var fillColor = defaultValue(options.fillColor, Color.WHITE);
            context2D.fillStyle = fillColor.toCssColorString();
            context2D.fillText(text, x + padding, y);
        }

        return canvas;
    }

    return writeTextToCanvas;
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. R. bot. Gdns Peradeniya 9: 319 (1925)

#### Original name
Sordaria caerulea Petch

### Remarks
null


text:
/**
 * CallToActionImage.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201406.video;

/**
 * Encapuslates a CallToAction thumbnail image. For {@code Set} operations
 * in VideoService,
 *             use {@code imageId}.
 */
public class CallToActionImage  implements java.io.Serializable {
    /* Raw image data.
     *
     *                 If id is set, then this field will be ignored.
     *                 If id is empty, then this field can be used to upload
     * an image.
     *
     *                 Note that this field is used only on uploads, and
     * will be empty on get() requests. */
    private byte[] data;

    /* The youtube url of the image, for preview purposes.
     *                 This field is read
     * only and will be ignored when sent to the API. */
    private java.lang.String imageUrl;

    public CallToActionImage() {
    }

    public CallToActionImage(
           byte[] data,
           java.lang.String imageUrl) {
           this.data = data;
           this.imageUrl = imageUrl;
    }

    /**
     * Gets the data value for this CallToActionImage.
     *
     * @return data   * Raw image data.
     *
     *                 If id is set, then this field will be ignored.
     *                 If id is empty, then this field can be used to upload
     * an image.
     *
     *                 Note that this field is used only on uploads, and
     * will be empty on get() requests.
     */
    public byte[] getData() {
        return data;
    }

    /**
     * Sets the data value for this CallToActionImage.
     *
     * @param data   * Raw image data.
     *
     *                 If id is set, then this field will be ignored.
     *                 If id is empty, then this field can be used to upload
     * an image.
     *
     *                 Note that this field is used only on uploads, and
     * will be empty on get() requests.
     */
    public void setData(byte[] data) {
        this.data = data;
    }

    /**
     * Gets the imageUrl value for this CallToActionImage.
     *
     * @return imageUrl   * The youtube url of the image, for preview purposes.
     *                 This field is read
     * only and will be ignored when sent to the API.
     */
    public java.lang.String getImageUrl() {
        return imageUrl;
    }

    /**
     * Sets the imageUrl value for this CallToActionImage.
     *
     * @param imageUrl   * The youtube url of the image, for preview purposes.
     *                 This field is read
     * only and will be ignored when sent to the API.
     */
    public void setImageUrl(java.lang.String imageUrl) {
        this.imageUrl = imageUrl;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof CallToActionImage)) return false;
        CallToActionImage other = (CallToActionImage) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.data==null && other.getData()==null) ||
             (this.data!=null &&
              java.util.Arrays.equals(this.data, other.getData()))) &&
            ((this.imageUrl==null && other.getImageUrl()==null) ||
             (this.imageUrl!=null &&
              this.imageUrl.equals(other.getImageUrl())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getData() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getData());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getData(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        if (getImageUrl() != null) {
            _hashCode += getImageUrl().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(CallToActionImage.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "CallToActionImage"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("data");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "data"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "base64Binary"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("imageUrl");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "imageUrl"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
package io.cattle.platform.json;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Extends the default the DefaultJsonMapper to be more compatible with GSON.
 * Specifically this means doing serialization based on fields and not getters.
 */
public class GsonStyleMapper extends JacksonJsonMapper {

    public GsonStyleMapper() {
        super();

        ObjectMapper mapper = getObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    }

}


text:
@class WDPEPrintTaskConfigurationSaveRequestedDeferral, WDPEPrintTaskConfigurationSaveRequest,
    WDPEPrintTaskConfigurationSaveRequestedEventArgs, WDPEPrintTaskConfiguration, WDPEPrintNotificationEventDetails,
    WDPEPrintExtensionContext;
@protocol WDPEIPrintTaskConfigurationSaveRequestedDeferral
, WDPEIPrintTaskConfigurationSaveRequest, WDPEIPrintTaskConfigurationSaveRequestedEventArgs, WDPEIPrintTaskConfiguration,
    WDPEIPrintNotificationEventDetails, WDPEIPrintExtensionContextStatic;

#include "WindowsFoundation.h"

// Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequestedDeferral
#ifndef __WDPEPrintTaskConfigurationSaveRequestedDeferral_DEFINED__
#define __WDPEPrintTaskConfigurationSaveRequestedDeferral_DEFINED__

WINRT_EXPORT
@interface WDPEPrintTaskConfigurationSaveRequestedDeferral : RTObject
- (void)complete;
@end

#endif // __WDPEPrintTaskConfigurationSaveRequestedDeferral_DEFINED__

// Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequest
#ifndef __WDPEPrintTaskConfigurationSaveRequest_DEFINED__
#define __WDPEPrintTaskConfigurationSaveRequest_DEFINED__

WINRT_EXPORT
@interface WDPEPrintTaskConfigurationSaveRequest : RTObject
@property (readonly) WFDateTime* deadline;
- (void)cancel;
- (void)save:(RTObject*)printerExtensionContext;
- (WDPEPrintTaskConfigurationSaveRequestedDeferral*)getDeferral;
@end

#endif // __WDPEPrintTaskConfigurationSaveRequest_DEFINED__

// Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequestedEventArgs
#ifndef __WDPEPrintTaskConfigurationSaveRequestedEventArgs_DEFINED__
#define __WDPEPrintTaskConfigurationSaveRequestedEventArgs_DEFINED__

WINRT_EXPORT
@interface WDPEPrintTaskConfigurationSaveRequestedEventArgs : RTObject
@property (readonly) WDPEPrintTaskConfigurationSaveRequest* request;
@end

#endif // __WDPEPrintTaskConfigurationSaveRequestedEventArgs_DEFINED__

// Windows.Devices.Printers.Extensions.PrintTaskConfiguration
#ifndef __WDPEPrintTaskConfiguration_DEFINED__
#define __WDPEPrintTaskConfiguration_DEFINED__

WINRT_EXPORT
@interface WDPEPrintTaskConfiguration : RTObject
@property (readonly) RTObject* printerExtensionContext;
- (EventRegistrationToken)addSaveRequestedEvent:(void (^)(WDPEPrintTaskConfiguration*,
                                                          WDPEPrintTaskConfigurationSaveRequestedEventArgs*))del;
- (void)removeSaveRequestedEvent:(EventRegistrationToken)tok;
@end

#endif // __WDPEPrintTaskConfiguration_DEFINED__

// Windows.Devices.Printers.Extensions.PrintNotificationEventDetails
#ifndef __WDPEPrintNotificationEventDetails_DEFINED__
#define __WDPEPrintNotificationEventDetails_DEFINED__

WINRT_EXPORT
@interface WDPEPrintNotificationEventDetails : RTObject
@property (copy) NSString* eventData;
@property (readonly) NSString* printerName;
@end

#endif // __WDPEPrintNotificationEventDetails_DEFINED__

// Windows.Devices.Printers.Extensions.PrintExtensionContext
#ifndef __WDPEPrintExtensionContext_DEFINED__
#define __WDPEPrintExtensionContext_DEFINED__

WINRT_EXPORT
@interface WDPEPrintExtensionContext : RTObject
+ (RTObject*)fromDeviceId:(NSString*)deviceId;
@end

#endif // __WDPEPrintExtensionContext_DEFINED__


text:
if [[ -a /etc/supervisor/conf.d/supervisord.conf ]]; then
  exit 0
fi

#supervisor
cat > /etc/supervisor/conf.d/supervisord.conf <<EOF
[supervisord]
nodaemon=false

[program:postfix]
command=/opt/postfix.sh

[program:rsyslog]
command=/usr/sbin/rsyslogd -n -c3
EOF

############
#  postfix
############
cat >> /opt/postfix.sh <<EOF
#!/bin/bash
service postfix start
busybox tail -F /var/log/mail.log
EOF
chmod +x /opt/postfix.sh
postconf -e myhostname=$mydestination
postconf -F '*/*/chroot = n'
postconf -e inet_protocols=ipv4
postconf -e message_size_limit=20480000
postconf -e 'home_mailbox=Maildir/'
postconf -e 'smtpd_banner=$myhostname Microsoft ESMTP MAIL Service ready'
postconf -e disable_vrfy_command=yes

postconf -e virtual_alias_domains=$mydestination
postconf -e virtual_alias_maps=hash:/etc/postfix/virtual
postconf -X mydestination

# catch-all
cat >> /etc/postfix/virtual <<EOF
@$mydestination mail@localhost
EOF
postmap /etc/postfix/virtual

# protective markings filter
# /etc/postfix/master.cf
postconf -M protective_markings/unix='protective_markings unix - n n - - pipe flags=Rq user=mail null_sender= argv=/opt/filter.sh -f ${sender} -- ${recipient}'

############
# SASL SUPPORT FOR CLIENTS
# The following options set parameters needed by Postfix to enable
# Cyrus-SASL support for authentication of mail clients.
############
# /etc/postfix/main.cf
postconf -e smtpd_sasl_auth_enable=no
postconf -e smtpd_recipient_restrictions=permit_sasl_authenticated,reject_unauth_destination
# smtpd.conf
cat >> /etc/postfix/sasl/smtpd.conf <<EOF
pwcheck_method: auxprop
auxprop_plugin: sasldb
mech_list: PLAIN LOGIN CRAM-MD5 DIGEST-MD5 NTLM
EOF
# sasldb2
echo $smtp_user | tr , \\n > /tmp/passwd
while IFS=':' read -r _user _pwd; do
  echo $_pwd | saslpasswd2 -p -c -u $maildomain $_user
done < /tmp/passwd
chown postfix.sasl /etc/sasldb2

# swiftmail
postconf -M swiftmail/unix='swiftmail unix - n n - - pipe flags=Rq user=mail null_sender= argv=/opt/swiftmail.sh -f ${sender} -- ${recipient}'
postconf -M smtp/inet="smtp   inet   n   -   n   -   -   smtpd"
postconf -P "smtp/inet/content_filter=swiftmail:dummy"

############
# Enable TLS
############
if [[ -n "$(find /etc/postfix/certs -iname *.pem)" ]]; then
  # /etc/postfix/main.cf
  postconf -e smtpd_tls_cert_file=$(find /etc/postfix/certs -iname *.pem)
  postconf -e smtpd_tls_key_file=$(find /etc/postfix/certs -iname *.pem)
  # /etc/postfix/master.cf
  postconf -M submission/inet="submission   inet   n   -   n   -   -   smtpd"
  postconf -P "submission/inet/syslog_name=postfix/submission"
  postconf -P "submission/inet/smtpd_tls_security_level=encrypt"
  postconf -P "submission/inet/smtpd_sasl_auth_enable=yes"
  postconf -P "submission/inet/milter_macro_daemon_name=ORIGINATING"
  postconf -P "submission/inet/smtpd_recipient_restrictions=permit_sasl_authenticated,reject_unauth_destination"
  postconf -P "submission/inet/content_filter=protective_markings:dummy"
  postconf -e smtpd_tls_ciphers=high
  postconf -e smtpd_tls_exclude_ciphers=aNULL,MD5
  postconf -e smtpd_tls_security_level=may
  # Preferred syntax with Postfix ≥ 2.5:
  postconf -e smtpd_tls_protocols=!SSLv2,!SSLv3
fi
# client TLS
postconf -e smtp_tls_security_level=may
postconf -e smtp_tls_ciphers=high
postconf -e smtp_tls_exclude_ciphers=aNULL,MD5
postconf -e smtp_tls_protocols=!SSLv2,!SSLv3

#############
#  opendkim
#############

if [[ -z "$(find /etc/opendkim/domainkeys -iname *.private)" ]]; then
  exit 0
fi
cat >> /etc/supervisor/conf.d/supervisord.conf <<EOF

[program:opendkim]
command=/usr/sbin/opendkim -f
EOF
# /etc/postfix/main.cf
postconf -e milter_protocol=2
postconf -e milter_default_action=accept
postconf -e smtpd_milters=inet:localhost:12301
postconf -e non_smtpd_milters=inet:localhost:12301

cat >> /etc/opendkim.conf <<EOF
AutoRestart             Yes
AutoRestartRate         10/1h
UMask                   002
Syslog                  yes
SyslogSuccess           Yes
LogWhy                  Yes

Canonicalization        relaxed/simple

ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts
InternalHosts           refile:/etc/opendkim/TrustedHosts
KeyTable                refile:/etc/opendkim/KeyTable
SigningTable            refile:/etc/opendkim/SigningTable

Mode                    sv
PidFile                 /var/run/opendkim/opendkim.pid
SignatureAlgorithm      rsa-sha256

UserID                  opendkim:opendkim

Socket                  inet:12301@localhost
EOF
cat >> /etc/default/opendkim <<EOF
SOCKET="inet:12301@localhost"
EOF

cat >> /etc/opendkim/TrustedHosts <<EOF
127.0.0.1
localhost
*.$maildomain
EOF
cat >> /etc/opendkim/KeyTable <<EOF
bridge._domainkey.$maildomain $maildomain:bridge:$(find /etc/opendkim/domainkeys -iname *.private)
EOF
cat >> /etc/opendkim/SigningTable <<EOF
*@$maildomain bridge._domainkey.$maildomain
EOF
chown opendkim:opendkim $(find /etc/opendkim/domainkeys -iname *.private) /etc/opendkim/domainkeys


text:
class Door
  def self.open
    Net::HTTP.get_response(URI.parse (ENV['DOOR_URL']))
  end
end


text:
package trees;

import java.util.*;

/**
 * Created by Jun on 11/13/2014.
 */
public class BinarySearchTree <T extends Comparable<T>> {
    T data;
    BinarySearchTree left;
    BinarySearchTree right;

    public BinarySearchTree(){}
    public BinarySearchTree(T t){
        this.data = t;
        left = right = null;
    }

    public BinarySearchTree(BinarySearchTree<T> tree){
        if(null == tree){
            return;
        }
        this.data = tree.data;
        if(tree.left != null){
            this.left = new BinarySearchTree(tree.left);
        }else {
            this.left = null;
        }
        if(tree.right != null){
            this.right = new BinarySearchTree(tree.right);
        }else {
            this.right = null;
        }
//        this.right = new BinarySearchTree(tree.right);
    }
    public BinarySearchTree(Collection<T> col){
        Iterator<T> it = col.iterator();
        while (it.hasNext()){
            this.add(it.next());
        }

    }

    public BinarySearchTree add(T t){
        if(this.data == null){
            this.data = t;
        }else if(this.data.compareTo(t)>=0){//if the new node is small, put it into the left subtree
            if(this.left != null){
                this.left.add(t);
            }else {
                this.left = new BinarySearchTree(t);
            }

        }else {                            //if the new node is big, put it into the right subtree
            if(this.right != null){
                this.right.add(t);
            }else {
                this.right = new BinarySearchTree(t);
            }
        }
        return this;
    }

    public String toString(){
        int hight = 0;
        ArrayList<BinarySearchTree> arr = new ArrayList<BinarySearchTree>();
        String tree = this.data.toString();
        arr.add(this.left);
        arr.add(this.right);
        while (!arr.isEmpty()){
            if(arr.get(0).left != null) {
                arr.add(arr.get(0).left);
            }
            if(arr.get(0).right != null) {
                arr.add(arr.get(0).right);
            }
            tree = tree + " " + arr.get(0).data.toString();
            arr.remove(0);
        }
        return tree;
    }
}


text:
package org.apache.aries.application.runtime.itests;

import static org.apache.aries.itest.ExtraOptions.mavenBundle;
import static org.apache.aries.itest.ExtraOptions.paxLogging;
import static org.apache.aries.itest.ExtraOptions.testOptions;
import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.aries.application.management.AriesApplication;
import org.apache.aries.application.management.AriesApplicationContext;
import org.apache.aries.application.management.AriesApplicationManager;
import org.apache.aries.itest.AbstractIntegrationTest;
import org.apache.aries.sample.HelloWorld;
import org.apache.aries.unittest.fixture.ArchiveFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture;
import org.apache.aries.util.filesystem.FileSystem;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.container.def.PaxRunnerOptions;
import org.ops4j.pax.exam.junit.MavenConfiguredJUnit4TestRunner;

@RunWith(MavenConfiguredJUnit4TestRunner.class)
public class BasicNoOpResolverTest extends AbstractIntegrationTest {

  /* Use @Before not @BeforeClass so as to ensure that these resources
   * are created in the paxweb temp directory, and not in the svn tree
   */
  static boolean createdApplications = false;
  @Before
  public static void createApplications() throws Exception {
    if (createdApplications) {
      return;
    }
    ZipFixture testEba = ArchiveFixture.newZip()
      .jar("sample.jar")
        .manifest().symbolicName("org.apache.aries.sample")
          .attribute("Bundle-Version", "1.0.0")
          .attribute("Import-Package", "org.apache.aries.sample")
          .end()
        .binary("org/apache/aries/sample/impl/HelloWorldImpl.class",
            BasicAppManagerTest.class.getClassLoader().getResourceAsStream("org/apache/aries/sample/impl/HelloWorldImpl.class"))
        .binary("OSGI-INF/blueprint/sample-blueprint.xml",
            BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/sample-blueprint.xml"))
        .end();

    FileOutputStream fout = new FileOutputStream("test.eba");
    testEba.writeOut(fout);
    fout.close();

    ZipFixture testEba2 = testEba.binary("META-INF/APPLICATION.MF",
        BasicAppManagerTest.class.getClassLoader().getResourceAsStream("basic/APPLICATION.MF"))
        .end();
    fout = new FileOutputStream("test2.eba");
    testEba2.writeOut(fout);
    fout.close();
    createdApplications = true;
  }

  @Test
  public void testAppWithoutApplicationManifest() throws Exception {

    AriesApplicationManager manager = context().getService(AriesApplicationManager.class);
    AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test.eba")));

    // application name should be equal to eba name since application.mf is not provided
    assertEquals("test.eba", app.getApplicationMetadata().getApplicationName());
    AriesApplicationContext ctx = manager.install(app);
    ctx.start();

    HelloWorld hw = context().getService(HelloWorld.class);
    String result = hw.getMessage();
    assertEquals (result, "hello world");

    ctx.stop();
    manager.uninstall(ctx);
  }

  @Test
  public void testAppWithApplicationManifest() throws Exception {
    AriesApplicationManager manager = context().getService(AriesApplicationManager.class);
    AriesApplication app = manager.createApplication(FileSystem.getFSRoot(new File("test2.eba")));

    // application name should equal to whatever Application name provided in the application.mf
    assertEquals("test application 2", app.getApplicationMetadata().getApplicationName());

    AriesApplicationContext ctx = manager.install(app);
    ctx.start();

    HelloWorld hw = context().getService(HelloWorld.class);
    String result = hw.getMessage();
    assertEquals (result, "hello world");

    ctx.stop();
    manager.uninstall(ctx);
  }

  private static Option[] generalConfiguration() {
    return testOptions(
        paxLogging("DEBUG"),

        // Bundles
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.api"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.management"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.noop"),
        mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces"),
        mavenBundle("org.apache.aries", "org.apache.aries.util"),
        mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint"),
        mavenBundle("org.ow2.asm", "asm-all"),
        mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy"),
        mavenBundle("org.osgi", "org.osgi.compendium"));

        /* For debugging, uncomment the next two lines
        vmOption ("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006"),
        waitForFrameworkStartup(),

        and add these imports:
        import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartup;
        import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
        */

  }

  @org.ops4j.pax.exam.junit.Configuration
  public static Option[] configuration()
  {
	  return testOptions(
			  generalConfiguration(),
			  PaxRunnerOptions.rawPaxRunnerOption("config", "classpath:ss-runner.properties")
	          );
  }

}


text:
<?php

namespace App\Http\Controllers;

use App\Event;
use App\Lesson;
use Illuminate\Http\Request;

use App\Http\Requests;

class LessonController extends Controller
{
    public function create(Request $request)
    {
        Lesson::create($request->all());
    }

    public function get(Lesson $lesson)
    {
        return json_encode($lesson);
    }

    public function update(Request $request)
    {
        $lesson = Lesson::findOrFail($request['id']);
        $lesson->update($request->all());
    }

    public function delete(Request $request)
    {
        $lesson = Lesson::findOrFail($request['id']);
        $lesson->delete();

    }
}


text:
using Microsoft.AspNetCore.Mvc;

namespace Cofoundry.Web.Admin;

public class StandardAngularModuleController : BaseAdminMvcController
{
    public ActionResult Index()
    {

        var vm = new StandardAngularModuleViewModel();
        vm.RouteLibrary = RouteData.DataTokens["RouteLibrary"] as AngularModuleRouteLibrary;
        if (vm.RouteLibrary == null) throw new Exception("The 'RouteLibrary' route data token should not be null.");

        vm.Title = RouteData.DataTokens["ModuleTitle"] as string;
        if (vm.RouteLibrary == null) throw new Exception("The 'ModuleTitle' route data token should not be null.");

        return View("~/Framework/Angular/StandardAngularModules/Routes/Index.cshtml", vm);
    }
}


text:
RSpec.describe RuboCop::Cop::Lint::ParenthesesAsGroupedExpression do
  subject(:cop) { described_class.new }

  it 'registers an offense for method call with space before the ' \
     'parenthesis' do
    inspect_source('a.func (x)')
    expect(cop.offenses.size).to eq(1)
  end

  it 'registers an offense for predicate method call with space ' \
     'before the parenthesis' do
    inspect_source('is? (x)')
    expect(cop.offenses.size).to eq(1)
  end

  it 'registers an offense for math expression' do
    expect_offense(<<-RUBY.strip_indent)
      puts (2 + 3) * 4
          ^ `(...)` interpreted as grouped expression.
    RUBY
  end

  it 'accepts a method call without arguments' do
    expect_no_offenses('func')
  end

  it 'accepts a method call with arguments but no parentheses' do
    expect_no_offenses('puts x')
  end

  it 'accepts a chain of method calls' do
    expect_no_offenses(<<-RUBY.strip_indent)
      a.b
      a.b 1
      a.b(1)
    RUBY
  end

  it 'accepts method with parens as arg to method without' do
    expect_no_offenses('a b(c)')
  end

  it 'accepts an operator call with argument in parentheses' do
    expect_no_offenses(<<-RUBY.strip_indent)
      a % (b + c)
      a.b = (c == d)
    RUBY
  end

  it 'accepts a space inside opening paren followed by left paren' do
    expect_no_offenses('a( (b) )')
  end

  it "doesn't register an offense for a call with multiple arguments" do
    # there is no ambiguity here
    expect_no_offenses('assert_equal (0..1.9), acceleration.domain')
  end
end


text:
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using osu.Framework.IO.Stores;

namespace osu.Framework.Graphics.Textures
{
    public class PrefixTextureStore : TextureStore
    {
        string Prefix;

        public PrefixTextureStore(string prefix, IResourceStore<RawTexture> stores)
            : base(stores)
        {
            Prefix = prefix;
        }

        public override Texture Get(string name)
        {
            return base.Get($@"{Prefix}-{name}");
        }
    }
}


text:
#ifndef _USES_THEORY_H_
#define _USES_THEORY_H_

#include"ast.h"

/**
   \brief Return true if the given expression contains a symbol of the given theory.
*/
bool uses_theory(expr * n, family_id fid);

/**
    \brief Return true if the given expression contains a symbol of the given theory.
    Only the expressions not marked as visited are checked. The set visited is updated
    with the new checked expressions.
*/
bool uses_theory(expr * n, family_id fid, expr_mark & visited);

#endif /* _USES_THEORY_H_ */


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Variant` struct in crate `serde_derive_internals`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Variant">

    <title>serde_derive_internals::attr::Variant - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

serde_derive_internals::<wbr>attr

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Struct serde_derive_internals::<wbr>attr::<wbr>Variant

                       [−]

               [src]

pub struct Variant { /* fields omitted */ }

Represents variant attribute information

Methods

impl Variant

[src]

fn from_ast(cx: &Ctxt, variant: &Variant) -> Self

fn name(&self) -> &Name

fn rename_by_rule(&mut self, rule: &RenameRule)

fn rename_all(&self) -> &RenameRule

fn skip_deserializing(&self) -> bool

fn skip_serializing(&self) -> bool

fn other(&self) -> bool

Trait Implementations

impl Debug for Variant

[src]

fn fmt(&self, __arg_0: &mut Formatter) -> Result

Formats the value using the given formatter.

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
extern "C" {
#endif
//------------------------------------------------------------------------------
// Custom Profile
//
// Author: Jacob Portukalian
//
// Sky Wave Design, LLC
// 7083 Hollywood Blvd
// Los Angeles, CA 90028
// jacob@skywavedesign.com
// www.skywavedesign.com
//
// Sky Wave Design, LLC is a consulting firm which provides engineering design
// services.  We provide turnkey electronics design, from schematics and
// circuit designs to PCB layouts, mechanical enclosures, firmware, software,
// and volume manufacturing.
//
// This code is heavily modified from examples provided by Nordic Semiconductor.
//
// The custom profile module is more than just a profile, it also is responisble
// for setting up the stack.  It also serves as the custom profile, as it loads
// the custom service as well as the adopted services for device information and
// battery.
//
// This code gives you an example of how to set up your own profile with your
// own custom service, however the custom service itself is defined in a
// separate module.
//------------------------------------------------------------------------------
// Bluetooth Configuration Defines
#define IS_SRVC_CHANGED_CHARACT_PRESENT  1

#define DEVICE_NAME                     "Template App Build 0001"
#define MANUFACTURER_NAME               "ACME BLE Design"

#define MODEL_NUMBER					"PCA00028"
#define SERIAL_NUMBER					"0000-0001"
#define HARDWARE_REVISION				"Rev 1"
#define FIRMWARE_REVISION				"0.0.1 Build 0003"

#define APP_ADV_INTERVAL                 500
#define APP_ADV_TIMEOUT_IN_SECONDS       180

#define MIN_CONN_INTERVAL                MSEC_TO_UNITS(20, UNIT_1_25_MS)
#define MAX_CONN_INTERVAL                MSEC_TO_UNITS(40, UNIT_1_25_MS)
#define SLAVE_LATENCY                    0
#define CONN_SUP_TIMEOUT                 MSEC_TO_UNITS(4000, UNIT_10_MS)

#define FIRST_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(500, 0)
#define NEXT_CONN_PARAMS_UPDATE_DELAY    APP_TIMER_TICKS(30000, 0)
#define MAX_CONN_PARAMS_UPDATE_COUNT     3

#define SEC_PARAM_BOND                   1
#define SEC_PARAM_MITM                   0
#define SEC_PARAM_IO_CAPABILITIES        BLE_GAP_IO_CAPS_NONE
#define SEC_PARAM_OOB                    0
#define SEC_PARAM_MIN_KEY_SIZE           7
#define SEC_PARAM_MAX_KEY_SIZE           16

#define DEAD_BEEF                        0xDEADBEEF
#ifdef BLE_DFU_APP_SUPPORT
#define DFU_REV_MAJOR                    0x00
#define DFU_REV_MINOR                    0x01
#define DFU_REVISION                     ((DFU_REV_MAJOR << 8) | DFU_REV_MINOR)
#define APP_SERVICE_HANDLE_START         0x000C
#define BLE_HANDLE_MAX                   0xFFFF

STATIC_ASSERT(IS_SRVC_CHANGED_CHARACT_PRESENT);
#endif // BLE_DFU_APP_SUPPORT
//------------------------------------------------------------------------------
// Stack Init initializes the stack.
void CP_StackInit();
//------------------------------------------------------------------------------
void CP_Init();
//------------------------------------------------------------------------------
void CP_AdvertisingStart();
//------------------------------------------------------------------------------
void CP_BatteryServiceUpdate(uint8_t level);
//------------------------------------------------------------------------------
void CP_SetStatus(uint8_t);
//------------------------------------------------------------------------------
#if defined(__cplusplus)
}
#endif

#endif