text:
/**
 * themelist helper, can be used to display lists of themes based on the config theme array
 *
 * Usage:
 *
 * {{themelist current=theme.id}}
 *
 */

'use strict';

const hbs = require('hbs');
const config = require('config');
const themes = config.has('themes') && Array.isArray(config.get('themes')) ? config.get('themes') : false;

module.exports = function () {
	const context = arguments[arguments.length - 1];
	const defaultTheme = themes ? themes.find((theme) => theme.isDefault).id : false;
	const themeId = context.hash.current ? context.hash.current : process.env.THEME || defaultTheme;
	const markup = [];

	if (themes) {
		markup.push('
');
		for (const theme of themes) {
			if (theme.id === themeId) {
				markup.push(`<li><span>${theme.name} (current)</span></li>`);
			} else {
				markup.push(`<li><a href="/theme/${theme.id}">${theme.name}</a></li>`);
			}
		}
		markup.push('
');
	} else {
		markup.push('
no themes defined
');
	}

	return new hbs.handlebars.SafeString(markup.join(''));
};


text:
#ifndef LOG_H
#define LOG_H
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dirent.h>

#define TIME_STRING_SIZE 10
#define MAX_MESSAGE_SIZE 1024

/*
 * Shows commits in chronological order.
 */
void show_commits();

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace backend\models\search;

use common\models\Lang;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Stock;

/**
 * StockSearch represents the model behind the search form about `backend\models\Stock`.
 */
class StockSearch extends Stock
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'created_at', 'updated_at', 'enabled', 'stock_city_id'], 'integer'],
            [['title'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Stock::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id'            => $this->id,
            'created_at'    => $this->created_at,
            'updated_at'    => $this->updated_at,
            'enabled'       => $this->enabled,
            'stock_city_id' => $this->stock_city_id
        ]);

        /**
         * Filtering by the multilingual fields
         */
        $query->join('left join', $this->tableLang, $this->tableLang . '.stock_id = ' . self::tableName() . '.id');

        $query->andFilterWhere([
            'like', 'title', $this->title,
        ])->andFilterWhere([
            'like', 'language', Lang::getCurrent()->url
        ]);

        return $dataProvider;
    }
}


text:
package com.cloudcog.images.resize.worker;

import java.io.File;
import java.util.concurrent.ExecutorService;

import com.cloudcog.images.resize.FolderWatcher;
import com.cloudcog.images.resize.utils.FileUtils;

/**
 *
 * @author mpahic
 *
 */
public class WorkersFactory {

	private ExecutorService threadExecutor;
	private FolderWatcher folderWatcher;

	public WorkersFactory(ExecutorService threadExecutor, FolderWatcher folderWatcher) {
		this.threadExecutor = threadExecutor;
		this.folderWatcher = folderWatcher;
	}

	public void startFileWorker(File file) {
		if(FileUtils.isFileImage(file.getName())) {
			threadExecutor.execute(new ResizeWorker(file));
		} else if (FileUtils.isFileZip(file.getName())) {
    		threadExecutor.execute(new UnzipWorker(file));

    	} else if (file.isDirectory()) {
    		folderWatcher.watchFolder(file);
    	}
	}
}


text:
package org.apache.hyracks.storage.am.lsm.rtree.impls;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.storage.am.common.api.ITreeIndex;
import org.apache.hyracks.storage.am.common.api.IndexException;
import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager;
import org.apache.hyracks.storage.am.lsm.common.impls.LSMComponentFileReferences;
import org.apache.hyracks.storage.am.lsm.common.impls.TreeIndexFactory;
import org.apache.hyracks.storage.common.file.IFileMapProvider;

public class LSMRTreeFileManager extends AbstractLSMIndexFileManager {
    private static final String RTREE_STRING = "r";
    private static final String BTREE_STRING = "b";

    private final TreeIndexFactory<? extends ITreeIndex> rtreeFactory;
    private final TreeIndexFactory<? extends ITreeIndex> btreeFactory;

    private static FilenameFilter btreeFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return !name.startsWith(".") && name.endsWith(BTREE_STRING);
        }
    };

    private static FilenameFilter rtreeFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return !name.startsWith(".") && name.endsWith(RTREE_STRING);
        }
    };

    public LSMRTreeFileManager(IFileMapProvider fileMapProvider, FileReference file,
            TreeIndexFactory<? extends ITreeIndex> rtreeFactory, TreeIndexFactory<? extends ITreeIndex> btreeFactory) {
        super(fileMapProvider, file, null);
        this.rtreeFactory = rtreeFactory;
        this.btreeFactory = btreeFactory;
    }

    @Override
    public LSMComponentFileReferences getRelFlushFileReference() {
        String ts = getCurrentTimestamp();
        String baseName = baseDir + ts + SPLIT_STRING + ts;
        // Begin timestamp and end timestamp are identical since it is a flush
        return new LSMComponentFileReferences(createFlushFile(baseName + SPLIT_STRING + RTREE_STRING),
                createFlushFile(baseName + SPLIT_STRING + BTREE_STRING), createFlushFile(baseName + SPLIT_STRING
                        + BLOOM_FILTER_STRING));
    }

    @Override
    public LSMComponentFileReferences getRelMergeFileReference(String firstFileName, String lastFileName)
            throws HyracksDataException {
        String[] firstTimestampRange = firstFileName.split(SPLIT_STRING);
        String[] lastTimestampRange = lastFileName.split(SPLIT_STRING);

        String baseName = baseDir + firstTimestampRange[0] + SPLIT_STRING + lastTimestampRange[1];
        // Get the range of timestamps by taking the earliest and the latest
        // timestamps
        return new LSMComponentFileReferences(createMergeFile(baseName + SPLIT_STRING + RTREE_STRING),
                createMergeFile(baseName + SPLIT_STRING + BTREE_STRING), createMergeFile(baseName + SPLIT_STRING
                        + BLOOM_FILTER_STRING));
    }

    @Override
    public List<LSMComponentFileReferences> cleanupAndGetValidFiles() throws HyracksDataException, IndexException {
        List<LSMComponentFileReferences> validFiles = new ArrayList<LSMComponentFileReferences>();
        ArrayList<ComparableFileName> allRTreeFiles = new ArrayList<ComparableFileName>();
        ArrayList<ComparableFileName> allBTreeFiles = new ArrayList<ComparableFileName>();
        ArrayList<ComparableFileName> allBloomFilterFiles = new ArrayList<ComparableFileName>();

        // Create a transaction filter <- to hide transaction components->
        FilenameFilter transactionFilter = getTransactionFileFilter(false);

        // Gather files.
        cleanupAndGetValidFilesInternal(getCompoundFilter(transactionFilter, btreeFilter), btreeFactory, allBTreeFiles);
        HashSet<String> btreeFilesSet = new HashSet<String>();
        for (ComparableFileName cmpFileName : allBTreeFiles) {
            int index = cmpFileName.fileName.lastIndexOf(SPLIT_STRING);
            btreeFilesSet.add(cmpFileName.fileName.substring(0, index));
        }
        validateFiles(btreeFilesSet, allRTreeFiles, getCompoundFilter(transactionFilter, rtreeFilter), rtreeFactory);
        validateFiles(btreeFilesSet, allBloomFilterFiles, getCompoundFilter(transactionFilter, bloomFilterFilter), null);

        // Sanity check.
        if (allRTreeFiles.size() != allBTreeFiles.size() || allBTreeFiles.size() != allBloomFilterFiles.size()) {
            throw new HyracksDataException(
                    "Unequal number of valid RTree, BTree, and Bloom Filter files found. Aborting cleanup.");
        }

        // Trivial cases.
        if (allRTreeFiles.isEmpty() || allBTreeFiles.isEmpty() || allBloomFilterFiles.isEmpty()) {
            return validFiles;
        }

        if (allRTreeFiles.size() == 1 && allBTreeFiles.size() == 1 && allBloomFilterFiles.size() == 1) {
            validFiles.add(new LSMComponentFileReferences(allRTreeFiles.get(0).fileRef, allBTreeFiles.get(0).fileRef,
                    allBloomFilterFiles.get(0).fileRef));
            return validFiles;
        }

        // Sorts files names from earliest to latest timestamp.
        Collections.sort(allRTreeFiles);
        Collections.sort(allBTreeFiles);
        Collections.sort(allBloomFilterFiles);

        List<ComparableFileName> validComparableRTreeFiles = new ArrayList<ComparableFileName>();
        ComparableFileName lastRTree = allRTreeFiles.get(0);
        validComparableRTreeFiles.add(lastRTree);

        List<ComparableFileName> validComparableBTreeFiles = new ArrayList<ComparableFileName>();
        ComparableFileName lastBTree = allBTreeFiles.get(0);
        validComparableBTreeFiles.add(lastBTree);

        List<ComparableFileName> validComparableBloomFilterFiles = new ArrayList<ComparableFileName>();
        ComparableFileName lastBloomFilter = allBloomFilterFiles.get(0);
        validComparableBloomFilterFiles.add(lastBloomFilter);

        for (int i = 1; i < allRTreeFiles.size(); i++) {
            ComparableFileName currentRTree = allRTreeFiles.get(i);
            ComparableFileName currentBTree = allBTreeFiles.get(i);
            ComparableFileName currentBloomFilter = allBloomFilterFiles.get(i);
            // Current start timestamp is greater than last stop timestamp.
            if (currentRTree.interval[0].compareTo(lastRTree.interval[1]) > 0
                    && currentBTree.interval[0].compareTo(lastBTree.interval[1]) > 0
                    && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[1]) > 0) {
                validComparableRTreeFiles.add(currentRTree);
                validComparableBTreeFiles.add(currentBTree);
                validComparableBloomFilterFiles.add(currentBloomFilter);
                lastRTree = currentRTree;
                lastBTree = currentBTree;
                lastBloomFilter = currentBloomFilter;
            } else if (currentRTree.interval[0].compareTo(lastRTree.interval[0]) >= 0
                    && currentRTree.interval[1].compareTo(lastRTree.interval[1]) <= 0
                    && currentBTree.interval[0].compareTo(lastBTree.interval[0]) >= 0
                    && currentBTree.interval[1].compareTo(lastBTree.interval[1]) <= 0
                    && currentBloomFilter.interval[0].compareTo(lastBloomFilter.interval[0]) >= 0
                    && currentBloomFilter.interval[1].compareTo(lastBloomFilter.interval[1]) <= 0) {
                // Invalid files are completely contained in last interval.
                File invalidRTreeFile = new File(currentRTree.fullPath);
                invalidRTreeFile.delete();
                File invalidBTreeFile = new File(currentBTree.fullPath);
                invalidBTreeFile.delete();
                File invalidBloomFilterFile = new File(currentBloomFilter.fullPath);
                invalidBloomFilterFile.delete();
            } else {
                // This scenario should not be possible.
                throw new HyracksDataException("Found LSM files with overlapping but not contained timetamp intervals.");
            }
        }

        // Sort valid files in reverse lexicographical order, such that newer
        // files come first.
        Collections.sort(validComparableRTreeFiles, recencyCmp);
        Collections.sort(validComparableBTreeFiles, recencyCmp);
        Collections.sort(validComparableBloomFilterFiles, recencyCmp);

        Iterator<ComparableFileName> rtreeFileIter = validComparableRTreeFiles.iterator();
        Iterator<ComparableFileName> btreeFileIter = validComparableBTreeFiles.iterator();
        Iterator<ComparableFileName> bloomFilterFileIter = validComparableBloomFilterFiles.iterator();
        while (rtreeFileIter.hasNext() && btreeFileIter.hasNext()) {
            ComparableFileName cmpRTreeFileName = rtreeFileIter.next();
            ComparableFileName cmpBTreeFileName = btreeFileIter.next();
            ComparableFileName cmpBloomFilterFileName = bloomFilterFileIter.next();
            validFiles.add(new LSMComponentFileReferences(cmpRTreeFileName.fileRef, cmpBTreeFileName.fileRef,
                    cmpBloomFilterFileName.fileRef));
        }
        return validFiles;
    }

    @Override
    public LSMComponentFileReferences getNewTransactionFileReference() throws IOException {
        String ts = getCurrentTimestamp();
        // Create transaction lock file
        Files.createFile(Paths.get(baseDir + TRANSACTION_PREFIX + ts));

        String baseName = baseDir + ts + SPLIT_STRING + ts;
        return new LSMComponentFileReferences(createFlushFile(baseName + SPLIT_STRING + RTREE_STRING),
                createFlushFile(baseName + SPLIT_STRING + BTREE_STRING), createFlushFile(baseName + SPLIT_STRING
                        + BLOOM_FILTER_STRING));
    }

    @Override
    public LSMComponentFileReferences getTransactionFileReferenceForCommit() throws HyracksDataException {
        FilenameFilter transactionFilter;
        File dir = new File(baseDir);
        String[] files = dir.list(transactionFileNameFilter);
        if (files.length == 0) {
            return null;
        }
        if (files.length != 1) {
            throw new HyracksDataException("More than one transaction lock found:" + files.length);
        } else {
            transactionFilter = getTransactionFileFilter(true);
            String txnFileName = dir.getPath() + File.separator + files[0];
            // get the actual transaction files
            files = dir.list(transactionFilter);
            if (files.length < 3) {
                throw new HyracksDataException("LSM Rtree transaction has less than 3 files :" + files.length);
            }
            try {
                Files.delete(Paths.get(txnFileName));
            } catch (IOException e) {
                throw new HyracksDataException("Failed to delete transaction lock :" + txnFileName);
            }
        }
        File rTreeFile = null;
        File bTreeFile = null;
        File bloomFilterFile = null;
        for (String fileName : files) {
            if (fileName.endsWith(BTREE_STRING)) {
                bTreeFile = new File(dir.getPath() + File.separator + fileName);
            } else if (fileName.endsWith(RTREE_STRING)) {
                rTreeFile = new File(dir.getPath() + File.separator + fileName);
            } else if (fileName.endsWith(BLOOM_FILTER_STRING)) {
                bloomFilterFile = new File(dir.getPath() + File.separator + fileName);
            } else {
                throw new HyracksDataException("unrecognized file found = " + fileName);
            }
        }
        FileReference rTreeFileRef = new FileReference(rTreeFile);
        FileReference bTreeFileRef = new FileReference(bTreeFile);
        FileReference bloomFilterFileRef = new FileReference(bloomFilterFile);
        return new LSMComponentFileReferences(rTreeFileRef, bTreeFileRef, bloomFilterFileRef);
    }
}


text:
package com.ibm.bi.dml.test.integration.applications.pydml;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import com.ibm.bi.dml.test.integration.applications.CsplineCGTest;

@RunWith(value = Parameterized.class)
public class CsplineCGPyDMLTest extends CsplineCGTest {

	public CsplineCGPyDMLTest(int rows, int cols) {
		super(rows, cols);
	}

	@Test
	public void testCsplineCGPyDml() {
		testCsplineCG(ScriptType.PYDML);
	}

}


text:
var KNETMAPS = KNETMAPS || {};

KNETMAPS.KnetMaps = function() {

	var maskloader = KNETMAPS.MaskLoader();
	var generator = KNETMAPS.Generator();

	var drawDiv = function(target/*, networkId*/) {
		$(target).html("
"
				+ "<input type='submit' id='maximizeOverlay' class='max unhover' value='' title='Toggle full screen' onclick='KNETMAPS.Menu().OnMaximizeClick();' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
				+ "<input type='submit' id='showAll' value='' class='unhover' onclick='KNETMAPS.Menu().showAll();' title='Show all the concept & relations in the Network' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
				+ "<input type='submit' id='openItemInfoBtn' value='' class='unhover' onclick='KNETMAPS.Menu().popupItemInfo();' title='Show Info box' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
				+ "<input type='submit' id='relayoutNetwork' value='' class='unhover' onclick='KNETMAPS.Menu().rerunLayout();' title='Re-run the Layout' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
				+ "<input type='submit' id='resetNetwork' value='' class='unhover' onclick='KNETMAPS.Menu().resetGraph();' title='Reposition (reset and re-fit) the graph' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
                                + ""
				+ "<select id='layouts_dropdown' class='knet-dropdowns' onChange='KNETMAPS.Menu().rerunLayout();' title='Select network layout'>"
				+ "<option value='cose_layout' selected='selected' title='using CoSE layout algorithm (useful for larger networks with clustering)'>CoSE layout</option>"
				+ "<option value='ngraph_force_layout' title='using ngraph_force layout (works well on planar graphs)'>Force layout</option>"
				+ "<option value='circle_layout'>Circular layout</option>"
				+ "<option value='concentric_layout'>Concentric layout</option>"
				+ "<option value='coseBilkent_layout' title='using CoSE-Bilkent layout (with node clustering, but performance-intensive for larger networks)'>CoSE-Bilkent layout</option>"
			/*	+ "<option value='euler_layout'>Euler layout</option>"
                                + "<option* value='random_layout'>Random layout</option>" */
				+ "</select>"
				+ "<select id='changeLabelVisibility' class='knet-dropdowns' onChange='KNETMAPS.Menu().showHideLabels(this.value);' title='Select label visibility'>"
				+ "<option value='None' selected='selected'>Labels: None</option>"
				+ "<option value='Concepts'>Labels: Concepts</option>"
				+ "<option value='Relations'>Labels: Relations</option>"
				+ "<option value='Both'>Labels: Both</option>"
				+ "</select>"
				+ "<select id='changeLabelFont' class='knet-dropdowns' onChange='KNETMAPS.Menu().changeLabelFontSize(this.value);' title='Select label font size'>"
				+ "<option value='8'>Label size: 8px</option>"
				+ "<option value='12'>Label size: 12px</option>"
				+ "<option value='16' selected='selected'>Label size: 16px</option>"
				+ "<option value='20'>Label size: 20px</option>"
				+ "<option value='24'>Label size: 24px</option>"
				+ "<option value='28'>Label size: 28px</option>"
				+ "<option value='32'>Label size: 32px</option>"
				+ "<option value='36'>Label size: 36px</option>"
				+ "<option value='40'>Label size: 40px</option>"
				+ "</select>"
				+ ""
			/*	+ "<input type='submit' id='saveJSON' value='' class='unhover' onclick='KNETMAPS.Menu().exportAsJson(\""+networkId+"\");' title='Save the knetwork to knetspace' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
				+ "<input type='submit' id='openJSON' value='' class='unhover' onclick='KNETMAPS.Menu().importJson();' title='Import a kNetwork json' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
				+ "<input type='submit' id='savePNG' value='' class='unhover' onclick='KNETMAPS.Menu().exportAsImage();' title='Export the network as a .png image' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>" */
				+ "<input type='submit' id='helpURL' value='' class='unhover' onclick='KNETMAPS.Menu().openKnetHelpPage();' title='Go to help documentation' onmouseover='KNETMAPS.Menu().onHover($(this));' onmouseout='KNETMAPS.Menu().offHover($(this));'>"
			/*	+ "<input type='file' accept='.json,.cyjs.json,.cyjs,.cx' id='openNetworkFile' onchange='KNETMAPS.Menu().OpenKnetFile(event);' >"
                                + "<button id='saveJSON' style='float:right;' class='btn knet_button' onclick='KNETMAPS.Menu().exportAsJson(\""+networkId+"\");' title='Save the knetwork to knetspace'>Save</button>" */
				+ "
 "
				+ "
 "
				+ "
"
				+ "
Info box:	"
				+ "<input type='submit' id='btnCloseItemInfoPane' value='' onclick='KNETMAPS.ItemInfo().closeItemInfoPane();'>	"
				+ "

"
				+ "
"
				+ ""
				+ "

"
				+ ""
				+ "
Concepts:
"
				+ ""
				+ "
KnetMaps
"
				+ "

 "
				);
	};

	var showDiv = function(target) {
		$(target).css("display", "block"); // show the KnetMaps block
	};

	var my = function() {};

	// Exposed API

	my.drawRaw = function(target, graph/*, networkId*/) {
		drawDiv(target/*, networkId*/);
		showDiv(target);
		maskloader.showNetworkLoader(target);
		generator.generateNetworkGraphRaw(graph);
		maskloader.removeNetworkLoader(target);
	};

	my.draw = function(target, eles_jsons, metadata_json, eles_styles/*, networkId*/) {
		drawDiv(target/*, networkId*/);
		showDiv(target);
		maskloader.showNetworkLoader(target);
		generator.generateNetworkGraph(eles_jsons, metadata_json, eles_styles);
		maskloader.removeNetworkLoader(target);
	};

	return my;
};


text:
<form class="form-horizontal form-complex">

	Dropdown List *

<select name="action.puppet_enterprise_victorops_integration.param.dropdown_list" id="puppet_enterprise_victorops_integration_dropdown_list">
        <option value="CRITICAL">CRITICAL</option>
        <option value="ACKNOWLEDGEMENT">ACKNOWLEDGEMENT</option>
        <option value="INFO">INFO</option>
</select>

	Alert Entity ID *

	<input type="text" name="action.puppet_enterprise_victorops_integration.param.alert_entity_id" id="puppet_enterprise_victorops_integration_alert_entity_id"/>

	State Message *

	<input type="text" name="action.puppet_enterprise_victorops_integration.param.state_message" id="puppet_enterprise_victorops_integration_state_message"/>

</form>


text: Gerador de QrCodes usando o google url Shorter


text:
/**
 * @brief Service B.5
 *
 *  This code is auto-generated from the Excel Workbook
 *  'GATT_Test_Databases.xlsm' Sheet: 'Large Database 1'
 */
#include <zephyr/sys/byteorder.h>
#include <zephyr/sys/printk.h>

#include <zephyr/bluetooth/gatt.h>

#include "gatt_macs.h"

/**
 *  @brief UUID for the Service B.5
 */
#define BT_UUID_SERVICE_B_5             BT_UUID_DECLARE_16(0xa00b)

/**
 *  @brief UUID for the Value V8 Characteristic
 */
#define BT_UUID_VALUE_V8                BT_UUID_DECLARE_16(0xb008)

/**
 *  @brief UUID for the Descriptor V8D1 Characteristic
 */
#define BT_UUID_DES_V8D1                BT_UUID_DECLARE_16(0xb015)

/**
 *  @brief UUID for the Descriptor V8D2 Characteristic
 */
#define BT_UUID_DES_V8D2                BT_UUID_DECLARE_16(0xb016)

/**
 *  @brief UUID for the Descriptor V8D3 Characteristic
 */
#define BT_UUID_DES_V8D3                BT_UUID_DECLARE_16(0xb017)

static uint8_t   value_v8_value = 0x08;
static uint8_t   des_v8d1_value = 0x01;
static uint8_t   des_v8d2_value = 0x02;
static uint8_t   des_v8d3_value = 0x03;
static bool   bAuthorized;

/**
 * @brief Attribute read call back for the Value V8 attribute
 *
 * @param conn   The connection that is requesting to read
 * @param attr   The attribute that's being read
 * @param buf    Buffer to place the read result in
 * @param len    Length of data to read
 * @param offset Offset to start reading from
 *
 * @return       Number of bytes read, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t read_value_v8(struct bt_conn *conn,
			     const struct bt_gatt_attr *attr, void *buf,
			     uint16_t len, uint16_t offset)
{
	const uint8_t *value = attr->user_data;

	return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
				 sizeof(value_v8_value));
}

/**
 * @brief Attribute write call back for the Value V8 attribute
 *
 * @param conn   The connection that is requesting to write
 * @param attr   The attribute that's being written
 * @param buf    Buffer with the data to write
 * @param len    Number of bytes in the buffer
 * @param offset Offset to start writing from
 * @param flags  Flags (BT_GATT_WRITE_*)
 *
 * @return       Number of bytes written, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t write_value_v8(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, const void *buf,
			      uint16_t len, uint16_t offset, uint8_t flags)
{
	uint8_t *value = attr->user_data;

	if (offset >= sizeof(value_v8_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
	if (offset + len > sizeof(value_v8_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);

	memcpy(value + offset, buf, len);

	return len;
}

/**
 * @brief Attribute read call back for the Descriptor V8D1 attribute
 *
 * @param conn   The connection that is requesting to read
 * @param attr   The attribute that's being read
 * @param buf    Buffer to place the read result in
 * @param len    Length of data to read
 * @param offset Offset to start reading from
 *
 * @return       Number of bytes read, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t read_des_v8d1(struct bt_conn *conn,
			     const struct bt_gatt_attr *attr, void *buf,
			     uint16_t len, uint16_t offset)
{
	const uint8_t *value = attr->user_data;

	return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
				 sizeof(des_v8d1_value));
}

/**
 * @brief Attribute write call back for the Descriptor V8D1 attribute
 *
 * @param conn   The connection that is requesting to write
 * @param attr   The attribute that's being written
 * @param buf    Buffer with the data to write
 * @param len    Number of bytes in the buffer
 * @param offset Offset to start writing from
 * @param flags  Flags (BT_GATT_WRITE_*)
 *
 * @return       Number of bytes written, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t write_des_v8d1(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, const void *buf,
			      uint16_t len, uint16_t offset, uint8_t flags)
{
	uint8_t *value = attr->user_data;

	if (offset >= sizeof(des_v8d1_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
	if (offset + len > sizeof(des_v8d1_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);

	memcpy(value + offset, buf, len);

	return len;
}

/**
 * @brief Attribute read call back for the Descriptor V8D2 attribute
 *
 * @param conn   The connection that is requesting to read
 * @param attr   The attribute that's being read
 * @param buf    Buffer to place the read result in
 * @param len    Length of data to read
 * @param offset Offset to start reading from
 *
 * @return       Number of bytes read, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t read_des_v8d2(struct bt_conn *conn,
			     const struct bt_gatt_attr *attr, void *buf,
			     uint16_t len, uint16_t offset)
{
	const uint8_t *value = attr->user_data;

	if (!bAuthorized)
		return BT_GATT_ERR(BT_ATT_ERR_AUTHORIZATION);

	return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
				 sizeof(des_v8d2_value));
}

/**
 * @brief Attribute write call back for the Descriptor V8D2 attribute
 *
 * @param conn   The connection that is requesting to write
 * @param attr   The attribute that's being written
 * @param buf    Buffer with the data to write
 * @param len    Number of bytes in the buffer
 * @param offset Offset to start writing from
 * @param flags  Flags (BT_GATT_WRITE_*)
 *
 * @return       Number of bytes written, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t write_des_v8d2(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, const void *buf,
			      uint16_t len, uint16_t offset, uint8_t flags)
{
	uint8_t *value = attr->user_data;

	if (offset >= sizeof(des_v8d2_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
	if (offset + len > sizeof(des_v8d2_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
	if (!bAuthorized)
		return BT_GATT_ERR(BT_ATT_ERR_AUTHORIZATION);

	memcpy(value + offset, buf, len);

	return len;
}

/**
 * @brief Attribute read call back for the Descriptor V8D3 attribute
 *
 * @param conn   The connection that is requesting to read
 * @param attr   The attribute that's being read
 * @param buf    Buffer to place the read result in
 * @param len    Length of data to read
 * @param offset Offset to start reading from
 *
 * @return       Number of bytes read, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t read_des_v8d3(struct bt_conn *conn,
			     const struct bt_gatt_attr *attr, void *buf,
			     uint16_t len, uint16_t offset)
{
	const uint8_t *value = attr->user_data;

	return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
				 sizeof(des_v8d3_value));
}

/**
 * @brief Attribute write call back for the Descriptor V8D3 attribute
 *
 * @param conn   The connection that is requesting to write
 * @param attr   The attribute that's being written
 * @param buf    Buffer with the data to write
 * @param len    Number of bytes in the buffer
 * @param offset Offset to start writing from
 * @param flags  Flags (BT_GATT_WRITE_*)
 *
 * @return       Number of bytes written, or in case of an error - BT_GATT_ERR()
 *               with a specific ATT error code.
 */
static ssize_t write_des_v8d3(struct bt_conn *conn,
			      const struct bt_gatt_attr *attr, const void *buf,
			      uint16_t len, uint16_t offset, uint8_t flags)
{
	uint8_t *value = attr->user_data;

	if (offset >= sizeof(des_v8d3_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
	if (offset + len > sizeof(des_v8d3_value))
		return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);

	memcpy(value + offset, buf, len);

	return len;
}

struct bt_gatt_attr service_b_5_1_attrs[] = {
	BT_GATT_H_PRIMARY_SERVICE(BT_UUID_SERVICE_B_5, 0x80),
	BT_GATT_H_CHARACTERISTIC(BT_UUID_VALUE_V8,
		BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
		BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_ENCRYPT,
		read_value_v8, write_value_v8, &value_v8_value, 0x81),
	BT_GATT_H_DESCRIPTOR(BT_UUID_DES_V8D1,
		BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN,
		read_des_v8d1, write_des_v8d1, &des_v8d1_value, 0x83),
	BT_GATT_H_DESCRIPTOR(BT_UUID_DES_V8D2,
		BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
		read_des_v8d2, write_des_v8d2, &des_v8d2_value, 0x84),
	BT_GATT_H_DESCRIPTOR(BT_UUID_DES_V8D3,
		BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_WRITE_ENCRYPT,
		read_des_v8d3, write_des_v8d3, &des_v8d3_value, 0x85)
};

static struct bt_gatt_service service_b_5_1_svc =
		    BT_GATT_SERVICE(service_b_5_1_attrs);

/**
 * @brief Register the Service B.5 and all its Characteristics...
 */
void service_b_5_1_init(void)
{
	bt_gatt_service_register(&service_b_5_1_svc);
}

/**
 * @brief Un-Register the Service B.5 and all its Characteristics...
 */
void service_b_5_1_remove(void)
{
	bt_gatt_service_unregister(&service_b_5_1_svc);
}

/**
 * @brief Set authorization for Characteristics and Descriptors in Service B.5.
 */
void service_b_5_1_authorize(bool authorized)
{
	bAuthorized = authorized;
}


text:
package nl.esciencecenter.xenon;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import nl.esciencecenter.xenon.engine.XenonEngine;

/**
 * @author Jason Maassen <J.Maassen@esciencecenter.nl>
 *
 */
public class Util {
    /**
     * Invoke the private constructor of XenonEngine. Needed in some tests.
     *
     * @param properties
     *            the properties to pass to the XenonEngine.
     * @return a new XenonEngine.
     * @throws Exception
     *             if the XenonEngine could not be created or throws an exception.
     */
    public static XenonEngine createXenonEngine(HashMap<String, String> properties) throws Exception {
        Constructor<XenonEngine> constructor = XenonEngine.class.getDeclaredConstructor(Map.class);
        constructor.setAccessible(true);
        return constructor.newInstance(properties);
    }

    /**
     * Invoke the private end method of XenonEngine. Needed in some tests.
     *
     * @param e
     *            the XenonEngine to end.
     * @throws Exception
     *             if the method could not be invoked.
     */
    public static void endXenonEngine(XenonEngine e) throws Exception {
        Method method = XenonEngine.class.getDeclaredMethod("end");
        method.setAccessible(true);
        method.invoke(e);
    }

    private Util() {
        // utility class only
    }
}


text:
package com.github.aha.isis.tester;

import java.io.IOException;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

import com.github.aha.isis.tester.dto.IsisTestDTO;
import com.github.aha.isis.tester.dto.Question;
import com.github.aha.isis.tester.dto.Response;
import com.github.aha.isis.tester.dto.Section;
import com.github.aha.isis.tester.service.XmlMarshaller;

@RunWith(SpringRunner.class)
@SpringBootTest
public class IsisTestDTOTests {

    /**
     * Class logger
     */
    private static final Logger LOG = LoggerFactory.getLogger(IsisTestDTOTests.class);

	private static final String TEST_541 = "3PA541";

    @Value("${data.xml.path}")
    private String xmlPath;

	@Autowired
	private XmlMarshaller xmlMarshaller;

	@Test
	public void loadXML() throws IOException {
		long startTime = System.currentTimeMillis();
		String fileName = String.format("%s/%s.xml", xmlPath, TEST_541);
		IsisTestDTO dto = (IsisTestDTO) this.xmlMarshaller.loadXML(fileName);
        LOG.debug("comment={}, loading={}ms" , dto.getComment(), System.currentTimeMillis() - startTime);
        if (!CollectionUtils.isEmpty(dto.getSections())) {
        	LOG.debug("no. of params={}" , dto.getSections().size());
        	for (Section section : dto.getSections()) {
        		LOG.debug("Section [ident={}, title={}]", section.getIdent(), section.getTitle());
        		Collection<Question> questions = section.getQuestions();
        		if (!CollectionUtils.isEmpty(questions)) {
        			for (Question question : questions) {
        				LOG.debug("\tQuestion [ident={}, type={}, title={}]", question.getIdent(), question.getType(), question.getTitle());
                		Collection<Response> responses = question.getResponses();
                		if (!CollectionUtils.isEmpty(responses)) {
                			for (Response response : responses) {
                				LOG.debug("\t\tResponse [ident={}, right={}, title={}]", response.getIdent(), response.getRight(), response.getTitle());
                			}
                		}
        			}
        		}
			}
        }
	}
}


text:
#pragma once

#include "ExceptionOr.h"
#include "SVGPropertyTraits.h"

namespace WebCore {

class SVGAngleValue {
    WTF_MAKE_FAST_ALLOCATED;
public:
    enum Type {
        SVG_ANGLETYPE_UNKNOWN = 0,
        SVG_ANGLETYPE_UNSPECIFIED = 1,
        SVG_ANGLETYPE_DEG = 2,
        SVG_ANGLETYPE_RAD = 3,
        SVG_ANGLETYPE_GRAD = 4
    };

    Type unitType() const { return m_unitType; }

    void setValue(float);
    float value() const;

    void setValueInSpecifiedUnits(float valueInSpecifiedUnits) { m_valueInSpecifiedUnits = valueInSpecifiedUnits; }
    float valueInSpecifiedUnits() const { return m_valueInSpecifiedUnits; }

    ExceptionOr<void> setValueAsString(const String&);
    String valueAsString() const;

    ExceptionOr<void> newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
    ExceptionOr<void> convertToSpecifiedUnits(unsigned short unitType);

private:
    Type m_unitType { SVG_ANGLETYPE_UNSPECIFIED };
    float m_valueInSpecifiedUnits { 0 };
};

template<> struct SVGPropertyTraits<SVGAngleValue> {
    static SVGAngleValue initialValue() { return SVGAngleValue(); }
    static String toString(const SVGAngleValue& type) { return type.valueAsString(); }
};

}


text:
layout: page
title: Phelps Excellent Limited Show
date: 2016-05-24
author: Nicole Jimenez
tags: weekly links, java
status: published
summary: Quisque luctus convallis molestie. Phasellus tincidunt semper enim.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 12/23/2018
  endDate: 12/27/2018
  ctyhocn: FATWHHX
  groupCode: PELS
published: true
---
Vivamus posuere mollis odio vel rhoncus. Integer magna erat, elementum ut urna eget, mattis posuere dolor. In ultrices sollicitudin vehicula. Nam nisi urna, malesuada eu metus vestibulum, interdum eleifend purus. Aenean scelerisque diam eu lorem pretium mattis. Nam in ante elit. Curabitur porttitor semper tortor non volutpat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam mi arcu, venenatis nec rhoncus ac, egestas et sem. Duis ut tortor porttitor, egestas nibh vitae, dapibus elit. Donec eleifend arcu ac diam cursus, a pretium neque convallis.

* Fusce tincidunt est ac odio tincidunt aliquam
* Phasellus vitae lorem interdum, pretium est id, porta felis
* Nullam tristique lorem ut ipsum vehicula, a varius ligula imperdiet
* Sed volutpat lectus eget sapien finibus, vitae efficitur augue gravida.

Nullam vitae eros diam. Curabitur hendrerit nisl dui, a consequat est faucibus non. Donec eu ex in eros scelerisque cursus. Sed interdum, risus sit amet ornare rhoncus, nisi tortor aliquet libero, ut lacinia magna tortor vitae nunc. Nunc orci nisl, congue et molestie vitae, maximus id enim. Nunc libero ante, lacinia at diam pharetra, fringilla sollicitudin eros. Duis sed purus orci.


text:
require 'test_helper'

class WitnessTest < ActiveSupport::TestCase
  test "privacy withholds witness name and contact details" do
    witness = witnesses(:alice)

    privacy_withheld_str = '(Withheld)'

    witness.privacy = Witness.privacy_levels[:private]
    assert_equal privacy_withheld_str, witness.name, 'Witness name not withheld when privacy set to private'
    assert_equal privacy_withheld_str, witness.contact, 'Witness contact details not withheld when privacy set to private'

    witness.privacy = Witness.privacy_levels[:public]
    refute_equal privacy_withheld_str, witness.name, 'Witness name withheld when privacy set to public'
    refute_equal privacy_withheld_str, witness.contact, 'Witness contact details withheld when privacy set to public'
  end

  test "can set private levels via level, string, and symbol" do
    witness = Witness.new

    inputs = [0, :public, "Public"]
    inputs.each do |input|
      assert_nil witness.privacy_level
      witness.privacy = input
      assert_equal Witness.privacy_levels[:public], witness.privacy_level
      witness.privacy_level = nil
    end
  end

  test "correct mapping of privacy level to canonical meanings" do
    assert_equal 0, Witness.privacy_levels[:public]
    assert_equal 1, Witness.privacy_levels[:private]
  end

  test "can get human-readble privacy setting" do
    witness = witnesses(:alice)
    witness.privacy = Witness.privacy_levels[:private]
    assert_equal 'Private', witness.privacy

    witness.privacy = Witness.privacy_levels[:public]
    assert_equal 'Public', witness.privacy
  end
end


text:
    <form role="form" name="form">

            Change options like '_excludedNonValids'

                {blur : maxLnegth(5)}; Change options on the fly. Current excluded non-valids behaviour '{{getCurrentExcludedNonValidsBeh()}}';
                <button ng-click="setCurrentExcludedNonValidsBeh('validate')" id="switchBehToValidateBtn">Switch to 'validate'</button>
                <button ng-click="setCurrentExcludedNonValidsBeh('setValid')" id="switchBehToSetValidBtn">Switch to 'setValid'</button>
                <input type="text"
                       class="form-control"
                       name="controllerExampleA"
                       ng-model="controllerExampleA"
                       ng-dynamic-validator="{blur: maxLength(5)}"
                       controller-demo-directive />
                Model state : {{controllerExampleA}}

            Add \ remove input to validate together groups
            Values must be equal. To get the expected validation behaviour - click the 'add to group' button. Otherwise validation will lag by one character.

                This input is already included in the right group
                <input type="text"
                       class="form-control"
                       name="controllerExampleBValA"
                       ng-model="vtgTestValues.a"
                       ng-dynamic-validator="{default: aMustEqualB,
                                            _validateTogetherGroups:['dce']}"
                       controller-demo-directive />
                Model state : {{vtgTestValues.a}}

                    This input is currently {{isPartOfVTGroup() ? 'included in the right group' : 'not included in the right group'}}
                    <button ng-click="addToValidateTogetherGroup()" id="addToVTGBtn">Add to group</button>
                    <button ng-click="removeFromValidateTogetherGroup()" id="removeFromVTGBtn">Remove from group </button>

                <input type="text"
                       class="form-control"
                       name="controllerExampleBValB"
                       ng-model="vtgTestValues.b"
                       ng-dynamic-validator="{default: aMustEqualB}"
                       controller-demo-directive />
                Model state : {{vtgTestValues.b}}

            Add \ remove input to request groups

                    This input is currently {{isPartOfRequestGroup() ? 'included in the group' : 'not included in the group'}}
                    <button ng-click="addToRequestGroup()" id="addToRGBtn">Add to group</button>
                    <button ng-click="removeFromRequestGroup()" id="removeFromRGBtn">Remove from group </button>

                <input type="text"
                       class="form-control"
                       name="controllerExampleC"
                       ng-model="controllerExampleC"
                       ng-dynamic-validator="{$testRequest: maxLength(5)}"
                       controller-demo-directive />
                Model state : {{controllerExampleC}}

                    <button class="btn btn-primary" id="requestGroupValidationBtn" ng-click="requestValidation()"> Request group validation maxLength(5)</button>

            Add \ remove validators

                    This minLength(5) validator is currently {{hasMinLengthValidator() ? 'present' : 'not present'}}
                    <button ng-click="addMinLengthValidator()" id="addValidatorBtn">Add validator</button>
                    <button ng-click="removeMinLengthValidator()" id="removeValidatorBtn">Remove validator</button>

                <input type="text"
                       class="form-control"
                       name="controllerExampleD"
                       ng-model="controllerExampleD"
                       ng-dynamic-validator="{}"
                       controller-demo-directive />
                Model state : {{controllerExampleD}}

    </form>


text:
<?php

namespace CfdiUtilsTests\Elements\Cfdi33;

use CfdiUtils\Elements\Cfdi33\Addenda;
use CfdiUtils\Nodes\Node;
use PHPUnit\Framework\TestCase;

final class AddendaTest extends TestCase
{
    /** @var Addenda */
    public $element;

    public function setUp(): void
    {
        parent::setUp();
        $this->element = new Addenda();
    }

    public function testGetElementName()
    {
        $this->assertSame('cfdi:Addenda', $this->element->getElementName());
    }

    public function testAdd()
    {
        $this->assertCount(0, $this->element);

        $firstChild = new Node('first');
        $addReturn = $this->element->add($firstChild);
        $this->assertSame($this->element, $addReturn);
        $this->assertCount(1, $this->element);
        $this->assertSame($firstChild, $this->element->searchNode('first'));

        $secondChild = new Node('second');
        $this->element->add($secondChild);
        $this->assertCount(2, $this->element);
        $this->assertSame($secondChild, $this->element->searchNode('second'));
    }
}


text:
<?php

namespace Common\Core;

/**
 * This class will initiate the application
 *
 * @author Ghazi Triki <ghazi.triki@inhanx.com>
 */
abstract class Init extends \KernelLoader
{
    /**
     * Current type
     *
     * @var    string
     */
    protected $type;

    /**
     * Allowed types
     *
     * @var array
     */
    protected $allowedTypes;

    /**
     * @param string $type The type of init to load, possible values are: frontend, frontend_ajax, frontend_js.
     */
    public function initialize($type)
    {
        $type = (string) $type;

        // check if this is a valid type
        if (!in_array($type, $this->allowedTypes)) {
            exit('Invalid init-type');
        }
        $this->type = $type;

        // set a default timezone if no one was set by PHP.ini
        if (ini_get('date.timezone') == '') {
            date_default_timezone_set('Europe/Brussels');
        }

        // get last modified time for globals
        $lastModifiedTime = @filemtime(PATH_WWW . '/app/config/parameters.yml');

        // reset last modified time if needed when invalid or debug is active
        if ($lastModifiedTime === false || $this->getContainer()->getParameter('kernel.debug')) {
            $lastModifiedTime = time();
        }

        // define as a constant
        defined('LAST_MODIFIED_TIME') || define('LAST_MODIFIED_TIME', $lastModifiedTime);
    }
}


text:
package com.alipay.api;

import java.io.Serializable;

/**
 *
 *
 * @author jiehua
 * @version $Id: EncryptReponseItem.java, v 0.1 2016-3-28 下午6:20:04 jiehua Exp $
 */
public class ResponseEncryptItem implements Serializable {

    /**  */
    private static final long serialVersionUID = 6680775791485372169L;

    /**
     * 响应返回
     */
    private String            respContent;

    /**
     * 处理完后的返回
     */
    private String            realContent;

    /**
     * @param respContent
     * @param realContent
     */
    public ResponseEncryptItem(String respContent, String realContent) {
        super();
        this.respContent = respContent;
        this.realContent = realContent;
    }

    /**
     * Getter method for property <tt>respContent</tt>.
     *
     * @return property value of respContent
     */
    public String getRespContent() {
        return respContent;
    }

    /**
     * Getter method for property <tt>realContent</tt>.
     *
     * @return property value of realContent
     */
    public String getRealContent() {
        return realContent;
    }

}


text:
<?php

namespace Slim\Extras\Middleware\Cache;

Interface ICacheHandler
{
    /**
     * Retrieve content from cache.
     * Looks up content in the cache for the given key and returns either
     * an array with the content or false if the content is not found.
     *
     * @param string $key the cache key
     * @return array|false array with the elements content_type and body on
     *  success, false if content not found
     */
    public function fetch($key);

    /**
     * Store content in the cache.
     * Persists content in the cache storeage for later lookup.
     *
     * @param string $key the cache key
     * @param string $contenType the content's Content-Type
     * @param string $body the content
     */
    public function save($key, $contentType, $body);
}


text:
package org.apache.flink.runtime.taskmanager;

import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.TaskInfo;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.blob.BlobCache;
import org.apache.flink.runtime.broadcast.BroadcastVariableManager;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor;
import org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor;
import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.librarycache.LibraryCacheManager;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.JobInformation;
import org.apache.flink.runtime.executiongraph.TaskInformation;
import org.apache.flink.runtime.filecache.FileCache;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.network.NetworkEnvironment;
import org.apache.flink.runtime.io.network.netty.PartitionProducerStateChecker;
import org.apache.flink.runtime.io.network.partition.ResultPartitionConsumableNotifier;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.StoppableTask;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.metrics.groups.TaskIOMetricGroup;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.concurrent.Executor;

import scala.concurrent.duration.FiniteDuration;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ TaskDeploymentDescriptor.class, JobID.class, FiniteDuration.class })
public class TaskStopTest {
	private Task task;

	public void doMocking(AbstractInvokable taskMock) throws Exception {

		TaskInfo taskInfoMock = mock(TaskInfo.class);
		when(taskInfoMock.getTaskNameWithSubtasks()).thenReturn("dummyName");

		TaskManagerRuntimeInfo tmRuntimeInfo = mock(TaskManagerRuntimeInfo.class);
		when(tmRuntimeInfo.getConfiguration()).thenReturn(new Configuration());

		TaskMetricGroup taskMetricGroup = mock(TaskMetricGroup.class);
		when(taskMetricGroup.getIOMetricGroup()).thenReturn(mock(TaskIOMetricGroup.class));

		task = new Task(
			mock(JobInformation.class),
			new TaskInformation(
				new JobVertexID(),
				"test task name",
				1,
				1,
				"foobar",
				new Configuration()),
			mock(ExecutionAttemptID.class),
			mock(AllocationID.class),
			0,
			0,
			Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
			Collections.<InputGateDeploymentDescriptor>emptyList(),
			0,
			mock(TaskStateSnapshot.class),
			mock(MemoryManager.class),
			mock(IOManager.class),
			mock(NetworkEnvironment.class),
			mock(BroadcastVariableManager.class),
			mock(TaskManagerActions.class),
			mock(InputSplitProvider.class),
			mock(CheckpointResponder.class),
			mock(BlobCache.class),
			mock(LibraryCacheManager.class),
			mock(FileCache.class),
			tmRuntimeInfo,
			taskMetricGroup,
			mock(ResultPartitionConsumableNotifier.class),
			mock(PartitionProducerStateChecker.class),
			mock(Executor.class));
		Field f = task.getClass().getDeclaredField("invokable");
		f.setAccessible(true);
		f.set(task, taskMock);

		Field f2 = task.getClass().getDeclaredField("executionState");
		f2.setAccessible(true);
		f2.set(task, ExecutionState.RUNNING);
	}

	@Test(timeout = 20000)
	public void testStopExecution() throws Exception {
		StoppableTestTask taskMock = new StoppableTestTask();
		doMocking(taskMock);

		task.stopExecution();

		while (!taskMock.stopCalled) {
			Thread.sleep(100);
		}
	}

	@Test(expected = RuntimeException.class)
	public void testStopExecutionFail() throws Exception {
		AbstractInvokable taskMock = mock(AbstractInvokable.class);
		doMocking(taskMock);

		task.stopExecution();
	}

	private final static class StoppableTestTask extends AbstractInvokable implements StoppableTask {
		public volatile boolean stopCalled = false;

		@Override
		public void invoke() throws Exception {
		}

		@Override
		public void stop() {
			this.stopCalled = true;
		}
	}

}


text:
package ru.skuznetsov;
/**
* Class som info about class.
*/
public class Counter {
	/**
	* Method calculates the sum of even numbers in ramge.
	* @param start - first number on range
	* @param finish - last number on range
	* @return sum of numbers in range.
	*/
    public int add(int start, int finish) {

      int counter = 0;
        if (start < finish) {

            for (int i = start; i < finish; i++) {
                if (i % 2 == 0) {
					counter += i;
				}
            }

         return counter;
        } else if (start > finish) {

            for (int i = finish; i < start; i++) {
                if (i % 2 == 0) {
					counter += i;
				}
            }
         return counter;

        } else {
         return 0;
        }
    }
}


text:
package org.apache.vxquery.xmlquery.ast;

import java.util.List;

import org.apache.vxquery.util.SourceLocation;

public class LetClauseNode extends FLWORClauseNode {
    private List<LetVarDeclNode> variables;

    public LetClauseNode(SourceLocation loc) {
        super(loc);
    }

    @Override
    public ASTTag getTag() {
        return ASTTag.LET_CLAUSE;
    }

    public List<LetVarDeclNode> getVariables() {
        return variables;
    }

    public void setVariables(List<LetVarDeclNode> variables) {
        this.variables = variables;
    }
}


text:
import * as React from 'react';
import Router from './Router';

type E = React.ReactElement;
export function isReactChildren(object: E | E[]): boolean;
export function createRouteFromReactElement(element: E): Router.PlainRoute;
export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[];
export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[];


text:
package daemon

import (
	"encoding/json"
	"fmt"
	"github.com/rancher/convoy/api"
	"net/http"
)

func decodeRequest(r *http.Request, v interface{}) error {
	return json.NewDecoder(r.Body).Decode(v)
}

func sendResponse(w http.ResponseWriter, v interface{}) error {
	resp, err := api.ResponseOutput(v)
	if err != nil {
		return err
	}
	_, err = w.Write(resp)
	if err != nil {
		return err
	}
	return nil
}

func writeResponseOutput(w http.ResponseWriter, v interface{}) error {
	output, err := api.ResponseOutput(v)
	if err != nil {
		return err
	}
	log.Debugln("Response: ", string(output))
	_, err = w.Write(output)
	return err
}

func writeStringResponse(w http.ResponseWriter, s string) error {
	log.Debugln("Response: ", s)
	_, err := w.Write([]byte(s))
	return err
}

func (s *daemon) doInfo(version string, w http.ResponseWriter, r *http.Request, objs map[string]string) error {
	s.GlobalLock.RLock()
	defer s.GlobalLock.RUnlock()

	var err error
	_, err = w.Write([]byte(fmt.Sprint("{\n\"General\": ")))
	if err != nil {
		return err
	}

	data, err := api.ResponseOutput(&s.daemonConfig)
	if err != nil {
		return err
	}
	_, err = w.Write(data)
	if err != nil {
		return err
	}
	for _, driver := range s.ConvoyDrivers {
		if _, err := w.Write([]byte(fmt.Sprintf(",\n\"%v\": ", driver.Name()))); err != nil {
			return err
		}

		info, err := driver.Info()
		if err != nil {
			return err
		}
		data, err = api.ResponseOutput(info)
		if err != nil {
			return err
		}
		_, err = w.Write(data)
		if err != nil {
			return err
		}
	}

	if _, err := w.Write([]byte(fmt.Sprint("\n}"))); err != nil {
		return err
	}

	return nil
}


text:
package org.apache.pulsar.broker.loadbalance.impl;

import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import java.util.Map;
import java.util.Random;
import org.apache.pulsar.broker.loadbalance.PlacementStrategy;
import org.apache.pulsar.broker.loadbalance.ResourceUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * This class implements PlacementStrategy based on Weighted Round Robin Algorithm.
 */
public class WRRPlacementStrategy implements PlacementStrategy {
    private static final Logger log = LoggerFactory.getLogger(WRRPlacementStrategy.class);
    private final Random rand = new Random();

    /**
     * Function : getByWeightedRoundRobin returns ResourceUnit selected by WRR algorithm
     *              based on available resource on RU.
     * <code>
     * ^
     * |
     * |
     * |
     * |                |                        |                                |     |
     * |                |                        |                                |     |
     * |   Broker 2     |       Broker 3         |         Broker 1               |  B4 |
     * |                |                        |                                |     |
     * +----------------+------------------------+--------------------------------+---------
     * 0                20                       50                               90    100
     *
     * This is weighted Round robin, we calculate weight based on availability of resources;
     * total availability is taken as a full range then each broker is given range based on
     *  its resource availability, if the number generated within total range happens to be in
     * broker's range, that broker is selected
     * </code>
     */
    public ResourceUnit findBrokerForPlacement(Multimap<Long, ResourceUnit> finalCandidates) {
        if (finalCandidates.isEmpty()) {
            return null;
        }
        log.debug("Total Final Candidates selected - [{}]", finalCandidates.size());
        int totalAvailability = 0;
        for (Map.Entry<Long, ResourceUnit> candidateOwner : finalCandidates.entries()) {
            totalAvailability += candidateOwner.getKey().intValue();
        }
        ResourceUnit selectedRU = null;
        if (totalAvailability <= 0) {
            // todo: this means all the brokers are overloaded and we can't assign this namespace to any broker
            // for now, pick anyone and return that one, because when we don't have ranking we put O for each broker
            return Iterables.get(finalCandidates.get(0L), rand.nextInt(finalCandidates.size()));
        }
        int weightedSelector = rand.nextInt(totalAvailability);
        log.debug("Generated Weighted Selector Number - [{}] ", weightedSelector);
        int weightRangeSoFar = 0;
        for (Map.Entry<Long, ResourceUnit> candidateOwner : finalCandidates.entries()) {
            weightRangeSoFar += candidateOwner.getKey();
            if (weightedSelector < weightRangeSoFar) {
                selectedRU = candidateOwner.getValue();
                log.debug(" Weighted Round Robin Selected RU - [{}]", candidateOwner.getValue().getResourceId());
                break;
            }
        }
        return selectedRU;
    }
}


text:
import { DDDraggable } from './dd-draggable';

export class DDManager {
  static dragElement: DDDraggable;
}


text:
layout: post.njk
title: "PreviewJS"
summary: "Lets you preview your React components within Visual Studio Code. Great because it lets you see how it will look without having to start a server. You can pass along properties and supports storybook. There's even a pro edition if you want to support the developer with a few extra options."
thumb: "/images/toolbox/2022-04-13_12-09-22.png"
links:
  - website: "https://previewjs.com/"
category:
tags:
  - external
---


text:
<?php

class Google_Service_ShoppingContent_MerchantOrderReturnItem extends Google_Collection
{
  protected $collection_key = 'returnShipmentIds';
  protected $customerReturnReasonType = 'Google_Service_ShoppingContent_CustomerReturnReason';
  protected $customerReturnReasonDataType = '';
  public $itemId;
  protected $merchantRejectionReasonType = 'Google_Service_ShoppingContent_MerchantRejectionReason';
  protected $merchantRejectionReasonDataType = '';
  protected $merchantReturnReasonType = 'Google_Service_ShoppingContent_RefundReason';
  protected $merchantReturnReasonDataType = '';
  protected $productType = 'Google_Service_ShoppingContent_OrderLineItemProduct';
  protected $productDataType = '';
  protected $refundableAmountType = 'Google_Service_ShoppingContent_MonetaryAmount';
  protected $refundableAmountDataType = '';
  public $returnItemId;
  public $returnShipmentIds;
  public $shipmentGroupId;
  public $shipmentUnitId;
  public $state;

  /**
   * @param Google_Service_ShoppingContent_CustomerReturnReason
   */
  public function setCustomerReturnReason(Google_Service_ShoppingContent_CustomerReturnReason $customerReturnReason)
  {
    $this->customerReturnReason = $customerReturnReason;
  }
  /**
   * @return Google_Service_ShoppingContent_CustomerReturnReason
   */
  public function getCustomerReturnReason()
  {
    return $this->customerReturnReason;
  }
  public function setItemId($itemId)
  {
    $this->itemId = $itemId;
  }
  public function getItemId()
  {
    return $this->itemId;
  }
  /**
   * @param Google_Service_ShoppingContent_MerchantRejectionReason
   */
  public function setMerchantRejectionReason(Google_Service_ShoppingContent_MerchantRejectionReason $merchantRejectionReason)
  {
    $this->merchantRejectionReason = $merchantRejectionReason;
  }
  /**
   * @return Google_Service_ShoppingContent_MerchantRejectionReason
   */
  public function getMerchantRejectionReason()
  {
    return $this->merchantRejectionReason;
  }
  /**
   * @param Google_Service_ShoppingContent_RefundReason
   */
  public function setMerchantReturnReason(Google_Service_ShoppingContent_RefundReason $merchantReturnReason)
  {
    $this->merchantReturnReason = $merchantReturnReason;
  }
  /**
   * @return Google_Service_ShoppingContent_RefundReason
   */
  public function getMerchantReturnReason()
  {
    return $this->merchantReturnReason;
  }
  /**
   * @param Google_Service_ShoppingContent_OrderLineItemProduct
   */
  public function setProduct(Google_Service_ShoppingContent_OrderLineItemProduct $product)
  {
    $this->product = $product;
  }
  /**
   * @return Google_Service_ShoppingContent_OrderLineItemProduct
   */
  public function getProduct()
  {
    return $this->product;
  }
  /**
   * @param Google_Service_ShoppingContent_MonetaryAmount
   */
  public function setRefundableAmount(Google_Service_ShoppingContent_MonetaryAmount $refundableAmount)
  {
    $this->refundableAmount = $refundableAmount;
  }
  /**
   * @return Google_Service_ShoppingContent_MonetaryAmount
   */
  public function getRefundableAmount()
  {
    return $this->refundableAmount;
  }
  public function setReturnItemId($returnItemId)
  {
    $this->returnItemId = $returnItemId;
  }
  public function getReturnItemId()
  {
    return $this->returnItemId;
  }
  public function setReturnShipmentIds($returnShipmentIds)
  {
    $this->returnShipmentIds = $returnShipmentIds;
  }
  public function getReturnShipmentIds()
  {
    return $this->returnShipmentIds;
  }
  public function setShipmentGroupId($shipmentGroupId)
  {
    $this->shipmentGroupId = $shipmentGroupId;
  }
  public function getShipmentGroupId()
  {
    return $this->shipmentGroupId;
  }
  public function setShipmentUnitId($shipmentUnitId)
  {
    $this->shipmentUnitId = $shipmentUnitId;
  }
  public function getShipmentUnitId()
  {
    return $this->shipmentUnitId;
  }
  public function setState($state)
  {
    $this->state = $state;
  }
  public function getState()
  {
    return $this->state;
  }
}


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

<TITLE>
Uses of Package org.springframework.jmx.export.metadata (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.springframework.jmx.export.metadata

Packages that use org.springframework.jmx.export.metadata

org.springframework.jmx.export.annotation
JDK 1.5+ annotations for MBean exposure.

org.springframework.jmx.export.assembler
Provides a strategy for MBeanInfo assembly.

org.springframework.jmx.export.metadata
Provides generic JMX metadata classes and basic support for reading
JMX metadata in a provider-agnostic manner.

org.springframework.jmx.export.naming
Provides a strategy for ObjectName creation.

Classes in org.springframework.jmx.export.metadata used by org.springframework.jmx.export.annotation

InvalidMetadataException

          Thrown by the JmxAttributeSource when it encounters
 incorrect metadata on a managed resource or one of its methods.

JmxAttributeSource

          Interface used by the MetadataMBeanInfoAssembler to
 read source-level metadata from a managed resource's class.

ManagedAttribute

          Metadata that indicates to expose a given bean property as JMX attribute.

ManagedNotification

          Metadata that indicates a JMX notification emitted by a bean.

ManagedOperation

          Metadata that indicates to expose a given method as JMX operation.

ManagedOperationParameter

          Metadata about JMX operation parameters.

ManagedResource

          Metadata indicating that instances of an annotated class
 are to be registered with a JMX server.

Classes in org.springframework.jmx.export.metadata used by org.springframework.jmx.export.assembler

JmxAttributeSource

          Interface used by the MetadataMBeanInfoAssembler to
 read source-level metadata from a managed resource's class.

ManagedNotification

          Metadata that indicates a JMX notification emitted by a bean.

Classes in org.springframework.jmx.export.metadata used by org.springframework.jmx.export.metadata

AbstractJmxAttribute

          Base class for all JMX metadata classes.

InvalidMetadataException

          Thrown by the JmxAttributeSource when it encounters
 incorrect metadata on a managed resource or one of its methods.

JmxAttributeSource

          Interface used by the MetadataMBeanInfoAssembler to
 read source-level metadata from a managed resource's class.

ManagedAttribute

          Metadata that indicates to expose a given bean property as JMX attribute.

ManagedNotification

          Metadata that indicates a JMX notification emitted by a bean.

ManagedOperation

          Metadata that indicates to expose a given method as JMX operation.

ManagedOperationParameter

          Metadata about JMX operation parameters.

ManagedResource

          Metadata indicating that instances of an annotated class
 are to be registered with a JMX server.

Classes in org.springframework.jmx.export.metadata used by org.springframework.jmx.export.naming

JmxAttributeSource

          Interface used by the MetadataMBeanInfoAssembler to
 read source-level metadata from a managed resource's class.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2007 The Spring Framework.