text:
<!doctype html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script src="../../assert_selection.js"></script>
<script>
// Soft line break after white space
const kStyle = 'line-break:after-white-space; width:100px; font: 20px monospace;';
const isMac = navigator.platform.indexOf('Mac') === 0;
const kBehaviors = window.internals ? ['mac', 'win'] : isMac ? ['mac'] : ['win'];
for (const behavior of kBehaviors) {
  if (window.internals) {
    internals.settings.setEditingBehavior(behavior);
    internals.settings.setSelectTrailingWhitespaceEnabled(behavior !== 'mac');
  }

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">|line1 line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">^line1| line2 a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">^line1 |line2 a line3</div>`,
  `${behavior} 22-0 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">l|ine1 line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">l^ine1| line2 a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">l^ine1 |line2 a line3</div>`,
  `${behavior} 22-1 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">li|ne1 line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">li^ne1| line2 a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">li^ne1 |line2 a line3</div>`,
  `${behavior} 22-2 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">lin|e1 line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">lin^e1| line2 a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">lin^e1 |line2 a line3</div>`,
  `${behavior} 22-3 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line|1 line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line^1| line2 a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line^1 |line2 a line3</div>`,
  `${behavior} 22-4 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1| line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1^ line2| a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1^ |line2 a line3</div>`,
  `${behavior} 22-5 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 |line2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 ^line2| a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 ^line2 |a line3</div>`,
  `${behavior} 22-6 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 l|ine2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 l^ine2| a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 l^ine2 |a line3</div>`,
  `${behavior} 22-7 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 li|ne2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 li^ne2| a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 li^ne2 |a line3</div>`,
  `${behavior} 22-8 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 lin|e2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 lin^e2| a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 lin^e2 |a line3</div>`,
  `${behavior} 22-9 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line|2 a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line^2| a line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line^2 |a line3</div>`,
  `${behavior} 22-10 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2| a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2^ a| line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2^ |a line3</div>`,
  `${behavior} 22-11 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 |a line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 ^a| line3</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 ^a |line3</div>`,
  `${behavior} 22-12 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 a| line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  behavior === 'mac'
      ? `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a^ line3|</div>`
      : `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a^ |line3</div>`,
  `${behavior} 22-13 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 a |line3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a ^line3|</div>`,
  `${behavior} 22-14 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 a l|ine3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a l^ine3|</div>`,
  `${behavior} 22-15 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 a li|ne3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a li^ne3|</div>`,
  `${behavior} 22-16 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 a lin|e3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a lin^e3|</div>`,
  `${behavior} 22-17 rtl left word`);

selection_test(
  `<div contenteditable dir="rtl" style="${kStyle}">line1 line2 a line|3</div>`,
  selection => selection.modify('extend', 'left', 'word'),
  `<div contenteditable dir="rtl" style="line-break:after-white-space; width:100px; font: 20px monospace;">line1 line2 a line^3|</div>`,
  `${behavior} 22-18 rtl left word`);
}
</script>


text:
module.exports = function (moduleName : string) {
'use strict';

angular.module(moduleName + 'Module')
    .controller(moduleName + 'Controller',
        ['$scope',
            function ($scope) {

    console.log(moduleName + 'Controller');
}]);

};

redpajama_set_name: RedPajamaGithub


text:
{% extends 'base.html' %}
{% block title %}
Applicant Home Page
{% endblock %}
{% block hrefbrand %}
{% url 'index' %}
{% endblock %}
{% block dropdown %}

  Log Out

{% endblock %}
{% block content %}

Hello, {{ user.First_Name }} {{ user.Last_Name }}

This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.

To futher advance your applicantion, you are required to submit requirements and fill up the education form.

      Skill Matching

Employee's Data

Employee No: {{ user.employee.Employee_No }}

Name: {{ user.Last_Name }}, {{ user.First_Name }}

Gender: {{ user.applicant.Gender }}

Civil Status: {{ user.applicant.Civil_Status }}

Phone: {{ user.applicant.Phone }}

Address: {{ user.applicant.Bldg_No }}, {{ user.applicant.Street }},
                        {{ user.applicant.Municipality }}, {{ user.applicant.City }},
                        {{ user.applicant.Country }}

Birth Date: {{ user.applicant.Birth_Date }}

Birth Place: {{ user.applicant.Birth_Place }}

Mobile: {{ user.applicant.Mobile }}

{{ applicant.NickName }}

{% endblock %}


text:
package org.elasticsearch.xpack.ml.dataframe.process;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.dataframe.extractor.DataFrameDataExtractor;
import org.elasticsearch.xpack.ml.dataframe.extractor.DataFrameDataExtractorFactory;
import org.elasticsearch.xpack.ml.dataframe.process.results.MemoryUsageEstimationResult;

import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;

public class MemoryUsageEstimationProcessManager {

    private static final Logger LOGGER = LogManager.getLogger(MemoryUsageEstimationProcessManager.class);

    private final ExecutorService executorServiceForJob;
    private final ExecutorService executorServiceForProcess;
    private final AnalyticsProcessFactory<MemoryUsageEstimationResult> processFactory;

    public MemoryUsageEstimationProcessManager(ExecutorService executorServiceForJob,
                                               ExecutorService executorServiceForProcess,
                                               AnalyticsProcessFactory<MemoryUsageEstimationResult> processFactory) {
        this.executorServiceForJob = Objects.requireNonNull(executorServiceForJob);
        this.executorServiceForProcess = Objects.requireNonNull(executorServiceForProcess);
        this.processFactory = Objects.requireNonNull(processFactory);
    }

    public void runJobAsync(String jobId,
                            DataFrameAnalyticsConfig config,
                            DataFrameDataExtractorFactory dataExtractorFactory,
                            ActionListener<MemoryUsageEstimationResult> listener) {
        executorServiceForJob.execute(() -> {
            try {
                MemoryUsageEstimationResult result = runJob(jobId, config, dataExtractorFactory);
                listener.onResponse(result);
            } catch (Exception e) {
                listener.onFailure(e);
            }
        });
    }

    private MemoryUsageEstimationResult runJob(String jobId,
                                               DataFrameAnalyticsConfig config,
                                               DataFrameDataExtractorFactory dataExtractorFactory) {
        DataFrameDataExtractor dataExtractor = dataExtractorFactory.newExtractor(false);
        DataFrameDataExtractor.DataSummary dataSummary = dataExtractor.collectDataSummary();
        if (dataSummary.rows == 0) {
            throw ExceptionsHelper.badRequestException(
                "[{}] Unable to estimate memory usage as no documents in the source indices [{}] contained all the fields selected for "
                    + "analysis. If you are relying on automatic field selection then there are currently mapped fields that do not exist "
                    + "in any indexed documents, and you will have to switch to explicit field selection and include only fields that "
                    + "exist in indexed documents.",
                jobId,
                Strings.arrayToCommaDelimitedString(config.getSource().getIndex()));
        }
        Set<String> categoricalFields = dataExtractor.getCategoricalFields(config.getAnalysis());
        AnalyticsProcessConfig processConfig =
            new AnalyticsProcessConfig(
                jobId,
                dataSummary.rows,
                dataSummary.cols,
                // For memory estimation the model memory limit here should be set high enough not to trigger an error when C++ code
                // compares the limit to the result of estimation.
                new ByteSizeValue(1, ByteSizeUnit.PB),
                1,
                "",
                categoricalFields,
                config.getAnalysis(),
                dataExtractorFactory.getExtractedFields());
        AnalyticsProcess<MemoryUsageEstimationResult> process =
            processFactory.createAnalyticsProcess(
                config,
                processConfig,
                false,
                executorServiceForProcess,
                // The handler passed here will never be called as AbstractNativeProcess.detectCrash method returns early when
                // (processInStream == null) which is the case for MemoryUsageEstimationProcess.
                reason -> {});
        try {
            return readResult(jobId, process);
        } catch (Exception e) {
            String errorMsg =
                new ParameterizedMessage(
                    "[{}] Error while processing process output [{}], process errors: [{}]",
                    jobId, e.getMessage(), process.readError()).getFormattedMessage();
            throw ExceptionsHelper.serverError(errorMsg, e);
        } finally {
            process.consumeAndCloseOutputStream();
            try {
                LOGGER.debug("[{}] Closing process", jobId);
                process.close();
                LOGGER.debug("[{}] Closed process", jobId);
            } catch (Exception e) {
                String errorMsg =
                    new ParameterizedMessage(
                        "[{}] Error while closing process [{}], process errors: [{}]",
                        jobId, e.getMessage(), process.readError()).getFormattedMessage();
                throw ExceptionsHelper.serverError(errorMsg, e);
            }
        }
    }

    /**
     * Extracts {@link MemoryUsageEstimationResult} from process' output.
     */
    private static MemoryUsageEstimationResult readResult(String jobId, AnalyticsProcess<MemoryUsageEstimationResult> process) {
        Iterator<MemoryUsageEstimationResult> iterator = process.readAnalyticsResults();
        if (iterator.hasNext() == false) {
            String errorMsg =
                new ParameterizedMessage("[{}] Memory usage estimation process returned no results", jobId).getFormattedMessage();
            throw ExceptionsHelper.serverError(errorMsg);
        }
        MemoryUsageEstimationResult result = iterator.next();
        if (iterator.hasNext()) {
            String errorMsg =
                new ParameterizedMessage("[{}] Memory usage estimation process returned more than one result", jobId).getFormattedMessage();
            throw ExceptionsHelper.serverError(errorMsg);
        }
        return result;
    }
}


text:
using Onychophora.Domain.Entities;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace Onychophora.Domain.Interfaces.Services
{
    public interface ISpecimenService : IServiceBase<Specimen>
    {
        void Add(Specimen specimen, NameValueCollection requestParams);

        void Update(Specimen specimen, NameValueCollection requestParams);

        new void Remove(Specimen specimen);

        IEnumerable<Specimen> GetByOrganizationId(int organizationId);

        Specimen GetSpecimenStructure(int? taxonId = null);

        IEnumerable<Specimen> Search(Specimen specimen, NameValueCollection requestParams);
    }
}


text:
			<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
				{{rowIndex+1}}
			</template>

			<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
				<button type="button" (click)="EditItem(row)" class="btn btn-theme btn-sm btn-grid"></button>
			</template>

		<template let-row pTemplate="rowexpansion">
			Loading....

					<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
						{{rowIndex+1}}
					</template>

					<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
						<numtext [iscurrency]="false" [islabel]="true" id="{{'nmtxt_' + rowIndex + '1'}}" css="inlinetextbox" [(ngModel)]="row.qty"></numtext>
					</template>

					<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
						<numtext [iscurrency]="false" [islabel]="true" id="{{'nmtxt_' + rowIndex + '2'}}" css="inlinetextbox" [(ngModel)]="row.rate"></numtext>
					</template>

					<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
						<numtext [iscurrency]="false" [islabel]="true" id="{{'nmtxt_' + rowIndex + '3'}}" css="inlinetextbox" [(ngModel)]="row.dis"></numtext>
					</template>

					<template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="editor">
						<numtext [iscurrency]="false" [islabel]="true" id="{{'nmtxt_' + rowIndex + '4'}}" css="inlinetextbox" [(ngModel)]="row.amt"></numtext>
					</template>

							{{totalqty}}

							{{totalamt}}

		</template>


text:
layout: post
title: The great US patent spike on SureChEMBL
date: '2014-09-29T13:08:00.001+01:00'
author: George Papadatos
tags:
- Patents
- SureChEMBL
modified_time: '2014-09-29T15:10:22.673+01:00'
thumbnail: http://4.bp.blogspot.com/-OsOhTsGgDcA/VBvs1Ic4IMI/AAAAAAAAAbw/7ErLk5YRx4I/s72-c/Screen%2BShot%2B2014-09-19%2Bat%2B09.43.40.png
blogger_id: tag:blogger.com,1999:blog-2546008714740235720.post-111453019866877758
blogger_orig_url: http://chembl.blogspot.com/2014/09/the-great-us-patent-spike-on-surechembl.html
---

Apparently, there was a huge spike of new granted US patents released by the USPTO a few days ago. The reason?

In March 2013, US patent law changed. The 'first to invent' became 'first inventor to file' for patent protection purposes (see more on this here). As a result, a lot of people rushed to submit applications just before the change. Fast forward 18 months later (last week), a huge spike in USPTO granted patents is observed.

Did SureChEMBL pick that up? See below the cumulative count plot of new patent documents:

And the corresponding compound count extracted from these patents:

For more information on SureChEMBL, see our previous posts.

George


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKFACETWRITERWRAP_H
#define NATIVE_EXTENSION_VTK_VTKFACETWRITERWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkFacetWriter.h>

#include "vtkPolyDataAlgorithmWrap.h"
#include "../../plus/plus.h"

class VtkFacetWriterWrap : public VtkPolyDataAlgorithmWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkFacetWriterWrap(vtkSmartPointer<vtkFacetWriter>);
		VtkFacetWriterWrap();
		~VtkFacetWriterWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Write(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKFACETWRITERWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKFACETWRITERWRAP_CLASSDEF
#endif
};

#endif


text:
using System.Collections.Generic;
using Problems.DegreesOfBacon.DataProvider;

namespace Problems.DegreesOfBacon
{
    public class DegreesOfBacon
    {
        public WorkSummary FindSomeBacon()
        {
            WS = new WorkSummary();
            SeedTheWorkQueue();
            ProcessWorkQueue();
            return WS;
        }

        private void ProcessWorkQueue()
        {
            while (WQ.Count > 0)
            {
                WorkItem w = WQ.Dequeue();

                WS.TotalProductsExamined++;

                if (w.ProductToProcess.Category == Categories.Bacon)
                {
                    WS.FirstMatchingProduct = w.ProductToProcess;
                    WS.DistanceFromStart = w.DistanceFromStart;
                    return;
                }
                else
                {
                    AddProductsToWorkQueue(
                        ProductDataStore.GetRecommendations(
                            w.ProductToProcess.ProductId
                        ),
                        w.DistanceFromStart + 1
                    );
                }
            }
        }

        private void SeedTheWorkQueue()
        {
            WQ = new WorkQueue();
            Product seedProduct = new Product()
            {
                ProductId = 1,
                Category = Categories.NotBacon
            };
            AddProductsToWorkQueue(
                new List<Product>() { seedProduct }
            );
            AddProductsToWorkQueue(
                ProductDataStore.GetRecommendations(seedProduct.ProductId)
            );
        }

        private void AddProductsToWorkQueue(List<Product> products, int distance = 0)
        {
            foreach (Product p in products)
            {
                if (WQ.Enqueue(new WorkItem()
                    {
                        ProductToProcess = p,
                        DistanceFromStart = distance
                    }))
                {
                    WS.TotalProductsEnqueued++;
                }

            }
        }

        private WorkQueue WQ;
        private WorkSummary WS;
    }
}


text:
<!-- This is a generated file. Do not edit. Built by $(USER) on $(TSTAMP) -->
<pre>
$(MAIN)
</pre>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package demofx;

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

/**
 *
 * @author Novi
 */
public class DemoFX extends Application {

    @FXML private AnchorPane mainPane;
    @FXML private Stage stage;

    @Override
    public void start(Stage primaryStage)throws IOException {

        mainPane=(AnchorPane)FXMLLoader.load(DemoFX.class.getResource("MainFXML.fxml"));
        stage=primaryStage;
        Scene scene = new Scene(mainPane);
        primaryStage.setTitle("Main FXML");
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}


text:
from typing import Dict, List, Optional

from great_expectations.core import ExpectationConfiguration
from great_expectations.rule_based_profiler.domain import Domain
from great_expectations.rule_based_profiler.expectation_configuration_builder import (
    ExpectationConfigurationBuilder,
)
from great_expectations.rule_based_profiler.parameter_container import (
    ParameterNode,
    get_fully_qualified_parameter_names,
    get_parameter_values_for_fully_qualified_parameter_names,
)
from great_expectations.rule_based_profiler.rule.rule_state import RuleState

class RuleOutput:
    """
    RuleOutput provides methods for extracting useful information from RuleState using directives and application logic.
    """

    def __init__(
        self,
        rule_state: RuleState,
    ) -> None:
        """
        Args:
            rule_state: RuleState object represented by "Domain" objects and parameters,.computed for one Rule object.
        """
        self._rule_state = rule_state

    @property
    def rule_state(self) -> RuleState:
        return self._rule_state

    def get_expectation_configurations(self) -> List[ExpectationConfiguration]:
        expectation_configurations: List[ExpectationConfiguration] = []

        domains: List[Domain] = self.rule_state.domains

        domain: Domain
        expectation_configuration_builder: ExpectationConfigurationBuilder
        for domain in domains:
            expectation_configuration_builders: List[ExpectationConfigurationBuilder]
            if (
                self.rule_state.rule
                and self.rule_state.rule.expectation_configuration_builders
            ):
                expectation_configuration_builders = (
                    self.rule_state.rule.expectation_configuration_builders
                )
            else:
                expectation_configuration_builders = []

            for expectation_configuration_builder in expectation_configuration_builders:
                expectation_configurations.append(
                    expectation_configuration_builder.build_expectation_configuration(
                        domain=domain,
                        variables=self.rule_state.variables,
                        parameters=self.rule_state.parameters,
                    )
                )

        return expectation_configurations

    def get_fully_qualified_parameter_names_by_domain(self) -> Dict[Domain, List[str]]:
        domain: Domain
        return {
            domain: self.get_fully_qualified_parameter_names_for_domain(domain=domain)
            for domain in self.rule_state.domains
        }

    def get_fully_qualified_parameter_names_for_domain_id(
        self, domain_id: str
    ) -> List[str]:
        domains_dict: Dict[str, Domain] = self.rule_state.get_domains_as_dict()
        domain: Domain = domains_dict[domain_id]
        fully_qualified_parameter_names: List[
            str
        ] = self.get_fully_qualified_parameter_names_for_domain(domain=domain)
        return fully_qualified_parameter_names

    def get_fully_qualified_parameter_names_for_domain(
        self,
        domain: Optional[Domain] = None,
    ) -> List[str]:
        fully_qualified_parameter_names: List[
            str
        ] = get_fully_qualified_parameter_names(
            domain=domain,
            variables=self.rule_state.variables,
            parameters=self.rule_state.parameters,
        )
        return fully_qualified_parameter_names

    def get_parameter_values_for_fully_qualified_parameter_names_by_domain(
        self,
    ) -> Dict[Domain, Dict[str, ParameterNode]]:
        domain: Domain
        return {
            domain: self.get_parameter_values_for_fully_qualified_parameter_names_for_domain(
                domain=domain
            )
            for domain in self.rule_state.domains
        }

    def get_parameter_values_for_fully_qualified_parameter_names_for_domain_id(
        self, domain_id: str
    ) -> Dict[str, ParameterNode]:
        domains_dict: Dict[str, Domain] = self.rule_state.get_domains_as_dict()
        domain: Domain = domains_dict[domain_id]
        parameter_values_for_fully_qualified_parameter_names: Dict[
            str, ParameterNode
        ] = self.get_parameter_values_for_fully_qualified_parameter_names_for_domain(
            domain=domain
        )
        return parameter_values_for_fully_qualified_parameter_names

    def get_parameter_values_for_fully_qualified_parameter_names_for_domain(
        self,
        domain: Optional[Domain] = None,
    ) -> Dict[str, ParameterNode]:
        parameter_values_for_fully_qualified_parameter_names: Dict[
            str, ParameterNode
        ] = get_parameter_values_for_fully_qualified_parameter_names(
            domain=domain,
            variables=self.rule_state.variables,
            parameters=self.rule_state.parameters,
        )
        return parameter_values_for_fully_qualified_parameter_names


text:
package anthony.muller.celestia.abell.model;

public class ItemContainer {

}


text:
import os.path

from setuptools import setup

setup(
    name = 'TracIncludeMacro',
    version = '2.1fub3',
    packages = ['includemacro'],

    author = 'Manuel Holtgrewe',
    author_email = 'manuel.holtgrewe@fu-berlin.de',
    description = 'Include the contents of external URLs and other Trac objects in a wiki page.  Extended version that supports fragments.',
    long_description = open(os.path.join(os.path.dirname(__file__), 'README')).read(),
    license = 'BSD',
    keywords = 'trac 0.11 plugin wiki include macro',
    url = 'http://trac-hacks.org/wiki/IncludeMacro',
    classifiers = [
        'Framework :: Trac',
    ],

    install_requires = ['Trac'],

    entry_points = {
        'trac.plugins': [
            'includemacro.macros = includemacro.macros',
        ]
    }
)


text:
package es.ucm.gpd.irparser.ast.assertion;

import es.ucm.gpd.irparser.ast.ASTNode;

/**
 * @author Santiago Saavedra
 */
public interface AssertionExpr extends ASTNode {
}


text:
package test.configuration;

import org.testng.annotations.Test;

public class BaseGroupsASampleTest extends Base {
  @Test(groups = "foo")
  public void a() {
    //       System.out.println( "a" );
  }
}


text:
package org.onosproject.pcep.pcepio.types;

import java.util.Objects;

import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.pcep.pcepio.protocol.PcepVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.MoreObjects;

/**
 * Provides IPv4 Interface Address .
 */
public class IPv4InterfaceAddressSubTlv implements PcepValueType {

    /*
     * reference :[RFC5305]/3.2
      0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |           Type=6              |             Length=4          |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |                IPv4 Interface Address                         |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     */

    protected static final Logger log = LoggerFactory.getLogger(IPv4InterfaceAddressSubTlv.class);

    public static final short TYPE = 7;
    public static final short LENGTH = 4;

    private final int rawValue;

    /**
     * Constructor to initialize rawValue.
     *
     * @param rawValue of IPv4-Interface-Address.
     */
    public IPv4InterfaceAddressSubTlv(int rawValue) {
        this.rawValue = rawValue;
    }

    /**
     * Returns newly created IPv4InterfaceAddressTlv object.
     *
     * @param raw value of IPv4-Interface-Address
     * @return object of IPv4-Interface-Address-Tlv
     */
    public static IPv4InterfaceAddressSubTlv of(final int raw) {
        return new IPv4InterfaceAddressSubTlv(raw);
    }

    /**
     * Returns value of IPv4 Interface Address.
     *
     * @return rawValue IPv4 Interface Address
     */
    public int getInt() {
        return rawValue;
    }

    @Override
    public PcepVersion getVersion() {
        return PcepVersion.PCEP_1;
    }

    @Override
    public short getType() {
        return TYPE;
    }

    @Override
    public short getLength() {
        return LENGTH;
    }

    @Override
    public int hashCode() {
        return Objects.hash(rawValue);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof IPv4InterfaceAddressSubTlv) {
            IPv4InterfaceAddressSubTlv other = (IPv4InterfaceAddressSubTlv) obj;
            return Objects.equals(rawValue, other.rawValue);
        }
        return false;
    }

    @Override
    public int write(ChannelBuffer c) {
        int iLenStartIndex = c.writerIndex();
        c.writeShort(TYPE);
        c.writeShort(LENGTH);
        c.writeInt(rawValue);
        return c.writerIndex() - iLenStartIndex;
    }

    /**
     * Reads the channel buffer and returns object of IPv4InterfaceAddressTlv.
     *
     * @param c input channel buffer
     * @return object of IPv4-Interface-Address-Tlv
     */
    public static IPv4InterfaceAddressSubTlv read(ChannelBuffer c) {
        return IPv4InterfaceAddressSubTlv.of(c.readInt());
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .add("Type", TYPE)
                .add("Length", LENGTH)
                .add("Value", rawValue)
                .toString();
    }
}


text:
'use strict';

var app = angular.module('App');

app.controller('HomeCtrl', ['$scope','$state', '$rootScope', 'GameService',
 function($scope, $state, $rootScope, GameService){

  $rootScope.rootClass = 'home';

  var home = this;
  home.user = {};

  home.start = function (){
    GameService.login(this.user.name, this.user.email).then(function(response){
      //debugger;
      $state.go('overview');
    })
  }

}])


text:
package com.microsoft.azure.management.mediaservices.v2019_05_01_preview;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A track selection condition.
 */
public class LiveEventInputTrackSelection {
    /**
     * Property name to select.
     */
    @JsonProperty(value = "property")
    private String property;

    /**
     * Comparing operation.
     */
    @JsonProperty(value = "operation")
    private String operation;

    /**
     * Property value to select.
     */
    @JsonProperty(value = "value")
    private String value;

    /**
     * Get property name to select.
     *
     * @return the property value
     */
    public String property() {
        return this.property;
    }

    /**
     * Set property name to select.
     *
     * @param property the property value to set
     * @return the LiveEventInputTrackSelection object itself.
     */
    public LiveEventInputTrackSelection withProperty(String property) {
        this.property = property;
        return this;
    }

    /**
     * Get comparing operation.
     *
     * @return the operation value
     */
    public String operation() {
        return this.operation;
    }

    /**
     * Set comparing operation.
     *
     * @param operation the operation value to set
     * @return the LiveEventInputTrackSelection object itself.
     */
    public LiveEventInputTrackSelection withOperation(String operation) {
        this.operation = operation;
        return this;
    }

    /**
     * Get property value to select.
     *
     * @return the value value
     */
    public String value() {
        return this.value;
    }

    /**
     * Set property value to select.
     *
     * @param value the value value to set
     * @return the LiveEventInputTrackSelection object itself.
     */
    public LiveEventInputTrackSelection withValue(String value) {
        this.value = value;
        return this;
    }

}


text:
;(function( $ ){

  var sidrMoving = false,
      sidrOpened = false;

  // Private methods
  var privateMethods = {
    // Check for valids urls
    // From : http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url
    isUrl: function (str) {
      var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
      if(!pattern.test(str)) {
        return false;
      } else {
        return true;
      }
    },
    // Loads the content into the menu bar
    loadContent: function($menu, content) {
      $menu.html(content);
    },
    // Add sidr prefixes
    addPrefix: function($element) {
      var elementId = $element.attr('id'),
          elementClass = $element.attr('class');

      if(typeof elementId === 'string' && '' !== elementId) {
        $element.attr('id', elementId.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-id-$1'));
      }
      if(typeof elementClass === 'string' && '' !== elementClass && 'sidr-inner' !== elementClass) {
        $element.attr('class', elementClass.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-class-$1'));
      }
      $element.removeAttr('style');
    },
    execute: function(action, name, callback) {
      // Check arguments
      if(typeof name === 'function') {
        callback = name;
        name = 'sidr';
      }
      else if(!name) {
        name = 'sidr';
      }

      // Declaring
      var $menu = $('#' + name),
          $body = $($menu.data('body')),
          $html = $('html'),
          menuWidth = $menu.outerWidth(true),
          speed = $menu.data('speed'),
          side = $menu.data('side'),
          displace = $menu.data('displace'),
          onOpen = $menu.data('onOpen'),
          onClose = $menu.data('onClose'),
          bodyAnimation,
          menuAnimation,
          scrollTop,
          bodyClass = (name === 'sidr' ? 'sidr-open' : 'sidr-open ' + name + '-open'),
          $menuToggler = $($menu.data('toggler'));

      // Open Sidr
      if('open' === action || ('toggle' === action && !$menu.is(':visible'))) {
        // Check if we can open it
        if( $menu.is(':visible') || sidrMoving ) {
          return;
        }

        // If another menu opened close first
        if(sidrOpened !== false) {
          methods.close(sidrOpened, function() {
            methods.open(name);
          });

          return;
        }

        // Lock sidr
        sidrMoving = true;

        // Left or right?
        if(side === 'left') {
          bodyAnimation = {left: menuWidth + 'px'};
          menuAnimation = {left: '0px'};
        }
        else {
          bodyAnimation = {right: menuWidth + 'px'};
          menuAnimation = {right: '0px'};
        }

        // Prepare page if container is body
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.css('overflow-x', 'hidden').scrollTop(scrollTop);
        }

        // Open menu
        if(displace){
          $body.addClass('sidr-animating').css({
            width: $body.width(),
            position: 'absolute'
          }).animate(bodyAnimation, speed, function() {
            $(this).addClass(bodyClass);
          });
        }
        else {
          $menuToggler.animate(bodyAnimation, speed);
          setTimeout(function() {
            $(this).addClass(bodyClass);
          }, speed);
        }
        $menu.css('display', 'block').animate(menuAnimation, speed, function() {
          sidrMoving = false;
          sidrOpened = name;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onOpen callback
        onOpen();
      }
      // Close Sidr
      else {
        // Check if we can close it
        if( !$menu.is(':visible') || sidrMoving ) {
          return;
        }

        // Lock sidr
        sidrMoving = true;

        // Right or left menu?
        if(side === 'left') {
          bodyAnimation = {left: 0};
          menuAnimation = {left: '-' + menuWidth + 'px'};
        }
        else {
          bodyAnimation = {right: 0};
          menuAnimation = {right: '-' + menuWidth + 'px'};
        }

        // Close menu
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.removeAttr('style').scrollTop(scrollTop);
        }
        if (displace) {
          $body.addClass('sidr-animating').animate(bodyAnimation, speed).removeClass(bodyClass);
        } else {
          $menuToggler.animate(bodyAnimation, speed);
        }
        $menu.animate(menuAnimation, speed, function() {
          $menu.removeAttr('style').hide();
          $body.removeAttr('style');
          $('html').removeAttr('style');
          sidrMoving = false;
          sidrOpened = false;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onClose callback
        onClose();
      }
    }
  };

  // Sidr public methods
  var methods = {
    open: function(name, callback) {
      privateMethods.execute('open', name, callback);
    },
    close: function(name, callback) {
      privateMethods.execute('close', name, callback);
    },
    toggle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    },
    // I made a typo, so I mantain this method to keep backward compatibilty with 1.1.1v and previous
    toogle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    }
  };

  $.sidr = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    }
    else if ( typeof method === 'function' || typeof method === 'string' || ! method ) {
      return methods.toggle.apply( this, arguments );
    }
    else {
      $.error( 'Method ' + method + ' does not exist on jQuery.sidr' );
    }

  };

  $.fn.sidr = function( options ) {

    var settings = $.extend( {
      name          : 'sidr',         // Name for the 'sidr'
      speed         : 200,            // Accepts standard jQuery effects speeds (i.e. fast, normal or milliseconds)
      side          : 'left',         // Accepts 'left' or 'right'
      source        : null,           // Override the source of the content.
      toggler       : null,           // Menu Toggler element
      renaming      : true,           // The ids and classes will be prepended with a prefix when loading existent content
      body          : 'body',         // Page container selector,
      displace      : false,           // Displace the body content or not
      onOpen        : function() {},  // Callback when sidr opened
      onClose       : function() {}   // Callback when sidr closed
    }, options);

    var name = settings.name,
        $sideMenu = $('#' + name);

    // If the side menu do not exist create it
    if( $sideMenu.length === 0 ) {
      $sideMenu = $('
')
        .attr('id', name)
        .appendTo($('body'));
    }

    // Adding styles and options
    $sideMenu
      .addClass('sidr')
      .addClass(settings.side)
      .data({
        speed          : settings.speed,
        side           : settings.side,
        body           : settings.body,
        toggler        : settings.toggler,
        displace      : settings.displace,
        onOpen         : settings.onOpen,
        onClose        : settings.onClose
      });

    // The menu content
    if(typeof settings.source === 'function') {
      var newContent = settings.source(name);
      privateMethods.loadContent($sideMenu, newContent);
    }
    else if(typeof settings.source === 'string' && privateMethods.isUrl(settings.source)) {
      $.get(settings.source, function(data) {
        privateMethods.loadContent($sideMenu, data);
      });
    }
    else if(typeof settings.source === 'string') {
      var htmlContent = '',
          selectors = settings.source.split(',');

      $.each(selectors, function(index, element) {
        htmlContent += '
' + $(element).html() + '
';
      });

      // Renaming ids and classes
      if(settings.renaming) {
        var $htmlContent = $('
').html(htmlContent);
        $htmlContent.find('*').each(function(index, element) {
          var $element = $(element);
          privateMethods.addPrefix($element);
        });
        htmlContent = $htmlContent.html();
      }
      privateMethods.loadContent($sideMenu, htmlContent);
    }
    else if(settings.source !== null) {
      $.error('Invalid Sidr Source');
    }

    return this.each(function(){
      var $this = $(this),
          data = $this.data('sidr');

      // If the plugin hasn't been initialized yet
      if ( ! data ) {

        $this.data('sidr', name);
        if('ontouchstart' in document.documentElement) {
          $this.bind('touchstart', function(e) {
            var theEvent = e.originalEvent.touches[0];
            this.touched = e.timeStamp;
          });
          $this.bind('touchend', function(e) {
            var delta = Math.abs(e.timeStamp - this.touched);
            if(delta < 200) {
              e.preventDefault();
              methods.toggle(name);
            }
          });
        }
        else {
          $this.click(function(e) {
            e.preventDefault();
            methods.toggle(name);
          });
        }
      }
    });
  };

})( jQuery );


text:
@interface RestoreServerViewController ()

@end

@implementation RestoreServerViewController {
    GroupManager *group;
}

- (void)viewDidLoad {
    if (DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [super viewDidLoad];
    group = [GroupManager sharedInstance];
}

#pragma mark - Action
- (IBAction)restore:(id)sender {
    if (DEBUG) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [group restoreExistedServer:_addressTextField.text
                    byAccessKey:_accessKeyTextField.text
                     completion:^(BOOL success, NSString *message) {
                         if (success) {
                             [self.navigationController popViewControllerAnimated:YES];
                         } else {
                             [self showTip:message];
                         }
                     }];
}
@end


text:
package panels;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Title extends JPanel
{

    private JLabel Title;

    public Title(){

        //Set Varying Stats panel.
        Dimension TitleDimension = new Dimension(600, 100);
        this.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.lightGray));
        this.setVisible(true);
        this.setBackground(Color.black);
        this.setPreferredSize(TitleDimension);

        //Sets the Title to this Panel.
        Title = new JLabel();
        Title.setText("Tower Explorer");
        Title.setFont( new Font("Bookman Old Style", Font.PLAIN, 50));
        Title.setForeground(Color.YELLOW);
        this.add(Title);

    }
}


text:
package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import guitests.guihandles.TaskCardHandle;
import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class AddCommandTest extends TaskManagerGuiTest {

    @Test
    public void add() {
    	//TODO
    	/*
        //add one task
        TestTask[] currentList = td.getTypicalTasks();
        TestTask taskToAdd = TypicalTestTasks.task1;

        assertAddSuccess(taskToAdd, currentList);
        currentList = TestUtil.addTasksToList(currentList, taskToAdd);

        //add another task
        taskToAdd = TypicalTestTasks.task2;
        assertAddSuccess(taskToAdd, currentList);
        currentList = TestUtil.addTasksToList(currentList, taskToAdd);

        //add duplicate task
        commandBox.runCommand(TypicalTestTasks.task1.getAddCommand());
        assertResultMessage(AddCommand.MESSAGE_DUPLICATE_TASK);
        assertTrue(taskListPanel.isListMatching(currentList));

        //add to empty list
        commandBox.runCommand("clear");
        assertAddSuccess(TypicalTestTasks.task3);

        //invalid command
        commandBox.runCommand("adds Homework");
        assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
        */
    }

    private void assertAddSuccess(TestTask taskToAdd, TestTask... currentList) {

    	commandBox.runCommand(taskToAdd.getAddCommand());

        //confirm the new card contains the right data
        TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToAdd.getTitle().fullTitle);
        assertMatching(taskToAdd, addedCard);

        //confirm the list now contains all previous tasks plus the new task
        TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd);
        assertTrue(taskListPanel.isListMatching(expectedList));
    }

}


text:
import { initAutoload, noop, cleanupOpenAPI } from '@whook/whook';
import {
  Knifecycle,
  SPECIAL_PROPS,
  wrapInitializer,
  constant,
  alsoInject,
} from 'knifecycle';
import { YError } from 'yerror';
import {
  dereferenceOpenAPIOperations,
  getOpenAPIOperations,
} from '@whook/http-router';
import type {
  Injector,
  Autoloader,
  Initializer,
  Dependencies,
  Service,
  ServiceInitializerWrapper,
} from 'knifecycle';
import type { WhookBuildConstantsService } from '@whook/whook';
import type { WhookRawOperation } from '@whook/http-router';
import type { LogService } from 'common-services';
import type { OpenAPIV3 } from 'openapi-types';
import type { WhookAPIOperationGCPFunctionConfig } from '../index.js';

const initializerWrapper: ServiceInitializerWrapper<
  Autoloader<Initializer<Dependencies, Service>>,
  Dependencies
> = (async (
  {
    BUILD_CONSTANTS = {},
    $injector,
    $instance,
    log = noop,
  }: {
    BUILD_CONSTANTS?: WhookBuildConstantsService;
    $injector: Injector<Service>;
    $instance: Knifecycle;
    log: LogService;
  },
  $autoload: Autoloader<Initializer<Dependencies, Service>>,
): Promise<
  (serviceName: string) => Promise<{
    initializer: Initializer<Dependencies, Service>;
    path: string;
  }>
> => {
  let API: OpenAPIV3.Document;
  let OPERATION_APIS: WhookRawOperation<WhookAPIOperationGCPFunctionConfig>[];
  const getAPIOperation = (() => {
    return async (serviceName) => {
      // eslint-disable-next-line
      API = API || (await $injector(['API'])).API;
      // eslint-disable-next-line
      OPERATION_APIS =
        OPERATION_APIS ||
        getOpenAPIOperations<WhookAPIOperationGCPFunctionConfig>(API);

      const OPERATION = OPERATION_APIS.find(
        (operation) =>
          serviceName ===
          (((operation['x-whook'] || {}).sourceOperationId &&
            'OPERATION_API_' +
              (operation['x-whook'] || {}).sourceOperationId) ||
            'OPERATION_API_' + operation.operationId) +
            ((operation['x-whook'] || {}).suffix || ''),
      );

      if (!OPERATION) {
        log('error', '💥 - Unable to find a lambda operation definition!');
        throw new YError('E_OPERATION_NOT_FOUND', serviceName);
      }

      // eslint-disable-next-line
      const OPERATION_API = cleanupOpenAPI({
        ...API,
        paths: {
          [OPERATION.path]: {
            [OPERATION.method]: API.paths[OPERATION.path]?.[OPERATION.method],
          },
        },
      });

      return {
        ...OPERATION_API,
        paths: {
          [OPERATION.path]: {
            [OPERATION.method]: (
              await dereferenceOpenAPIOperations(OPERATION_API, [
                {
                  path: OPERATION.path,
                  method: OPERATION.method,
                  ...OPERATION_API.paths[OPERATION.path]?.[OPERATION.method],
                  parameters: OPERATION.parameters,
                },
              ])
            )[0],
          },
        },
      };
    };
  })();

  log('debug', '🤖 - Initializing the `$autoload` build wrapper.');

  return async (serviceName) => {
    try {
      // TODO: add initializer map to knifecycle public API
      const initializer = ($instance as any)._initializers.get(serviceName);

      if (initializer && initializer[SPECIAL_PROPS.TYPE] === 'constant') {
        log(
          'debug',
          `🤖 - Reusing a constant initializer directly from the Knifecycle instance: "${serviceName}".`,
        );
        return {
          initializer,
          path: `instance://${serviceName}`,
        };
      }

      if (serviceName.startsWith('OPERATION_API_')) {
        const OPERATION_API = await getAPIOperation(serviceName);

        return {
          initializer: constant(serviceName, OPERATION_API),
          path: `api://${serviceName}`,
        };
      }

      if (BUILD_CONSTANTS[serviceName]) {
        return {
          initializer: constant(serviceName, BUILD_CONSTANTS[serviceName]),
          path: `constant://${serviceName}`,
        };
      }

      return $autoload(serviceName);
    } catch (err) {
      log('error', `Build error while loading "${serviceName}".`);
      log('error-stack', (err as Error).stack || 'no_stack_trace');
      throw err;
    }
  };
}) as any;

/**
 * Wrap the _autoload service in order to build AWS
 *  Lambda compatible code.
 * @param  {Object}   services
 * The services ENV depends on
 * @param  {Object}   services.NODE_ENV
 * The injected NODE_ENV value to add it to the build env
 * @param  {Object}   [services.PROXYED_ENV_VARS={}]
 * A list of environment variable names to proxy
 * @param  {Object}   [services.log=noop]
 * An optional logging service
 * @return {Promise<Object>}
 * A promise of an object containing the reshaped env vars.
 */
export default alsoInject(
  ['?BUILD_CONSTANTS', '$instance', '$injector', '?log'],
  wrapInitializer(initializerWrapper as any, initAutoload),
);


text:
package com.github.openwebnet.service;

import com.github.openwebnet.model.LightModel;

import java.util.List;

import rx.Observable;

public interface LightService extends DomoticService<LightModel> {

    Observable<List<LightModel>> requestByEnvironment(Integer id);

    Observable<List<LightModel>> requestFavourites();

    Observable<LightModel> turnOn(LightModel light);

    Observable<LightModel> turnOff(LightModel light);

}


text:
require 'spec_helper'
module Alf
  describe Relation, '.split' do

    let(:type){ Relation[name: String, status: Integer] }

    subject{ type.split(attr_list) }

    context 'with an empty attribute list' do
      let(:attr_list){ AttrList.new([]) }

      it 'splits as expected' do
        subject.should eq([ Relation[{}], type ])
      end

      it 'reuses the initial instance' do
        subject.last.should be(type)
      end
    end

    context 'with an non empty attribute list' do
      let(:attr_list){ AttrList.new([:name]) }

      it 'splits as expected' do
        subject.should eq([ Relation[name: String], Relation[status: Integer] ])
      end
    end

  end
end


text:
<?php
class Cache_Manage{
	const CACHE_TYPE_MEMCACHE = 1;
	const CACHE_TYPE_MEMCACHED = 2;
	const CACHE_TYPE_ZCACHE = 3;

	private static $_AdapterList = array();

	private $_cacheAdapter = null;

	/**
	 * 获取实例 目前只支持 memcache 和 memcached
	 * 以后由新的cache形式可以再添加
	 *
	 * @param unknown $cacheType
	 */
	public static function getInstance($cacheConfig = null,$cacheType = 0,$runtime = ''){
		$cacheConfig = $cacheConfig ? $cacheConfig : Config::Get('cache');
		$cacheType = $cacheType ? $cacheType : self::CACHE_TYPE_MEMCACHE;
		$runtime = $runtime ? $runtime : RUNTIME;

		if(!self::$_AdapterList[$runtime][$cacheType]){
			switch ($cacheType){
				case self::CACHE_TYPE_MEMCACHED:
					$servers = $cacheConfig['server'];
					$defaultWeight = intval($cacheConfig['default_weight']);
					foreach ($servers as $serverInfo){
						list($serverStr,$weight) = explode(' ', $serverInfo);
						list($host,$port) = explode(':', $serverStr);
						$weight = $weight ? intval($weight) : intval($defaultWeight);
						$weight = $weight > 0 ? $weight : 1;
						$server = array($host,$port,$weight);
						$memecacheServers[] = $server;
					}

					$cacheAdapter = new Cache_Adapter_Memcached();
					$cacheAdapter->ini($memecacheServers);
					break;
				case self::CACHE_TYPE_MEMCACHE:
				default:
					$servers = $cacheConfig['server'];
					$defaultWeight = intval($cacheConfig['default_weight']);
					foreach ($servers as $serverInfo){
						list($serverStr,$weight) = explode(' ', $serverInfo);
						list($host,$port) = explode(':', $serverStr);
						$weight = $weight ? intval($weight) : intval($defaultWeight);
						$weight = $weight > 0 ? $weight : 1;
						$server = array($host,$port,$weight);
						$memecacheServers[] = $server;
					}

					$cacheAdapter = new Cache_Adapter_Memcache();
					$cacheAdapter->ini($memecacheServers);
					break;
			}

			$cacheManage = new Cache_Manage($cacheAdapter);
			self::$_AdapterList[$runtime][$cacheType] = $cacheManage;
		}

		return self::$_AdapterList[$runtime][$cacheType];
	}

	public function __construct($cacheAdapter){
		$this->_cacheAdapter = $cacheAdapter;
	}

	public function set($key,$value,$expire = 0){
		return $this->_cacheAdapter->set($key, $value,$expire);
	}

	public function get($key){
		return $this->_cacheAdapter->get($key);
	}

	public function setMulti($items,$expire = 0){
		return $this->_cacheAdapter->setMulti($items,$expire);
	}

	public function getMulti($keys){
		return $this->_cacheAdapter->getMulti($keys);
	}

	public function delete($key,$timeout = 0){
		return $this->_cacheAdapter->delete($key,$timeout);
	}

	public function deleteMulti($keys,$timeout = 0){
		return $this->_cacheAdapter->deleteMulti($keys,$timeout);
	}

	public function getStatus(){
		return $this->_cacheAdapter->getStatus();
	}

	///////////////工具性方法
	public static function GenKey($key){
		$hash = dirname(__FILE__);
		$key = md5( $hash . $key );
		return $key;
	}
}


text:
from .base_object import BaseObject

class MCLink(BaseObject):
    item_url = None

    def __init__(self, json_data={}):
        super(MCLink, self).__init__()
        self.rel = None
        self.href = None
        self.method = None
        self.targetSchema = None

        if json_data:
            self.rel = json_data.get('rel')
            self.href = json_data.get('href')
            self.method = json_data.get('method')
            self.targetSchema = json_data.get('targetSchema')


text:
using System.Web;
using System.Web.Mvc;

namespace sales_record_web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}


text:
package org.hisp.dhis.dxf2.metadata.objectbundle;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dxf2.metadata.objectbundle.feedback.ObjectBundleValidationReport;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.legend.LegendSet;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.render.RenderFormat;
import org.hisp.dhis.render.RenderService;
import org.hisp.dhis.user.UserService;
import org.hisp.dhis.visualization.Visualization;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
class ObjectBundleServiceFavoritesTest extends DhisSpringTest
{

    @Autowired
    private ObjectBundleService objectBundleService;

    @Autowired
    private ObjectBundleValidationService objectBundleValidationService;

    @Autowired
    private IdentifiableObjectManager manager;

    @Autowired
    private RenderService _renderService;

    @Autowired
    private UserService _userService;

    @Override
    protected void setUpTest()
        throws Exception
    {
        renderService = _renderService;
        userService = _userService;
    }

    @Test
    void testCreateMetadataWithVisualization()
        throws IOException
    {
        Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService.fromMetadata(
            new ClassPathResource( "dxf2/favorites/metadata_with_visualization.json" ).getInputStream(),
            RenderFormat.JSON );
        ObjectBundleParams params = new ObjectBundleParams();
        params.setObjectBundleMode( ObjectBundleMode.COMMIT );
        params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE );
        params.setObjects( metadata );
        ObjectBundle bundle = objectBundleService.create( params );
        ObjectBundleValidationReport validate = objectBundleValidationService.validate( bundle );
        assertFalse( validate.hasErrorReports() );
        objectBundleService.commit( bundle );
        List<DataSet> dataSets = manager.getAll( DataSet.class );
        List<OrganisationUnit> organisationUnits = manager.getAll( OrganisationUnit.class );
        List<DataElement> dataElements = manager.getAll( DataElement.class );
        List<Visualization> visualizations = manager.getAll( Visualization.class );
        assertEquals( 1, dataSets.size() );
        assertEquals( 1, organisationUnits.size() );
        assertEquals( 4, dataElements.size() );
        assertEquals( 3, visualizations.size() );
        assertNotNull( visualizations.get( 0 ).getFontSize() );
        assertNotNull( visualizations.get( 1 ).getFontSize() );
        assertNotNull( visualizations.get( 2 ).getFontSize() );
        assertNotNull( visualizations.get( 0 ).getSeries() );
        assertNotNull( visualizations.get( 1 ).getSeries() );
        assertNotNull( visualizations.get( 2 ).getSeries() );
        assertNotNull( visualizations.get( 0 ).getAxes() );
        assertNotNull( visualizations.get( 1 ).getAxes() );
        assertNotNull( visualizations.get( 2 ).getAxes() );
        assertNotNull( visualizations.get( 0 ).getSeriesKey() );
        assertNotNull( visualizations.get( 1 ).getSeriesKey() );
        assertNotNull( visualizations.get( 2 ).getSeriesKey() );
        assertEquals( 2, visualizations.get( 0 ).getSeries().size() );
        assertEquals( 2, visualizations.get( 1 ).getSeries().size() );
        assertEquals( 2, visualizations.get( 2 ).getSeries().size() );
        assertEquals( 2, visualizations.get( 0 ).getAxes().size() );
        assertEquals( 2, visualizations.get( 1 ).getAxes().size() );
        assertEquals( 2, visualizations.get( 2 ).getAxes().size() );
        assertNotNull( visualizations.get( 0 ).getFontStyle() );
        assertNotNull( visualizations.get( 1 ).getFontStyle() );
        assertNotNull( visualizations.get( 2 ).getFontStyle() );
        assertNotNull( visualizations.get( 0 ).getFontStyle().getVisualizationTitle() );
        assertNotNull( visualizations.get( 1 ).getFontStyle().getVisualizationTitle() );
        assertNotNull( visualizations.get( 2 ).getFontStyle().getVisualizationTitle() );
        assertEquals( "color_set_01", visualizations.get( 0 ).getColorSet() );
        assertEquals( "color_set_01", visualizations.get( 1 ).getColorSet() );
        assertEquals( "color_set_01", visualizations.get( 2 ).getColorSet() );
    }

    @Test
    void testCreateMetadataWithVisualizationsWithPeriods()
        throws IOException
    {
        Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService.fromMetadata(
            new ClassPathResource( "dxf2/favorites/metadata_with_visualization_periods.json" ).getInputStream(),
            RenderFormat.JSON );
        ObjectBundleParams params = new ObjectBundleParams();
        params.setObjectBundleMode( ObjectBundleMode.COMMIT );
        params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE );
        params.setObjects( metadata );
        ObjectBundle bundle = objectBundleService.create( params );
        ObjectBundleValidationReport validate = objectBundleValidationService.validate( bundle );
        assertFalse( validate.hasErrorReports() );
        objectBundleService.commit( bundle );
        List<DataSet> dataSets = manager.getAll( DataSet.class );
        List<OrganisationUnit> organisationUnits = manager.getAll( OrganisationUnit.class );
        List<DataElement> dataElements = manager.getAll( DataElement.class );
        List<Visualization> visualizations = manager.getAll( Visualization.class );
        assertEquals( 1, dataSets.size() );
        assertEquals( 1, organisationUnits.size() );
        assertEquals( 4, dataElements.size() );
        assertEquals( 4, visualizations.size() );
        Visualization visualization = manager.get( Visualization.class, "ziCoxdcXRQz" );
        assertNotNull( visualization );
        assertEquals( 5, visualization.getPeriods().size() );
    }

    @Test
    void testCreateLegendSets()
        throws IOException
    {
        Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService
            .fromMetadata( new ClassPathResource( "dxf2/favorites/legends.json" ).getInputStream(), RenderFormat.JSON );
        ObjectBundleParams params = new ObjectBundleParams();
        params.setObjectBundleMode( ObjectBundleMode.COMMIT );
        params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE );
        params.setObjects( metadata );
        ObjectBundle bundle = objectBundleService.create( params );
        ObjectBundleValidationReport validate = objectBundleValidationService.validate( bundle );
        assertFalse( validate.hasErrorReports() );
        objectBundleService.commit( bundle );
        List<LegendSet> legendSets = manager.getAll( LegendSet.class );
        assertEquals( 1, legendSets.size() );
        LegendSet legendSet = legendSets.get( 0 );
        assertEquals( "fqs276KXCXi", legendSet.getUid() );
        assertEquals( "ANC Coverage", legendSet.getName() );
        assertEquals( 7, legendSet.getLegends().size() );
    }

    @Test
    void testDeleteLegendSet()
        throws IOException
    {
        Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService
            .fromMetadata( new ClassPathResource( "dxf2/favorites/legends.json" ).getInputStream(), RenderFormat.JSON );
        ObjectBundleParams params = new ObjectBundleParams();
        params.setObjectBundleMode( ObjectBundleMode.COMMIT );
        params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE );
        params.setObjects( metadata );
        ObjectBundle bundle = objectBundleService.create( params );
        ObjectBundleValidationReport validate = objectBundleValidationService.validate( bundle );
        assertFalse( validate.hasErrorReports() );
        objectBundleService.commit( bundle );
        List<LegendSet> legendSets = manager.getAll( LegendSet.class );
        assertEquals( 1, legendSets.size() );
        LegendSet legendSet = legendSets.get( 0 );
        assertEquals( "fqs276KXCXi", legendSet.getUid() );
        assertEquals( "ANC Coverage", legendSet.getName() );
        assertEquals( 7, legendSet.getLegends().size() );
        manager.delete( legendSet );
        legendSets = manager.getAll( LegendSet.class );
        assertTrue( legendSets.isEmpty() );
    }
}


text:
namespace iroha {
namespace writer {
namespace verilog {

Port::Port(const string &prefix, const string &name, enum PortType type,
	   int width)
  : prefix_(prefix), name_(name), full_name_(prefix + name), type_(type),
    width_(width), axi_addr_width_(0), fixed_value_(-1), is_axi_(false) {
}

Port::~Port() {
}

void Port::SetComment(const string &comment) {
  comment_ = comment;
}

const string &Port::GetPrefix() {
  return prefix_;
}

const string &Port::GetFullName() {
  return full_name_;
}

const string &Port::GetName() {
  return name_;
}

enum Port::PortType Port::GetType() {
  return type_;
}

int Port::GetWidth() {
  return width_;
}

void Port::SetFixedValue(int fixed_value) {
  fixed_value_ = fixed_value;
}

int Port::GetFixedValue() const {
  return fixed_value_;
}

void Port::SetIsAxi(bool is_axi) {
  is_axi_ = is_axi;
}

bool Port::GetIsAxi() {
  return is_axi_;
}

void Port::SetAxiAddrWidth(int axi_addr_width) {
  axi_addr_width_ = axi_addr_width;
}

int Port::GetAxiAddrWidth() {
  return axi_addr_width_;
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha


text:
package edu.hm.cs.jenkins.monitor.view.holder;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Used to hold the views retrieved from the layout
 * {@link edu.hm.cs.jenkins.monitor.controller.fragment.list.BuildFragment}.
 * <p/>
 * Keeping those views in the holder allows to avoid the
 * findViewById() method in a list adapter.
 *
 * @author Tobias Wochinger
 */
//CHECKSTYLE:OFF
public class BuildHolder {

    public TextView date;

    public TextView number;

    public TextView duration;

    public ImageView result;

    public LinearLayout layout;
}
//CHECKSTYLE:ON


text:
from pyramid.config import Configurator
from pyramid.events import NewRequest

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')

    allow_cors(config)
    register_routes(config)

    return config.make_wsgi_app()

def register_routes(config):
    config.add_static_view('static', 'static', cache_max_age=1)
    config.add_route('home', '/')
    config.add_route('autos_api', '/api/autos')
    config.add_route('auto_api', '/api/autos/{car_id}')
    config.scan()

def allow_cors(config):
    def add_cors_headers_response_callback(event):
        def cors_headers(request, response):
            if r'/api/' not in request.path:
                return
            response.headers.update({
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS',
                'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Authorization',
                'Access-Control-Allow-Credentials': 'true',
                'Access-Control-Max-Age': '1728000',
            })
        event.request.add_response_callback(cors_headers)
    config.add_subscriber(add_cors_headers_response_callback, NewRequest)


text:
package confformat

import "fmt"

// MarshalAll takes some data stored in structs
// and converts them to the various data formats
func MarshalAll() error {
	t := TOMLData{
		Name: "Name1",
		Age:  20,
	}

	j := JSONData{
		Name: "Name2",
		Age:  30,
	}

	y := YAMLData{
		Name: "Name3",
		Age:  40,
	}

	tomlRes, err := t.ToTOML()
	if err != nil {
		return err
	}

	fmt.Println("TOML Marshal =", tomlRes.String())

	jsonRes, err := j.ToJSON()
	if err != nil {
		return err
	}

	fmt.Println("JSON Marshal=", jsonRes.String())

	yamlRes, err := y.ToYAML()
	if err != nil {
		return err
	}

	fmt.Println("YAML Marshal =", yamlRes.String())
	return nil
}


text:
<?php
namespace Utility\Video\Metadata;

class WMA extends WMV {}


text:
class MenuController {
    constructor(data) {
        this.data = data;
    }

    searchOne(req, res) {
        const meal = req.query.search;
        this.data.meals.filterBy({name: meal})
            .then((m) => {
                res.render('menu', { meals: m });
        });
    }
}

const init = (data) => {
    return new MenuController(data);
};

module.exports = { init };


text:
// Copyright (c) 2015-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bench/bench.h>

#include <clientversion.h>
#include <crypto/sha256.h>
#include <fs.h>
#include <util/strencodings.h>
#include <util/system.h>

#include <chrono>
#include <cstdint>
#include <iostream>
#include <sstream>
#include <vector>

static const char* DEFAULT_BENCH_FILTER = ".*";
static constexpr int64_t DEFAULT_MIN_TIME_MS{10};
/** Priority level default value, run "all" priority levels */
static const std::string DEFAULT_PRIORITY{"all"};

static void SetupBenchArgs(ArgsManager& argsman)
{
    SetupHelpOptions(argsman);

    argsman.AddArg("-asymptote=<n1,n2,n3,...>", "Test asymptotic growth of the runtime of an algorithm, if supported by the benchmark", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
    argsman.AddArg("-filter=<regex>", strprintf("Regular expression filter to select benchmark by name (default: %s)", DEFAULT_BENCH_FILTER), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
    argsman.AddArg("-list", "List benchmarks without executing them", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
    argsman.AddArg("-min-time=<milliseconds>", strprintf("Minimum runtime per benchmark, in milliseconds (default: %d)", DEFAULT_MIN_TIME_MS), ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);
    argsman.AddArg("-output-csv=<output.csv>", "Generate CSV file with the most important benchmark results", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
    argsman.AddArg("-output-json=<output.json>", "Generate JSON file with all benchmark results", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
    argsman.AddArg("-sanity-check", "Run benchmarks for only one iteration", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
    argsman.AddArg("-priority-level=<l1,l2,l3>", strprintf("Run benchmarks of one or multiple priority level(s) (%s), default: '%s'",
                                                           benchmark::ListPriorities(), DEFAULT_PRIORITY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
}

// parses a comma separated list like "10,20,30,50"
static std::vector<double> parseAsymptote(const std::string& str) {
    std::stringstream ss(str);
    std::vector<double> numbers;
    double d;
    char c;
    while (ss >> d) {
        numbers.push_back(d);
        ss >> c;
    }
    return numbers;
}

static uint8_t parsePriorityLevel(const std::string& str) {
    uint8_t levels{0};
    for (const auto& level: SplitString(str, ',')) {
        levels |= benchmark::StringToPriority(level);
    }
    return levels;
}

int main(int argc, char** argv)
{
    /* FIXME: Re-enable benchmarking after it has been fixed for auxpow.
       See https://github.com/namecoin/namecoin-core/issues/273.  */
    fprintf(stderr, "bench_bitcoin is disabled in Namecoin/Auxpow\n");
    return EXIT_SUCCESS;

    ArgsManager argsman;
    SetupBenchArgs(argsman);
    SHA256AutoDetect();
    std::string error;
    if (!argsman.ParseParameters(argc, argv, error)) {
        tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
        return EXIT_FAILURE;
    }

    if (HelpRequested(argsman)) {
        std::cout << "Usage:  bench_bitcoin [options]\n"
                     "\n"
                  << argsman.GetHelpMessage()
                  << "Description:\n"
                     "\n"
                     "  bench_bitcoin executes microbenchmarks. The quality of the benchmark results\n"
                     "  highly depend on the stability of the machine. It can sometimes be difficult\n"
                     "  to get stable, repeatable results, so here are a few tips:\n"
                     "\n"
                     "  * Use pyperf [1] to disable frequency scaling, turbo boost etc. For best\n"
                     "    results, use CPU pinning and CPU isolation (see [2]).\n"
                     "\n"
                     "  * Each call of run() should do exactly the same work. E.g. inserting into\n"
                     "    a std::vector doesn't do that as it will reallocate on certain calls. Make\n"
                     "    sure each run has exactly the same preconditions.\n"
                     "\n"
                     "  * If results are still not reliable, increase runtime with e.g.\n"
                     "    -min-time=5000 to let a benchmark run for at least 5 seconds.\n"
                     "\n"
                     "  * bench_bitcoin uses nanobench [3] for which there is extensive\n"
                     "    documentation available online.\n"
                     "\n"
                     "Environment Variables:\n"
                     "\n"
                     "  To attach a profiler you can run a benchmark in endless mode. This can be\n"
                     "  done with the environment variable NANOBENCH_ENDLESS. E.g. like so:\n"
                     "\n"
                     "    NANOBENCH_ENDLESS=MuHash ./bench_bitcoin -filter=MuHash\n"
                     "\n"
                     "  In rare cases it can be useful to suppress stability warnings. This can be\n"
                     "  done with the environment variable NANOBENCH_SUPPRESS_WARNINGS, e.g:\n"
                     "\n"
                     "    NANOBENCH_SUPPRESS_WARNINGS=1 ./bench_bitcoin\n"
                     "\n"
                     "Notes:\n"
                     "\n"
                     "  1. pyperf\n"
                     "     https://github.com/psf/pyperf\n"
                     "\n"
                     "  2. CPU pinning & isolation\n"
                     "     https://pyperf.readthedocs.io/en/latest/system.html\n"
                     "\n"
                     "  3. nanobench\n"
                     "     https://github.com/martinus/nanobench\n"
                     "\n";

        return EXIT_SUCCESS;
    }

    try {
        benchmark::Args args;
        args.asymptote = parseAsymptote(argsman.GetArg("-asymptote", ""));
        args.is_list_only = argsman.GetBoolArg("-list", false);
        args.min_time = std::chrono::milliseconds(argsman.GetIntArg("-min-time", DEFAULT_MIN_TIME_MS));
        args.output_csv = argsman.GetPathArg("-output-csv");
        args.output_json = argsman.GetPathArg("-output-json");
        args.regex_filter = argsman.GetArg("-filter", DEFAULT_BENCH_FILTER);
        args.sanity_check = argsman.GetBoolArg("-sanity-check", false);
        args.priority = parsePriorityLevel(argsman.GetArg("-priority-level", DEFAULT_PRIORITY));

        benchmark::BenchRunner::RunAll(args);

        return EXIT_SUCCESS;
    } catch (const std::exception& e) {
        tfm::format(std::cerr, "Error: %s\n", e.what());
        return EXIT_FAILURE;
    }
}


text:
package eventstore
package core
package operations

import scala.util.{ Failure, Success }
import org.specs2.mutable.Specification
import OperationError._
import Inspection.Decision.{Retry, Stop, Fail}
import TestData._

class TransactionStartInspectionSpec extends Specification {
  val inspection = TransactionStartInspection(transactionStart).pf

  "TransactionStartInspection" should {

    "handle TransactionStartCompleted" in {
      inspection(Success(transactionStartCompleted)) mustEqual Stop
    }

    "handle CommitTimeout" in {
      inspection(Failure(CommitTimeout)) mustEqual Retry
    }

    "handle ForwardTimeout" in {
      inspection(Failure(ForwardTimeout)) mustEqual Retry
    }

    "handle PrepareTimeout" in {
      inspection(Failure(PrepareTimeout)) mustEqual Retry
    }

    "handle WrongExpectedVersion" in {
      inspection(Failure(WrongExpectedVersion)) must beLike {
        case Fail(_: WrongExpectedVersionException) => ok
      }
    }

    "handle StreamDeleted" in {
      inspection(Failure(StreamDeleted)) must beLike {
        case Fail(_: StreamDeletedException) => ok
      }
    }

    "handle InvalidTransaction" in {
      inspection(Failure(InvalidTransaction)) mustEqual Fail(InvalidTransactionException)
    }

    "handle AccessDenied" in {
      inspection(Failure(AccessDenied)) must beLike {
        case Fail(_: AccessDeniedException) => ok
      }
    }
  }
}


text:
package com.blazebit.persistence.view;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Adds {@link CTEProvider}s that should be invoked when applying the annotated entity view.
 *
 * @author Giovanni Lovato
 * @since 1.4.0
 */
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface With {

    /**
     * The CTE providers.
     *
     * @return the CTE providers
     */
    Class<? extends CTEProvider>[] value();

}


text:
using System.Collections.Generic;

namespace System.Reflection {

    public class TypeInfo {

        private readonly Type _type;

        internal TypeInfo(Type type) {
            _type = type;
        }

        public bool IsAnsiClass => _type.IsAnsiClass;
        public bool IsUnicodeClass => _type.IsUnicodeClass;
        public bool IsAutoClass => _type.IsAutoClass;
        public bool IsNotPublic => _type.IsNotPublic;
        public bool IsPublic => _type.IsPublic;
        public bool IsNestedPublic => _type.IsNestedPublic;
        public bool IsNestedPrivate => _type.IsNestedPrivate;
        public bool IsNestedFamily => _type.IsNestedFamily;
        public bool IsNestedAssembly => _type.IsNestedAssembly;
        public bool IsNestedFamANDAssem => _type.IsNestedFamANDAssem;
        public bool IsNestedFamORAssem => _type.IsNestedFamORAssem;
        public bool IsAutoLayout => _type.IsAutoLayout;
        public bool IsLayoutSequential => _type.IsLayoutSequential;
        public bool IsExplicitLayout => _type.IsExplicitLayout;
        public bool IsClass => _type.IsClass;
        public bool IsInterface => _type.IsInterface;
        public bool IsAbstract => _type.IsAbstract;
        public bool IsSealed => _type.IsSealed;
        public bool IsSpecialName => _type.IsSpecialName;
        public bool IsImport => _type.IsImport;
        public bool IsSerializable => _type.IsSerializable;

        public virtual Type BaseType => _type.BaseType;
        public virtual bool IsValueType => _type.IsValueType;
        public virtual bool IsGenericType => _type.IsGenericType;
        public virtual bool IsGenericTypeDefinition => _type.IsGenericTypeDefinition;
        public virtual bool IsAssignableFrom(TypeInfo ti) => _type.IsAssignableFrom(ti._type);

        public virtual Type[] GenericTypeParameters => _type.GetGenericArguments();
        public virtual IEnumerable<Type> ImplementedInterfaces => _type.GetInterfaces();
        public virtual IEnumerable<MethodInfo> DeclaredMethods => _type.GetMethods();
        public virtual IEnumerable<PropertyInfo> DeclaredProperties => _type.GetProperties();

        public virtual IEnumerable<TypeInfo> DeclaredNestedTypes {
            get {
                var types = _type.GetNestedTypes();
                var typeInfos = new TypeInfo[types.Length];
                for (int i = 0; i < types.Length; i++) {
                    typeInfos[i] = new TypeInfo(types[i]);
                }
                return typeInfos;
            }
        }

        public virtual MethodInfo GetDeclaredMethod(string name) => _type.GetMethod(name);
        public virtual PropertyInfo GetDeclaredProperty(string name) => _type.GetProperty(name);

        public virtual TypeInfo GetDeclaredNestedType(string name) {
            var type = _type.GetNestedType(name);
            return (type != null) ? new TypeInfo(type) : null;
        }

    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Comment extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('generiq','generiq');
		$this->generiq->initialise('Commentaire', array('Comment,UserComment,EmailComment,DateComment,'), array('IDComment' => 'asc'), 'IDComment');
	}

	public function add_comment($iduser)
	{
		$this->_validate();
		$this->_validatemail();
		$data = array();
		foreach ($this->input->post('inputs') as $key => $value) {
			$data[$key] =  $value;
		}
		$data["DateComment"] = date("Y.m.d");
		$data["FkUser"] = $iduser;
		$insert = $this->generiq->save($data);
		echo json_encode(array("status" => TRUE));
	}

	private function _validate()
	{
		$data = array();
		$data['status'] = TRUE;
		foreach ($this->input->post('inputs') as $key => $value) {
			if($value == '')
			{
				$data['status'] = FALSE;
				$data['type'] = "vide";
			}
			if((preg_match("/^[a-zA-Z0-9 @ èéçà.,;':]+$/", $value) != 1))
			{
				$data['inputerror'][] = $key;
				$data['error_string'][] = 'Entrer une chaine valide';
				$data['status'] = FALSE;
			}
		}

		if($data['status'] === FALSE)
		{
			echo json_encode($data);
			exit();
		}
	}

	private function _validatemail()
	{
		$data['status'] = TRUE;
		$email = $this->input->post('inputs[EmailComment]');
		if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
		{
			$data['status'] = FALSE;
			$data['type'] = "mail";
		}

		if($data['status'] === FALSE)
		{
			echo json_encode($data);
			exit();
		}
	}
}


text:
package foundation.softwaredesign.orbi.model.game.server;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * @author Lucas Reeh <lr86gm@gmail.com>
 */
@XmlRootElement
public class MessageOfTheDay {

    @XmlTransient
    private Long id;
    private String message;
    @XmlTransient
    private String expires;
    private String created;

    public Long getId() {
        return id;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getExpires() {
        return expires;
    }

    public void setExpires(String expires) {
        this.expires = expires;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }
}


text:
<!DOCTYPE html>

	<title>Demo HTTPS Server</title>
	<link rel='stylesheet' href='/stylesheets/style.css'></link>

Demo HTTPS Server accessing /proc via client-side timer

CPU Info

Linux version

Command Line

BBB Uptime

Current up time [s], and time in idle process [s]:


text:
package com.sri.ai.grinder.helper;

import static com.sri.ai.expresso.helper.Expressions.FALSE;
import static com.sri.ai.grinder.interpreter.DefaultAssignment.assignment;

import java.util.List;
import java.util.Random;

import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.api.Type;
import com.sri.ai.expresso.type.FunctionType;
import com.sri.ai.expresso.type.IntegerExpressoType;
import com.sri.ai.expresso.type.IntegerInterval;
import com.sri.ai.expresso.type.RealExpressoType;
import com.sri.ai.expresso.type.RealInterval;
import com.sri.ai.grinder.api.Context;
import com.sri.ai.grinder.interpreter.Assignment;
import com.sri.ai.grinder.library.set.Sets;
import com.sri.ai.grinder.library.set.extensional.ExtensionalSets;
import com.sri.ai.grinder.rewriter.api.Rewriter;
import com.sri.ai.grinder.theory.differencearithmetic.DifferenceArithmeticTheory;
import com.sri.ai.grinder.theory.differencearithmetic.RangeAndExceptionsSet;
import com.sri.ai.grinder.theory.differencearithmetic.SingleVariableDifferenceArithmeticConstraint;
import com.sri.ai.grinder.theory.differencearithmetic.ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver;
import com.sri.ai.grinder.theory.linearrealarithmetic.IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver;
import com.sri.ai.grinder.theory.linearrealarithmetic.LinearRealArithmeticTheory;
import com.sri.ai.grinder.theory.linearrealarithmetic.SingleVariableLinearRealArithmeticConstraint;
import com.sri.ai.util.collect.EZIterator;
import com.sri.ai.util.collect.NIterator;

/**
 * An assignments iterator that samples over the space of possible assignments.
 * The iterator never ends unless the set to sample from is empty.
 * To limit to a number of samples, use the {@link NIterator} adaptor.
 * Currently, only a single variable is supported and an exception is thrown if more than one is received.
 *
 * @author oreilly
 *
 */
public class AssignmentsSamplingIterator extends EZIterator<Assignment> {
	private Expression index;
	private Type typeToSampleFrom;
	private Expression condition;
	private Rewriter conditionRewriter;
	private Random random;
	private Context context;
	private boolean nothingToSampleFrom;

	public AssignmentsSamplingIterator(List<Expression> indices, Expression condition, Rewriter conditionRewriter, Random random, Context context) {
		if (indices.size() != 1) {
			throw new UnsupportedOperationException("Assignment sampling iterator only supports a single index currently, received: " + indices);
		}
		this.index = indices.get(0);

		this.typeToSampleFrom = getTypeToSampleFrom(index, condition, context);
		this.nothingToSampleFrom = this.typeToSampleFrom == null;

		this.condition         = condition;
		this.conditionRewriter = conditionRewriter;
		this.random            = random;
		this.context           = context;
	}

	@Override
	protected Assignment calculateNext() {
		if (nothingToSampleFrom) {
			return null;
		}
		Expression sampledValue;
		do {
			sampledValue = sampleValue();
		} while (conditionIsNotSatisfied(sampledValue));
		Assignment result = assignment(index, sampledValue);
		return result;
	}

	private Expression sampleValue() {
		Expression result = typeToSampleFrom.sampleUniquelyNamedConstant(random);
		return result;
	}

	private boolean conditionIsNotSatisfied(Expression sampledValue) {
		Expression conditionValue = evaluateCondition(sampledValue);
		return conditionValue.equals(FALSE);
	}

	private Expression evaluateCondition(Expression sampledValue) {
		Context contextExtendedWithSampledAssignment = makeContextExtendedBySampledValue(sampledValue);
		Expression conditionValue = evaluateConditionUnder(contextExtendedWithSampledAssignment);
		return conditionValue;
	}

	private Context makeContextExtendedBySampledValue(Expression sampledValue) {
		Assignment sampledAssignment = makeIndexAssignment(sampledValue);
		Context contextExtendedWithSampledAssignment = sampledAssignment.extend(context);
		return contextExtendedWithSampledAssignment;
	}

	private Assignment makeIndexAssignment(Expression sampledValue) {
		Assignment result = assignment(index, sampledValue);
		return result;
	}

	private Expression evaluateConditionUnder(Context contextWithSampledAssignment) {
		return conditionRewriter.apply(condition, contextWithSampledAssignment);
	}

	public static Type getTypeToSampleFrom(Expression variable, Expression condition, Context context) {
		Type result = GrinderUtil.getTypeOfExpression(variable, context);

		if (result instanceof FunctionType) {
			FunctionType functionType = (FunctionType) result;
			result = new LazySampledFunctionType(functionType.getCodomain(), functionType.getArgumentTypes().toArray(new Type[functionType.getArity()]));
		}
		else {
			if (condition.equals(false)) {
				result = null;
			}
			else if (condition.equals(true)) {
				// we leave as is.
			}
			else if (result instanceof RealExpressoType || result instanceof RealInterval) {

				LinearRealArithmeticTheory theory = new LinearRealArithmeticTheory(true, true);
				SingleVariableLinearRealArithmeticConstraint constraint = (SingleVariableLinearRealArithmeticConstraint) theory.makeSingleVariableConstraint(variable, context);
				constraint = (SingleVariableLinearRealArithmeticConstraint) constraint.conjoin(condition, context);

				IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver solver =
						new IntervalWithMeasureEquivalentToSingleVariableLinearRealArithmeticConstraintStepSolver(constraint);

				Expression realInterval = solver.solve(context);
				if (Sets.isEmptySet(realInterval)) {
					result = null; // used to indicate an empty set.
				}
				else if (ExtensionalSets.isExtensionalSet(realInterval) && ExtensionalSets.isSingleton(realInterval)) {
					String singletonValue = realInterval.get(0).toString();
					result = new RealInterval("["+singletonValue+";"+singletonValue+"]");
				}
				else {
					result = new RealInterval(realInterval.toString());
				}
			}
			else if (result instanceof IntegerExpressoType || result instanceof IntegerInterval) {

				DifferenceArithmeticTheory theory = new DifferenceArithmeticTheory(true, true);
				SingleVariableDifferenceArithmeticConstraint constraint = (SingleVariableDifferenceArithmeticConstraint) theory.makeSingleVariableConstraint(variable, context);
				constraint = (SingleVariableDifferenceArithmeticConstraint) constraint.conjoin(condition, context);

				ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver solver = new ValuesOfSingleVariableDifferenceArithmeticConstraintStepSolver(constraint);

				// NOTE: the exceptions set returned here is implicit in the condition so no need to use it here.
				RangeAndExceptionsSet rangeAndExceptionsSet = (RangeAndExceptionsSet) solver.solve(context);

				if (rangeAndExceptionsSet.isEmpty()) {
					result = null; // used to indicate an empty set.
				}
				else if (rangeAndExceptionsSet.isSingleton()) {
					result = new IntegerInterval(rangeAndExceptionsSet.getSingleValue().intValueExact(), rangeAndExceptionsSet.getSingleValue().intValueExact());
				}
				else {
					result = new IntegerInterval(rangeAndExceptionsSet.getStrictLowerBound().intValueExact()+1, rangeAndExceptionsSet.getNonStrictUpperBound().intValueExact());
				}
			}
		}

		if (result != null && !result.isSampleUniquelyNamedConstantSupported()) {
			throw new IllegalArgumentException("Unable to sample " + variable + " from " + result);
		}

		return result;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/search" android:state_selected="true"></item>
    <item android:drawable="@drawable/search" android:state_pressed="true"></item>
    <item android:drawable="@drawable/search_light"></item>

</selector>


text:
name: "Mark Zediker"
pic: mark_zediker_bw.png
social:
    - title: linkedin
      url: https://www.linkedin.com/in/mark-zediker-40b87ba
company_affiliations:
    - name: Foro Energy

category: People

---


text:
var localizedStrings = {
	"Zone" : "Room"
};


text:
package io.kubernetes.client.openapi.models;

import io.kubernetes.client.fluent.Fluent;

/** Generated */
public interface V1SubjectFluent<A extends V1SubjectFluent<A>> extends Fluent<A> {
  public String getApiGroup();

  public A withApiGroup(String apiGroup);

  public Boolean hasApiGroup();

  public String getKind();

  public A withKind(String kind);

  public Boolean hasKind();

  public String getName();

  public A withName(String name);

  public Boolean hasName();

  public String getNamespace();

  public A withNamespace(String namespace);

  public Boolean hasNamespace();
}


text:
/*
 * The Spring Framework is published under the terms
 * of the Apache Software License.
 */

package com.interface21.aop.framework;

import com.interface21.core.NestedRuntimeException;

/**
 *
 * @author Rod Johnson
 * @since 13-Mar-2003
 * @version $Revision: 1.1 $
 */
public class AopConfigException extends NestedRuntimeException {

	/**
	 * @param mesg
	 */
	public AopConfigException(String mesg) {
		super(mesg);
	}

}


text:
<?php

namespace WebModule\Komin\Beef\Server\ValidationTestServer\ValidationTest;

use Bee\Component\Log\SuperLogger\SuperLogger;
use WebModule\Komin\Base\Lang\Translator\Stazy\StazyTranslator;

/**
 * BaseValidationTest
 * @author Lingtalfi
 * 2015-01-07
 *
 */
abstract class BaseValidationTest implements ValidationTestInterface
{

    protected function getMandatoryParam($name, array $params)
    {

        if (array_key_exists($name, $params)) {
            return $params[$name];
        }
        $msg = sprintf("Validation test: missing mandatory param: %s", $name);
        SuperLogger::getInst()->log('Komin.Beef.Server.Validation.missingMandatoryParam', $msg);
        throw new ValidationTestException($msg);

    }

    protected function translateTags($msgId, array $errorTags = [], $catalogInfo = null, $tags = null, $pluralNumber = null, $lang = null)
    {
        $r = StazyTranslator::getInst()->translate($msgId, $catalogInfo, $tags, $pluralNumber, $lang);
        $keys = array_keys($errorTags);
        $values = array_values($errorTags);
        array_walk($keys, function (&$v) {
            $v = '[' . $v . ']';
        });
        $r = str_replace($keys, $values, $r);
        return $r;
    }

    protected function translate($msgId, $catalogInfo = null, $tags = null, $pluralNumber = null, $lang = null)
    {
        return StazyTranslator::getInst()->translate($msgId, $catalogInfo, $tags, $pluralNumber, $lang);
    }

}