text:
#assumes you have gnu sed, osx sed might need slight syntax changeo
#c.f. http://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files

#written by shen-noether monero research labs

import os #for copying and sed etc.
import glob #for copy files
import textwrap #for comments etc

print("make sure you have cat and grep installed")
print("also assumes gnu sed syntax, c.f. :http://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files")
print("I believe osx may have slightly different version of sed")
print("maybe someone smart can replace the sed with perl..")

a = ""

license = textwrap.dedent("""\
    // Copyright (c) 2014-2017, The Monero Project
    //
    // All rights reserved.
    //
    // Redistribution and use in source and binary forms, with or without modification, are
    // permitted provided that the following conditions are met:
    //
    // 1. Redistributions of source code must retain the above copyright notice, this list of
    //    conditions and the following disclaimer.
    //
    // 2. Redistributions in binary form must reproduce the above copyright notice, this list
    //    of conditions and the following disclaimer in the documentation and/or other
    //    materials provided with the distribution.
    //
    // 3. Neither the name of the copyright holder nor the names of its contributors may be
    //    used to endorse or promote products derived from this software without specific
    //    prior written permission.
    //
    // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
    // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
    // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
    // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    //
    // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
    """)

crypto_ops_includes = textwrap.dedent("""\
    #include <assert.h>
    #include <stdint.h>

    #include "warnings.h"
    #include "crypto-ops.h"

    DISABLE_VS_WARNINGS(4146 4244)
    """)

predeclarations = textwrap.dedent("""\
    /* Predeclarations */

    static void fe_mul(fe, const fe, const fe);
    static void fe_sq(fe, const fe);
    static void fe_tobytes(unsigned char *, const fe);
    static int fe_isnonzero(const fe);
    static void ge_madd(ge_p1p1 *, const ge_p3 *, const ge_precomp *);
    static void ge_msub(ge_p1p1 *, const ge_p3 *, const ge_precomp *);
    static void ge_p2_0(ge_p2 *);
    static void ge_p3_dbl(ge_p1p1 *, const ge_p3 *);
    static void ge_sub(ge_p1p1 *, const ge_p3 *, const ge_cached *);
    static void fe_divpowm1(fe, const fe, const fe);
    """)

fe_comments = textwrap.dedent("""\
    /*
    fe means field element.
    Here the field is \Z/(2^255-19).
    An element t, entries t[0]...t[9], represents the integer
    t[0]+2^26 t[1]+2^51 t[2]+2^77 t[3]+2^102 t[4]+...+2^230 t[9].
    Bounds on each t[i] vary depending on context.
    */
    """)

sc_comments = textwrap.dedent("""\
    /*
     *
     * sc code
     *
     *
    The set of scalars is \Z/l
    where l = 2^252 + 27742317777372353535851937790883648493.

    This is the order of the curve ed25519.
    The point is that if a is a scalar and P is a point,
    and b is congruent to a mod l, then aP = bP.
    Thus, reducing mod l can possibly give you a smaller scalar,
    so your elliptic curve operations take less time
    */
    """)

ge_comments = textwrap.dedent("""\
    /*
     *
     * ge code
     *
     *
    ge means group element.

    Here the group is the set of pairs (x,y) of field elements (see fe.h)
    satisfying -x^2 + y^2 = 1 + d x^2y^2
    where d = -121665/121666.

    Representations:
      ge_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z
      ge_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT
      ge_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T
      ge_precomp (Duif): (y+x,y-x,2dxy)
    */
    """)

xmr_comments = textwrap.dedent("""\
    /*
     *
     * xmr specific code
     *
     *
    This code is from the original CryptoNote.
    Some additional functions were needed to compute ring signatures
    which are not needed for signing.
    Note that sc_sub and sc_mulsub have been given their own file
    since these have been rewritten

    */
    """)

def qhasmToC(fi, header, out):
    #replaces mentiones of "header" in "fi" with output in "out"
    #also removes qhasm comments
    out1 = out+".tmp"
    rem_qhasm = " |grep -v 'qhasm' |grep -v ' asm'"
    com = "sed -e '/#include \""+header+"\"/ {' -e 'r "+header+"' -e 'd' -e '}' "+fi+rem_qhasm+" > "+out1
    com2 = "awk 'NF' "+out1+" > "+out
    print(com)
    os.system(com)
    print(com2)
    os.system(com2)
    os.remove(out1) #temporary

while (a != "m") and (a != "m") and (a != "c"):
    a = raw_input("Make / Clean/ Quit    m / c / q?")

if a == "m":
    print("making crypto-ops.c and crypto-ops.h")

    #ref10 header files

    #ref10 c files

    #fe things
    #still need to do d2, d, sqrtm1
    print("making fe.c")
    print(fe_comments)
    fe = glob.glob("fe*.c")
    for g in fe:
        os.system("cp "+g+" "+g.replace("fe", "fe.monero."))
    qhasmToC("fe_pow22523.c", "pow22523.h", "fe.monero._pow22523.c")
    qhasmToC("fe_invert.c", "pow225521.h", "fe.monero._invert.c")
    os.system("rm fe.monero._isnonzero.c") #since it's modified, it's in xmrSpecificOld
    os.system("cat fe.monero.*.c | grep -v '^#include' > fe.monero.c")

    #sc things
    print("\nmaking sc.c")
    print(sc_comments)
    #so you don't get multiple "loads"
    os.system("tail -n +24 sc_reduce.c > sc.monero._reduce.c") #also good on linux
    os.system("tail -n +24 sc_muladd.c > sc.monero._muladd.c")
    os.system("tail -n +31 sc_sub.xmr.c > sc.monero._sub.xmr.c") #careful with the tails if you change these files!
    os.system("cat sc.monero.*.c | grep -v '^#include' > sc.monero.c")

    #ge stuff
    print("making ge.c")
    ge = glob.glob("ge*.c")
    for g in ge:
        os.system("cp "+g+" "+g.replace("ge", "ge.monero."))
    print(ge_comments)
    #need to substitute the below lines for their .h files in the appropriate places
    qhasmToC("ge_add.c", "ge_add.h", "ge.monero._add.c")
    qhasmToC("ge_madd.c", "ge_madd.h", "ge.monero._madd.c")
    qhasmToC("ge_sub.c", "ge_sub.h", "ge.monero._sub.c")
    qhasmToC("ge_msub.c", "ge_msub.h", "ge.monero._msub.c")
    qhasmToC("ge_p2_dbl.c", "ge_p2_dbl.h", "ge.monero._p2_dbl.c")
    qhasmToC("ge_frombytes.c", "d.h", "ge.monero._frombytes.c")
    qhasmToC("ge.monero._frombytes.c", "sqrtm1.h", "ge.monero._frombytes.c")
    qhasmToC("ge_p3_to_cached.c", "d2.h", "ge.monero._p3_to_cached.c")

    #also ge_double_scalarmult needs base2.h for ge_precomp Bi
    #note, base2.h is a large file!
    #also in ge_scalarmult_base ge_precomp base needs base.h included

    qhasmToC("ge_double_scalarmult.c", "base2.h", "ge.monero._double_scalarmult.c")
    qhasmToC("ge_scalarmult_base.c", "base.h", "ge.monero._scalarmult_base.c")
    #qhasmToC("ge.monero._scalarmult_base.c", "base.h", "ge.monero._scalarmult_base.c")
    os.system("sed -i 's/ cmov/ ge_precomp_cmov/g' ge.monero._scalarmult_base.c")
    os.system("cat ge.monero.*.c | grep -v '^#include' > ge.monero.c")

    print("making crypto-ops.c")

    #sqrtm1 things

    #comments
    with open("fe.monero.comments", "w") as text_file:
            text_file.write(fe_comments)
    with open("ge.monero.comments", "w") as text_file:
            text_file.write(ge_comments)
    with open("sc.monero.comments", "w") as text_file:
            text_file.write(sc_comments)
    with open("xmr.monero.comments", "w") as text_file:
            text_file.write(xmr_comments)
    with open("xmr.monero.predeclarations", "w") as text_file:
            text_file.write(predeclarations)

    #license
    with open("monero.license", "w") as text_file:
            text_file.write(license)

    #crypto-ops.c includes
    with open("crypto-ops.monero.includes", "w") as text_file:
        text_file.write(crypto_ops_includes)

    #note you may have duplicates of load_3, load_4 and possibly some other functions ...
    os.system("cat monero.license crypto-ops.monero.includes xmr.monero.predeclarations fe.monero.comments fe.monero.c sc.monero.comments sc.monero.c ge.monero.comments ge.monero.c xmr.monero.comments xmrSpecificOld.c > crypto-ops.c")

    #monero specific header files
    #print("making crypto-ops-tmp.h")
    #os.system("cat fe.h ge.h sc.h |grep -v crypto_sign_ed25519 |grep -v fe.h > crypto-ops-tmp.h")
    #we'll just use the old header crypto-ops.h

    #replace crypto_ints
    os.system("sed -i 's/crypto_int32/int32_t/g' crypto-ops.c")
    os.system("sed -i 's/crypto_int64/int64_t/g' crypto-ops.c")
    os.system("sed -i 's/crypto_uint32/uint32_t/g' crypto-ops.c")
    os.system("sed -i 's/crypto_uint64/uint64_t/g' crypto-ops.c")

    #cleaning up
    os.system("rm *monero*")

    #monero specific c files
if a == "c":
    #turn the directory back into ref10
    os.system("rm *monero*")
    os.system("rm crypto-ops.c")


text:
using namespace cocos2d;

namespace SpaceFighter
{
	class Background : public ParallaxElement
	{
	public:
		Background();
		~Background();

		// param scrollSpeed: pixel/sec
		void Background::Update(const float dT, const float scrollSpeed, const Vec2& playerPos);

		virtual float GetParallaxWidth() const override;

	private:
		Sprite* _TopSprite;
		Sprite* _BotSprite;

		Sprite* _CreateSprite(const Vec2& spritePos);
	};
}

#endif

redpajama_set_name: RedPajamaGithub


text:
import os
import re

# DJANGO IMPORTS
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils.six.moves import input

# FILEBROWSER IMPORTS
from filebrowser.settings import EXTENSION_LIST, EXCLUDE, DIRECTORY, VERSIONS, EXTENSIONS
from filebrowser.base import FileListing, FileObject

filter_re = []
for exp in EXCLUDE:
    filter_re.append(re.compile(exp))
for k, v in VERSIONS.items():
    exp = (r'_%s(%s)') % (k, '|'.join(EXTENSION_LIST))
    filter_re.append(re.compile(exp))

class Command(BaseCommand):
    args = '<media_path>'
    help = "(Re)Generate image versions."

    def handle(self, *args, **options):
        media_path = ""

        if len(args):
            media_path = args[0]
            path = media_path
        else:
            path = DIRECTORY

        if not os.path.isdir(os.path.join(settings.MEDIA_ROOT, path)):
            raise CommandError('<media_path> must be a directory in MEDIA_ROOT (If you don\'t add a media_path the default path is DIRECTORY).\n"%s" is no directory.' % path)

        # get version name
        while 1:
            self.stdout.write('\nSelect a version you want to generate:\n')
            for version in VERSIONS:
                self.stdout.write(' * %s\n' % version)

            version_name = input('(leave blank to generate all versions): ')

            if version_name == "":
                selected_version = None
                break
            else:
                try:
                    tmp = VERSIONS[version_name]
                    selected_version = version_name
                    break
                except:
                    self.stderr.write('Error: Version "%s" doesn\'t exist.\n' % version_name)
                    version_name = None
                    continue

        # filelisting
        filelisting = FileListing(path, filter_func=self.filter_images)  # FIXME filterfunc: no hidden files, exclude list, no versions, just images!
        for fileobject in filelisting.files_walk_filtered():
            if fileobject.filetype == "Image":
                if selected_version:
                    self.stdout.write('generating version "%s" for: %s\n' % (selected_version, fileobject.path))
                    versionobject = fileobject.version_generate(selected_version)  # FIXME force?
                else:
                    self.stdout.write('generating all versions for: %s\n' % fileobject.path)
                    for version in VERSIONS:
                        versionobject = fileobject.version_generate(selected_version)  # FIXME force?

        # # walkt throu the filebrowser directory
        # # for all/new files (except file versions itself and excludes)
        # for dirpath,dirnames,filenames in os.walk(path, followlinks=True):
        #     rel_dir = os.path.relpath(dirpath, os.path.realpath(settings.MEDIA_ROOT))
        #     for filename in filenames:
        #         filtered = False
        #         # no "hidden" files (stating with ".")
        #         if filename.startswith('.'):
        #             continue
        #         # check the exclude list
        #         for re_prefix in filter_re:
        #             if re_prefix.search(filename):
        #                 filtered = True
        #         if filtered:
        #             continue
        #         (tmp, extension) = os.path.splitext(filename)
        #         if extension in EXTENSIONS["Image"]:
        #             self.createVersions(os.path.join(rel_dir, filename), selected_version)

    def filter_images(self, item):
        filtered = item.filename.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(item.filename):
                filtered = True
        if filtered:
            return False
        return True


text:
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/prow/kube"
	"k8s.io/test-infra/prow/pjutil"
	"k8s.io/test-infra/prow/pod-utils/clone"
)

type gitRefs struct {
	gitRefs []kube.Refs
}

func (r *gitRefs) String() string {
	representation := bytes.Buffer{}
	for _, ref := range r.gitRefs {
		fmt.Fprintf(&representation, "%s,%s=%s", ref.Org, ref.Repo, ref.String())
	}
	return representation.String()
}

// Set parses out a kube.Refs from the user string.
// The following example shows all possible fields:
//   org,repo=base-ref:base-sha[,pull-number:pull-sha]...
// For the base ref and every pull number, the SHAs
// are optional and any number of them may be set or
// unset.
func (r *gitRefs) Set(value string) error {
	gitRef, err := clone.ParseRefs(value)
	if err != nil {
		return err
	}
	r.gitRefs = append(r.gitRefs, gitRef)
	return nil
}

var (
	srcRoot = flag.String("src-root", "", "Where to root source checkouts")
	log     = flag.String("log", "", "Where to write logs")
)

func main() {
	var gitRefs gitRefs
	flag.Var(&gitRefs, "repo", "Mapping of Git URI to refs to check out, can be provided more than once")
	flag.Parse()

	if *srcRoot == "" {
		logrus.Fatal("No source root specified")
	}

	if *log == "" {
		logrus.Fatal("No log file specified")
	}

	jobRefs, err := pjutil.ResolveSpecFromEnv()
	if err != nil {
		logrus.WithError(err).Fatal("Could not determine job refs")
	}

	results := []clone.Record{
		clone.Run(jobRefs.Refs, *srcRoot),
	}
	for _, gitRef := range gitRefs.gitRefs {
		results = append(results, clone.Run(gitRef, *srcRoot))
	}

	logData, err := json.Marshal(results)
	if err != nil {
		logrus.WithError(err).Fatal("Failed to marshal clone records")
	} else {
		if err := ioutil.WriteFile(*log, logData, 0755); err != nil {
			logrus.WithError(err).Fatal("Failed to write clone records")
		}
	}
}


text:
package com.amazonaws.services.connect.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.connect.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * UpdateTaskTemplateRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateTaskTemplateRequestMarshaller {

    private static final MarshallingInfo<String> TASKTEMPLATEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PATH).marshallLocationName("TaskTemplateId").build();
    private static final MarshallingInfo<String> INSTANCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
            .marshallLocationName("InstanceId").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
    private static final MarshallingInfo<String> CONTACTFLOWID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ContactFlowId").build();
    private static final MarshallingInfo<StructuredPojo> CONSTRAINTS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Constraints").build();
    private static final MarshallingInfo<StructuredPojo> DEFAULTS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Defaults").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Status").build();
    private static final MarshallingInfo<List> FIELDS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Fields").build();

    private static final UpdateTaskTemplateRequestMarshaller instance = new UpdateTaskTemplateRequestMarshaller();

    public static UpdateTaskTemplateRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(UpdateTaskTemplateRequest updateTaskTemplateRequest, ProtocolMarshaller protocolMarshaller) {

        if (updateTaskTemplateRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(updateTaskTemplateRequest.getTaskTemplateId(), TASKTEMPLATEID_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getInstanceId(), INSTANCEID_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getName(), NAME_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getContactFlowId(), CONTACTFLOWID_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getConstraints(), CONSTRAINTS_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getDefaults(), DEFAULTS_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(updateTaskTemplateRequest.getFields(), FIELDS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
'''
This module generates datasets for training handwritten digits (0-9) classifiers
from the TRAINING_IMAGE_FILE image (MNIST samples, from the OpenCV 2.4.12 Python 2 samples)
'''

import numpy as np
import cv2, os
from opencv_functions import prepKNN

SCRIPT_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) # needed because ev3's brickman messes with relative paths - see https://github.com/ev3dev/ev3dev/issues/263

CELL_SIZE = 20
TRAINING_IMAGE_FILE = SCRIPT_DIRECTORY + '/data/handwritten_digits/handwritten_digits.png'
SAMPLES_FILE = SCRIPT_DIRECTORY + '/data/handwritten_digits/samples.npy'
LABELS_FILE = SCRIPT_DIRECTORY + '/data/handwritten_digits/labels.npy'

# load training image
print 'Loading training image from ' + TRAINING_IMAGE_FILE + '...'
trainingImage = cv2.imread(TRAINING_IMAGE_FILE, cv2.IMREAD_GRAYSCALE)

# split training image
imageHeight, imageWidth = trainingImage.shape[:2]
samples = [np.hsplit(row, imageWidth//CELL_SIZE) for row in np.vsplit(trainingImage, imageHeight//CELL_SIZE)]
samples = prepKNN(samples, CELL_SIZE, 'none')

# generate labels corresponding to the training images
labels = np.repeat(np.arange(10), len(samples)//10)

# save data
np.save(SAMPLES_FILE, samples)
np.save(LABELS_FILE, labels)
print 'Data for handwritten_digits saved.'


text:
"use strict";

const log = require("../../log");
const colors = require("chalk");
const program = require("commander");
const fs = require("fs");
const Helper = require("../../helper");
const Utils = require("../utils");

program
	.command("add <name>")
	.description("Add a new user")
	.on("--help", Utils.extraHelp)
	.action(function(name) {
		if (!fs.existsSync(Helper.getUsersPath())) {
			log.error(`${Helper.getUsersPath()} does not exist.`);
			return;
		}

		const ClientManager = require("../../clientManager");
		const manager = new ClientManager();
		const users = manager.getUsers();

		if (users === undefined) {
			// There was an error, already logged
			return;
		}

		if (users.includes(name)) {
			log.error(`User ${colors.bold(name)} already exists.`);
			return;
		}

		log.prompt(
			{
				text: "Enter password:",
				silent: true,
			},
			function(err, password) {
				if (!password) {
					log.error("Password cannot be empty.");
					return;
				}

				if (!err) {
					log.prompt(
						{
							text: "Save logs to disk?",
							default: "yes",
						},
						function(err2, enableLog) {
							if (!err2) {
								add(
									manager,
									name,
									password,
									enableLog.charAt(0).toLowerCase() === "y"
								);
							}
						}
					);
				}
			}
		);
	});

function add(manager, name, password, enableLog) {
	const hash = Helper.password.hash(password);
	manager.addUser(name, hash, enableLog);

	log.info(`User ${colors.bold(name)} created.`);
	log.info(`User file located at ${colors.green(Helper.getUserConfigPath(name))}.`);
}


text:
require 'mechanize'

module Proxifier
  class Agent
    def self.create
      Mechanize.new
    end
  end
end


text:
package org.apache.cassandra.db.marshal;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;

import org.apache.cassandra.cql.jdbc.JdbcDecimal;
import org.apache.cassandra.utils.ByteBufferUtil;

public class DecimalType extends AbstractType<BigDecimal>
{
    public static final DecimalType instance = new DecimalType();

    DecimalType() {} // singleton

    public int compare(ByteBuffer bb0, ByteBuffer bb1)
    {
        if (bb0.remaining() == 0)
        {
            return bb1.remaining() == 0 ? 0 : -1;
        }
        if (bb1.remaining() == 0)
        {
            return 1;
        }

        return compose(bb0).compareTo(compose(bb1));
    }

    public BigDecimal compose(ByteBuffer bytes)
    {
        return JdbcDecimal.instance.compose(bytes);
    }

    /**
     * The bytes of the ByteBuffer are made up of 4 bytes of int containing the scale
     * followed by the n bytes it takes to store a BigInteger.
     */
    public ByteBuffer decompose(BigDecimal value)
    {
        if (value == null) return ByteBufferUtil.EMPTY_BYTE_BUFFER;

        BigInteger bi = value.unscaledValue();
        Integer scale = value.scale();
        byte[] bibytes = bi.toByteArray();
        byte[] sbytes = ByteBufferUtil.bytes(scale).array();
        byte[] bytes = new byte[bi.toByteArray().length+4];

        for (int i = 0 ; i < 4 ; i++) bytes[i] = sbytes[i];
        for (int i = 4 ; i < bibytes.length+4 ; i++) bytes[i] = bibytes[i-4];

        return ByteBuffer.wrap(bytes);
    }

    public String getString(ByteBuffer bytes)
    {
        return JdbcDecimal.instance.getString(bytes);
    }

    public ByteBuffer fromString(String source) throws MarshalException
    {
        // Return an empty ByteBuffer for an empty string.
        if (source.isEmpty()) return ByteBufferUtil.EMPTY_BYTE_BUFFER;

        BigDecimal decimal;

        try
        {
            decimal = new BigDecimal(source);
        }
        catch (Exception e)
        {
            throw new MarshalException(String.format("unable to make BigDecimal from '%s'", source), e);
        }

        return decompose(decimal);
    }

    public void validate(ByteBuffer bytes) throws MarshalException
    {
        // no useful check for invalid decimals.
    }
}


text:
package cn.com.newcapec.citycard.system.action;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import cn.com.newcapec.common.domain.Node;
import cn.com.newcapec.common.exception.BusinessException;
import cn.com.newcapec.common.page.utils.Page;
import cn.com.newcapec.common.page.utils.PageHelper;
import cn.com.newcapec.common.util.Constants;
import cn.com.newcapec.citycard.common.action.CommonAction;
import cn.com.newcapec.citycard.common.po.TOrgPermission;
import cn.com.newcapec.citycard.common.po.TOrgUser;
import cn.com.newcapec.citycard.system.service.IModuleInfoService;

/**
 * <p>
 * 功能描述:模块管理Action
 *
 * Author : Wangjian
 * Date   : 2008-06-03
 * Time   : 11:04:15
 * Version: 1.0
 * </p>
 */
public class ModuleInfoAction extends CommonAction {
	private static final long serialVersionUID = -8894181403301296225L;

	private IModuleInfoService moduleInfoService;// 模块管理服务接口

	private TOrgPermission moduleInfo; // 模块信息

	private List<TOrgPermission> moduleInfoList; // 模块信息列表

	private Integer parentId; // 父模块ID号

	public Integer getParentId() {
		return parentId;
	}

	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}

	public TOrgPermission getModuleInfo() {
		return moduleInfo;
	}

	public void setModuleInfo(TOrgPermission moduleInfo) {
		this.moduleInfo = moduleInfo;
	}

	public List<TOrgPermission> getModuleInfoList() {
		return moduleInfoList;
	}

	public void setModuleInfoList(List<TOrgPermission> moduleInfoList) {
		this.moduleInfoList = moduleInfoList;
	}

	public void setModuleInfoService(IModuleInfoService moduleInfoService) {
		this.moduleInfoService = moduleInfoService;
	}

	private String leftFrame;// 左边导航菜单

	public String getLeftFrame() {
		return leftFrame;
	}

	private String rightFrame;// 右边页面

	public String getRightFrame() {
		return rightFrame;
	}

	/* 菜单管理主框架 */
	public String listFrame() throws Exception {
		leftFrame = "/system/moduleInfo_listTree.action";
		rightFrame = "/system/jsp/blank.jsp";
		return "listFrame_success";
	}

	private List<Node> nodeList;// 树型菜单结点列表

	public List<Node> getNodeList() {
		return nodeList;
	}

	/* 菜单管理树 */
	public String listTree() throws Exception {
		try {
			nodeList = moduleInfoService.getModuleInfoTreeNodeList();
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error(e.getMessage(), e.getCause());
			}
		}
		return "listTree_success";
	}

	/* 根据菜单的ID号获取其下层一级的功能菜单列表 */
	public String listAllChildNodeById() throws Exception {
		try {
			// 分页总数
			int total = moduleInfoService.getModuleInfoCountByQuery(parentId);
			Page page = PageHelper.getPage(ServletActionContext.getRequest(),
					total, Constants.DEFAULT_PAGE_NUM);

			moduleInfoList = moduleInfoService.getAllChildNodeById(parentId,
					page.getFirstResult() - 1, page.getPageListNum());
			rightFrame = "/system/jsp/moduleInfoViewMain.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			if (log.isDebugEnabled()) {
				log.error(e.getMessage(), e.getCause());
			}
		}
		return "listAllChildNode_success";
	}

	/* 根据菜单的ID号获取其下层一级的功能菜单列表 */
	public String listAllChildNodeByIdNoFresh() throws Exception {
		try {
			// 分页总数
			int total = moduleInfoService.getModuleInfoCountByQuery(parentId);
			Page page = PageHelper.getPage(ServletActionContext.getRequest(),
					total, Constants.DEFAULT_PAGE_NUM);

			moduleInfoList = moduleInfoService.getAllChildNodeById(parentId,
					page.getFirstResult() - 1, page.getPageListNum());
			rightFrame = "/system/jsp/moduleInfoViewMain.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			if (log.isDebugEnabled()) {
				log.error(e.getMessage(), e.getCause());
			}
		}
		return "listAllChildNodeByIdNoFresh_success";
	}

	/* 模块预添加 */
	public String add() throws Exception {
		rightFrame = "/system/jsp/moduleInfoAdd.jsp";
		return "add_pre";
	}

	/* 子模块添加 */
	public String addNext() throws Exception {

		//添加日志,动作/内容/模块/用户
		logInfo.setAction((String)logAction.getDatas().get("ADD"));
		logInfo.setLogContent(logInfo.getAction()+":""+ moduleInfo.getPermName().trim() +""功能模块。");
		logInfo.setModule((String)logModule.getDatas().get("SYSTEM_ADMIN_ORG")+"_模块管理");

		try {
			parentId = moduleInfo.getPid();
			moduleInfo.setPermName(moduleInfo.getPermName().trim());
			if( null != moduleInfo.getPermUrl()){
				moduleInfo.setPermUrl(moduleInfo.getPermUrl().trim());
			}
			if( null != moduleInfo.getRemark()){
				moduleInfo.setRemark(moduleInfo.getRemark().trim());
			}
			moduleInfoService.saveOrUpdateModuleInfo(moduleInfo);

			logInfoService.saveTLog(logInfo);
		} catch (Exception e) {
			if (log.isDebugEnabled()) {
				log.error(e.getMessage(), e.getCause());// 角色重复异常
			}
			if (e instanceof BusinessException) {
				prompt = e.getMessage();// 页面显示消息
			} else {
				prompt = "出错了,请和管理员联系!";
			}
			return "add_failure";
		}
		return "add_success";
	}

	/* 模块预修改 */
	public String update() throws Exception {
		try {
			moduleInfo = moduleInfoService
					.getModuleInfoByPK(moduleInfo.getId());
		} catch (Exception e) {
			if (log.isDebugEnabled()) {
				log.error(e.getMessage(), e.getCause());
			}
		}
		return "update_pre";
	}

	/* 模块修改 */
	public String updateNext() throws Exception {

		//添加日志,动作/内容/模块/用户
		logInfo.setAction((String)logAction.getDatas().get("UPDATE"));
		logInfo.setLogContent(logInfo.getAction()+":""+ moduleInfo.getPermName().trim() +""功能模块。");
		logInfo.setModule((String)logModule.getDatas().get("SYSTEM_ADMIN_ORG")+"_模块管理");

		try {
			parentId = moduleInfo.getPid();
			moduleInfo.setPermName(moduleInfo.getPermName().trim());
			if( null != moduleInfo.getPermUrl()){
				moduleInfo.setPermUrl(moduleInfo.getPermUrl().trim());
			}
			if( null != moduleInfo.getRemark()){
				moduleInfo.setRemark(moduleInfo.getRemark().trim());
			}
			moduleInfoService.saveOrUpdateModuleInfo(moduleInfo);
			logInfoService.saveTLog(logInfo);
		} catch (Exception e) {
			if (log.isDebugEnabled()) {
				log.error(e.getMessage(), e.getCause());
			}
			if (e instanceof BusinessException) {
				prompt = e.getMessage();// 页面显示消息
			} else {
				prompt = "出错了,请和管理员联系!";
			}
			return moduleInfo.getId() == null ? "add_failure"
					: "update_failure";
		}

		return "update_success";
	}

	/* 多条模块数据批量删除 */
	public String delete() throws Exception {
		//添加日志,动作/内容/模块/用户
		logInfo.setAction((String)logAction.getDatas().get("DELETE"));
		logInfo.setLogContent(logInfo.getAction()+":"+id.size()+"条功能模块记录。");
		logInfo.setModule((String)logModule.getDatas().get("SYSTEM_ADMIN_ORG")+"_模块管理");
		try {
			moduleInfoService.deleteModuleInfo(id);
			logInfoService.saveTLog(logInfo);
		} catch (Exception e) {
			if (log.isDebugEnabled()) {
				e.printStackTrace();
				log.error(e.getMessage(), e.getCause());
			}
		}
		return "delete_success";
	}

	/* 模块详情 */
	public String viewModuleById() throws Exception {
		try {
			rightFrame = "/system/jsp/moduleInfoView.jsp";
			moduleInfo = moduleInfoService.getModuleInfoByPK(moduleInfo.getId());
		} catch (Exception e) {
			if (log.isDebugEnabled()) {
				log.error(e.getMessage(), e.getCause());
			}
		}
		return "view_success";
	}

}


text:
class AdditionalInformationForm < Form
  boolean   :has_miscellaneous_information
  attribute :miscellaneous_information, :string

  before_validation :reset_miscellaneous_information!,
    unless: :has_miscellaneous_information?

  validates :miscellaneous_information, length: { maximum: 2500 }

  def has_miscellaneous_information
    self.has_miscellaneous_information = miscellaneous_information.present?
  end

  private

  def reset_miscellaneous_information!
    self.miscellaneous_information = nil
  end
end


text:
<?php

namespace Integrated\Bundle\ContentBundle\Form\Type;

use Symfony\Contracts\Translation\TranslatorInterface;
use Doctrine\Bundle\MongoDBBundle\Form\Type\DocumentType;
use Integrated\Bundle\ContentBundle\Document\Channel\Channel;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @author Johan Liefers <johan@e-active.nl>
 */
class PrimaryChannelType extends AbstractType
{
    /**
     * @var TranslatorInterface
     */
    protected $translator;

    /**
     * PrimaryChannelType constructor.
     *
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => Channel::class,
            'choice_label' => 'name',
            'required' => false,
            'attr' => [
                'class' => 'primary-channel',
                'data-make-primary-text' => $this->translator->trans('make primary'),
            ],
        ]);
    }

    public function getParent()
    {
        return DocumentType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'integrated_primary_channel';
    }
}


text:
package etcdcache

import (
	"context"
	"errors"
	"sync"

	etcd "github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/mvcc/mvccpb"
	"github.com/innovate-technologies/Dispatch/dispatchd/etcdclient"
)

var etcdAPI = etcdclient.GetEtcdv3()

// EtcdCache stores etcd records in memory to do requests on
type EtcdCache struct {
	cache      map[string]*mvccpb.KeyValue
	cacheMutex sync.Mutex
}

// New gives a new empty EtcdCache
func New() *EtcdCache {
	return &EtcdCache{
		cache:      map[string]*mvccpb.KeyValue{},
		cacheMutex: sync.Mutex{},
	}
}

// NewForPrefix  returns a new EtcdCache prefilled with the keys of a specific prefix
func NewForPrefix(prefix string) (*EtcdCache, error) {
	cache := New()
	res, err := etcdAPI.Get(context.Background(), prefix, etcd.WithPrefix())
	if err != nil {
		return cache, err
	}
	for _, kv := range res.Kvs {
		cache.Put(kv)
	}

	return cache, nil
}

// Get gets a key out of the cache
func (e *EtcdCache) Get(key string) (*mvccpb.KeyValue, error) {
	e.cacheMutex.Lock()
	defer e.cacheMutex.Unlock()
	if val, ok := e.cache[key]; ok {
		return val, nil
	}
	return nil, errors.New("Key not in cache")
}

// Put allows to add a new record
func (e *EtcdCache) Put(val *mvccpb.KeyValue) {
	e.cacheMutex.Lock()
	e.cache[string(val.Key)] = val
	e.cacheMutex.Unlock()
}

// GetAll returns all cached keysaa
func (e *EtcdCache) GetAll() []*mvccpb.KeyValue {
	out := []*mvccpb.KeyValue{}

	for _, val := range e.cache {
		out = append(out, val)
	}

	return out
}

// Invalidate removes a key from cache
func (e *EtcdCache) Invalidate(key string) {
	if _, exists := e.cache[key]; exists {
		delete(e.cache, key)
	}
}


text:
var test = require('tape'),
  buffer = require('../lib/buffer'),
  PassThrough = require('stream').PassThrough;

test('buffer test', function(t) {
  t.plan(2);

  var stream = new PassThrough();
  stream.push('h');
  stream.push('i');
  stream.push(null);

  buffer(stream, 32, function(err, output) {
    t.equal(err, null);
    t.equal('hi', output.toString());
  });
});

test('buffer too large test', function(t) {
  t.plan(2);

  var stream = new PassThrough();
  stream.push('h');
  stream.push('i');
  stream.push(null);

  buffer(stream, 1, function(err, output) {
    t.equal(err.message, 'Answer is too large');
    t.equal(output, undefined);
  });
});

test('buffer error test', function(t) {
  t.plan(2);

  var stream = new PassThrough();
  stream.push('h');
  stream.push('i');

  buffer(stream, 32, function(err, output) {
    t.equal(err.message, 'Error reading response from qna');
    t.equal(output, undefined);
  });

  process.nextTick(function() {
    stream.emit('error', new Error('oh no!'));
  });
});


text:
package com.jillesvangurp.iterables;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.zip.GZIPInputStream;

/**
 * Iterate over lines in a stream.
 */
public class LineIterable implements Iterable<String>, Closeable{
    private final BufferedReader bufferedReader;

    /**
     * @param r any reader. Note. this class creates its own buffered reader so there is no need to create one in advance.
     */
    public LineIterable(Reader r) {
        bufferedReader = new BufferedReader(r);
    }

    public static LineIterable openGzipFile(String fileName) throws IOException {
        return new LineIterable(new InputStreamReader(new GZIPInputStream(new FileInputStream(fileName)), Charset.forName("UTF-8")));
    }

    @Override
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            boolean hasMoreLines=true;
            String nextLine=null;

            @Override
            public boolean hasNext() {
                if(hasMoreLines && nextLine==null) {
                    nextLine = readNextLine();
                }
                return hasMoreLines && nextLine!=null;
            }

            @Override
            public String next() {
                if(!hasNext()) {
                    throw new NoSuchElementException();
                } else {
                    String result=nextLine;
                    nextLine=null;
                    return result;
                }
            }

            private String readNextLine() {
                String line = null;
                if(hasMoreLines) {
                    try {
                        line = bufferedReader.readLine();
                    } catch (IOException e) {
                        hasMoreLines=false;
                        throw new IllegalStateException("could not read line", e);
                    }
                    if(line==null) {
                        hasMoreLines=false;
                    }
                }
                return line;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("cannot remove lines");
            }
        };
    }

    @Override
    public void close() throws IOException {
        bufferedReader.close();
    }
}


text:
(function() {
  var event, events, registerEvent, _i, _len;

  events = ['scrollstart', 'scrollstop', 'swipe', 'swipeleft', 'swiperight', 'tap', 'taphold'];

  registerEvent = function(eventName) {
    var _ref;
    if ((typeof window !== "undefined" && window !== null ? (_ref = window.jQuery) != null ? _ref.fn[eventName] : void 0 : void 0) != null) {
      return Batman.DOM[eventName] = function(node, callback, view) {
        return Batman.DOM.events.click(node, callback, view, eventName);
      };
    } else {
      throw new Error("Missing jQuery Event: '" + eventName + "'");
    }
  };

  if (((typeof window !== "undefined" && window !== null ? window.Batman : void 0) != null) && ((typeof window !== "undefined" && window !== null ? window.jQuery : void 0) != null)) {
    for (_i = 0, _len = events.length; _i < _len; _i++) {
      event = events[_i];
      registerEvent(event);
    }
  }

  if ((typeof window !== "undefined" && window !== null ? window.Batman : void 0) == null) {
    throw new ReferenceError("Batman is not defined");
  }

  if ((typeof window !== "undefined" && window !== null ? window.jQuery : void 0) == null) {
    throw new ReferenceError("jQuery is not defined");
  }

}).call(this);


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

using Mono.Unix;
using Gtk;

using IA=InternetArchive;

namespace Banshee.InternetArchive
{
    public class Actions : Banshee.Gui.BansheeActionGroup
    {
        public Actions (HomeSource source) : base ("InternetArchive")
        {
            Add (
                new ActionEntry ("IaResultPopup", null, null, null, null, (o, a) => {
                    ShowContextMenu ("/IaResultPopup");
                }),
                new ActionEntry ("ViewItemDetails", null, Catalog.GetString ("View Item Details"), null, null, (o, a) => {
                    var item = source.SearchSource.FocusedItem;
                    if (item != null && item.Id != null) {
                        string id = item.Id;
                        var src = new DetailsSource (id, item.Title, item.MediaType);
                        source.AddChildSource (src);
                        Banshee.ServiceStack.ServiceManager.SourceManager.SetActiveSource (src);
                    }
                }),
                new ActionEntry ("OpenItemWebsite", Stock.JumpTo, Catalog.GetString ("Open Webpage"), null, null, (o, a) => {
                    string uri = null;
                    var src = ActiveSource as DetailsSource;
                    if (src != null) {
                        uri = src.Item.Details.WebpageUrl;
                    } else {
                        var item = source.SearchSource.FocusedItem;
                        if (item != null) {
                            uri = item.WebpageUrl;
                        }
                    }

                    if (uri != null) {
                        Banshee.Web.Browser.Open (uri);
                    }
                })
            );

            AddImportant (
                new ActionEntry ("VisitInternetArchive", Stock.JumpTo, Catalog.GetString ("Visit Archive.org"), null, null, (o, a) => {
                    Banshee.Web.Browser.Open ("http://archive.org");
                })
            );

            AddUiFromFile ("GlobalUI.xml");

            Register ();
        }
    }
}


text:
'use strict';

/**
 * Permissions information.
 */
class PermissionGetResult extends Array {
  /**
   * Create a PermissionGetResult.
   * @member {string} [nextLink] The URL to use for getting the next set of
   * results.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of PermissionGetResult
   *
   * @returns {object} metadata of PermissionGetResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'PermissionGetResult',
      type: {
        name: 'Composite',
        className: 'PermissionGetResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'PermissionElementType',
                  type: {
                    name: 'Composite',
                    className: 'Permission'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = PermissionGetResult;


text:
require "staticmatic/compass"

project_type = :staticmatic


text:
1. [Overview](#overview)
2. [Module Description - What the module does and why it is useful](#module-description)
3. [Setup - The basics of getting started with build_kernel_modules](#setup)
    * [What build_kernel_modules affects](#what-build_kernel_modules-affects)
    * [Setup requirements](#setup-requirements)
    * [Beginning with build_kernel_modules](#beginning-with-build_kernel_modules)
4. [Usage - Configuration options and additional functionality](#usage)
5. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
5. [Limitations - OS compatibility, etc.](#limitations)
6. [Development - Guide for contributing to the module](#development)

## Overview

Make sure kernel modules can be built on a system.

Should work under any Red Hattish Linux (RHEL, CentOS, Fedora, OEL,
SL, ...).

## Module Description

This module installs the packages necessary to enable the building of
kernel modules. This may be necessary in order to be able to install a
proprietary video driver, some virtualization software, some antivirus
software, or other such software that needs to hook into the kernel.

If you have
[DKMS](https://en.wikipedia.org/wiki/Dynamic_Kernel_Module_Support),
and the software you are installing is wise enough to expect and use
it, you probably don't need this module. DKMS seems to be used more
often under Ubuntu and Debian than CentOS, Fedora or RHEL.

If the software you are using is well-integrated into the Linux
distribution you are using, you probably don't need this module,
because the necessary kernel modules are pre-packaged.

## Setup

### What build_kernel_modules affects

* Installs make
* Installs gcc
* Installs kernel-devel

### Beginning with build_kernel_modules

```
    include build_kernel_modules
```

## Usage

## Reference

`build_kernel_modules`: Include this class for kernel module buildability.

## Limitations

## Development

Contributions welcome. Please file issues and send pull requests on GitHub.

## Release Notes/Contributors/Etc

Nothing to report yet.


text:
<?php
namespace Application\Service;

use Application\Entity\Article as Article;
use Application\Entity\Auteur;
use Application\Entity\Categorie;
use DateTime;

class ArticleService
{
    public function __construct($em, $articleRepository){
        $this->em = $em;
        $this->articleRepository = $articleRepository;
    }

    /**
     * @var Article
     */
    private $artciles;

    /**
     * @param Article $articles
     */
    public function setArticles(Article $articles)
    {
        $this->articles = $articles;
    }

    /**
     * @return Article
     */
    public function getArticle()
    {
        return $this->articles;
    }

    public function getArticleByID($id)
    {
        return $this->articleRepository->findOneBy(array('id' => $id));
    }

    public function getAllActivesArticles()
    {
        $criteria = array('en_ligne' => true);
        $orderBy = array('date' => 'desc');

        return $this->articleRepository->findBy($criteria, $orderBy, null, null);
    }

    public function getAllArticles()
    {
        $criteria = array();
        $orderBy = array('date' => 'desc');

        return $this->articleRepository->findBy($criteria, $orderBy, null, null);
    }

    public function desactivateArticle($articleID)
    {

        $article = new Article();
        $article = $this->articleRepository->findOneBy(array('id' => $articleID));
        if($article){
            if($article->getEn_Ligne())
            {
                $article->setEn_Ligne(false);
                $this->em->persist($article);
                $this->em->flush();
            }
        }
    }

    public function activateArticle($articleID)
    {

        $article = new Article();
        $article = $this->articleRepository->findOneBy(array('id' => $articleID));

        if($article){
            if(!$article->getEn_Ligne())
            {
                $article->setEn_Ligne(true);
                $this->em->persist($article);
                $this->em->flush();
            }
        }
    }

    public function saveArticle($post, Categorie $categorie, Auteur $auteur)
    {
        $articleToSave = new Article();
        $date = new \DateTime('now',  new \DateTimeZone( 'UTC' ));

        try
        {
            $articleToSave->setAuteur($auteur);
            $articleToSave->setCategorie($categorie);
            $articleToSave->setTitre($post["titre"]);
            $articleToSave->setContenu($post["contenu"]);
            $articleToSave->setDate($date);
            $articleToSave->setChapeau("c");
            $articleToSave->setEn_ligne(isset($post["en_ligne"])? true : false);

            $this->em->persist($articleToSave);
            $this->em->flush();
        }
        catch (\Exception $e){
            $this->getServiceLocator()->get('Zend\LogError')->err('Erreur au moment de sauvegarder un article');
            throw $e;
        }
    }

    public function isValidPost($post)
    {

        $error =array();
        $hasError = false;

        if($post["categorie"] != null && $post["titre"] != null)
        {
            $validation = array('valide' => true);
            return $validation;
        }
        if ($post["categorie"] == null )
        {
            array_push($error, 'Please choose a category');
            $hasError = true;
        }
        if($post["titre"] == null)
        {
            array_push($error, 'Please choose a title');
            $hasError = true;
        }
        if($hasError)
        {
            $validation = array('valide' => false,
                                'error'  => $error
            );
        }

        return $validation;
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Grammar of Graphics with ES6 and React</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="etc/style/spectre.min.css">
    <link rel="stylesheet" href="etc/style/axis-defaults.css">
    <link rel="stylesheet" href="etc/style/monthly-defaults.css">
    <link rel="stylesheet" href="etc/style/tabs.css">
    <link rel="stylesheet" href="etc/style/sections-grid.css">
    <link rel="stylesheet" href="etc/style/app.css">


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>iBase4J-Web</display-name>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>iBase4J-Web</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:Spring-config.xml</param-value>
    </context-param>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>csrfFilter</filter-name>
        <filter-class>org.ibase4j.core.filter.CsrfFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>csrfFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>xssFilter</filter-name>
        <filter-class>org.ibase4j.core.filter.XssFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>xssFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.ibase4j.core.listener.ServerListerner</listener-class>
    </listener>
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:Spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
</web-app>


text:
package com.moilioncircle.redis.replicator.extension.module.cmd.parser;

import com.moilioncircle.redis.replicator.cmd.CommandName;
import com.moilioncircle.redis.replicator.extension.module.cmd.NameableCommandParser;
import com.moilioncircle.redis.replicator.extension.module.cmd.impl.JsonArrPopCommand;

import java.math.BigDecimal;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @author Leon Chen
 * @since 1.0.0
 */
public class JsonArrPopParser implements NameableCommandParser<JsonArrPopCommand> {
    @Override
    public JsonArrPopCommand parse(Object[] command) {
        int idx = 1;
        String key = new String((byte[]) command[idx++], UTF_8);
        String path = idx == command.length ? "." : new String((byte[]) command[idx++], UTF_8);
        int index = idx == command.length ? -1 : new BigDecimal(new String((byte[]) command[idx++], UTF_8)).intValueExact();
        return new JsonArrPopCommand(key, path, index);
    }

    @Override
    public CommandName name() {
        return CommandName.name("JSON.ARRPOP");
    }
}


text:
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.EntityFrameworkIntegration.Saga
{
    using System;
    using System.Data.Entity;
    using System.Threading.Tasks;
    using Context;
    using Logging;
    using MassTransit.Saga;
    using Util;

    public class EntityFrameworkSagaConsumeContext<TSaga, TMessage> :
        ConsumeContextProxyScope<TMessage>,
        SagaConsumeContext<TSaga, TMessage>
        where TMessage : class
        where TSaga : class, ISaga
    {
        static readonly ILog _log = Logger.Get<EntityFrameworkSagaRepository<TSaga>>();
        readonly DbContext _dbContext;
        readonly bool _existing;

        public EntityFrameworkSagaConsumeContext(DbContext dbContext, ConsumeContext<TMessage> context, TSaga instance, bool existing = true)
            : base(context)
        {
            Saga = instance;
            _dbContext = dbContext;
            _existing = existing;
        }

        Guid? MessageContext.CorrelationId => Saga.CorrelationId;

        SagaConsumeContext<TSaga, T> SagaConsumeContext<TSaga>.PopContext<T>()
        {
            var context = this as SagaConsumeContext<TSaga, T>;
            if (context == null)
                throw new ContextException($"The ConsumeContext<{TypeMetadataCache<TMessage>.ShortName}> could not be cast to {TypeMetadataCache<T>.ShortName}");

            return context;
        }

        public async Task SetCompleted()
        {
            IsCompleted = true;
            if (_existing)
            {
                _dbContext.Set<TSaga>().Remove(Saga);

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("SAGA:{0}:{1} Removed {2}", TypeMetadataCache<TSaga>.ShortName, TypeMetadataCache<TMessage>.ShortName,
                        Saga.CorrelationId);
                }

                await _dbContext.SaveChangesAsync(CancellationToken).ConfigureAwait(false);
            }
        }

        public bool IsCompleted { get; private set; }
        public TSaga Saga { get; }
    }
}


text:
FactoryBot.define do
  # The `:base_transaction` represents the attributes
  # common to all other factories.  It does not have enough
  # attributes to be valid, but that's ok because we never use
  # it directly in any tests.
  factory :base_transaction, :class => :transaction do
    year { Time.now.year }
    association :user, factory: :user, strategy: :build
    association :updated_by_user, factory: :user, strategy: :build
    sequence(:amount) { |n| n * 3 }
  end

  # To use the `shared_examples_for_controllers`, we need a valid
  # factory with the same name as the model.  I've chosen to copy
  # `:tr_comp` because it is the simplest.
  factory :transaction, :parent => :base_transaction do
    trantype { 'C' } # comp
    instrument { nil }
  end

  factory :tr_comp, :parent => :base_transaction do
    trantype { 'C' } # comp
    instrument { nil }
  end

  factory :tr_refund, :parent => :base_transaction do
    trantype { 'R' }
    i = %w[K S].sample
    instrument { i }
    check_number { 101 } if (i == 'K')
  end

  factory :tr_sale, :parent => :base_transaction do
    trantype { 'S' } # sale
    ins = %w[C S].sample
    instrument { ins }
    if ins == 'C'
      gwdate { generate(:gwdate) }
      sequence(:gwtranid) { |n| n }
    end
  end

  sequence :gwdate do |n|
    month = rand(11) + 1
    day = rand(27) + 1
    Time.utc(Time.now.year, month, day)
  end
end


text:
#ifndef COMPNAT_TP1_UTILS_HPP
#define COMPNAT_TP1_UTILS_HPP

#include <cmath>
#include <limits>
#include <sstream>
#include <string>

namespace utils {

/// Safe division, returns default if b is 0.
template <typename T> T safeDiv(const T &a, const T &b, const T &def = 0) {
  // Simplification to also support integers. Considers the epsilon as 0.
  if (std::abs(b) <= std::numeric_limits<T>::epsilon()) {
    return def;
  }
  return a / b;
}

template <typename T> void strCatter_(std::stringstream &ss, const T &t) {
  ss << t;
}

template <typename T, typename... Args>
void strCatter_(std::stringstream &ss, const T &t, const Args &... args) {
  ss << t;
  strCatter_(ss, args...);
}

/// Concatenates the given values into a single string.
template <typename... Args> std::string strCat(const Args &... args) {
  std::stringstream ss;
  strCatter_(ss, args...);
  return ss.str();
}

/// Padded strCat, fills with spaces until size.
template <typename... Args>
std::string paddedStrCat(size_t size, const Args &... args) {
  std::string str = strCat(args...);
  if (str.size() < size) {
    str += std::string(size - str.size(), ' ');
  }

  return str;
}

template <typename T> void strSplitter_(std::istringstream &iss, T &t) {
  iss >> t;
}

template <typename T, typename... Args>
void strSplitter_(std::istringstream &iss, T &t, Args &... args) {
  iss >> t;
  strSplitter_(iss, args...);
}

/// Extracts the given string into the given values.
template <typename... Args>
void strSplit(const std::string &str, Args &... args) {
  std::istringstream iss(str);
  strSplitter_(iss, args...);
}

} // namespace utils

#endif // !COMPNAT_TP1_UTILS_HPP


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

namespace biz.ritter.javapi.util.zip
{

    /**
     * Holds information about a checksum which was computed with the methods
     * implementing a checksum algorithm.
     */
    public interface Checksum {

        /**
         * Returns the current calculated checksum value.
         *
         * @return the checksum.
         */
        long getValue();

        /**
         * Resets the checksum value applied before beginning calculations on a new
         * stream of data.
         */
        void reset();

        /**
         * Updates the checksum with the given bytes.
         *
         * @param buf
         *            the byte array from which to read the bytes.
         * @param off
         *            the initial position in {@code buf} to read the bytes from.
         * @param nbytes
         *            the number of bytes to read from {@code buf}.
         */
        void update(byte[] buf, int off, int nbytes);

        /**
         * Updates the checksum value with the given byte.
         *
         * @param val
         *            the byte to update the checksum with.
         */
        void update(int val);
    }
}


text:
/*
################################################################################
#  THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY  #
#  Please refer to the README for information about making permanent changes.  #
################################################################################
*/
#ifndef Q_SPRK_DATASET_H
#define Q_SPRK_DATASET_H

#include "qsprk.h"

class QT_SPRK_EXPORT QSprkDataset : public QObject
{
    Q_OBJECT
public:

    //  Copy-construct to return the proper wrapped c types
    QSprkDataset (sprk_dataset_t *self, QObject *qObjParent = 0);

    //  Destroy the sprk_dataset.
    ~QSprkDataset ();

    //  Checkpoints all blocks and their transformations across executors.
    void checkpoint ();

    //  Multiplies all values by the multiplier.
    void mul (float multiplier);

    //  Calculates the sum of all values in the dataset.
    float sum ();

    //  Self test of this class.
    static void test (bool verbose);

    sprk_dataset_t *self;
};
#endif //  Q_SPRK_DATASET_H
/*
################################################################################
#  THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY  #
#  Please refer to the README for information about making permanent changes.  #
################################################################################
*/


text:
namespace Sitecore.FakeDb.Tests.Configuration
{
  using FluentAssertions;
  using Sitecore.FakeDb.Configuration;
  using Xunit;

  public class ClientDataStoreStubTest
  {
    private readonly OpenClientDataStoreStub dataStore;

    public ClientDataStoreStubTest()
    {
      this.dataStore = new OpenClientDataStoreStub();
    }

    [Fact]
    public void ShouldNotThrowExceptionOnCompactData()
    {
      // act & assert
      this.dataStore.CompactData();
    }

    [Fact]
    public void ShouldReturnNullOnLoadData()
    {
      // act & assert
      this.dataStore.LoadData("key").Should().BeNull();
    }

    [Fact]
    public void ShouldNotThrowExceptionOnSaveData()
    {
      // act & assert
      this.dataStore.SaveData("key", "data");
    }

    [Fact]
    public void ShouldNotThrowExceptionOnRemoveData()
    {
      // act & assert
      this.dataStore.RemoveData("key");
    }

    private class OpenClientDataStoreStub : ClientDataStoreStub
    {
      new public void CompactData()
      {
        base.CompactData();
      }

      new public string LoadData(string key)
      {
        return base.LoadData(key);
      }

      new public void SaveData(string key, string data)
      {
        base.SaveData(key, data);
      }

      new public void RemoveData(string key)
      {
        base.RemoveData(key);
      }
    }
  }
}


text:
/*
 * (C) 2015-2017 Augustin Cavalier
 * All rights reserved. Distributed under the terms of the MIT license.
 */
#include "script/Debugger.h"

#include <iostream>

#include "script/Interpreter.h"
#include "util/StringUtil.h"
#include "util/TermUtil.h"

using std::string;
using std::vector;

namespace Script {

static void DrawVerticalLine(TermUtil& tu, int x, int startY, int height)
{
	for (int y = startY; y < height; y++) {
		tu.moveCursorTo(x, y);
		tu.write(" ");
	}
}
static void DrawHorizontalLine(TermUtil& tu, int startX, int y, int width)
{
	tu.moveCursorTo(startX, y);
	tu.write(string(width, ' '));
}

Object Debugger(Stack* stack, std::string path)
{
	TermUtil tu;
	tu.startup();

	std::pair<int /*width*/, int /*height*/> size = tu.size();
	int codeview_height, codeview_width;
	codeview_height = size.second * 2/3;
	codeview_width = size.first * 2/3;

	std::string runningPath;
	std::string runningCode;
	int runningLine = 0;

	auto DrawBorders = [&]() -> void {
		tu.setBackgroundColor(TermUtil::Yellow);
		tu.setColor(TermUtil::Black);
		DrawHorizontalLine(tu, 0, codeview_height, size.first);
		DrawVerticalLine(tu, codeview_width, 0, codeview_height);
		DrawHorizontalLine(tu, 0, 0, size.first);
		tu.moveCursorTo(1, 0);
		tu.write("Source");
		tu.moveCursorTo(codeview_width + 1, 0);
		tu.write("Variables");
		tu.resetColors();
	}; DrawBorders();
	auto DrawCode = [&]() -> void {
		const int startLine = std::max(runningLine - (codeview_height / 2), 1);
		const int width = std::max(std::to_string(startLine).size(),
			std::to_string(startLine + codeview_height).size()) + 1;

		// Draw the left-hand bar
		tu.setBackgroundColor(TermUtil::Gray);
		tu.setColor(TermUtil::Black);
		for (int y = 1; y < codeview_height; y++) {
			const int line = startLine + (y - 1);
			tu.moveCursorTo(0, y);
			string lineno = std::to_string(line);
			tu.write(lineno + string(width - lineno.size() -
				(line == runningLine ? 1 : 0), ' '));
			if (line == runningLine) {
				tu.write(">");
			}
		}
		tu.resetColors();

		// Draw the actual code
		vector<string> lines = StringUtil::split(runningCode, "\n");
		const int end = (codeview_width - width);
		for (int y = 1; y < codeview_height; y++) {
			const int line = startLine + (y - 1);
			// First, clear the line completely
			tu.moveCursorTo(width, y);
			tu.write(string(end, ' '));
			// Then add the syntax-highlighted source
			tu.moveCursorTo(width, y);
			const string& linestr = lines[line - 1];
			for (string::size_type i = 0; i < end && i < linestr.size(); i++) {
				char c = linestr[i];
				bool resetAfter = false;
				switch (c) {
				case '\t':
					c = ' '; // FIXME: should be 4 spaces
				break;
				case '#':
					tu.setColor(TermUtil::Gray);
					tu.write(linestr.substr(i, end - i));
					i = end;
					continue;
				case '(': case ')': case '[': case ']': case '=': case ',': case '.':
				case ';': case ':': case '&': case '|': case '/': case '*': case '+':
				case '-':
					tu.setColor(TermUtil::Cyan);
					resetAfter = true;
				break;
				case '"': case '\'':
					tu.setColor(TermUtil::Gray);
					tu.write(c);
					i++;
					for (; linestr[i] != c && i < end; i++) {
						tu.write(linestr[i]);
						if (linestr[i] == '\\') {
							tu.write(linestr[i + 1]);
							i++;
						}
					}
					resetAfter = true;
				break;
				}
				tu.write(c);
				if (resetAfter)
					tu.resetColors();
			}
			tu.resetColors();
		}
	};
	auto DrawStack = [&]() {
		vector<ObjectMap>& stk = stack->get();
		int y = 1;
		int end = size.first - (codeview_width + 1);
		for (vector<ObjectMap>::const_reverse_iterator m = stk.rbegin(); m != stk.rend(); m++) {
			for (ObjectMap::const_iterator it = m->begin(); it != m->end() && y < codeview_height; it++) {
				tu.moveCursorTo(codeview_width + 1, y);
				tu.write(it->first.substr(0, end));
				string val = it->second->asStringRaw();
				if ((it->first.size() + 3) < end) {
					int x = codeview_width + 1 + it->first.size() + 1;
					tu.moveCursorTo(x, y);
					tu.write(val.substr(0, size.first - x));
				}
				y++;
			}
		}
	};

	stack->mInterpreterHook = [&](const std::string& path, const std::string& code,
			const uint32_t line) -> void {
		runningPath = path;
		runningCode = code;
		runningLine = line;
		DrawCode();
		DrawStack();

		std::string str;
		std::getline(std::cin, str);
	};

	Object ret = Script::Run(stack, path);
	tu.shutdown();
	return ret;
}

}


text:
struct TestFixtureConversion : public ::testing::Test {
};

#endif // TEST_FIXTURE_CONVERSION_H


text:
using GenericLoginFramework;
using System.Globalization;
using System;
using System.Windows.Forms;

namespace GLFToolboxWF
{
    [ProvideToolboxControl("GLFToolboxWF.Generic", false)]
    public partial class Generic : UserControl
    {
        public string Username { get; private set; }
        public string Password { get; private set; }

        public Generic()
        {
            InitializeComponent();
        }

        private void LoginBtn_Click(object sender, EventArgs e)
        {
            Username = UsernameTxtBx.Text;
            Password = PasswordTxtBx.Text;
            this.OnClick(e);
        }
    }
}


text:
¿Qué ha cambiado?

- [ ] Frontend
- [ ] Backend
- [ ] Configuración del server

# Comó puedo provar los cambios?
en que url y forma puedo ver el update


text:
from Database.Controllers.Disciplina import Disciplina
from Database.Controllers.Prereq import Prereq

class Ass_disc_pre(object):

	def __init__(self,dados=None):
		if dados is not None:
			self.id = dados ['id']
			self.id_disciplina = dados ['id_disciplina']
			self.id_prereq = dados ['id_prereq']

	def getId(self):
		return self.id

	def setId_disciplina(self,disciplina):
		self.id_disciplina = (Disciplina().pegarDisciplina('nome = %s',(disciplina,))).getId()

	def getId_disciplina(self):
		return self.id_disciplina

	def getDisciplina(self):
		return (Disciplina().pegarDisciplina('id = %s',(self.id_disciplina,))).getNome()

	def setId_prereq(self,disciplina_requisito,grupo):
		id_disc_pre = (Disciplina().pegarDisciplina('nome = %s',(disciplina_requisito,))).getId()
		self.id_prereq = (Prereq().pegarPrereq('id_disc_pre = %s AND grupo = %s',(id_disc_pre,grupo))).getId()

	def getId_prereq(self):
		return self.id_prereq


text:
 Debug Log

**Namespace:** [OfficeDevPnP.Core.Diagnostics](OfficeDevPnP.Core.Diagnostics.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public void LogDebug(String message, params Object[] args)
```
### Parameters
#### message
  Type: System.String
  Message string

#### args
  Type: System.Object[]
  Arguments object

### Return Value
Type: void

## See also
- [PnPMonitoredScope](OfficeDevPnP.Core.Diagnostics.PnPMonitoredScope.md)
- [OfficeDevPnP.Core.Diagnostics](OfficeDevPnP.Core.Diagnostics.md)


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Leaflet edit</title>


text:
package energy.usef.brp.workflow.plan.flexorder.acknowledge;

import energy.usef.brp.service.business.BrpPlanboardBusinessService;
import energy.usef.brp.workflow.plan.connection.forecast.PrepareFlexRequestsEvent;
import energy.usef.core.model.AcknowledgementStatus;
import energy.usef.core.model.PlanboardMessage;
import energy.usef.core.util.DateTimeUtil;

import javax.enterprise.event.Event;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

@RunWith(PowerMockRunner.class)
public class BrpFlexOrderAcknowledgementCoordinatorTest {

    private BrpFlexOrderAcknowledgementCoordinator coordinator;

    @Mock
    private BrpPlanboardBusinessService brpPlanboardBusinessService;
    @Mock
    private Event<PrepareFlexRequestsEvent> eventManager;

    @Before
    public void setUp() throws Exception {
        coordinator = new BrpFlexOrderAcknowledgementCoordinator();
        Whitebox.setInternalState(coordinator, brpPlanboardBusinessService);
        Whitebox.setInternalState(coordinator, eventManager);
    }

    @Test
    public void testHandleEvent() throws Exception {
        // stubbing of brpPlanboardBusinessService
        PowerMockito.when(brpPlanboardBusinessService.updateFlexOrdersWithAcknowledgementStatus(Matchers.any(Long.class),
                Matchers.any(AcknowledgementStatus.class), Matchers.any(String.class))).thenReturn(buildPlanboardMessage());

        coordinator.handleEvent(buildFlexOrderAcknowledgementEvent());

        ArgumentCaptor<PrepareFlexRequestsEvent> eventCaptor = ArgumentCaptor.forClass(PrepareFlexRequestsEvent.class);
        Mockito.verify(eventManager, Mockito.times(1)).fire(eventCaptor.capture());
        // verify that an event to trigger the flex request workflow has been fired for the right period.
        Assert.assertEquals(DateTimeUtil.getCurrentDate(), eventCaptor.getValue().getPeriod());
    }

    private FlexOrderAcknowledgementEvent buildFlexOrderAcknowledgementEvent() {
        return new FlexOrderAcknowledgementEvent(1L, AcknowledgementStatus.REJECTED, "agr.usef-example.com");
    }

    private PlanboardMessage buildPlanboardMessage() {
        PlanboardMessage planboardMessage = new PlanboardMessage();
        planboardMessage.setPeriod(DateTimeUtil.getCurrentDate());
        return planboardMessage;
    }
}


text:
cd ../modules/flowable-ui-modeler/
./start-modeler.sh


text:
NAME=$1
FILE=$2

URL=http://localhost:8983/solandra/$NAME

curl $URL --data-binary @$FILE -H 'Content-type:text/xml; charset=utf-8' > /dev/null

echo "posted $FILE to $URL"


text:
require 'spec_helper'

klass = OneviewSDK::API300::Synergy::IDPool
RSpec.describe klass, integration: true, type: DELETE, sequence: rseq(klass) do
  let(:current_client) { $client_300_synergy }
  include_examples 'IDPoolDeleteExample', 'integration api300 context'
end


text:
import {Client} from '../mnubo';
import {authenticate} from '../decorators';
import {encodeObjectForUrlParams} from '../utils/underscore'

export interface EventsSendOptions {
    reportResults?: boolean;
    objectsMustExist?: boolean;
}

export class Events {
  private path: string;

  constructor(private client: Client) {
    this.path = '/api/v3/events';
  }

  @authenticate
  send(payload: any, options?: EventsSendOptions): Promise<any> {
    let path = this.path;

    if (options) {
      path += `?${encodeObjectForUrlParams(options)}`;
    }

    return this.client.post(`${path}`, payload);
  }

  @authenticate
  sendFromDevice(deviceId: string, payload: any): Promise<any> {
    return this.client.post(`/api/v3/objects/${deviceId}/events`, payload);
  }

  @authenticate
  exists(eventIds: Array<string>|string): Promise<any> {
    const path = `${this.path}/exists`;

    if (Array.isArray(eventIds)) {
      return this.client.post(`${path}`, eventIds);
    } else {
      return this.client.get(`${path}/${eventIds}`);
    }
  }
}


text:
/**
 * Provides Login skeleton
 */
package de.tudarmstadt.ukp.clarin.webanno.webapp.page.login;


text:
import EmailValidator from 'catela/model/validation/EmailValidator'
import LengthRangeValidator from 'catela/model/validation/LengthRangeValidator'
import NumberValidator from 'catela/model/validation/NumberValidator'
import PhoneNumberValidator from 'catela/model/validation/PhoneNumberValidator'
import RequiredValidator from 'catela/model/validation/RequiredValidator'
import ValueRangeValidator from 'catela/model/validation/ValueRangeValidator'
import AlphanumericValidator from 'catela/model/validation/AlphanumericValidator'
import StrongPasswordValidator from 'catela/model/validation/StrongPasswordValidator'
import MatchValidator from 'catela/model/validation/MatchValidator'

export default {
  EmailValidator: EmailValidator,
  LengthRangeValidator: LengthRangeValidator,
  NumberValidator: NumberValidator,
  PhoneNumberValidator: PhoneNumberValidator,
  RequiredValidator: RequiredValidator,
  ValueRangeValidator: ValueRangeValidator,
  AlphanumericValidator: AlphanumericValidator,
  StrongPasswordValidator: StrongPasswordValidator,
  MatchValidator: MatchValidator
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Flecht. Eur. no. 629 (1860)

#### Original name
Verrucaria contorta Hoffm.

### Remarks
null


text:
require 'kconv'
require 'zip'

module Cms::Addon::Import
  module Page
    extend ActiveSupport::Concern
    extend SS::Addon

    included do
      attr_accessor :in_file, :root_files, :import_date, :imported
      permit_params :in_file, :root_files, :import_date

      validates :in_file, presence: true, on: :import
    end

    def import
      @imported = 0
      return false if in_file.blank?

      if ::File.extname(in_file.original_filename) =~ /^\.zip$/i
        import_from_zip(root_files: root_files.present?)
      else
        import_from_file
      end
    end

    def save_with_import
      @imported = 0
      return false unless save(context: :import)
      return import
    end

    private

    def save_import_page(file, import_filename)
      import_html = file.read.force_encoding("utf-8")
      import_html = modify_relative_paths(import_html)

      item = Cms::ImportPage.new
      item.filename = import_filename
      item.name = ::File.basename(import_filename)
      item.html = import_html
      item.cur_site = @cur_site
      item.group_ids = group_ids
      item.save

      set_errors(item, import_filename)
      return item.errors.empty?
    end

    def save_import_node(file, import_filename)
      item = Cms::Node::ImportNode.new
      item.filename = import_filename
      item.name = ::File.basename(import_filename)
      item.cur_site = @cur_site
      item.group_ids = group_ids
      item.save

      set_errors(item, import_filename)
      return item.errors.empty?
    end

    def upload_import_file(file, import_filename)
      import_path = "#{@cur_site.path}/#{import_filename}"

      item = Uploader::File.new(path: import_path, binary: file.read)
      item.save

      set_errors(item, import_filename)
      return item.errors.empty?
    end

    def set_errors(item, import_filename)
      item.errors.each do |n, e|
        if n == :filename
          self.errors.add :base, "#{item.filename}#{e}"
        elsif n == :name
          self.errors.add :base, "#{import_filename}#{e}"
        else
          self.errors.add :base, "#{import_filename} #{item.class.t(n)}#{e}"
        end
      end
    end

    def import_from_zip(opts = {})
      root_files = (opts[:root_files] == true)

      Zip::File.open(in_file.path) do |archive|
        archive.each do |entry|
          fname = entry.name.toutf8.split(/\//)
          fname.shift unless root_files
          fname = fname.join('/')
          next if fname.blank?

          import_filename = "#{self.filename}/#{fname}"
          import_filename = import_filename.sub(/\/$/, "")

          if entry.directory?
            @imported += 1 if save_import_node(entry.get_input_stream, import_filename)
          elsif ::File.extname(import_filename) =~ /^\.(html|htm)$/i
            @imported += 1 if save_import_page(entry.get_input_stream, import_filename)
          elsif upload_import_file(entry.get_input_stream, import_filename)
            @imported += 1
          end
        end
      end

      return errors.empty?
    end

    def import_from_file
      import_filename = "#{self.filename}/#{in_file.original_filename}"

      if ::File.extname(import_filename) =~ /^\.(html|htm)$/i
        @imported += 1 if save_import_page(in_file, import_filename)
      elsif upload_import_file(in_file, import_filename)
        @imported += 1
      end

      return errors.empty?
    end

    def modify_relative_paths(html)
      html.gsub(/(href|src)="\/(.*?)"/) do
        attr = $1
        path = $2
        "#{attr}=\"\/#{self.filename}/#{path}\""
      end
    end
  end
end


text:
"use strict";

!function (scope, dependencyScope) {

    //noinspection JSUnresolvedVariable
    var misc = dependencyScope.misc;
    if (misc.check(window, 'AttributeCollection')) {
        return;
    }

    var AttributeCollection = function () {
        this._defaultValues = {};
        this._settings = {};
        this._attributes = {};
        this._groups = {};
    };

    AttributeCollection.prototype = {

        defaults: function () {
            return this._defaultValues;
        },

        default: function (attribute) {
            return this._defaultValues[attribute];
        },

        all: function () {
            return this._attributes;
        },

        /**
         * Adds a key to the attributes. The settings define some settings for the specified attribute, i.e.,
         * - name (optional string, default key, defines the name of the attributes, used to read from an object)
         * - validate (optional function, default none, function triggered to validate a value of the attribute)
         * - defaultValue (optional, default undefined, the value used if no value is defined)
         * - group (optional unique identifier, default undefined, specifies a group of attributes, which may have to be present if one is set
         * - optional (optional boolean, default true, specifies if the attribute has to have a value when in a group)
         *
         * @param {string} key the key used to access the attributes name from outside
         * @param {object} setting the settings of the attribute
         */
        add: function (key, setting) {
            var name;

            if ($.isPlainObject(setting)) {
                if (typeof setting.name === 'string') {
                    name = setting.name;
                } else {
                    name = key;
                }
            } else if (typeof setting === 'string') {
                name = setting;
                setting = {
                    name: setting
                }
            } else {
                name = key;
                setting = {
                    name: key
                }
            }

            this._attributes[key] = name;
            this._settings[name] = setting;
            this._defaultValues[name] = setting.defaultValue;

            if (typeof setting.group !== 'undefined' && setting.optional === false) {
                var group = this._groups[setting.group];
                if (!$.isArray(group)) {
                    group = [];
                    this._groups[setting.group] = group;
                }

                group.push(setting);
            }
        },

        is: function (attribute) {
            return this._settings.hasOwnProperty(attribute);
        },

        setting: function (attribute) {
            var setting = this._settings[attribute];

            if (setting === null || typeof setting === 'undefined') {
                return null;
            } else {
                return setting;
            }
        },

        group: function (attribute) {
            var group = this._groups[attribute];

            if (group === null || typeof group === 'undefined') {
                return null;
            } else {
                return group;
            }
        },

        validate: function (attribute, value) {
            var setting = this.setting(attribute);

            if (setting === null) {
                return false;
            } else if ($.isFunction(setting.validate)) {
                return setting.validate(value);
            } else {
                return true;
            }
        },

        validateProperties: function (obj) {
            var instance = this;
            var groups = {};

            $.each(obj, function (attribute, value) {

                // check if it's a valid value
                if (!instance.is(attribute)) {
                    throw new Error('The attribute "' + attribute + '" is not valid.');
                } else if (!instance.validate(attribute, value)) {
                    throw new Error('The value "' + value + '" is invalid for the property "' + attribute + '".');
                }

                var setting = instance.setting(attribute);
                var groupName = setting.group;

                if (typeof groupName !== 'undefined' && setting.optional === false) {
                    var group = groups[groupName];
                    if (!$.isArray(group)) {
                        group = [];
                        groups[groupName] = group;
                    }

                    group.push(setting.name);
                }
            });

            // check the groups, we validate if for each found group the needed values exists
            $.each(groups, function (groupName, attributeNames) {
                var group = instance.group(groupName);

                // get all the settings for the group (i.e., all the none-optional attributes)
                $.each(group, function (idx, groupSetting) {
                    if ($.inArray(groupSetting.name, attributeNames) === -1) {
                        throw new Error('The group "' + groupName + '" expects a valid value for the attribute "' + groupSetting.name + '".');
                    }
                });
            });

            return true;
        }
    };

    //noinspection JSUnresolvedFunction
    misc.export(dependencyScope, 'AttributeCollection', AttributeCollection);
}(window, dependencyScope);


text:
@class KNThirdViewController;

@interface KNSecondViewController : UIViewController {
  KNThirdViewController * semiVC;
}
- (IBAction)buttonDidTouch:(id)sender;

- (IBAction)dismissBtnClick:(id)sender;

@end


text:
shared_any<InstallerLog *, close_delete> InstallerLog::Instance;

InstallerLog::InstallerLog(void)
    : m_enabled(false)
{

}

void InstallerLog::Write(const std::wstring& message)
{
	if (! IsEnabled() || message.empty())
		return;

    if (get(m_hFile) == INVALID_HANDLE_VALUE)
    {
        if (m_logfile.empty())
        {
			m_logfile = DVLib::DirectoryCombine(DVLib::GetTemporaryDirectoryW(), L"dotNetInstallerLog.txt").c_str();
        }

		std::wstring path = DVLib::GetFileDirectoryW(m_logfile);
		if (path.length()) DVLib::DirectoryCreate(path);

		reset(m_hFile, ::CreateFile(m_logfile.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
			NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL));

		CHECK_WIN32_BOOL(m_hFile,
			L"Error creating or opening \"" << m_logfile << L"\"");

	    SetFilePointer(get(m_hFile), 0, 0, FILE_END);
    }

	DWORD l_BytesWritten = 0;

	std::stringstream message_s;
	message_s << DVLib::FormatCurrentDateTimeA() << "\t" << DVLib::wstring2string(message) << "\r\n";

	CHECK_WIN32_BOOL(WriteFile(get(m_hFile), message_s.str().c_str(), message_s.str().size(),  & l_BytesWritten, NULL),
		L"Error writing to \"" << m_logfile << L"\"");
}

void InstallerLog::SetLogFile(const std::wstring& filename)
{
	m_logfile = InstallerSession::Instance->ExpandVariables(filename);
}

void InstallerLog::CloseLog()
{
	reset(m_hFile);
}


text:
'use strict';

var _ = require('lodash');
var qs = require('querystring');
var path = require('path');
var async = require('async');
var request = require('request');

var config = require(path.join(__dirname, '..', '..', '..', 'config/env'));
var tokenService = require(path.join(__dirname, '..', '..', '..', 'services/token'));
var db = require(path.join(__dirname, '..', '..', '..', 'config/sequelize'));

exports.loginWithTwitter = function(req, res) {
  var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
  var accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
  var profileUrl = 'https://api.twitter.com/1.1/users/show.json?screen_name=';

  if (!req.body.oauth_token || !req.body.oauth_verifier) {
    var requestTokenOauth = {
      consumer_key: config.TWITTER_KEY,
      consumer_secret: config.TWITTER_SECRET,
      callback: req.body.redirectUri
    };

    // Step 1. Exchange authorization code for access token.
    request.post({
      url: requestTokenUrl,
      oauth: requestTokenOauth
    }, function(err, response, body) {
      var oauthToken = qs.parse(body);
      res.send(oauthToken);
    });
  } else {
    var accessTokenOauth = {
      consumer_key: config.TWITTER_KEY,
      consumer_secret: config.TWITTER_SECRET,
      token: req.body.oauth_token,
      verifier: req.body.oauth_verifier
    };

    request.post(accessTokenUrl, {
      url: accessTokenUrl,
      oauth: accessTokenOauth
    }, function(err, response, token) {
      var accessToken = qs.parse(token);

      var profileOauth = {
        consumer_key: config.TWITTER_KEY,
        consumer_secret: config.TWITTER_SECRET,
        oauth_token: accessToken.oauth_token
      };

      // Step 2. Retrieve profile information about the current user.
      request.get({
        url: profileUrl + accessToken.screen_name,
        oauth: profileOauth,
        json: true
      }, function(err, response, profile) {
        if (profile.error) {
          return res.status(500).send({
            message: profile.error.message
          });
        }
        // Step 3a. Link user accounts.
        if (req.headers.authorization) {
          db.User.findOne({
            where: {
              twitter: profile.id
            }
          }).then(function(existingUser) {
            if (existingUser) {
              return res.status(409).send({
                message: 'There is already a Twitter account that belongs to you'
              });
            }
            var token = req.headers.authorization.split(' ')[1];
            var payload = tokenService.decodeToken(token, config.TOKEN_SECRET);

            db.User.findById(payload.sub).then(function(user) {
              user.twitter = profile.id;
              user.displayName = user.displayName || profile.name;
              user.picture = user.picture || profile.profile_image_url.replace('_normal', '');
              user.save().then(function() {
                var token = tokenService.issueToken(user);
                res.send({
                  token: token
                });
              }).catch(function(err) {
                return res.status(400).send({
                  message: err
                });
              });
            }).catch(function() {
              return res.status(400).send({
                message: 'User not found'
              });
            });
          }).catch(function(err) {
            return res.status(400).send({
              message: err
            });
          });
        } else {
          // Step 3b. Create a new user account or return an existing one.
          db.User.findOne({
            where: {
              twitter: profile.id
            }
          }).then(function(existingUser) {
            if (existingUser) {
              return res.send({
                token: tokenService.issueToken(existingUser)
              });
            }
            db.User.create({
              twitter: profile.id,
              displayName: profile.name,
              picture: profile.profile_image_url.replace('_normal', '')
            }).then(function (user) {
              var token = tokenService.issueToken(user);
              res.send({
                token: token
              });
            }).catch(function (err) {
              return res.status(400).send({
                message: err
              });
            });

          }).catch(function(err) {
            return res.status(400).send({
              message: err
            });
          });
        }
      });
    });
  }
};


text:
package com.sequenceiq.cloudbreak.cm;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;

import com.cloudera.api.swagger.ClouderaManagerResourceApi;
import com.cloudera.api.swagger.ClustersResourceApi;
import com.cloudera.api.swagger.client.ApiClient;
import com.cloudera.api.swagger.client.ApiException;
import com.cloudera.api.swagger.model.ApiCommand;
import com.cloudera.api.swagger.model.ApiCommandList;
import com.cloudera.api.swagger.model.ApiConfigureForKerberosArguments;
import com.sequenceiq.cloudbreak.client.HttpClientConfig;
import com.sequenceiq.cloudbreak.cm.client.ClouderaManagerApiClientProvider;
import com.sequenceiq.cloudbreak.cm.client.ClouderaManagerClientInitException;
import com.sequenceiq.cloudbreak.cm.client.retry.ClouderaManagerApiFactory;
import com.sequenceiq.cloudbreak.cm.polling.ClouderaManagerPollingServiceProvider;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.domain.stack.cluster.Cluster;
import com.sequenceiq.cloudbreak.dto.KerberosConfig;
import com.sequenceiq.cloudbreak.service.CloudbreakException;
import com.sequenceiq.cloudbreak.template.kerberos.KerberosDetailService;
import com.sequenceiq.cloudbreak.type.KerberosType;

@RunWith(MockitoJUnitRunner.class)
public class ClouderaManagerKerberosServiceTest {

    @Mock
    private ClouderaManagerPollingServiceProvider clouderaManagerPollingServiceProvider;

    @Mock
    private ApplicationContext applicationContext;

    @Mock
    private ClouderaManagerResourceApi clouderaManagerResourceApi;

    @Mock
    private ClouderaManagerModificationService modificationService;

    @Mock
    private ClustersResourceApi clustersResourceApi;

    @Mock
    private ClouderaManagerApiClientProvider clouderaManagerApiClientProvider;

    @Mock
    private ClouderaManagerApiFactory clouderaManagerApiFactory;

    @Mock
    private ClouderaManagerClusterDecommissionService decommissionService;

    @Mock
    private KerberosDetailService kerberosDetailService;

    @Mock
    private ApiClient client;

    @Mock
    private ClouderaManagerConfigService clouderaManagerConfigService;

    @Mock
    private ClouderaManagerCommonCommandService clouderaManagerCommonCommandService;

    @InjectMocks
    private ClouderaManagerKerberosService underTest;

    private Stack stack;

    private Cluster cluster;

    private HttpClientConfig clientConfig;

    @Before
    public void init() throws ClouderaManagerClientInitException {
        stack = new Stack();
        stack.setName("clusterName");
        stack.setGatewayPort(1);
        cluster = new Cluster();
        cluster.setName("clusterName");
        cluster.setCloudbreakUser("user");
        cluster.setCloudbreakPassword("password");
        stack.setCluster(cluster);
        stack.setResourceCrn("crn:cdp:cloudbreak:us-west-1:someone:stack:12345");
        clientConfig = new HttpClientConfig("1.2.3.4", null, null, null);
        when(clouderaManagerApiClientProvider.getV31Client(anyInt(), anyString(), anyString(), any())).thenReturn(client);
        when(clouderaManagerApiFactory.getClouderaManagerResourceApi(client)).thenReturn(clouderaManagerResourceApi);
        when(clouderaManagerApiFactory.getClustersResourceApi(client)).thenReturn(clustersResourceApi);
        when(applicationContext.getBean(eq(ClouderaManagerModificationService.class), eq(stack), eq(clientConfig))).thenReturn(modificationService);
        when(applicationContext.getBean(eq(ClouderaManagerClusterDecommissionService.class), eq(stack), eq(clientConfig))).thenReturn(decommissionService);
    }

    @Test
    public void testConfigureKerberosViaApi() throws CloudbreakException, ApiException {
        KerberosConfig kerberosConfig = KerberosConfig.KerberosConfigBuilder.aKerberosConfig()
                .withType(KerberosType.ACTIVE_DIRECTORY)
                .withRealm("TESTREALM")
                .withUrl("kdcs")
                .withAdminUrl("adminhosts")
                .withContainerDn("container")
                .withPrincipal("principal")
                .withPassword("pw")
                .build();

        when(clustersResourceApi.configureForKerberos(eq(cluster.getName()), any(ApiConfigureForKerberosArguments.class)))
                .thenReturn(new ApiCommand().id(BigDecimal.TEN));
        when(clouderaManagerResourceApi.generateCredentialsCommand()).thenReturn(new ApiCommand().id(BigDecimal.ZERO));
        when(clustersResourceApi.listActiveCommands(anyString(), anyString(), isNull())).thenReturn(new ApiCommandList().addItemsItem(
                new ApiCommand().name("NotDeployClusterClientConfig").id(BigDecimal.valueOf(1L))));
        when(clouderaManagerCommonCommandService.getDeployClientConfigCommandId(any(), any(), any())).thenReturn(BigDecimal.valueOf(2L));
        when(kerberosDetailService.isAdJoinable(kerberosConfig)).thenReturn(Boolean.TRUE);

        underTest.configureKerberosViaApi(client, clientConfig, stack, kerberosConfig);

        verify(modificationService).stopCluster(false);
        verify(clouderaManagerPollingServiceProvider).startPollingCmKerberosJob(stack, client, BigDecimal.TEN);
        verify(clouderaManagerPollingServiceProvider).startPollingCmKerberosJob(stack, client, BigDecimal.ZERO);
        verify(clouderaManagerCommonCommandService).getDeployClientConfigCommandId(any(), any(), any());
        verify(modificationService).startCluster();
    }

    @Test
    public void deleteCredentials() throws ApiException, CloudbreakException, ClouderaManagerClientInitException {
        when(clouderaManagerApiFactory.getClouderaManagerResourceApi(client)).thenReturn(clouderaManagerResourceApi);
        when(clouderaManagerResourceApi.deleteCredentialsCommand("all")).thenReturn(new ApiCommand().id(BigDecimal.ZERO));

        underTest.deleteCredentials(clientConfig, stack);

        verify(modificationService).stopCluster(false);
        clouderaManagerPollingServiceProvider.startPollingCmKerberosJob(stack, client, BigDecimal.ZERO);
    }
}