text:
package org.andengine.engine.options.resolutionpolicy;

import org.andengine.opengl.view.RenderSurfaceView;

import android.view.View.MeasureSpec;

/**
 * (c) 2010 Nicolas Gramlich (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 11:23:00 - 29.03.2010
 */
public class RelativeResolutionPolicy extends BaseResolutionPolicy {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private final float mWidthScale;
	private final float mHeightScale;

	// ===========================================================
	// Constructors
	// ===========================================================

	public RelativeResolutionPolicy(final float pScale) {
		this(pScale, pScale);
	}

	public RelativeResolutionPolicy(final float pWidthScale, final float pHeightScale) {
		this.mWidthScale = pWidthScale;
		this.mHeightScale = pHeightScale;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) {
		BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec);

		final int measuredWidth = (int) (MeasureSpec.getSize(pWidthMeasureSpec) * this.mWidthScale);
		final int measuredHeight = (int) (MeasureSpec.getSize(pHeightMeasureSpec) * this.mHeightScale);

		pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight);
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
<?php
	header("Content-type:application/json;charset=utf-8");
	$link = mysqli_connect('localhost','root','root','baidunews',8889);

	if($link){
		$newsid = $_POST['newsid'];

		$sql = "DELETE FROM `news` WHERE `id`='{$newsid}'";
		mysqli_query($link,'SET NAMES utf8');
		$result = mysqli_query($link,$sql);

		echo json_encode(array('删除'=>'成功'));
	}
	mysqli_close($link);
?>

redpajama_set_name: RedPajamaGithub


text:
package com.carlosroman.samples.camel.jaxb.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "domain")
@XmlAccessorType(XmlAccessType.FIELD)
public class DomainObject {

    private String valueOne;
    private String valueTwo;

    private DomainObject() {

    }

    private DomainObject(final Builder builder) {
        this.valueOne = builder.valueOne;
        this.valueTwo = builder.valueTwo;
    }

    public String getValueOne() {
        return valueOne;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

    @Override
    public boolean equals(final Object rhs) {
        return EqualsBuilder.reflectionEquals(this, rhs);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    public static class Builder {
        private String valueOne;
        private String valueTwo;

        public Builder withValueOne(final String valueOne) {
            this.valueOne = valueOne;
            return this;
        }

        public Builder withValueTwo(final String valueTwo) {
            this.valueTwo = valueTwo;
            return this;
        }

        public DomainObject build() {
            return new DomainObject(this);
        }
    }
}


text:
using BenchmarkDotNet.Portability;
using Xunit;

namespace BenchmarkDotNet.IntegrationTests.Xunit
{
    public class FactClassicDotNetOnlyAttribute : FactAttribute
    {
        public FactClassicDotNetOnlyAttribute(string skipReason)
        {
            // ReSharper disable once VirtualMemberCallInConstructor
            if (!RuntimeInformation.IsClassic())
                Skip = skipReason;
        }
    }
}


text:
FROM ubuntu:xenial
RUN apt-get update && apt-get install --yes --no-install-recommends build-essential devscripts python2.7 python3 debhelper\
	 python-setuptools python3-setuptools dh-python dh-systemd dh-virtualenv
RUN mkdir -p /build/package
RUN mkdir -p /packages
COPY ./ /build/package
WORKDIR /build/package
CMD dpkg-buildpackage && mv ../*.deb /packages


text:
package com.google.gerrit.pgm.util;

public class Die extends RuntimeException {
  private static final long serialVersionUID = 1L;

  public Die(final String why) {
    super(why);
  }

  public Die(final String why, final Throwable cause) {
    super(why, cause);
  }
}


text:
package org.apache.causeway.core.metamodel.valuesemantics;

import javax.annotation.Priority;
import javax.inject.Named;

import org.springframework.stereotype.Component;

import org.apache.causeway.applib.annotation.PriorityPrecedence;
import org.apache.causeway.applib.util.schema.CommandDtoUtils;
import org.apache.causeway.commons.collections.Can;
import org.apache.causeway.schema.cmd.v2.CommandDto;

@Component
@Named("causeway.val.CommandDtoValueSemantics")
@Priority(PriorityPrecedence.LATE)
public class CommandDtoValueSemantics
extends XmlValueSemanticsAbstract<CommandDto> {

    @Override
    public final Class<CommandDto> getCorrespondingClass() {
        return CommandDto.class;
    }

    // -- ENCODER DECODER

    @Override
    public final String toXml(final CommandDto commandDto) {
        return CommandDtoUtils.toXml(commandDto);
    }

    @Override
    public final CommandDto fromXml(final String xml) {
        return CommandDtoUtils.fromXml(xml);
    }

    // -- EXAMPLES

    @Override
    public Can<CommandDto> getExamples() {
        return Can.of(new CommandDto(), new CommandDto());
    }

}


text:
<Record>
<Term>Dynabac</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Dirithromycin</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "./dtd/document-v10.dtd">

<document>

        <title>Batik - Glossary</title>
        <subtitle>Batik and SVG Glossary</subtitle>
        <authors>
            <person name="Vincent Hardy" email="vincent.hardy@eng.sun.com"/>
        </authors>

        <anchor id="GVT" />
        <s1 title="GVT, Graphic Vector Toolkit">

        GVT (Graphic Vector Toolkit) is an object oriented framework that
        describes complex 2D graphics in terms of a tree of Java objects. GVT
        is used in Batik to represent how SVG images are to be rendered.

        </s1>

        <anchor id="SVGDOM" />
        <s1 title="SVG DOM">

        The SVG DOM (Document Object Model) defines the API that programming
        languages use to interact with SVG documents. There are different 'bindings'
        of the DOM API for different languages. For example, there is an ECMAScript
        binding which allows SVG scripts to access or modify SVG documents, for example
        in reaction to events. There is also a Java technology binding which allows
        Java programs to dynamically interact with SVG documents. The Java binding
        and the ECMA Script binding are both available in Batik.

        </s1>

        <anchor id="SVGGenerator" />
        <s1 title="SVG Generator">

        The SVG Generator is a module of Batik that allows Java applications
        to create SVG content without needing specific knowledge of SVG. Applications
        doing graphics in Java use an API, embodied by the Graphics2D class, to
        do all their rendering operations. They use the same code, but different
        implementations of that API, to render to various outputs such as a screen
        or a printer. The SVG Generator is another implementation of that API that
        instead of drawing to a screen or a printer generates SVG content. Because
        it implements the same API as for printing or drawing to the screen, the
        same code that does screen rendering and printing can be used with the
        generator to generate SVG content. For an example of how to use this
        module, follow this <link href="svggen.html">link</link>

        </s1>

        <anchor id="SVGParser" />
        <s1 title="SVG Parser">

        The SVG Parser module contains 'micro parsers' specific to SVG to convert SVG specific attributes,
        such as path data, transforms or color values into equivalent Java
        objects such as java.awt.geom.GeneralPath, java.awt.geom.AffineTransform
        or java.awt.Color.

        </s1>

</document>


text:
@interface DLFNavigationControllerDelegate : NSObject <UINavigationControllerDelegate>

@end


text:
package com.treode.disk

import java.io.IOException
import java.nio.file.{Path, Paths}
import scala.util.Random

import com.treode.async.{Async, Scheduler}, Async.supply
import com.treode.async.stubs.StubScheduler
import com.treode.async.stubs.implicits._
import com.treode.disk.stubs.StubDiskEvents
import com.treode.notify.Notification
import com.treode.disk.messages._
import com.treode.pickle.Picklers
import com.treode.tags.Periodic
import org.scalatest.FlatSpec

import DiskTestTools._

class DriveGroupSpec extends FlatSpec with DiskChecks {

  implicit val config = DiskTestConfig()
  implicit val events = new StubDiskEvents
  implicit val geom = DriveGeometry (8, 6, 1 << 14)

  /** The DriveGroup testing strategy is a no-op because the DrivesTracker in DiskChecks
    * already verifies everything we need. This no-op strategy assures us that the DriveGroup
    * works sans interference from other components.
    */
  private class DriveGroupTracker extends Tracker {

    def recover () (implicit
      scheduler: Scheduler,
      recovery: RecoveryAgent
    ) {
      // no-op
    }

    def launch () (implicit
      random: Random,
      scheduler: Scheduler,
      launch: DiskLaunch
    ) {
      // no-op
    }

    def verify (
      crashed: Boolean
    ) (implicit
      scheduler: Scheduler,
      launch: LaunchAgent
    ): Async [Unit] =
      supply {
        // no-op
      }

    override def toString = "new DriveGroupTracker"
  }

  /** The DriveGroup effect is a no-op because the scenarios in DiskChecks already verify
    * everything we need. This no-op effect assures us that the DriveGroup works sans interference
    * from other components.
    */
  private case object DriveGroupPhase extends Effect [DriveGroupTracker] {

    def start (
      tracker: DriveGroupTracker
    ) (implicit
      random: Random,
      scheduler: Scheduler,
      launch: LaunchAgent,
      drives: DrivesTracker
    ): Async [Unit] =
      supply {
        // no-op
      }

    override def toString = "DriveGroupPhase"
  }

  /** Convenient methods for testing. */
  implicit class RichDiskController (controller: DiskController) {

    def change (geom: DriveGeometry) (attach: String*) (drain: String*): Async [Notification [Unit]] = {
      val attachPaths = (attach map (Paths.get(_))) map (DriveAttachment (_, geom))
      val drainPaths = (drain map (Paths.get(_)))
      controller.asInstanceOf [DiskAgent] .change (DriveChange (attachPaths, drainPaths))
    }}

  def setup (paths: String*) (implicit scheduler: StubScheduler): DiskController = {
    implicit val files = new StubFileSystem
    implicit val recovery = new RecoveryAgent
    files.create (paths map (Paths.get (_)), 0, geom.blockBits)
    val launch = recovery.reattach().expectPass()
    launch.launch()
    launch.controller
  }

  "DriveGroup.change" should "reject nonexistant files" in {
    implicit val scheduler = StubScheduler.random()
    val controller = setup ("f1", "f2", "f3")
    val e = controller.attach (geom, "a") .expectFail [IOException]
    assertResult ("""File "a" does not exist.""") (e.getMessage)
  }

  it should "reject duplicate filenames (same operation)" in {
    implicit val scheduler = StubScheduler.random()
    val controller = setup ("f1", "f2", "f3")
    val e = controller.attach (geom, "f1", "f1") .expectPass()
    scheduler.run()
    assertEqNotification (AlreadyAttaching ("f1")) (e)
  }

  it should "reject duplicate filenames (different operation)" in {
    implicit val scheduler = StubScheduler.random()
    val controller = setup ("d1", "f2", "f3")
    val e1 = controller.attach (geom, "d1") .expectPass()
    scheduler.run()
    val e2 = controller.attach (geom, "d1") .expectPass()
    scheduler.run()
    assertEqNotification () (e1)
    assertEqNotification (AlreadyAttached ("d1")) (e2)
  }

  it should "reject duplicate draining of the same file" in {
    implicit val scheduler = StubScheduler.random()
    val controller = setup ("f1", "f2", "f3")
    val e1 = controller.attach (geom, "f1") .expectPass()
    val e2 = controller.drain ("f1", "f1") .expectPass()
    scheduler.run()
    assertEqNotification () (e1)
    assertEqNotification (AlreadyDraining ("f1")) (e2)
  }

  it should "reject draining unattached files" in {
    implicit val scheduler = StubScheduler.random()
    val controller = setup("f1", "f2", "f3")
    val e1 = controller.drain ("f1").expectPass()
    scheduler.run()
    assertEqNotification (NotAttached("f1")) (e1)
  }

  it should "reject attaching and draining a file in the same operation" in {
    implicit val scheduler = StubScheduler.random()
    val controller = setup ("f1", "f2", "f3")
    val e1 = controller.change (geom) ("f1") ("f1") .expectPass()
    scheduler.run()
    assertEqNotification (NotAttached("f1")) (e1)
  }

  "The DriveGroup" should "recover attached disks" taggedAs (Periodic) in {
    manyScenarios (new DriveGroupTracker, DriveGroupPhase)
  }}


text:
"""
Scan form/scripts for popular CSRF token names
"""
__author__ = "sword"

import sys
from os.path import dirname,abspath

# Importing PinkWave extensions
sys.path.append(dirname(dirname(dirname(abspath(__file__)))))
from extensions.Util import Util,report,payloads
import extensions.Request as Request

def labels():
    return ['A8 - Cross-Site Request Forgery (CSRF)']

def options():
    return ['target']

def start(pentest):
    tokenFound = None
    foundIn = None
    Request.get(pentest.target)

    # Scan forms
    forms = pentest.browser.driver.find_elements_by_xpath(".//form")
    if len(forms) != 0:
        for input in forms:
            content = input.get_attribute('innerHTML')
            for payload in payloads("csrftokennames",__file__):
                if payload.lower() in content.lower():
                    tokenFound = token
            foundIn = "form"

    # Scan scripts
    if tokenFound is None:
        forms = pentest.browser.driver.find_elements_by_xpath(".//script")
        for input in forms:
            content = input.get_attribute('innerHTML')
            for payload in payloads("csrftokennames",__file__):
                if payload.lower() in content.lower():
                    tokenFound = token
            foundIn = "script"

    if tokenFound is None:
        report("Potential CSRF vulnerability. No token names found in any forms")
    else:
        print "token(%s) found in %s " % ( str(tokenFound), foundIn )


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="Notifications">
        <CheckBoxPreference
            android:key="notification_state"
            android:title="Enable notifications"
            android:summary="Once enabled, you will be notified daily if your balances fall beneath the thresholds specified below"
            android:defaultValue="false" />
        <in.iamkelv.balances.preferences.TimePickerPreference
            android:key="prefs_time"
            android:title="@string/prefs_time_title"
            android:summary="@string/prefs_time_summary" />
        <in.iamkelv.balances.preferences.ThresholdPickerPreference
            android:key="prefs_lunch"
            android:title="@string/prefs_lunch_title"
            android:summary="@string/prefs_lunch_summary" />
        <in.iamkelv.balances.preferences.ThresholdPickerPreference
            android:key="prefs_tuck"
            android:title="@string/prefs_tuck_title"
            android:summary="@string/prefs_tuck_summary" />
    </PreferenceCategory>
    <PreferenceCategory
        android:title="Additional settings">
        <Preference
            android:key="prefs_reset"
            android:title="@string/prefs_reset_title"
            android:summary="@string/prefs_reset_summary" />
    </PreferenceCategory>

</PreferenceScreen>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Jap. Bot. 47(5): 129 (1972)

#### Original name
Usnea subintumescens Asahina

### Remarks
null


text:
<?php

namespace Omea\GestionTelco\PatesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('OmeaGestionTelcoPatesBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
/*
 * Arekkuusu / Improbable plot machine. 2018
 *
 * This project is licensed under the MIT.
 * The source code is available on github:
 * https://github.com/ArekkuusuJerii/Improbable-plot-machine
 */
package arekkuusu.implom.client.util.resource.sprite;

import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Tuple;

/**
 * Created by <Arekkuusu> on 23/07/2017.
 * It's distributed as part of Improbable plot machine.
 */
public class FrameSpriteResource extends SpriteResource {

	private final int rows, columns;
	private final double frames;
	private final double u;
	private final double v;

	public FrameSpriteResource(ResourceLocation location, int rows, int columns) {
		super(location);

		this.columns = columns;
		this.rows = rows;
		this.u = 1D / columns;
		this.v = 1D / rows;

		this.frames = rows * columns;
	}

	public Tuple<Double, Double> getUVFrame(int age) {
		int frame = (int) (age % frames);
		return new Tuple<>((frame % columns) * u, (frame / columns) * v);
	}

	public double getU() {
		return u;
	}

	public double getV() {
		return v;
	}

	public int getRows() {
		return rows;
	}

	public int getColumns() {
		return columns;
	}

	public double getFrames() {
		return frames;
	}
}


text:
<?php

namespace Kvartiri\KvartiriBundle\Form;

use Doctrine\ORM\EntityRepository;
use Kvartiri\KvartiriBundle\Entity\Hotels;
//use Kvartiri\KvartiriBundle\Form\PromotionEarlyBooking;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class PromotionsType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function __construct($hotelId) {
        $this->hotelId = $hotelId;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $hotelId = $this->hotelId;
        $builder
//            ->add('hotel')
        ->add('hotel', 'entity', array(
        'class' => 'KvartiriBundle:Hotels',
        'query_builder' => function (EntityRepository $er) use($hotelId) {
        return $er->createQueryBuilder('hotel')
        ->where('hotel.id = ?1')
        ->setParameter(1, $hotelId)
        ;
        },
        ))
//            ->add('promotionEarlyBooking', new PromotionEarlyBookingType())
        ->add('promotionEarlyBooking', 'collection', array(

        'type' => new PromotionEarlyBookingType(),
        'allow_add' => true,
        'allow_delete' => true,
        )

        )
        ->add('promotionFixedDates', 'collection', array(
                    'type' => new PromotionFixedDatesType(),
                    'allow_add' => true,
                    'allow_delete' => true,

                        )
                )
                ->add('promotionGroup', 'collection', array(
                    'type' => new PromotionGroupType(),
                    'allow_add' => true,
                    'allow_delete' => true,

                        )
                )
                ->add('promotionMoreNights', 'collection', array(
                    'type' => new PromotionMoreNightsType(),
                    'allow_add' => true,
                    'allow_delete' => true,

                        )
                )
                ->add('promotionPeriod', 'collection', array(
                    'type' => new PromotionPeriodType(),
                    'allow_add' => true,
                    'allow_delete' => true,

                        )
                )
                ->add('reductionChildren', 'collection', array(
                    'type' => new ReductionChildrenType(),
                    'allow_add' => true,
                    'allow_delete' => true,

                        )
                )
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Kvartiri\KvartiriBundle\Entity\Promotions'
        ));
    }

    /**
     * @return string
     */
    public function getName() {
        return 'kvartiri_kvartiribundle_promotions';
    }

}


text:
'use strict'

// Karma configuration
var webpack = require('webpack')

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '..',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha'],

        // list of files / patterns to load in the browser
        files: [
            'tests/*.js'
        ],

        webpack: {
            devtool: 'inline-source-map',
            plugins: [
            ],
            module: {
                loaders: [
                    // es6 / 7
                    {
                        test: /\.jsx?$/,
                        loader: 'babel-loader?stage=0&optional=runtime',
                        exclude: /node_modules/
                    }
                ]
            }
        },
        client: {
            mocha: {
                reporter: 'html' // change Karma's debug.html to the mocha web reporter
            }
        },

        // list of files to exclude
        exclude: [],

        // https://www.codementor.io/reactjs/tutorial/test-reactjs-components-karma-webpack
        preprocessors: {
            'tests/*.js': ['webpack', 'sourcemap']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true
    });
};


text:
@extends('layouts.admin')

@section('content')

                Advanced Form Elements
                Preview

 Home

Forms

Create Role

Role

                        <button class="btn btn-box-tool" data-widget="collapse"></button>
                        <button class="btn btn-box-tool" data-widget="remove"></button>

                @include('common.errors')
                    {{ Form::open(['url' => 'role/add', 'method' => 'post', 'role' =>'form']) }}

                    {{ csrf_field() }}

                                {{ Form::label('name', 'Name') }}
                                {{ Form::text('name', '', array('class' => 'form-control', 'placeholder'=>'Enter Role Name'))}}

                                {{ Form::checkbox('status', 'status') }}
                                {{ Form::label('status', 'Status') }}

Access Permissions

                                @foreach($accesses as $access)
                                {{ Form::checkbox('access[]',$access->id) }}
                                {{ $access->name }}
                                @endforeach

                                        Cancel

                                        <button style="height:35px;width:100px" type="submit" class="btn btn-primary btn-block btn-flat" style="right: 60%">Add New</button>

                    {{ Form::close() }}

@endsection


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

import io.prestosql.operator.GroupByIdBlock;
import io.prestosql.spi.Page;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.BlockBuilder;
import io.prestosql.spi.type.Type;

public interface GroupedAccumulator
{
    long getEstimatedSize();

    Type getFinalType();

    Type getIntermediateType();

    void addInput(GroupByIdBlock groupIdsBlock, Page page);

    void addIntermediate(GroupByIdBlock groupIdsBlock, Block block);

    void evaluateIntermediate(int groupId, BlockBuilder output);

    void evaluateFinal(int groupId, BlockBuilder output);

    void prepareFinal();
}


text:
package io.sphere.sdk.facets;

import io.sphere.sdk.search.FacetedSearchExpression;
import io.sphere.sdk.search.PagedSearchResult;
import io.sphere.sdk.search.model.FacetedSearchSearchModel;

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

/**
 * Interface that represents a facet, as used in a faceted search.
 * @param <T> type of the resource for this facet (e.g. ProductProjection)
 */
public interface Facet<T> {

    /**
     * Gets the string identifying this facet.
     * @return the key that identifies this facet
     */
    String getKey();

    /**
     * Gets the type of this facet.
     * @return the type of this facet
     */
    FacetType getType();

    /**
     * Gets the label displayed in the facet.
     * @return the label displayed in this facet, or absent if none defined
     */
    @Nullable
    String getLabel();

    /**
     * Whether the facet can be displayed or not.
     * @return true if the facet can be displayed, false otherwise
     */
    boolean isAvailable();

    /**
     * Whether the facet count should be hidden or not.
     * @return true if the count should be hidden, false otherwise
     */
    boolean isCountHidden();

    /**
     * Gets the selected values for this facet used to filter.
     * @return the selected values
     */
    List<String> getSelectedValues();

    /**
     * Gets the faceted search model associated with this facet, representing the attribute path.
     * With this search model you can build facet and filter expressions for this attribute.
     * @return the faceted search model for this facet
     */
    FacetedSearchSearchModel<T> getFacetedSearchSearchModel();

    /**
     * Gets the filter expressions associated to this facet, according to the selected values, as needed to obtain a faceted search.
     * @return the filter expressions for this facet
     */
    FacetedSearchExpression<T> getFacetedSearchExpression();

    /**
     * Gets a new instance of Facet with the same attributes as this, but with the facet result extracted from the given search result.
     * @param searchResult the search result containing the new facet result
     * @return a new instance with same attributes, but with the given facet result
     */
    Facet<T> withSearchResult(final PagedSearchResult<T> searchResult);

    /**
     * Gets a new instance of Facet with the same attributes as this, but with the given selected values.
     * @param selectedValues the new selected values for this facet
     * @return a new instance with same attributes, but with the given selected values
     */
    Facet<T> withSelectedValues(final List<String> selectedValues);

    /**
     * Gets a new instance of Facet with the same attributes as this, but with the given label.
     * @param label the new label
     * @return a new instance with same attributes, but with the given label
     */
    Facet<T> withLabel(final String label);

}


text:
{# -*- coding: utf-8 -*-

  This file is part of Invenio.
  Copyright (C) 2015-2018 CERN.

  Invenio is free software; you can redistribute it and/or modify it
  under the terms of the MIT License; see LICENSE file for more details.
#}
{%- if config.ACCOUNTS %}
  {%- if not current_user.is_authenticated %}
    <form>

        {{ _('Log in') }}
      {% if security.registerable %}

        {{ _('Sign up') }}

      {% endif %}
    </form>
  {%- else %}
    {%- if config.USERPROFILES %}

           {{ current_user.email|truncate(31,true) }}

            {%- for item in current_menu.submenu('settings').children if item.visible %}
              {{ item.text|safe }}

            {%- endfor %}

            {%- block profile_admin %}

            {%- endblock %}

              {{ _('Log out') }}

    {%- else %}
       {{ _('Log out') }}
    {%- endif %}
  {%- endif %}
{%- endif %}


text:
//
//  Path.cpp
//  Cycle_Basis_PF
//
//  Created by Sumiran on 17/06/2014.
//  Copyright (c) 2014 NICTA. All rights reserved.
//

#include "PowerTools++/Path.h"
#include <fstream>
#include "PowerTools++/Net.h"

/* @brief Returns true if the pair (n1,n2) is a source-destination pair for this path */
bool Path::source_dest(Node* n1, Node* n2){
    if(nodes.front()->ID==n1->ID && nodes.back()->ID==n2->ID)
        return true;
    if(nodes.front()->ID==n2->ID && nodes.back()->ID==n1->ID)
        return true;
    return false;
}

/* Returns the length of the path */
int Path::length(){
    return (int)nodes.size();
}

/* Returns true if the path is a cycle */
bool Path::cycle(){
    return (nodes.front()==nodes.back());
}

Path* Path::clone(){
    Path* newp = new Path();
    for (std::list<Node*>::iterator i = nodes.begin(); i != nodes.end(); i++) {
        newp->nodes.push_back((*i));
    }
    return newp;
}


text:
using System;

class ExchangeIfGreater
{
    static void Main()
    {
        /*
         *  Problem 1: Exchange If Greater
         *
         *  - Write an if-statement that takes two double variables a and b and exchanges their values if the first one is greater than the second one.
         *    As a result print the values a and b, separated by a space.
         *
         * */

        double varA;
        double varB;
        double varTemp;

        Console.Title = "Exchange if greater";

        Console.WriteLine("The program reads 2 variables A and B, and exchanges their values ");
        Console.WriteLine("if the first one is greater than the second one.\n");

        bool greaterAB;

        Console.Write("Enter the first variable: ");
        varA = Double.Parse(Console.ReadLine());

        Console.Write("Enter the second varialbe: ");
        varB = Double.Parse(Console.ReadLine());

        greaterAB = varA > varB;

        if (greaterAB)
        {
            varTemp = varA;
            varA = varB;
            varB = varTemp;
            Console.WriteLine("{0} {1}\n", varA, varB);
        }
        else
        {
            Console.WriteLine("{0} {1}\n", varA, varB);
        }
    }
}


text:
function [sequencerName, timeFactor] = osqDefinitions
% Define some aspects of this particular sequencer used.

sequencerName = 'LASOM2';
timeFactor = 1000; % LASOM expects time values in milliseconds. All olfstim values are in seconds.

end


text:
package main

import (
	"fmt"

	"../text"
)

func main() {
	fmt.Println("STRING:                >", "UpperCamelCase")
	fmt.Println("TOSPINAL:              >", text.ToSpinal("UpperCamelCase"))
	fmt.Println("TOTRAIN:               >", text.ToTrain("UpperCamelCase"))
	fmt.Println("TOSNAKE:               >", text.ToSnake("UpperCamelCase"))
	fmt.Println("TOSNAKEUPPER:          >", text.ToSnakeUpper("UpperCamelCase"))
	fmt.Println("TOCAMEL:               >", text.ToCamel("upper_camel_case"))
	fmt.Println("TOCAMELLOWER:          >", text.ToCamelLower("upper_camel_case"))
	fmt.Println("TOREVERSE:             >", text.ToReverse("upper_camel_case"))
	fmt.Println("TOTITLE:               >", text.ToTitle("upper camel case"))
	fmt.Println("GENERATERANDOM:        >", text.GenerateRandomString(40))
	fmt.Println("GENERATERANDOMSPECIAL: >", text.GenerateRandomStringSpecial(40))
	j := text.Jaro("string1", "string2")
	fmt.Println("SIMILARITYJARO:        >", j)
	text.SetBoostThreshold(0.7)
	text.SetPrefixScale(0.1)
	jw := text.JaroWinkler("string1", "string2")
	fmt.Println("SIMILARITYJAROW:       >", jw)
	jw = text.JaroWinkler("string1", "pesty")
	fmt.Println("SIMILARITYJAROW:       >", jw)
	jw = text.JaroWinkler("string1", "string1")
	fmt.Println("SIMILARITYJAROW:       >", jw)
	fmt.Println("FILENAMEEXT:           >", text.FileExtension("/tmp/test/testing.json"))
	fmt.Println("FORMAT:                >", text.Format("The {} says {}", "cow", "MOO!"))
	fmt.Println("FORMAT2:               >", text.Format("I have {} bananas", 871))
	fmt.Println("FORMAT3:               >", text.Format("{} I have bananas", true))
	fmt.Println("FORMAT4:               >", text.Format("It cost £{}", 9.99))
	fmt.Println("FORMAT5:               >", text.Format("This {} part test, is {} and is {} that it is {}% perfect.", 4, true, "trying to prove", 99.99))
	test := []string{"a", "b", "c", "d"}
	test2 := []string{"a", "b", "c", "d", "e", "f"}
	fmt.Println("SLICEINCLUDES1:        >", text.Includes(test, "a"))
	fmt.Println("SLICEINCLUDES2:        >", text.Includes(test, "e"))
	fmt.Println("SLICEEQUALS1:          >", text.Equals(test, test2))
	fmt.Println("SLICEEQUALS2:          >", text.Equals(test, test))
	fmt.Println("SLICESUBTRACT:         >", text.Subtract(test2, test))
	fmt.Println("TOMILITARY:            >", text.ToMilitary("TEST"))
	fmt.Println("TOMORSE:               >", text.ToMorse("TEST"))
	fmt.Println("ORDINISE1:             >", text.Ordinise(1))
	fmt.Println("ORDINISE2:             >", text.Ordinise(2))
	fmt.Println("ORDINISE3:             >", text.Ordinise(3))
	fmt.Println("ORDINISE4:             >", text.Ordinise(4))
	fmt.Println("ORDINISE5:             >", text.Ordinise(22))
	fmt.Println("ORDINISE6:             >", text.Ordinise(44))
	fmt.Println("ORDINISE7:             >", text.Ordinise(101))
	fmt.Println("ORDINISE8:             >", text.Ordinise(99))
	fmt.Println("TOORDINISE1:           >", text.ToOrdinise(1))
	fmt.Println("TOORDINISE2:           >", text.ToOrdinise(2))
	fmt.Println("TOORDINISE3:           >", text.ToOrdinise(3))
	fmt.Println("TOORDINISE4:           >", text.ToOrdinise(4))
	fmt.Println("TOORDINISE5:           >", text.ToOrdinise(22))
	fmt.Println("TOORDINISE6:           >", text.ToOrdinise(44))
	fmt.Println("TOORDINISE7:           >", text.ToOrdinise(101))
	fmt.Println("TOORDINISE8:           >", text.ToOrdinise(99))
}


text:
package se.thebutton;

import java.util.logging.Logger;

public class btnDevice {
	String User=null,DeviceID=null,CB=null,PubTopic=null;
	InitiateMQTT MQTT=null;
	private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
	public btnDevice() {

	}
	public void setUser(String string) {
		User=string;
	}
	public void setDeviceID(String string) {
		DeviceID=string;
		PubTopic="thebutton/cb/"+this.getDeviceID()+"/set";
		LOGGER.finer("Setting publish topic" + PubTopic);
	}
	public void setCB(String string) {
		CB=string;
	}
	public String getUser() {
		return User;
	}
	public String getDeviceID() {
		return DeviceID;
	}
	public String getCB() {
		return CB;
	}
	public void setPubTopic(String string) {
		PubTopic=string;
	}
	public String getPubTopic() {
		return PubTopic;
	}
	public void setMQTT(InitiateMQTT MQTT) {
		this.MQTT=MQTT;
	}
	public InitiateMQTT getMQTT() {
		return this.MQTT;
	}
}


text:
<?php

namespace TrainingTest\Controller;

use ApplicationTest\Bootstrap;
use Training\Controller\TrainingController;
use Zend\Http\Request;
use Zend\Stdlib\Parameters;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;
use PHPUnit_Framework_TestCase;

class TrainingControllerTest extends PHPUnit_Framework_TestCase {

    protected $controller;
    protected $request;
    protected $response;
    protected $routeMatch;
    protected $event;

    protected function setUp() {
        $serviceManager = Bootstrap::getServiceManager();
        $this->controller = new TrainingController();
        $this->request = new Request();
        $this->routeMatch = new RouteMatch(array('controller' => 'index'));
        $this->event = new MvcEvent();
        $config = $serviceManager->get('Config');
        $routerConfig = isset($config['router']) ? $config['router'] : array();
        $router = HttpRouter::factory($routerConfig);
        $this->event->setRouter($router);
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
        $this->controller->setServiceLocator($serviceManager);
    }

    public function testIndexActionCanBeAccessed() {
        $this->routeMatch->setParam('action', 'index');

        $result = $this->controller->dispatch($this->request);
        $response = $this->controller->getResponse();

        $this->assertEquals(200, $response->getStatusCode());
    }

    public function testCreateActionCannotBeAccessedWithoutLogin() {
        $this->routeMatch->setParam('action', 'create');

        $result = $this->controller->dispatch($this->request);
        $response = $this->controller->getResponse();

        $this->assertEquals(302, $response->getStatusCode());
    }

    public function testEditRedirectWithoutID() {
        $this->routeMatch->setParam('action', 'edit');

        $result = $this->controller->dispatch($this->request);
        $response = $this->controller->getResponse();

        $this->assertEquals(302, $response->getStatusCode());
    }

    public function testEditRedirect2WithWrongID() {
        $this->routeMatch->setParam('action', 'edit');
        $this->routeMatch->setParam('id', 5000);

        $result = $this->controller->dispatch($this->request);
        $response = $this->controller->getResponse();

        $this->assertEquals(302, $response->getStatusCode());
    }
}


text:
title:  "{::nomarkdown}Erster Kita-Tag nach den Ferien: Kind krank oder auch "so ein Krampf mit dem Fieber"!

{:/}"
date:   2022-08-30 10:00:00 +0200
header:
  teaser: ../../../../../images/homeofficemom_teaser.png
tags: ["Familienleben", "Schulkind", "Gesundheit"]
---

**Letzte Woche hatte ich mich wirklich darauf gefreut, ein Stück Alltag zurück zu bekommen. Was ich allerdings wirklich bekam, war nackte Panik und ein Heulkrampf auf dem Boden der Arztpraxis. Weil ich wirklich dachte, unser Alex stirbt mir in den Armen weg. Aber von vorn.**

Arbeiten mit krankem Kind PLUS zwei weiteren kleinen Kindern in der 1-Zimmer-Einliegerwohnung der Schwiegermutter. So sieht das dann aus..

Nachdem ich den Arbeitstag am Montag mit zu viel Netflix und zu viel "ja, nimm dir doch!" überstanden habe, kam der Dienstag. Endlich wieder Kindergarten. Meine Mäuse haben sich zum Glück genau so darauf gefreut wie ich. Denn ja: Natürlich liebe ich meine Kinder und verbringe gern Zeit mit ihnen aber nach drei Wochen allein mit drei kleinen Kindern, für die ich 24/7 allein zuständig bin: JA, dann freut man sich auch drauf, wenigstens den Vormittag ungestört zu arbeiten. Wobei ungestört ja auch schon wieder relativ ist. Denn ich hab ja immer noch ein 6-jähriges Schulkind, das gefühlt bis ans Ende meiner Tage noch Sommerferien hat. So.

2 von drei Kindern untergebracht - endlich ungestört arbeiten!

Jedenfalls lief der Vormittag ganz prima. Endlich mal wieder so richtig was weg geschafft im Homeoffice und Johanna ist auch glücklich mit Bibi Blocksberg. Mittagessen hab ich am Vortag schon vorgekocht, alle hatten riesen Hunger, alles weg gespachtelt und weil sie Bock hatten, habe ich die Kleinen nochmal zwei Stunden in die Nachmittagsbetreuung geben wollen. Die geht von 14 bis 16 Uhr. Also hab ich die Kinder abgegeben und bin dann frohen Mutes an die Baustelle. Tapeten abziehen im Erdgeschoss. Ich war SO motiviert.

"Holen Sie das Kind sofort ab. Er kann nicht mehr atmen!"

Eine Stunde später wurde ich jedoch jäh unterbrochen. Die Erzieherin der Kleinis war dran. Alex sei blau angelaufen und umgefallen und stünde seitdem total neben sich. Also hab ich den Spachtel fallen lassen und bin in die Kita gerannt. Buchstäblich. Und da liegt Alex mit weißen Lippen in den Armen seiner Erzieherin und röchelt immer wieder, er bekomme keine Luft. "Ich kann nicht atmen. Ich kriege keine Luft." Abgehackt stößt er diese Sätze wieder und wieder hervor.

Was für eine beschissene ärtzliche Versorgung auf dem Land!!!

Ich hab ihn mir geschnappt und die Kinderärzte der Umgebung abtelefoniert. Alle im Urlaub. Die Vertretungspraxen schieben sich gegenseitig Urlaubsvertretung zu. Die nächste geöffnete ist eine dreiviertel Stunde entfernt. Ins Kinderkrankenhaus nach Ravensburg brauche ich auch eine halbe Stunde. Keine dieser Optionen schien mir akzeptabel. Also hab ich die Kids ins Auto gepackt und bin die 300 Meter zum Hausarzt gerast. Keine Ahnung, ob der sich auch um Kinder kümmert. Aber das ist ein Notfall.

Am Boden

Also stand ich da mit dem heulenden, rasselnden Alexander, der sich so sehr aufgeregt hat, dass er direkt wieder ohnmächtig wurde. Die Mädels haben all das stumm und mit großen Augen verfolgt. Weil er nicht zum Arzt wollte und sich so sehr gesträubt hat, konnte ich Alex nicht mehr gut halten und bin auf den Boden gesunken. Da saß ich also, mit leblosem Kind in den Armen und zwei zu tiefst verängstigte große Schwestern daneben.

Diagnose: Fieberkrampf

Zumindest wurden wir direkt zum Arzt durchgeschleust. Der hörte ab, schaute in den Hals, maß Fieber und kam zur Diagnose: vermutlich ein Fieberkrampf. Lunge frei, keine Insektenstiche aber erhöhte Temperatur. Ich solle ihn beobachten und bei der kleinsten Verschlechterung ins Kinderkrankenhaus nach Ravensburg. Tatsächlich bekam Alex im Laufe des abends dann über 40 Grad Fieber. Auch am Folgetag war das Fieber noch hoch und auch am darauffolgenden Tag hing der kleine Mann wirklich in den Seilen. Nach dem Schock war ich fast erleichtert, dass er so eine miese Scheiß-Infektion hatte.

Ich wünsche mir Langeweile - gähnende Langeweile

Ganz ehrlich: Keine Ahnung, wie ich die restliche Woche Arbeit überlebt habe. Kind krank kann ich nämlich nicht nehmen, da die Kinder leider privat versichert sind. Ich aber nicht. Da bekomme ich nämlich keinen Cent und das können wir uns zur Zeit nicht leisten. Simon war auch keine Option. Der kam erst am Sonntag von seiner einwöchigen Geschäftsreise zurück. Also letzte Woche… da habe ich mich wirklich nach Ruhe und Langeweile gesehnt. Mal schauen, was diese Woche so für mich parat hält. Sonderlich langweilig fing sie schon mal nicht an. Aber dazu ein andermal mehr.


text:
#include "SuperHandler.h"

namespace chronotext
{
    void SuperHandler::addSubHandler(SubHandler *handler)
    {
        handlers.push_back(handler);
    }

    void SuperHandler::removeSubHandler(SubHandler *handler)
    {
        handlers.remove(handler);
    }

    void SuperHandler::handleMessage(const Message &message)
    {
        for (auto &handler : handlers)
        {
            if (handler->handleSubMessage(message))
            {
                break;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>debug</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module debug

Classes

    Pipe
    WebDebugger

Functions

    check_interaction
    communicate
    set_trace
    stop_trace

Variables

    __package__
    child_conn
    child_queue
    dbg
    debugger
    front_conn
    interact_lock
    logger
    parent_queue
    pipe_in
    pipe_out
    qdb_debugger
    run_lock
    web_debugger

[hide private]


text:
import subprocess
import sys
import unittest

_import_everything = b"""
# The event loop is not fork-safe, and it's easy to initialize an asyncio.Future
# at startup, which in turn creates the default event loop and prevents forking.
# Explicitly disallow the default event loop so that an error will be raised
# if something tries to touch it.
import asyncio
asyncio.set_event_loop(None)

import tornado.auth
import tornado.autoreload
import tornado.concurrent
import tornado.escape
import tornado.gen
import tornado.http1connection
import tornado.httpclient
import tornado.httpserver
import tornado.httputil
import tornado.ioloop
import tornado.iostream
import tornado.locale
import tornado.log
import tornado.netutil
import tornado.options
import tornado.process
import tornado.simple_httpclient
import tornado.tcpserver
import tornado.tcpclient
import tornado.template
import tornado.testing
import tornado.util
import tornado.web
import tornado.websocket
import tornado.wsgi

try:
    import pycurl
except ImportError:
    pass
else:
    import tornado.curl_httpclient
"""

class ImportTest(unittest.TestCase):
    def test_import_everything(self):
        # Test that all Tornado modules can be imported without side effects,
        # specifically without initializing the default asyncio event loop.
        # Since we can't tell which modules may have already beein imported
        # in our process, do it in a subprocess for a clean slate.
        proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)
        proc.communicate(_import_everything)
        self.assertEqual(proc.returncode, 0)

    def test_import_aliases(self):
        # Ensure we don't delete formerly-documented aliases accidentally.
        import tornado.ioloop
        import tornado.gen
        import tornado.util

        self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)
        self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)


text:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { populateDataFromLinkedIn } from 'actions/resumeActions';
import $ from 'jquery';

const mapStateToProps = (state) => ({
  resumeState: state.resumeReducer
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(ActionCreators, dispatch)
});

const ActionCreators = {
  populateDataFromLinkedIn
}

class LinkedinLoginView extends React.Component {
  componentWillMount() {
    localStorage.setItem("sendLinkedinData",true)
  }
  render() {
    return <div>"hello"</div>
  }
  //   $.ajax({
  //       url: '/cookie',
  //       method: 'post',
  //       success: function(data) {
  //         console.log(this.props.actions);
  //         this.props.actions.populateDataFromLinkedIn(data);
  //         console.log('This is the data',data);
  //       }.bind(this)
  //   })
  // }
}

export default connect(mapStateToProps, mapDispatchToProps)(LinkedinLoginView);


text:
void CompilerSupport::loadBytecode(const std::string &name, Bytecode &object)
{
#ifdef USE_RTLX
    for (size_t i = 0; i < sizeof(rtl_sources)/sizeof(rtl_sources[0]); i++) {
        if (name == rtl_sources[i].name) {
            auto tokens = tokenize(name, rtl_sources[i].source);
            auto parsetree = parse(*tokens);
            auto ast = analyze(this, parsetree.get());
            auto bytecode = compile(ast, nullptr);
            object.load("-builtin-", bytecode);
            return;
        }
    }
#endif

    std::pair<std::string, std::string> names = findModule(name);
    if (names.first.empty() && names.second.empty()) {
        throw BytecodeException("file not found");
    }

    std::ifstream obj_file(names.second, std::ios::binary);
    std::ifstream src_file(names.first);

    std::string source_text;
    if (src_file.good()) {
        std::stringstream buf;
        buf << src_file.rdbuf();
        source_text = buf.str();
    }

    if (not source_text.empty()) {
        if (obj_file.good()) {
            SHA256 sha256;
            sha256(source_text);
            unsigned char h[SHA256::HashBytes];
            sha256.getHash(h);
            std::string hash = std::string(h, h+sizeof(h));

            std::stringstream buf;
            buf << obj_file.rdbuf();
            std::vector<unsigned char> bytecode;
            std::string s = buf.str();
            std::copy(s.begin(), s.end(), std::back_inserter(bytecode));
            object.load(name, bytecode);

            if (object.source_hash == hash) {
                return;
            }
            object = Bytecode();
        }

        obj_file.close();
        const std::string objname = names.first + "x";
        remove(objname.c_str());
        {
            auto tokens = tokenize(names.first, source_text);
            auto parsetree = parse(*tokens);
            auto ast = analyze(this, parsetree.get());
            auto bytecode = compile(ast, nullptr);
            writeOutput(objname, bytecode);
            if (cproc != nullptr) {
                cproc(this, ast, "", {});
            }
        }
        obj_file.open(objname, std::ios::binary);
        if (not obj_file.good()) {
            throw BytecodeException("file not found");
        }
    }

    std::stringstream buf;
    buf << obj_file.rdbuf();
    std::vector<unsigned char> bytecode;
    std::string s = buf.str();
    std::copy(s.begin(), s.end(), std::back_inserter(bytecode));
    object.load(names.first.empty() ? names.second : names.first, bytecode);
}

void CompilerSupport::writeOutput(const std::string &name, const std::vector<unsigned char> &content)
{
    std::string::size_type slash = 0;
    while (true) {
        slash = name.find('/', slash+1);
        if (slash == std::string::npos) {
            break;
        }
        if (mkdir(name.substr(0, slash).c_str(), 0700) != 0) {
            if (errno != EEXIST) {
                printf("error: Could not create output path: %s\n", name.substr(0, slash).c_str());
                exit(1);
            }
        }
    }
    std::ofstream f(name, std::ios::binary);
    if (not f) {
        std::cerr << "error: Could not create output file: " << name << "\n";
        exit(1);
    }
    f.write(reinterpret_cast<const char *>(content.data()), content.size());
}


text:
from distutils.core import setup

with open('requirements.txt') as f:
    requirements = f.read().splitlines()

setup(
    name='matterbook',
    version='0.1',
    packages=[''],
    url='dziedziul.pl',
    license='MIT License',
    author='Łukasz Dziedziul',
    author_email='l.dziedziul at gmail',
    description='Tool for sending Facebook posts to the Mattermost',
    install_requires=requirements,
)


text:
from enum import Enum
from datetime import datetime

class DatapointType(Enum):
    """
    The type of datapoint to send (location or local sensor data)
    """

    SENSOR = 0,
    LOCATION = 1

def construct_influx_datapoint(measurement: str, *args) -> list:
    """
    Given a measurement string and at least one value, returns a
    formatted datapoint, ready to be inserted.
    """

    json_datapoint = []

    for point in args:
        json_datapoint.append(
            {
                'measurement': measurement,
                'tags': {},
                'time': str(datetime.utcnow()),
                'fields': {
                    'value': point
                }
            }
        )

    return json_datapoint


text:
<?php

namespace SR\Utilities\Transform;

abstract class AbstractTransform implements TransformInterface
{
    protected mixed $value = null;

    protected bool $mutable;

    public function __construct(mixed $value = null, bool $mutable = false)
    {
        $this->setMutable($mutable);

        if (null !== $value) {
            $this->set($value);
        }
    }

    public function __toString(): string
    {
        return (string) $this->get();
    }

    public static function create(mixed $value = null, bool $mutable = false): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        return new static($value, $mutable);
    }

    public function set(mixed $value): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        $this->value = $value;

        return $this;
    }

    public function get(): mixed
    {
        return $this->value;
    }

    public function has(): bool
    {
        return null !== $this->value;
    }

    public function setMutable(bool $mutable): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        $this->mutable = $mutable;

        return $this;
    }

    public function isMutable(): bool
    {
        return true === $this->mutable;
    }

    final public function isSame(mixed $to): bool
    {
        return $this->get() === $to;
    }

    final public function isNotSame(mixed $to): bool
    {
        return false === $this->isSame($to);
    }

    final public function isEqual(mixed $to): bool
    {
        return (string) $this->get() === (string) $to;
    }

    final public function isNotEqual(mixed $to): bool
    {
        return false === $this->isEqual($to);
    }

    final public function copy(): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        return clone $this;
    }

    final public function apply(\Closure $closure): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        return $this->returnInstance(
            $closure->call($bindTo = $this->getWriteContext(), $bindTo)
        );
    }

    final protected function returnInstance(mixed $value): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        return $this->getWriteContext()->set(
            $value instanceof TransformInterface ? $value->get() : $value
        );
    }

    protected static function isConsumable(mixed $value): bool
    {
        return false === is_array($value) && (false === is_object($value) || is_callable([$value, '__toString']));
    }

    private function getWriteContext(): TransformInterface|AbstractTransform|NumberTransform|StringTransform
    {
        return $this->isMutable() ? $this : $this->copy();
    }
}

/* EOF */


text:
Test.expect(solution('world') == 'dlrow')
Test.expect(solution('hello') == 'olleh')
Test.expect(solution('') == '')
Test.expect(solution('h') == 'h')


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('gent', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='family',
            name='owner',
            field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='item',
            name='owner',
            field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='tag',
            name='owner',
            field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL),
            preserve_default=False,
        ),
    ]


text:
using System;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

namespace LinqToDB.Interceptors
{
	public interface IConnectionInterceptor : IInterceptor
	{
		/// <summary>
		/// Event, triggered before connection open.
		/// </summary>
		/// <param name="eventData">Additional data for event.</param>
		/// <param name="connection">Connection instance.</param>
		void ConnectionOpening(ConnectionEventData eventData, DbConnection connection);

		/// <summary>
		/// Event, triggered before asynchronous connection open.
		/// </summary>
		/// <param name="eventData">Additional data for event.</param>
		/// <param name="connection">Connection instance.</param>
		/// <param name="cancellationToken">Cancellation token.</param>
		Task ConnectionOpeningAsync(ConnectionEventData eventData, DbConnection connection, CancellationToken cancellationToken);

		/// <summary>
		/// Event, triggered after connection opened.
		/// </summary>
		/// <param name="eventData">Additional data for event.</param>
		/// <param name="connection">Connection instance.</param>
		void ConnectionOpened(ConnectionEventData eventData, DbConnection connection);

		/// <summary>
		/// Event, triggered after connection opened asynchronously.
		/// </summary>
		/// <param name="eventData">Additional data for event.</param>
		/// <param name="connection">Connection instance.</param>
		/// <param name="cancellationToken">Cancellation token.</param>
		Task ConnectionOpenedAsync(ConnectionEventData eventData, DbConnection connection, CancellationToken cancellationToken);
	}
}


text:
<?php

namespace ReckiCT\Parser\Rules;

use ReckiCT\Parser\Rule;
use ReckiCT\Parser\State;

use PhpParser\Node;
use PhpParser\Node\Stmt\Label as AstLabel;
use ReckiCT\Graph\Vertex\NoOp;

class Label implements Rule
{
    public function test(Node $node)
    {
        return $node instanceof AstLabel;
    }

    public function parse(Node $stmt, State $state)
    {
        if (isset($state->labels[$stmt->name])) {
            throw new \RuntimeException('Found label with duplicate name');
        }
        $label = new NoOp();
        $state->addVertex($label);
        $state->labels[$stmt->name] = $label;
        if (isset($state->gotolist[$stmt->name])) {
            foreach ($state->gotolist[$stmt->name] as $node) {
                $state->graph->addDirectedEdge($node, $label);
            }
        }
    }

}


text:
<resources>
    <string name="app_name">Hermes</string>
</resources>


text:
package science.atlarge.graphalytics.domain.algorithms;

import science.atlarge.graphalytics.configuration.InvalidConfigurationException;
import org.apache.commons.configuration.Configuration;

/**
 * Factory interface that defines an API to parse algorithm-specific parameters from a Configuration.
 *
 * @author Mihai Capotă
 * @author Tim Hegeman
 * @author Wing Lung Ngai
 */
public interface ParameterFactory<T extends AlgorithmParameters> {

	/**
	 * Parses an object of type T from the properties of a Configuration object.
	 *
	 * @param configuration the Configuration describing the object of type T
	 * @return the parsed object
	 * @throws InvalidConfigurationException iff the configuration does not contain the required properties
	 */
	T fromConfiguration(Configuration configuration) throws InvalidConfigurationException;

}


text:
package xc2;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class XC2 {

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewJFrame2 GUIS  = new NewJFrame2();
                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
                GUIS.setLocation(dim.width/2-GUIS.getSize().width/2, dim.height/2-GUIS.getSize().height/2);
                GUIS.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                //GUIS.setResizable(false);
                GUIS.setVisible(true);
            }
        });
    }

//    public static void main(String[] args) throws Exception{
//
//        String lf;
//        if(System.getProperty("os.name").toLowerCase().startsWith("windows")){
//            lf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
//        }
//        else{
//            lf = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
//        }
//        UIManager.setLookAndFeel(lf);
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                NewJFrame login  = new NewJFrame();
//                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
//                login.setLocation(dim.width/2-login.getSize().width/2, dim.height/2-login.getSize().height/2);
//                login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//                login.setResizable(false);
//                login.setVisible(true);
//            }
//        });
//
//    }

}


text:
import argparse

import ipaddr
from maas_common import get_auth_ref
from maas_common import get_keystone_client
from maas_common import metric
from maas_common import metric_bool
from maas_common import print_output
from maas_common import status_err
from maas_common import status_ok
import requests
from requests import exceptions as exc

def check(auth_ref, args):
    # We call get_keystone_client here as there is some logic within to get a
    # new token if previous one is bad.
    keystone = get_keystone_client(auth_ref)
    auth_token = keystone.auth_token
    registry_endpoint = 'http://{ip}:9191'.format(ip=args.ip)

    s = requests.Session()

    s.headers.update(
        {'Content-type': 'application/json',
         'x-auth-token': auth_token})

    try:
        # /images returns a list of public, non-deleted images
        r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10)
        is_up = r.ok
    except (exc.ConnectionError, exc.HTTPError, exc.Timeout):
        is_up = False
    except Exception as e:
        status_err(str(e))

    status_ok()
    metric_bool('glance_registry_local_status', is_up)
    # only want to send other metrics if api is up
    if is_up:
        milliseconds = r.elapsed.total_seconds() * 1000
        metric('glance_registry_local_response_time', 'double',
               '%.3f' % milliseconds, 'ms')

def main(args):
    auth_ref = get_auth_ref()
    check(auth_ref, args)

if __name__ == "__main__":
    with print_output():
        parser = argparse.ArgumentParser(description='Check glance registry')
        parser.add_argument('ip',
                            type=ipaddr.IPv4Address,
                            help='glance registry IP address')
        args = parser.parse_args()
        main(args)


text:
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Make sure msvs_shard works correctly.
"""

import TestGyp

import sys

if sys.platform == 'win32':
  test = TestGyp.TestGyp(formats=['msvs', 'ninja'])

  CHDIR = 'shard'
  test.run_gyp('shard.gyp', chdir=CHDIR)
  test.build('shard.gyp', test.ALL, chdir=CHDIR)

  test.built_file_must_exist('shard_0.lib', chdir=CHDIR)
  test.built_file_must_exist('shard_1.lib', chdir=CHDIR)
  test.built_file_must_exist('shard_2.lib', chdir=CHDIR)
  test.built_file_must_exist('shard_3.lib', chdir=CHDIR)

  test.run_gyp('shard_ref.gyp', chdir=CHDIR)
  test.build('shard_ref.gyp', test.ALL, chdir=CHDIR)

  test.pass_test()