text:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

class Result {
    static class Pair {
        public int luck;
        public int importance;

        public Pair(int luck, int importance) {
            this.luck = luck;
            this.importance = importance;
        }
    }

    /*
     * Complete the 'luckBalance' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER k
     *  2. 2D_INTEGER_ARRAY contests
     */

    public static int luckBalance(int k, List<List<Integer>> list) {
        Pair[] contests = new Pair[list.size()];
        int luck = 0, noOfImportantContests = 0, noOfWins;

        for (List<Integer> contest : list) {
            if (contest.get(1) != 0) {
                noOfImportantContests++;
            }
        }

        noOfWins = Math.max(0, noOfImportantContests - k);

        for (int i = 0; i < list.size(); i++) {
            contests[i] = new Pair(list.get(i).get(0), list.get(i).get(1));
        }

        quickSort(contests, 0, contests.length - 1);

        for (Pair contest : contests) {
            if (noOfWins > 0 && contest.importance > 0) {
                luck -= contest.luck;

                noOfWins--;

                continue;
            }

            luck += contest.luck;
        }

        return luck;
    }

    public static void quickSort(Pair[] arr, int low, int high) {
        int i = low, j = high;
        Pair pivot = arr[low + (high - low) / 2], temp;

        while (i <= j) {
            while (arr[i].luck < pivot.luck) {
                i++;
            }
            while (arr[j].luck > pivot.luck) {
                j--;
            }

            if (i <= j) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

                i++;
                j--;
            }
        }

        if (low < j) {
            quickSort(arr, low, j);
        }

        if (i < high) {
            quickSort(arr, i, high);
        }
    }
}

// https://www.hackerrank.com/challenges/luck-balance/problem
public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int n = Integer.parseInt(firstMultipleInput[0]);

        int k = Integer.parseInt(firstMultipleInput[1]);

        List<List<Integer>> contests = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            String[] contestsRowTempItems = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

            List<Integer> contestsRowItems = new ArrayList<>();

            for (int j = 0; j < 2; j++) {
                int contestsItem = Integer.parseInt(contestsRowTempItems[j]);
                contestsRowItems.add(contestsItem);
            }

            contests.add(contestsRowItems);
        }

        int result = Result.luckBalance(k, contests);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package test.cwe335.semmle.tests;

import java.util.Random;
import java.security.SecureRandom;
import java.math.BigInteger;

class Test {
	public void test() {
		long time1 = System.currentTimeMillis();
		long time2 = System.nanoTime();

		// GOOD: We only care about SecureRandom generators.
		Random r = new Random(time1);
		r.nextInt();

		// GOOD: SecureRandom initialized with random seed.
		SecureRandom r1 = new SecureRandom();
		byte[] random_seed = new BigInteger(Long.toString(r1.nextLong())).toByteArray();
		SecureRandom r2 = new SecureRandom(random_seed);
		r2.nextInt();

		// BAD: SecureRandom initialized with times.
		SecureRandom r_time1 = new SecureRandom(new BigInteger(Long.toString(time1)).toByteArray());
		// BAD: SecureRandom initialized with times.
		SecureRandom r_time2 = new SecureRandom(new BigInteger(Long.toString(time2)).toByteArray());
		r_time1.nextInt(); r_time2.nextInt();

		// BAD: SecureRandom initialized with constant value.
		SecureRandom r_const = new SecureRandom(new BigInteger(Long.toString(12345L)).toByteArray());
		r_const.nextInt();

		// BAD: SecureRandom's seed set to constant with setSeed.
		SecureRandom r_const_set = new SecureRandom();
		r_const_set.setSeed(12345L);
		r_const_set.nextInt();

		// GOOD: SecureRandom self seeded and then seed is supplemented.
		SecureRandom r_selfseed = new SecureRandom();
		r_selfseed.nextInt();
		r_selfseed.setSeed(12345L);
		r_selfseed.nextInt();

		// GOOD: SecureRandom seed set to something random.
		SecureRandom r_random_set = new SecureRandom();
		r_random_set.setSeed(random_seed);
		r_random_set.nextInt();

		// GOOD: SecureRandom seeded with a bad seed but then seed is supplemented.
		SecureRandom r_suplseed = new SecureRandom();
		r_suplseed.setSeed(12345L);
		r_suplseed.setSeed(random_seed);
		r_suplseed.nextInt();

		// GOOD: SecureRandom seeded with composite seed that is partially random.
		SecureRandom r_composite = new SecureRandom();
		r_composite.setSeed(0L + r1.nextLong());
		r_composite.nextInt();
	}
}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <!--

  -->
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>hbase-build-configuration</artifactId>
    <groupId>org.apache.hbase</groupId>
    <version>3.0.0-SNAPSHOT</version>
    <relativePath>../hbase-build-configuration</relativePath>
  </parent>
  <artifactId>hbase-replication</artifactId>
  <name>Apache HBase - Replication</name>
  <description>HBase Replication Support</description>

  <build>
    <plugins>
      <plugin>
        <!--Make it so assembly:single does nothing in here-->
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <skipAssembly>true</skipAssembly>
        </configuration>
      </plugin>
      <!-- Make a jar and put the sources in the jar -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <configuration>
          <failOnViolation>true</failOnViolation>
        </configuration>
      </plugin>
      <plugin>
        <groupId>net.revelc.code</groupId>
        <artifactId>warbucks-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.apache.hbase.thirdparty</groupId>
      <artifactId>hbase-shaded-miscellaneous</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase.thirdparty</groupId>
      <artifactId>hbase-shaded-protobuf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-annotations</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-protocol-shaded</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-common</artifactId>
    </dependency>
    <!-- Intra-project dependencies -->
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-client</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-zookeeper</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-common</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-zookeeper</artifactId>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <!-- General dependencies -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <profiles>
    <!-- profile against Hadoop 2.x: This is the default. -->
    <profile>
      <id>hadoop-2.0</id>
      <activation>
        <property>
            <!--Below formatting for dev-support/generate-hadoopX-poms.sh-->
            <!--h2--><name>!hadoop.profile</name>
        </property>
      </activation>
      <dependencies>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-common</artifactId>
          <exclusions>
            <exclusion>
              <groupId>net.java.dev.jets3t</groupId>
              <artifactId>jets3t</artifactId>
            </exclusion>
            <exclusion>
              <groupId>javax.servlet.jsp</groupId>
              <artifactId>jsp-api</artifactId>
            </exclusion>
            <exclusion>
              <groupId>org.mortbay.jetty</groupId>
              <artifactId>jetty</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jersey</groupId>
              <artifactId>jersey-server</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jersey</groupId>
              <artifactId>jersey-core</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jersey</groupId>
              <artifactId>jersey-json</artifactId>
            </exclusion>
            <exclusion>
              <groupId>javax.servlet</groupId>
              <artifactId>servlet-api</artifactId>
            </exclusion>
            <exclusion>
              <groupId>tomcat</groupId>
              <artifactId>jasper-compiler</artifactId>
            </exclusion>
            <exclusion>
              <groupId>tomcat</groupId>
              <artifactId>jasper-runtime</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.google.code.findbugs</groupId>
              <artifactId>jsr305</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
      </dependencies>
    </profile>

    <!--
      profile for building against Hadoop 3.0.x. Activate using:
       mvn -Dhadoop.profile=3.0
    -->
    <profile>
      <id>hadoop-3.0</id>
      <activation>
        <property>
          <name>hadoop.profile</name>
          <value>3.0</value>
        </property>
      </activation>
      <properties>
        <hadoop.version>3.0-SNAPSHOT</hadoop.version>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-common</artifactId>
        </dependency>
      </dependencies>
    </profile>
    <profile>
      <id>eclipse-specific</id>
      <activation>
        <property>
          <name>m2e.version</name>
        </property>
      </activation>
      <build>
        <pluginManagement>
          <plugins>
            <!--This plugin's configuration is used to store Eclipse m2e settings
                 only. It has no influence on the Maven build itself.-->
            <plugin>
              <groupId>org.eclipse.m2e</groupId>
              <artifactId>lifecycle-mapping</artifactId>
              <configuration>
                <lifecycleMappingMetadata>
                  <pluginExecutions>
                  </pluginExecutions>
                </lifecycleMappingMetadata>
              </configuration>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </profile>
  </profiles>
</project>


text: export * from './admin';


text:
package com.helger.xml.microdom;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.helger.commons.string.StringHelper;

/**
 * A special marker interface that is implemented by classes, that really
 * support having children!
 *
 * @author Philip Helger
 */
public interface IMicroNodeWithChildren extends IMicroNode
{
  /**
   * Get the concatenated text content of all direct {@link IMicroText} child
   * nodes of this element.
   *
   * @return null if the element contains no text node as child
   */
  @Nullable
  String getTextContent ();

  /**
   * Get the concatenated text content of all direct {@link IMicroText} child
   * nodes of this element. After concatenation, all leading and trailing spaces
   * are removed.
   *
   * @return null if the element contains no text node as child
   */
  @Nullable
  default String getTextContentTrimmed ()
  {
    return StringHelper.trim (getTextContent ());
  }

  /**
   * Get the concatenated text content of all direct {@link IMicroText} child
   * nodes of this element. The value is converted via the
   * {@link com.helger.commons.typeconvert.TypeConverter} to the desired
   * destination class.
   *
   * @param <DSTTYPE>
   *        The destination type to convert the String textContent to.
   * @param aDstClass
   *        The destination class to which the text content should be converted.
   * @return null if the element contains no text node as child
   */
  @Nullable
  <DSTTYPE> DSTTYPE getTextContentWithConversion (@Nonnull Class <DSTTYPE> aDstClass);

  /**
   * {@inheritDoc}
   */
  @Nonnull
  IMicroNodeWithChildren getClone ();
}


text:
function Controller() {
    function triangleArea(A, B, C) {
        return C.x * B.y - B.x * C.y - (C.x * A.y - A.x * C.y) + (B.x * A.y - A.x * B.y);
    }
    function isPointInSqaure(poly, pt) {
        if (triangleArea(poly[0], poly[1], pt) > 0 || triangleArea(poly[1], poly[2], pt) > 0 || triangleArea(poly[2], poly[3], pt) > 0 || triangleArea(poly[3], poly[0], pt) > 0) return false;
        return true;
    }
    function locationCallback(e) {
        if (!e.success || e.error) return;
        var point = (e.coords.timestamp, {
            x: e.coords.latitude,
            y: e.coords.longitude
        }), DESig = false;
        if (isPointInSqaure(square, point) && false === DESig) {
            alert("You are in Dominion Enterprises");
            DESig = true;
        } else false === isPointInSqaure(square, point) && (DESig = false);
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.index = Ti.UI.createWindow({
        backgroundColor: "white",
        id: "index"
    });
    $.__views.index && $.addTopLevelView($.__views.index);
    exports.destroy = function() {};
    _.extend($, $.__views);
    var mapView = Titanium.Map.createView({
        mapType: Titanium.Map.STANDARD_TYPE,
        userLocation: true,
        animate: true,
        regionFit: true
    });
    var isAndroid = false;
    isAndroid || Ti.Geolocation.setPurpose("To find and track you");
    Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_NEAREST_TEN_METERS;
    var square = [];
    square.push({
        x: 36.847855,
        y: -76.291497
    });
    square.push({
        x: 36.847737,
        y: -76.290933
    });
    square.push({
        x: 36.847196,
        y: -76.291191
    });
    square.push({
        x: 36.847344,
        y: -76.291785
    });
    Titanium.Geolocation.addEventListener("location", locationCallback);
    $.index.add(mapView);
    $.index.open();
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
package com.winterwell.nlp.corpus.brown;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.Collection;
import java.util.Iterator;

import com.winterwell.nlp.corpus.ICorpus;
import com.winterwell.nlp.corpus.IDocument;
import com.winterwell.utils.TodoException;
import com.winterwell.utils.Utils;
import com.winterwell.utils.io.FileUtils;

/**
 *
 * @testedby BrownCorpusTest
 * @author Daniel
 *
 */
public class BrownCorpus implements ICorpus {

	File dir = new File(FileUtils.getWinterwellDir(),
			"code/winterwell.nlp/data/corpora/brown");

	// NLPWorkshop.get().getFilePointer("brown");

	public BrownCorpus() {
		if (dir.isDirectory()) return;
		File zip = new File(dir.getParentFile(), "brown.zip");
		if (zip.isFile()) {
			// TODO unzip
		}
		throw Utils.runtime(new FileNotFoundException("Cant find Brown corpus in: "+dir));
	}

	@Override
	public Iterable<? extends IDocument> getDocumentsByTitle(String title) {
		// TODO Auto-generated method stub
		throw new TodoException();
	}

	@Override
	public Iterable<? extends IDocument> getDocumentsUsing(String term) {
		// TODO Auto-generated method stub
		throw new TodoException();
	}

	@Override
	public Collection<IDocument> getSample(int num) {
		// TODO Auto-generated method stub
		throw new TodoException();
	}

	@Override
	public Iterator<IDocument> iterator() {
		assert dir.isDirectory() : dir.getAbsolutePath();
		final File[] files = dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.length() == 4;
			}
		});
		assert files != null;
		Iterator<IDocument> it = new Iterator<IDocument>() {
			int i = 0;

			@Override
			public boolean hasNext() {
				return i < files.length;
			}

			@Override
			public BrownDocument next() {
				i++;
				return new BrownDocument(files[i - 1]);
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
		return it;
	}

	@Override
	public int size() {
		// ??
		return dir.list().length - 4;
	}

}


text:
@implementation AFNetworkConnection

@dynamic delegate;

+ (Class)lowerLayerClass {
	return [AFNetworkTransport class];
}

+ (AFNetworkInternetTransportSignature)transportSignatureForScheme:(NSString *)scheme {
	@throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s, cannot provide an AFNetworkInternetTransportSignature for scheme (%@)", __PRETTY_FUNCTION__, scheme] userInfo:nil];
}

+ (NSString *)serviceDiscoveryType {
	@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%s, connot provide a service discovery type", __PRETTY_FUNCTION__] userInfo:nil];
}

- (id)initWithURL:(NSURL *)endpoint {
	CFHostRef host = (CFHostRef)[NSMakeCollectable(CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)[endpoint host])) autorelease];

	AFNetworkInternetTransportSignature transportSignature = [[self class] transportSignatureForScheme:[endpoint scheme]];

	if ([endpoint port] != nil) {
		transportSignature.port = [[endpoint port] integerValue];
	}

	AFNetworkHostSignature hostSignature = {
		.host = host,
		.transport = transportSignature,
	};

	return [self initWithTransportSignature:&hostSignature];
}

- (id)initWithService:(AFNetworkServiceScope *)serviceScope {
	CFNetServiceRef netService = (CFNetServiceRef)[NSMakeCollectable(CFNetServiceCreate(kCFAllocatorDefault, (CFStringRef)[serviceScope domain], (CFStringRef)[serviceScope type], (CFStringRef)[serviceScope name], 0)) autorelease];

	AFNetworkServiceSignature serviceSignature = {
		.service = netService,
	};

	return (id)[self initWithTransportSignature:&serviceSignature];
}

- (NSURL *)peer {
	CFTypeRef peer = [(id)self.lowerLayer peer];

	if (CFGetTypeID(peer) == CFHostGetTypeID()) {
		CFHostRef host = (CFHostRef)peer;

		NSArray *hostnames = (NSArray *)CFHostGetNames(host, NULL);
		if ([hostnames count] != 0) {
			return [NSURL URLWithString:[hostnames objectAtIndex:0]];
		}

		NSArray *addresses = (NSArray *)CFHostGetAddressing(host, NULL);
		if ([addresses count] != 0) {
			NSData *address = [addresses objectAtIndex:0];
			NSString *addressString = AFNetworkSocketAddressToPresentation(address, NULL);

			if (addressString != nil) {
				return [NSURL URLWithString:addressString];
			}
		}

		return nil;
	}
	else if (CFGetTypeID(peer) == CFNetServiceGetTypeID()) {
		CFNetServiceRef service = (CFNetServiceRef)peer;

		// Note: this is assuming that the service has already been resolved
		CFStringRef host = CFNetServiceGetTargetHost(service);
		SInt32 port = CFNetServiceGetPortNumber(service);

		return [NSURL URLWithString:[NSString stringWithFormat:@"%@:%lu", host, (unsigned long)port]];
	}

	@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%s, unsupported peer type %@", __PRETTY_FUNCTION__, peer] userInfo:nil];
	return nil;
}

- (void)networkLayer:(id <AFNetworkTransportLayer>)layer didWrite:(id)packet context:(void *)context {
	if ([self.delegate respondsToSelector:@selector(networkLayer:didWrite:context:)]) {
		[self.delegate networkLayer:self didWrite:packet context:context];
	}
}

- (void)networkLayer:(id <AFNetworkTransportLayer>)layer didRead:(id)packet context:(void *)context {
	if ([self.delegate respondsToSelector:@selector(networkLayer:didRead:context:)]) {
		[self.delegate networkLayer:self didRead:packet context:context];
	}
}

@end


text:
"""Support for AVM FRITZ!SmartHome temperature sensor only devices."""
from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
from typing import Final

from pyfritzhome.fritzhomedevice import FritzhomeDevice

from homeassistant.components.sensor import (
    STATE_CLASS_MEASUREMENT,
    STATE_CLASS_TOTAL_INCREASING,
    SensorEntity,
    SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    DEVICE_CLASS_BATTERY,
    DEVICE_CLASS_ENERGY,
    DEVICE_CLASS_HUMIDITY,
    DEVICE_CLASS_POWER,
    DEVICE_CLASS_TEMPERATURE,
    ENERGY_KILO_WATT_HOUR,
    PERCENTAGE,
    POWER_WATT,
    TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import FritzBoxEntity
from .const import CONF_COORDINATOR, DOMAIN as FRITZBOX_DOMAIN
from .model import FritzEntityDescriptionMixinBase

@dataclass
class FritzEntityDescriptionMixinSensor(FritzEntityDescriptionMixinBase):
    """Sensor description mixin for Fritz!Smarthome entities."""

    native_value: Callable[[FritzhomeDevice], float | int | None]

@dataclass
class FritzSensorEntityDescription(
    SensorEntityDescription, FritzEntityDescriptionMixinSensor
):
    """Description for Fritz!Smarthome sensor entities."""

SENSOR_TYPES: Final[tuple[FritzSensorEntityDescription, ...]] = (
    FritzSensorEntityDescription(
        key="temperature",
        name="Temperature",
        native_unit_of_measurement=TEMP_CELSIUS,
        device_class=DEVICE_CLASS_TEMPERATURE,
        state_class=STATE_CLASS_MEASUREMENT,
        suitable=lambda device: (
            device.has_temperature_sensor and not device.has_thermostat
        ),
        native_value=lambda device: device.temperature,  # type: ignore[no-any-return]
    ),
    FritzSensorEntityDescription(
        key="humidity",
        name="Humidity",
        native_unit_of_measurement=PERCENTAGE,
        device_class=DEVICE_CLASS_HUMIDITY,
        state_class=STATE_CLASS_MEASUREMENT,
        suitable=lambda device: device.rel_humidity is not None,
        native_value=lambda device: device.rel_humidity,  # type: ignore[no-any-return]
    ),
    FritzSensorEntityDescription(
        key="battery",
        name="Battery",
        native_unit_of_measurement=PERCENTAGE,
        device_class=DEVICE_CLASS_BATTERY,
        suitable=lambda device: device.battery_level is not None,
        native_value=lambda device: device.battery_level,  # type: ignore[no-any-return]
    ),
    FritzSensorEntityDescription(
        key="power_consumption",
        name="Power Consumption",
        native_unit_of_measurement=POWER_WATT,
        device_class=DEVICE_CLASS_POWER,
        state_class=STATE_CLASS_MEASUREMENT,
        suitable=lambda device: device.has_powermeter,  # type: ignore[no-any-return]
        native_value=lambda device: device.power / 1000 if device.power else 0.0,
    ),
    FritzSensorEntityDescription(
        key="total_energy",
        name="Total Energy",
        native_unit_of_measurement=ENERGY_KILO_WATT_HOUR,
        device_class=DEVICE_CLASS_ENERGY,
        state_class=STATE_CLASS_TOTAL_INCREASING,
        suitable=lambda device: device.has_powermeter,  # type: ignore[no-any-return]
        native_value=lambda device: device.energy / 1000 if device.energy else 0.0,
    ),
)

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Set up the FRITZ!SmartHome sensor from ConfigEntry."""
    coordinator = hass.data[FRITZBOX_DOMAIN][entry.entry_id][CONF_COORDINATOR]

    async_add_entities(
        [
            FritzBoxSensor(coordinator, ain, description)
            for ain, device in coordinator.data.items()
            for description in SENSOR_TYPES
            if description.suitable(device)
        ]
    )

class FritzBoxSensor(FritzBoxEntity, SensorEntity):
    """The entity class for FRITZ!SmartHome sensors."""

    entity_description: FritzSensorEntityDescription

    @property
    def native_value(self) -> float | int | None:
        """Return the state of the sensor."""
        return self.entity_description.native_value(self.device)


text:
package ru.job4j;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * test of Max class.
 *
 * @author Alexander Ivanov
 * @since 06.01.2016
 * @version 1.0
 */
public class MaxTest {
	/**
	 * test max. First > second.
	 */
	@Test
	public void whenFirstMoreThanSecond() {
		final int first = 10;
		final int second = 5;
		Max maximum = new Max();
		final int checkMax = 10;
		final int result = maximum.max(first, second);
		assertThat(result, is(checkMax));
	}

	/**
	 * test max. First < second.
	 */
	@Test
	public void whenFirstLessThanSecond() {
		final int first = 7;
		final int second = 12;
		Max maximum = new Max();
		final int checkMax = 12;
		final int result = maximum.max(first, second);
		assertThat(result, is(checkMax));
	}
}


text:
.class Lcom/google/gson/internal/e;
.super Ljava/lang/Object;

# interfaces
.implements Lcom/google/gson/internal/ObjectConstructor;

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Lcom/google/gson/internal/ObjectConstructor",
        "<TT;>;"
    }
.end annotation

# instance fields
.field final synthetic a:Lcom/google/gson/internal/ConstructorConstructor;

# direct methods
.method constructor <init>(Lcom/google/gson/internal/ConstructorConstructor;)V
    .locals 0

    iput-object p1, p0, Lcom/google/gson/internal/e;->a:Lcom/google/gson/internal/ConstructorConstructor;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public construct()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT;"
        }
    .end annotation

    new-instance v0, Ljava/util/LinkedHashMap;

    invoke-direct {v0}, Ljava/util/LinkedHashMap;-><init>()V

    return-object v0
.end method


text:
Professional website of Chloé Frommer, Anthropologist and Filmmaker. chloefrommer.com

## Team
Design & Development - Benjamin Kinzer (@kungfukoala) benjaminkinzer.com

## Colophon
###Technology
* [Jekyll](http://jekyllrb.com/)
* [SASS](http://sass-lang.com)
* [SASS Media Queries](http://github.com/paranoida/sass-mediaqueries) by Rafal Bromirski
* [Bourbon](http://bourbon.io)
* [Jeet](http://jeet.gs)
* [HTML5 Boilerplate](https://html5boilerplate.com)
* [Normalize](http://necolas.github.io/normalize.css/)
* [JQuery](https://jquery.com/)
* [Modernizer](http://modernizr.com/)
* [Fontello](http://fontello.com/)
* [Typekit](http://typekit.com/)

###Fonts
* Filosofia [Emigre](http://www.emigre.com/)
* JAF Lapture [Typekit](https://typekit.com/fonts/jaf-lapture)
* Alternate Gothic [Typekit](https://typekit.com/fonts/alternate-gothic)


text:
package ml.wolfe.examples

import ml.wolfe.SimpleFeatureIndex
import ml.wolfe.nlp.io.Riedel2010Reader
import ml.wolfe.term.TermImplicits._
import ml.wolfe.term._

object Riedel2010Example extends App {

  val x: Doubles.Term = ???
  x + x

  val d = Riedel2010Reader.read("/home/luke/Desktop/protobuff/train-Multiple.pb")

  val Labels = d.allLabels.toDom withOOV "[OOV]"
  val labels = d.allLabels.toConst(Labels)
  val Features = d.allFeatures.toDom
  val Instances = Seqs(Features, 0, d.maxFeatures)
  val Instancess = Seqs(Instances, 0, d.maxInstances)

  implicit val Y = FullMaps(Labels, Bools)
  implicit val Z = Seqs(Labels, 0, 1234) //todo: not this

  implicit val Thetas = Vectors(1000)
  implicit val index = new SimpleFeatureIndex(Thetas)

  case class Bag(label: Labels.Term, instances: Instancess.Term)

  val bags = for(bag <- d.bags) yield Bag(
    label = Labels.Const(bag.label),
    instances = Instancess.Const(bag.instances.map(_.features))
  )

  // Define model
   def model(theta:Thetas.Term)(y:Y.Term, z:Z.Term)(bag:Bag) = {
       sum(labels) { l =>
         phiJoin(y, l, bag.label)
       } + sum(0 until bag.instances.length) { i =>
         phiExtract(theta)(z(i), bag.instances(i))
       }
   }

   def phiJoin(y:Y.Term, r:Labels.Term, z:Labels.Term) = {
     //todo: fix (y(r) === (z === r))
     logI((y(r) && (z === r)) || (!y(r) && !(z === r)))
   }

   def phiExtract(theta:Thetas.Term)(z_i: Labels.Term, x_i:Instances.Term) = {
     theta dot phi(z_i, x_i)
   }

   def phi(z_i: Labels.Term, x_i:Instances.Term): Thetas.Term = cached(z_i, x_i) {
     //todo: implement VectorSum
//     sum(0 until x_i.length) { f =>
//       feature('Foo, z_i, x_i(f))
//     }
     Thetas.Const(Thetas.zero)
   }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.

-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <!-- Since this is a test case lets run a local ZK server -->
  <bean id="zkContainer" class="org.apache.camel.test.infra.zookeeper.services.ZooKeeperContainer" init-method="start" destroy-method="stop">
    <constructor-arg>
      <value>zookeeper</value>
    </constructor-arg>
  </bean>

  <bean id="zkConnectString" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="zkContainer"/>
    <property name="targetMethod" value="getConnectionString">
    </property>
  </bean>

  <bean id="curator" class="org.apache.camel.component.zookeepermaster.CuratorFactoryBean" depends-on="zkContainer">
    <property name="timeout" value="3000"/>
    <property name="connectString" ref="zkConnectString"/>
  </bean>

  <camelContext xmlns="http://camel.apache.org/schema/spring" depends-on="curator">
    <route>
      <from uri="zookeeper-master:master-000:seda:bar"/>
      <to uri="mock:results"/>
    </route>

  </camelContext>
</beans>


text:
docker-hubot-hipchat
====================

Hubot Hipchat Docker


text:
package org.uberfire.annotations.processors;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SimplePanel;
import org.uberfire.client.annotations.WorkbenchEditor;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.mvp.MyTestType;
import org.uberfire.client.mvp.QualifierAnnotation;
import org.uberfire.client.mvp.RegularAnnotation;

@QualifierAnnotation( classField = String.class, stringField = "someText", booleanField = true, intField = 13 )
@RegularAnnotation( classField = String.class, stringField = "someText", booleanField = true, intField = 13 )
@WorkbenchEditor(identifier = "test29", supportedTypes = { MyTestType.class })
public class WorkbenchEditorTest29 {

    @WorkbenchPartView
    public IsWidget getView() {
        return new SimplePanel();
    }

    @WorkbenchPartTitle
    public String getTitle() {
        return "title";
    }

}


text:
namespace CoinNews.Administration.Entities
{
    using Serenity.ComponentModel;
    using Serenity.Data;
    using Serenity.Data.Mapping;
    using System;
    using System.ComponentModel;

    [ConnectionKey("Default"), Module("Administration"), TableName("Roles")]
    [DisplayName("Roles"), InstanceName("Role")]
    [ReadPermission(PermissionKeys.Security)]
    [ModifyPermission(PermissionKeys.Security)]
    [LookupScript]
    public sealed class RoleRow : Row, IIdRow, INameRow
    {
        [DisplayName("Role Id"), Identity, ForeignKey("Roles", "RoleId"), LeftJoin("jRole")]
        public Int32? RoleId
        {
            get { return Fields.RoleId[this]; }
            set { Fields.RoleId[this] = value; }
        }

        [DisplayName("Role Name"), Size(100), NotNull, QuickSearch]
        public String RoleName
        {
            get { return Fields.RoleName[this]; }
            set { Fields.RoleName[this] = value; }
        }

        IIdField IIdRow.IdField
        {
            get { return Fields.RoleId; }
        }

        StringField INameRow.NameField
        {
            get { return Fields.RoleName; }
        }

        public static readonly RowFields Fields = new RowFields().Init();

        public RoleRow()
            : base(Fields)
        {
        }

        public class RowFields : RowFieldsBase
        {
            public Int32Field RoleId;
            public StringField RoleName;
        }
    }
}


text:
from base import TestCase

import jinja2_maps
from jinja2_maps.osm import osm_url

class TestOsm(TestCase):

    def test_filters_exist(self):
        filters = jinja2_maps.filters()
        self.assertIn("osm_url", filters)
        self.assertIn("osm_map", filters)

    def test_url_dict(self):
        url = "https://www.openstreetmap.org/?mlat=12.34&mlon=56.78" \
                "#map=42/12.3400/56.7800"
        self.assertEquals(url,
                osm_url(dict(latitude=12.34, longitude=56.78), zoom=42))


text:
package training.tests.tests;

import org.testng.annotations.BeforeClass;

import training.tests.app.Application;

public class TestBaseNew {

    public static ThreadLocal<Application> tlApp = new ThreadLocal<>();
    public Application app;

    @BeforeClass
    public void start() {
        if (tlApp.get() != null) {
            app = tlApp.get();
            return;
        }

        app = new Application();
        tlApp.set(app);

        Runtime.getRuntime().addShutdownHook(
                new Thread(() -> { app.quit(); app = null; }));
    }

}


text:
#include <string>
#include <vector>
#include <sstream>

#include <sys/types.h>
#include <unistd.h>

#include "base/stringprintf.h"
#include "common_runtime_test.h"
#include "runtime/arch/instruction_set.h"
#include "runtime/gc/heap.h"
#include "runtime/gc/space/image_space.h"
#include "runtime/os.h"
#include "runtime/utils.h"
#include "utils.h"

namespace art {

class DexListTest : public CommonRuntimeTest {
 protected:
  virtual void SetUp() {
    CommonRuntimeTest::SetUp();
    // Dogfood our own lib core dex file.
    dex_file_ = GetLibCoreDexFileNames()[0];
  }

  // Runs test with given arguments.
  bool Exec(const std::vector<std::string>& args, std::string* error_msg) {
    std::string file_path = GetTestAndroidRoot();
    if (IsHost()) {
      file_path += "/bin/dexlist";
    } else {
      file_path += "/xbin/dexlist";
    }
    EXPECT_TRUE(OS::FileExists(file_path.c_str())) << file_path << " should be a valid file path";
    std::vector<std::string> exec_argv = { file_path };
    exec_argv.insert(exec_argv.end(), args.begin(), args.end());
    return ::art::Exec(exec_argv, error_msg);
  }

  std::string dex_file_;
};

TEST_F(DexListTest, NoInputFileGiven) {
  std::string error_msg;
  ASSERT_FALSE(Exec({}, &error_msg)) << error_msg;
}

TEST_F(DexListTest, CantOpenOutput) {
  std::string error_msg;
  ASSERT_FALSE(Exec({"-o", "/joho", dex_file_}, &error_msg)) << error_msg;
}

TEST_F(DexListTest, IllFormedMethod) {
  std::string error_msg;
  ASSERT_FALSE(Exec({"-m", "joho", dex_file_}, &error_msg)) << error_msg;
}

TEST_F(DexListTest, FullOutput) {
  std::string error_msg;
  ASSERT_TRUE(Exec({"-o", "/dev/null", dex_file_}, &error_msg)) << error_msg;
}

TEST_F(DexListTest, MethodOutput) {
  std::string error_msg;
  ASSERT_TRUE(Exec({"-o", "/dev/null", "-m", "java.lang.Object.toString",
    dex_file_}, &error_msg)) << error_msg;
}

}  // namespace art


text:
package com.sgck.dtu.analysis.read;

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

public interface C2DataInput extends DataInput
{
	public void readOrgList(List<Byte> list);
	public void close() throws IOException;
	public int readCharC() throws IOException;
	public int readUnsignedInt() throws IOException;
	public void readUShortArray(int[] datas,List<Byte>orgList) throws IOException;
	public int read(byte b[], int off, int len) throws IOException;
}


text:
package com.github.edgar615.gateway.plugin.user;

import com.github.edgar615.gateway.core.definition.ApiPlugin;
import com.github.edgar615.gateway.core.definition.ApiPluginFactory;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.ArrayList;
import java.util.List;

/**
 * User控制策略的工厂类.
 *
 * @author Edgar  Date 2016/10/21
 */
public class UserRestrictionFactory implements ApiPluginFactory {
    @Override
    public ApiPlugin decode(JsonObject jsonObject) {
        if (!jsonObject.containsKey("user.restriction")) {
            return null;
        }
        JsonObject args = jsonObject.getJsonObject("user.restriction", new JsonObject());
        JsonArray whiteArray = args.getJsonArray("whitelist", new JsonArray());
        JsonArray blackArray = args.getJsonArray("blacklist", new JsonArray());
        List<String> whitelist = new ArrayList<>();
        List<String> blacklist = new ArrayList<>();
        for (int i = 0; i < whiteArray.size(); i++) {
            whitelist.add(whiteArray.getValue(i).toString());
        }
        for (int i = 0; i < blackArray.size(); i++) {
            blacklist.add(blackArray.getValue(i).toString());
        }

        UserRestriction plugin = new UserRestrictionImpl();
        whitelist.forEach(w -> plugin.addWhitelist(w));
        blacklist.forEach(b -> plugin.addBlacklist(b));
        return plugin;
    }

    @Override
    public JsonObject encode(ApiPlugin plugin) {
        UserRestriction userRestriction = (UserRestriction) plugin;
        return new JsonObject().put("user.restriction", new JsonObject()
                .put("whitelist", new JsonArray(userRestriction.whitelist()))
                .put("blacklist", new JsonArray(userRestriction.blacklist())));
    }

    @Override
    public String name() {
        return UserRestriction.class.getSimpleName();
    }

    @Override
    public ApiPlugin create() {
        return new UserRestrictionImpl();
    }
}


text:
require "google/cloud/beyond_corp/app_connections/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::BeyondCorp::AppConnections::V1::AppConnectionsService::Client#list_app_connections
#
def list_app_connections
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::BeyondCorp::AppConnections::V1::AppConnectionsService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::BeyondCorp::AppConnections::V1::ListAppConnectionsRequest.new

  # Call the list_app_connections method.
  result = client.list_app_connections request

  # The returned object is of type Gapic::PagedEnumerable. You can
  # iterate over all elements by calling #each, and the enumerable
  # will lazily make API calls to fetch subsequent pages. Other
  # methods are also available for managing paging directly.
  result.each do |response|
    # Each element is of type ::Google::Cloud::BeyondCorp::AppConnections::V1::AppConnection.
    p response
  end
end
# [END beyondcorp_v1_generated_AppConnectionsService_ListAppConnections_sync]


text:
import java.util.Vector;
/**
 * Acts as a factory and container for Components of all tastes.
 */
public class ComponentSystem{
  /**
  * Default-CTor
  */
  //TODO: dynamically sized containers. Either a vector or a arraylist.
  ComponentSystem(){
    rComps = new RenderableComponent[2605];
    pComps = new PhysicalComponent[2609];
    cComps = new ControllableComponent[2];
    sComps = new SnakeComponent[1305];
  }

  /**
  * Call for an instance of RenderableComponent.
  */
  public RenderableComponent getNewRendComp(Entity up, int type){
    //RenderableComponent ret = new RenderableComponent();
    for (int i = 0; i<rComps.length; i++) {
      if (rComps[i] == null) {
        //if (ret == null) {
        //  System.out.println("Error 1");
        //} // end of if
        rComps[i] = new RenderableComponent(i, up, type);
        //System.out.println("creating RComp at: " + i);
        return rComps[i];
      } // end of if
    } // end of for
    System.out.println("RComps Full");
    return null;
  }

  /**
  * Call for an instance of SnakeComponent.
  */
  public SnakeComponent getNewSComp(Entity up, SnakeComponent next){
    for (int i = 0; i<rComps.length; i++) {
      if (sComps[i] == null) {
        sComps[i] = new SnakeComponent(i, up, next);
        return sComps[i];
      } // end of if
    } // end of for
    System.out.println("SComps Full");
    return null;
  }

  /**
  * Call for an instance of PhysicalComponent.
  */
  public PhysicalComponent getNewPhysComp(Entity up, int x, int y, CollisionShape cShape, int type){
    for (int i = 0; i<pComps.length; i++) {
      if (pComps[i] == null) {
        pComps[i] = new PhysicalComponent(i, up, x, y, cShape, type);
        return pComps[i];
      } // end of if
    } // end of for
    System.out.println("PComps Full");
    return null;
  }

  /**
  * Call for an instance of ControllableComponent.
  */
  public ControllableComponent getNewContComp(Entity up){
    for (int i = 0; i<cComps.length; i++) {
      if (cComps[i] == null) {
        cComps[i] = new ControllableComponent(i, up);
        return cComps[i];
      } // end of if
    } // end of for
    System.out.println("CComps Full");
    return null;
  }

  protected SnakeComponent[] sComps;
  protected RenderableComponent[] rComps;
  protected PhysicalComponent[] pComps;
  protected ControllableComponent[] cComps;
}


text:
import __builtin__ as builtins
import json
import unittest
import mock

from django.core.exceptions import ValidationError
from nose.tools import *  # flake8: noqa (PEP8 asserts)

from framework.auth import Auth
from osf_tests.factories import (AuthUserFactory, NodeLicenseRecordFactory,
                                 ProjectFactory)
from tests.base import OsfTestCase
from osf.utils.migrations import ensure_licenses
from tests.utils import assert_logs, assert_not_logs
from website import settings
from osf.models.licenses import NodeLicense, serialize_node_license_record, serialize_node_license
from osf.models import NodeLog
from website.exceptions import NodeStateError

CHANGED_NAME = 'FOO BAR'
CHANGED_TEXT = 'Some good new text'
CHANGED_PROPERTIES = ['foo', 'bar']
LICENSE_TEXT = json.dumps({
    'MIT': {
        'name': CHANGED_NAME,
        'text': CHANGED_TEXT,
        'properties': CHANGED_PROPERTIES
    }
})

class TestNodeLicenses(OsfTestCase):

    def setUp(self):
        super(TestNodeLicenses, self).setUp()

        self.user = AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)
        self.LICENSE_NAME = 'MIT License'
        self.node_license = NodeLicense.objects.get(name=self.LICENSE_NAME)
        self.YEAR = '2105'
        self.COPYRIGHT_HOLDERS = ['Foo', 'Bar']
        self.node.node_license = NodeLicenseRecordFactory(
            node_license=self.node_license,
            year=self.YEAR,
            copyright_holders=self.COPYRIGHT_HOLDERS
        )
        self.node.save()

    def test_serialize_node_license(self):
        serialized = serialize_node_license(self.node_license)
        assert_equal(serialized['name'], self.LICENSE_NAME)
        assert_equal(serialized['id'], self.node_license.license_id)
        assert_equal(serialized['text'], self.node_license.text)

    def test_serialize_node_license_record(self):
        serialized = serialize_node_license_record(self.node.node_license)
        assert_equal(serialized['name'], self.LICENSE_NAME)
        assert_equal(serialized['id'], self.node_license.license_id)
        assert_equal(serialized['text'], self.node_license.text)
        assert_equal(serialized['year'], self.YEAR)
        assert_equal(serialized['copyright_holders'], self.COPYRIGHT_HOLDERS)

    def test_serialize_node_license_record_None(self):
        self.node.node_license = None
        serialized = serialize_node_license_record(self.node.node_license)
        assert_equal(serialized, {})

    def test_copy_node_license_record(self):
        record = self.node.node_license
        copied = record.copy()
        assert_is_not_none(copied._id)
        assert_not_equal(record._id, copied._id)
        for prop in ('license_id', 'name', 'node_license'):
            assert_equal(getattr(record, prop), getattr(copied, prop))

    def test_license_uniqueness_on_id_is_enforced_in_the_database(self):
        NodeLicense(license_id='foo', name='bar', text='baz').save()
        assert_raises(ValidationError, NodeLicense(license_id='foo', name='buz', text='boo').save)

    def test_ensure_licenses_updates_existing_licenses(self):
        assert_equal(ensure_licenses(), (0, 18))

    def test_ensure_licenses_no_licenses(self):
        before_count = NodeLicense.objects.all().count()
        NodeLicense.objects.all().delete()
        assert_false(NodeLicense.objects.all().count())

        ensure_licenses()
        assert_equal(before_count, NodeLicense.objects.all().count())

    def test_ensure_licenses_some_missing(self):
        NodeLicense.objects.get(license_id='LGPL3').delete()
        with assert_raises(NodeLicense.DoesNotExist):
            NodeLicense.objects.get(license_id='LGPL3')
        ensure_licenses()
        found = NodeLicense.objects.get(license_id='LGPL3')
        assert_is_not_none(found)

    def test_ensure_licenses_updates_existing(self):
        with mock.patch.object(builtins, 'open', mock.mock_open(read_data=LICENSE_TEXT)):
            ensure_licenses()
        MIT = NodeLicense.objects.get(license_id='MIT')
        assert_equal(MIT.name, CHANGED_NAME)
        assert_equal(MIT.text, CHANGED_TEXT)
        assert_equal(MIT.properties, CHANGED_PROPERTIES)

    @assert_logs(NodeLog.CHANGED_LICENSE, 'node')
    def test_Node_set_node_license(self):
        GPL3 = NodeLicense.objects.get(license_id='GPL3')
        NEW_YEAR = '2014'
        COPYLEFT_HOLDERS = ['Richard Stallman']
        self.node.set_node_license(
            {
                'id': GPL3.license_id,
                'year': NEW_YEAR,
                'copyrightHolders': COPYLEFT_HOLDERS
            },
            auth=Auth(self.user),
            save=True
        )

        assert_equal(self.node.node_license.license_id, GPL3.license_id)
        assert_equal(self.node.node_license.name, GPL3.name)
        assert_equal(self.node.node_license.copyright_holders, COPYLEFT_HOLDERS)

    @assert_not_logs(NodeLog.CHANGED_LICENSE, 'node')
    def test_Node_set_node_license_invalid(self):
        with assert_raises(NodeStateError):
            self.node.set_node_license(
                {
                    'id': 'SOME ID',
                    'year': 'foo',
                    'copyrightHolders': []
                },
                auth=Auth(self.user)
            )


text:
<?php

declare(strict_types=1);

return [

    /*
    |--------------------------------------------------------------------------
    | Segment Write Key
    |--------------------------------------------------------------------------
    |
    | This option specifies key which enables you to write to Segment's API.
    |
    | Default: ''
    |
    */

    'write_key' => '',

    /*
    |--------------------------------------------------------------------------
    | Segment Init Options
    |--------------------------------------------------------------------------
    |
    | This option specifies an array of options to initialize Segment.
    |
    | See: https://segment.com/docs/sources/server/php/#configuration.
    |
    | Default: []
    |
    */

    'init_options' => [],
];


text:
using FluentAssertions;
using TestableFileSystem.Fakes.Builders;
using TestableFileSystem.Interfaces;
using Xunit;

namespace TestableFileSystem.Fakes.Tests.Specs.FakeFileInfo
{
    public sealed class FileInfoLengthSpecs
    {
        private const string DefaultContents = "ABC";
        private const string AlternateContents = "ABC...XYZ";

        [Fact]
        private void When_getting_file_length_it_must_lazy_load()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                .IncludingTextFile(path, DefaultContents)
                .Build();

            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            fileSystem.File.WriteAllText(path, AlternateContents);

            // Act
            long length = fileInfo.Length;

            // Assert
            length.Should().Be(AlternateContents.Length);
        }

        [Fact]
        private void When_getting_file_length_it_must_cache()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                .IncludingTextFile(path, DefaultContents)
                .Build();

            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            long beforeLength = fileInfo.Length;

            fileSystem.File.WriteAllText(path, AlternateContents);

            // Act
            long afterLength = fileInfo.Length;

            // Assert
            beforeLength.Should().Be(DefaultContents.Length);
            afterLength.Should().Be(DefaultContents.Length);
        }

        [Fact]
        private void When_getting_file_length_after_external_change_it_must_update_cache_on_refresh()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                .IncludingTextFile(path, DefaultContents)
                .Build();

            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            long beforeLength = fileInfo.Length;

            fileSystem.File.WriteAllText(path, AlternateContents);

            // Act
            fileInfo.Refresh();

            // Assert
            long afterLength = fileInfo.Length;

            beforeLength.Should().Be(DefaultContents.Length);
            afterLength.Should().Be(AlternateContents.Length);
        }

        [Fact]
        private void When_changing_file_length_it_must_not_refresh_automatically()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                .IncludingTextFile(path, DefaultContents)
                .Build();

            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            long beforeLength = fileInfo.Length;

            // Act
            using (fileInfo.CreateText())
            {
            }

            // Assert
            long afterLength = fileInfo.Length;

            beforeLength.Should().Be(DefaultContents.Length);
            afterLength.Should().Be(DefaultContents.Length);
        }
    }
}


text:
#include "segment_image_abstract.h"
#include "../algs.h"
#include <vector>
#include "../geometry.h"
#include "../disjoint_subsets.h"
#include "../set.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    namespace impl
    {
        template <typename T>
        inline T edge_diff_uint(
            const T& a,
            const T& b
        )
        {
            if (a > b)
                return a - b;
            else
                return b - a;
        }

    // ----------------------------------------

        template <typename T, typename enabled = void>
        struct edge_diff_funct
        {
            typedef double diff_type;

            template <typename pixel_type>
            double operator()(
                const pixel_type& a,
                const pixel_type& b
            ) const
            {
                return length(pixel_to_vector<double>(a) - pixel_to_vector<double>(b));
            }
        };

        template <>
        struct edge_diff_funct<uint8,void>
        {
            typedef uint8 diff_type;
            uint8 operator()( const uint8& a, const uint8& b) const { return edge_diff_uint(a,b); }
        };

        template <>
        struct edge_diff_funct<uint16,void>
        {
            typedef uint16 diff_type;
            uint16 operator()( const uint16& a, const uint16& b) const { return edge_diff_uint(a,b); }
        };

        template <>
        struct edge_diff_funct<uint32,void>
        {
            typedef uint32 diff_type;
            uint32 operator()( const uint32& a, const uint32& b) const { return edge_diff_uint(a,b); }
        };

        template <>
        struct edge_diff_funct<double,void>
        {
            typedef double diff_type;
            double operator()( const double& a, const double& b) const { return std::abs(a-b); }
        };

        template <typename T>
        struct edge_diff_funct<T, typename enable_if<is_matrix<T> >::type>
        {
            typedef double diff_type;
            double operator()(
                const T& a,
                const T& b
            ) const
            {
                return length(a-b);
            }
        };

    // ------------------------------------------------------------------------------------

        template <typename T>
        struct graph_image_segmentation_data_T
        {
            graph_image_segmentation_data_T() : component_size(1), internal_diff(0) {}
            unsigned long component_size;
            T internal_diff;
        };

    // ------------------------------------------------------------------------------------

        template <typename T>
        struct segment_image_edge_data_T
        {
            segment_image_edge_data_T (){}

            segment_image_edge_data_T (
                const rectangle& rect,
                const point& p1,
                const point& p2,
                const T& diff_
            ) :
                idx1(p1.y()*rect.width() + p1.x()),
                idx2(p2.y()*rect.width() + p2.x()),
                diff(diff_)
            {}

            bool operator<(const segment_image_edge_data_T& item) const
            { return diff < item.diff; }

            unsigned long idx1;
            unsigned long idx2;
            T diff;
        };

    // ------------------------------------------------------------------------------------

        template <typename image_view_type>
        struct uint8_or_uint16_pixels
        {
            typedef typename image_view_type::pixel_type pixel_type;
            const static bool value = is_same_type<pixel_type,uint8>::value ||
                is_same_type<pixel_type,uint16>::value;
        };

        // This is an overload of get_pixel_edges() that is optimized to segment images
        // with 8bit or 16bit  pixels very quickly.  We do this by using a radix sort
        // instead of quicksort.
        template <typename in_image_type, typename T>
        typename enable_if<uint8_or_uint16_pixels<in_image_type> >::type
        get_pixel_edges (
            const in_image_type& in_img,
            std::vector<segment_image_edge_data_T<T> >& sorted_edges
        )
        {
            typedef typename in_image_type::pixel_type ptype;
            typedef T diff_type;
            std::vector<unsigned long> counts(std::numeric_limits<ptype>::max()+1, 0);

            edge_diff_funct<ptype> edge_diff;

            border_enumerator be(get_rect(in_img), 1);
            // we are going to do a radix sort on the edge weights.  So the first step
            // is to accumulate them into count.
            const rectangle area = get_rect(in_img);
            while (be.move_next())
            {
                const long r = be.element().y();
                const long c = be.element().x();
                const ptype pix = in_img[r][c];
                if (area.contains(c-1,r))   counts[edge_diff(pix, in_img[r  ][c-1])] += 1;
                if (area.contains(c+1,r))   counts[edge_diff(pix, in_img[r  ][c+1])] += 1;
                if (area.contains(c  ,r-1)) counts[edge_diff(pix, in_img[r-1][c  ])] += 1;
                if (area.contains(c  ,r+1)) counts[edge_diff(pix, in_img[r+1][c  ])] += 1;
            }
            for (long r = 1; r+1 < in_img.nr(); ++r)
            {
                for (long c = 1; c+1 < in_img.nc(); ++c)
                {
                    const ptype pix = in_img[r][c];
                    counts[edge_diff(pix, in_img[r-1][c+1])] += 1;
                    counts[edge_diff(pix, in_img[r  ][c+1])] += 1;
                    counts[edge_diff(pix, in_img[r+1][c  ])] += 1;
                    counts[edge_diff(pix, in_img[r+1][c+1])] += 1;
                }
            }

            const unsigned long num_edges = shrink_rect(area,1).area()*4 + in_img.nr()*2*3 - 4 + (in_img.nc()-2)*2*3;
            typedef segment_image_edge_data_T<T> segment_image_edge_data;
            sorted_edges.resize(num_edges);

            // integrate counts.  The idea is to have sorted_edges[counts[i]] be the location that edges
            // with an edge_diff of i go.  So counts[0] == 0, counts[1] == number of 0 edge diff edges, etc.
            unsigned long prev = counts[0];
            for (unsigned long i = 1; i < counts.size(); ++i)
            {
                const unsigned long temp = counts[i];
                counts[i] += counts[i-1];
                counts[i-1] -= prev;
                prev = temp;
            }
            counts[counts.size()-1] -= prev;

            // now build a sorted list of all the edges
            be.reset();
            while(be.move_next())
            {
                const point p = be.element();
                const long r = p.y();
                const long c = p.x();
                const ptype pix = in_img[r][c];
                if (area.contains(c-1,r))
                {
                    const diff_type diff = edge_diff(pix, in_img[r  ][c-1]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c-1,r),diff);
                }

                if (area.contains(c+1,r))
                {
                    const diff_type diff = edge_diff(pix, in_img[r  ][c+1]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c+1,r),diff);
                }

                if (area.contains(c  ,r-1))
                {
                    const diff_type diff = edge_diff(pix, in_img[r-1][c  ]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c  ,r-1),diff);
                }

                if (area.contains(c  ,r+1))
                {
                    const diff_type diff = edge_diff(pix, in_img[r+1][c  ]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c  ,r+1),diff);
                }
            }
            // same thing as the above loop but now we do it on the interior of the image and therefore
            // don't have to include the boundary checking if statements used above.
            for (long r = 1; r+1 < in_img.nr(); ++r)
            {
                for (long c = 1; c+1 < in_img.nc(); ++c)
                {
                    const point p(c,r);
                    const ptype pix = in_img[r][c];
                    diff_type diff;

                    diff = edge_diff(pix, in_img[r  ][c+1]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c+1,r),diff);
                    diff = edge_diff(pix, in_img[r-1][c+1]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c+1,r-1),diff);
                    diff = edge_diff(pix, in_img[r+1][c+1]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c+1,r+1),diff);
                    diff = edge_diff(pix, in_img[r+1][c  ]);
                    sorted_edges[counts[diff]++] = segment_image_edge_data(area,p,point(c  ,r+1),diff);
                }
            }
        }

    // ----------------------------------------------------------------------------------------

        // This is the general purpose version of get_pixel_edges().  It handles all pixel types.
        template <typename in_image_type, typename T>
        typename disable_if<uint8_or_uint16_pixels<in_image_type> >::type
        get_pixel_edges (
            const in_image_type& in_img,
            std::vector<segment_image_edge_data_T<T> >& sorted_edges
        )
        {
            const rectangle area = get_rect(in_img);
            sorted_edges.reserve(area.area()*4);

            typedef typename in_image_type::pixel_type ptype;
            edge_diff_funct<ptype> edge_diff;
            typedef T diff_type;
            typedef segment_image_edge_data_T<T> segment_image_edge_data;

            border_enumerator be(get_rect(in_img), 1);

            // now build a sorted list of all the edges
            be.reset();
            while(be.move_next())
            {
                const point p = be.element();
                const long r = p.y();
                const long c = p.x();
                const ptype& pix = in_img[r][c];
                if (area.contains(c-1,r))
                {
                    const diff_type diff = edge_diff(pix, in_img[r  ][c-1]);
                    sorted_edges.push_back(segment_image_edge_data(area,p,point(c-1,r),diff));
                }

                if (area.contains(c+1,r))
                {
                    const diff_type diff = edge_diff(pix, in_img[r  ][c+1]);
                    sorted_edges.push_back(segment_image_edge_data(area,p,point(c+1,r),diff));
                }

                if (area.contains(c  ,r-1))
                {
                    const diff_type diff = edge_diff(pix, in_img[r-1][c  ]);
                    sorted_edges.push_back( segment_image_edge_data(area,p,point(c  ,r-1),diff));
                }
                if (area.contains(c  ,r+1))
                {
                    const diff_type diff = edge_diff(pix, in_img[r+1][c  ]);
                    sorted_edges.push_back( segment_image_edge_data(area,p,point(c  ,r+1),diff));
                }
            }
            // same thing as the above loop but now we do it on the interior of the image and therefore
            // don't have to include the boundary checking if statements used above.
            for (long r = 1; r+1 < in_img.nr(); ++r)
            {
                for (long c = 1; c+1 < in_img.nc(); ++c)
                {
                    const point p(c,r);
                    const ptype& pix = in_img[r][c];
                    diff_type diff;

                    diff = edge_diff(pix, in_img[r  ][c+1]);
                    sorted_edges.push_back( segment_image_edge_data(area,p,point(c+1,r),diff));
                    diff = edge_diff(pix, in_img[r+1][c+1]);
                    sorted_edges.push_back( segment_image_edge_data(area,p,point(c+1,r+1),diff));
                    diff = edge_diff(pix, in_img[r+1][c  ]);
                    sorted_edges.push_back( segment_image_edge_data(area,p,point(c  ,r+1),diff));
                    diff = edge_diff(pix, in_img[r-1][c+1]);
                    sorted_edges.push_back( segment_image_edge_data(area,p,point(c+1,r-1),diff));
                }
            }

            std::sort(sorted_edges.begin(), sorted_edges.end());

        }

    // ------------------------------------------------------------------------------------

    } // end of namespace impl

// ----------------------------------------------------------------------------------------

    template <
        typename in_image_type,
        typename out_image_type
        >
    void segment_image (
        const in_image_type& in_img_,
        out_image_type& out_img_,
        const double k = 200,
        const unsigned long min_size = 10
    )
    {
        using namespace dlib::impl;
        typedef typename image_traits<in_image_type>::pixel_type ptype;
        typedef typename edge_diff_funct<ptype>::diff_type diff_type;

        // make sure requires clause is not broken
        DLIB_ASSERT(is_same_object(in_img_, out_img_) == false,
            "\t void segment_image()"
            << "\n\t The input images can't be the same object."
            );

        COMPILE_TIME_ASSERT(is_unsigned_type<typename image_traits<out_image_type>::pixel_type>::value);

        const_image_view<in_image_type> in_img(in_img_);
        image_view<out_image_type> out_img(out_img_);

        out_img.set_size(in_img.nr(), in_img.nc());
        // don't bother doing anything if the image is too small
        if (in_img.nr() < 2 || in_img.nc() < 2)
        {
            assign_all_pixels(out_img,0);
            return;
        }

        disjoint_subsets sets;
        sets.set_size(in_img.size());

        std::vector<segment_image_edge_data_T<diff_type> > sorted_edges;
        get_pixel_edges(in_img, sorted_edges);

        std::vector<graph_image_segmentation_data_T<diff_type> > data(in_img.size());

        // now start connecting blobs together to make a minimum spanning tree.
        for (unsigned long i = 0; i < sorted_edges.size(); ++i)
        {
            const unsigned long idx1 = sorted_edges[i].idx1;
            const unsigned long idx2 = sorted_edges[i].idx2;

            unsigned long set1 = sets.find_set(idx1);
            unsigned long set2 = sets.find_set(idx2);
            if (set1 != set2)
            {
                const diff_type diff = sorted_edges[i].diff;
                const diff_type tau1 = static_cast<diff_type>(k/data[set1].component_size);
                const diff_type tau2 = static_cast<diff_type>(k/data[set2].component_size);

                const diff_type mint = std::min(data[set1].internal_diff + tau1,
                                                data[set2].internal_diff + tau2);
                if (diff <= mint)
                {
                    const unsigned long new_set = sets.merge_sets(set1, set2);
                    data[new_set].component_size = data[set1].component_size + data[set2].component_size;
                    data[new_set].internal_diff = diff;
                }
            }
        }

        // now merge any really small blobs
        if (min_size != 0)
        {
            for (unsigned long i = 0; i < sorted_edges.size(); ++i)
            {
                const unsigned long idx1 = sorted_edges[i].idx1;
                const unsigned long idx2 = sorted_edges[i].idx2;

                unsigned long set1 = sets.find_set(idx1);
                unsigned long set2 = sets.find_set(idx2);
                if (set1 != set2 && (data[set1].component_size < min_size || data[set2].component_size < min_size))
                {
                    const unsigned long new_set = sets.merge_sets(set1, set2);
                    data[new_set].component_size = data[set1].component_size + data[set2].component_size;
                    //data[new_set].internal_diff = sorted_edges[i].diff;
                }
            }
        }

        unsigned long idx = 0;
        for (long r = 0; r < out_img.nr(); ++r)
        {
            for (long c = 0; c < out_img.nc(); ++c)
            {
                out_img[r][c] = sets.find_set(idx++);
            }
        }
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
//                     Candidate object location generation code.
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    namespace impl
    {
        struct edge_data
        {
            double edge_diff;
            unsigned long set1;
            unsigned long set2;
            bool operator<(const edge_data& item) const
            {
                return edge_diff < item.edge_diff;
            }
        };

        template <
            typename in_image_type,
            typename diff_type
            >
        void find_basic_candidate_object_locations (
            const in_image_type& in_img,
            const std::vector<dlib::impl::segment_image_edge_data_T<diff_type> >& sorted_edges,
            std::vector<rectangle>& out_rects,
            std::vector<edge_data>& edges,
            const double k,
            const unsigned long min_size
        )
        {
            using namespace dlib::impl;

            std::vector<dlib::impl::segment_image_edge_data_T<diff_type> > rejected_edges;
            rejected_edges.reserve(sorted_edges.size());

            out_rects.clear();
            edges.clear();

            // don't bother doing anything if the image is too small
            if (in_img.nr() < 2 || in_img.nc() < 2)
            {
                return;
            }

            disjoint_subsets sets;
            sets.set_size(in_img.size());

            std::vector<graph_image_segmentation_data_T<diff_type> > data(in_img.size());

            std::pair<unsigned long,unsigned long> last_blob_edge(std::numeric_limits<unsigned long>::max(),
                                                                  std::numeric_limits<unsigned long>::max());;
            // now start connecting blobs together to make a minimum spanning tree.
            for (unsigned long i = 0; i < sorted_edges.size(); ++i)
            {
                const unsigned long idx1 = sorted_edges[i].idx1;
                const unsigned long idx2 = sorted_edges[i].idx2;

                unsigned long set1 = sets.find_set(idx1);
                unsigned long set2 = sets.find_set(idx2);
                if (set1 != set2)
                {
                    const diff_type diff = sorted_edges[i].diff;
                    const diff_type tau1 = static_cast<diff_type>(k/data[set1].component_size);
                    const diff_type tau2 = static_cast<diff_type>(k/data[set2].component_size);

                    const diff_type mint = std::min(data[set1].internal_diff + tau1,
                        data[set2].internal_diff + tau2);
                    if (diff <= mint)
                    {
                        const unsigned long new_set = sets.merge_sets(set1, set2);
                        data[new_set].component_size = data[set1].component_size + data[set2].component_size;
                        data[new_set].internal_diff = diff;
                    }
                    else
                    {
                        // Don't bother keeping multiple edges from the same pair of blobs, we
                        // only need one for what we will do later.
                        if (std::make_pair(set1,set2) != last_blob_edge)
                        {
                            segment_image_edge_data_T<diff_type> temp = sorted_edges[i];
                            temp.idx1 = set1;
                            temp.idx2 = set2;
                            rejected_edges.push_back(temp);
                            last_blob_edge = std::make_pair(set1,set2);
                        }
                    }
                }
            }

            // merge small blobs
            for (unsigned long i = 0; i < rejected_edges.size(); ++i)
            {
                const unsigned long idx1 = rejected_edges[i].idx1;
                const unsigned long idx2 = rejected_edges[i].idx2;

                unsigned long set1 = sets.find_set(idx1);
                unsigned long set2 = sets.find_set(idx2);
                rejected_edges[i].idx1 = set1;
                rejected_edges[i].idx2 = set2;
                if (set1 != set2 && (data[set1].component_size < min_size || data[set2].component_size < min_size))
                {
                    const unsigned long new_set = sets.merge_sets(set1, set2);
                    data[new_set].component_size = data[set1].component_size + data[set2].component_size;
                    data[new_set].internal_diff = rejected_edges[i].diff;
                }
            }

            // find bounding boxes of each blob
            std::map<unsigned long, rectangle> boxes;
            std::map<unsigned long, unsigned long> box_id_map;
            unsigned long idx = 0;
            for (long r = 0; r < in_img.nr(); ++r)
            {
                for (long c = 0; c < in_img.nc(); ++c)
                {
                    const unsigned long id = sets.find_set(idx++);
                    // Accumulate the current point into its box and if it is the first point
                    // in the box then also record the id number for this box.
                    if ((boxes[id] += point(c,r)).area() == 1)
                        box_id_map[id] = boxes.size()-1;
                }
            }

            // copy boxes into out_rects
            out_rects.resize(boxes.size());
            for (std::map<unsigned long,rectangle>::iterator i = boxes.begin(); i != boxes.end(); ++i)
            {
                out_rects[box_id_map[i->first]] = i->second;
            }

            // Now find the edges between the boxes
            typedef dlib::memory_manager<char>::kernel_2c mm_type;
            dlib::set<std::pair<unsigned long, unsigned long>, mm_type>::kernel_1a neighbors_final;
            for (unsigned long i = 0; i < rejected_edges.size(); ++i)
            {
                const unsigned long idx1 = rejected_edges[i].idx1;
                const unsigned long idx2 = rejected_edges[i].idx2;

                unsigned long set1 = sets.find_set(idx1);
                unsigned long set2 = sets.find_set(idx2);
                if (set1 != set2)
                {
                    std::pair<unsigned long, unsigned long> p = std::make_pair(set1,set2);
                    if (!neighbors_final.is_member(p))
                    {
                        neighbors_final.add(p);

                        edge_data temp;
                        const diff_type mint = std::min(data[set1].internal_diff ,
                                                        data[set2].internal_diff );
                        temp.edge_diff = rejected_edges[i].diff - mint;
                        temp.set1 = box_id_map[set1];
                        temp.set2 = box_id_map[set2];
                        edges.push_back(temp);
                    }
                }
            }

            std::sort(edges.begin(), edges.end());
        }
    } // end namespace impl

// ----------------------------------------------------------------------------------------

    template <typename alloc>
    void remove_duplicates (
        std::vector<rectangle,alloc>& rects
    )
    {
        std::sort(rects.begin(), rects.end(), std::less<rectangle>());
        unsigned long num_unique = 1;
        for (unsigned long i = 1; i < rects.size(); ++i)
        {
            if (rects[i] != rects[i-1])
            {
                rects[num_unique++] = rects[i];
            }
        }
        if (rects.size() != 0)
            rects.resize(num_unique);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename in_image_type,
        typename EXP
        >
    void find_candidate_object_locations (
        const in_image_type& in_img_,
        std::vector<rectangle>& rects,
        const matrix_exp<EXP>& kvals,
        const unsigned long min_size = 20,
        const unsigned long max_merging_iterations = 50
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(is_vector(kvals) && kvals.size() > 0,
            "\t void find_candidate_object_locations()"
            << "\n\t Invalid inputs were given to this function."
            << "\n\t is_vector(kvals): " << is_vector(kvals)
            << "\n\t kvals.size():     " << kvals.size()
            );

        typedef dlib::memory_manager<char>::kernel_2c mm_type;
        typedef dlib::set<rectangle, mm_type>::kernel_1a set_of_rects;

        using namespace dlib::impl;
        typedef typename image_traits<in_image_type>::pixel_type ptype;
        typedef typename edge_diff_funct<ptype>::diff_type diff_type;

        const_image_view<in_image_type> in_img(in_img_);

        // don't bother doing anything if the image is too small
        if (in_img.nr() < 2 || in_img.nc() < 2)
        {
            return;
        }

        std::vector<edge_data> edges;
        std::vector<rectangle> working_rects;
        std::vector<segment_image_edge_data_T<diff_type> > sorted_edges;
        get_pixel_edges(in_img, sorted_edges);

        disjoint_subsets sets;

        for (long j = 0; j < kvals.size(); ++j)
        {
            const double k = kvals(j);

            find_basic_candidate_object_locations(in_img, sorted_edges, working_rects, edges, k, min_size);
            rects.insert(rects.end(), working_rects.begin(), working_rects.end());

            // Now iteratively merge all the rectangles we have and record the results.
            // Note that, unlike what is described in the paper
            //    Segmentation as Selective Search for Object Recognition" by Koen E. A. van de Sande, et al.
            // we don't use any kind of histogram/SIFT like thing to order the edges
            // between the blobs.  Here we simply order by the pixel difference value.
            // Additionally, note that we keep progressively merging boxes in the outer
            // loop rather than performing just a single iteration as indicated in the
            // paper.
            set_of_rects detected_rects;
            bool did_merge = true;
            for (unsigned long iter = 0; did_merge && iter < max_merging_iterations; ++iter)
            {
                did_merge = false;
                sets.clear();
                sets.set_size(working_rects.size());

                // recursively merge neighboring blobs until we have merged everything
                for (unsigned long i = 0; i < edges.size(); ++i)
                {
                    edge_data temp = edges[i];

                    temp.set1 = sets.find_set(temp.set1);
                    temp.set2 = sets.find_set(temp.set2);
                    if (temp.set1 != temp.set2)
                    {
                        rectangle merged_rect = working_rects[temp.set1] + working_rects[temp.set2];
                        // Skip merging this pair of blobs if it was merged in a previous
                        // iteration.  Doing this lets us consider other possible blob
                        // merges.
                        if (!detected_rects.is_member(merged_rect))
                        {
                            const unsigned long new_set = sets.merge_sets(temp.set1, temp.set2);
                            rects.push_back(merged_rect);
                            working_rects[new_set] = merged_rect;
                            did_merge = true;
                            detected_rects.add(merged_rect);
                        }
                    }
                }
            }
        }

        remove_duplicates(rects);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename in_image_type
        >
    void find_candidate_object_locations (
        const in_image_type& in_img,
        std::vector<rectangle>& rects
    )
    {
        find_candidate_object_locations(in_img, rects, linspace(50, 200, 3));
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_SEGMENT_ImAGE_Hh_


text:
package com.kc.shiptransport.mvp.upcoming;

import com.kc.shiptransport.db.backlog.BackLog;
import com.kc.shiptransport.mvp.BasePresenter;
import com.kc.shiptransport.mvp.BaseView;

import java.util.List;

/**
 * @author 邱永恒
 * @time 2017/9/8  15:57
 * @desc ${TODD}
 */

public interface UpcomingContract {
    interface View extends BaseView<Presenter> {
        void showPending(List<BackLog> list);
    }

    interface Presenter extends BasePresenter {
        void getPending(int PageSize, int PageCount);
        void getPendingForDB();
    }
}


text:
set -e
set -u
set -o pipefail
set -x

function setup_cluster_for_vms() {
  snip_setup_wd

  snip_setup_iop

  echo y | snip_install_istio

  snip_install_eastwest

  snip_expose_istio
}

function setup_vm() {
  snip_install_namespace || true
  snip_install_sa || true

  snip_create_wg
  snip_apply_wg
  snip_configure_wg

  # Rather than spinning up a real VM, we will use a docker container
  # We do the implicit "Securely transfer the files from "${WORK_DIR}" to the virtual machine." step by
  # a volume mount
  # shellcheck disable=SC2086
  docker run --rm -it --init -d --network=kind --name vm \
    -v "${WORK_DIR}:/root" -v "${PWD}/content/en/docs/setup/install/virtual-machine:/test" \
    ${EXTRA_VM_ARGS:-} \
    -w "/root" \
    gcr.io/istio-release/base:${BASE_VERSION}

  POD_CIDR=$(kubectl get node -ojsonpath='{.items[0].spec.podCIDR}')
  DOCKER_IP=$(docker inspect -f "{{ .NetworkSettings.Networks.kind.IPAddress }}" istio-testing-control-plane)
  # Here, we run the snippets *inside* the docker VM. This mirrors the docs telling to run the commands
  # on the VM
  docker exec --privileged vm bash -c "
    # Setup connectivity
    ip route add ${POD_CIDR} via ${DOCKER_IP}
    # Docker sets up a bunch of rules for DNS which messes with things. Just remove all of them
    sudo iptables -P INPUT ACCEPT
    sudo iptables -P FORWARD ACCEPT
    sudo iptables -P OUTPUT ACCEPT
    sudo iptables -t nat -F
    sudo iptables -t mangle -F
    sudo iptables -F
    sudo iptables -X
    echo nameserver 8.8.8.8 | sudo tee /etc/resolv.conf
    source /test/snips.sh
    snip_configure_the_virtual_machine_1
    snip_configure_the_virtual_machine_2
    # TODO: we should probably have a better way to get the debian package
    curl -LO https://storage.googleapis.com/istio-build/dev/${TAG}/deb/istio-sidecar.deb
    sudo dpkg -i istio-sidecar.deb
    snip_configure_the_virtual_machine_5
    snip_configure_the_virtual_machine_6
    snip_configure_the_virtual_machine_7
    snip_configure_the_virtual_machine_8
  "
}

function start_vm() {
  # We cannot use systemd inside docker (since its a pain). Just run it directly.
  docker exec --privileged -w / -e ISTIO_AGENT_FLAGS="--log_output_level=dns:debug" -d vm /usr/local/bin/istio-start.sh
}


text:
package com.android.tools.lint.detector.api;

import junit.framework.TestCase;

import java.util.EnumSet;

@SuppressWarnings("javadoc")
public class ScopeTest extends TestCase {
    public void testIntersect() {
        assertEquals(Scope.RESOURCE_FILE_SCOPE,
                Scope.intersect(Scope.RESOURCE_FILE_SCOPE, Scope.RESOURCE_FILE_SCOPE));

        assertEquals(EnumSet.of(Scope.RESOURCE_FILE),
                Scope.intersect(
                        EnumSet.of(Scope.RESOURCE_FILE),
                        EnumSet.of(Scope.RESOURCE_FILE)));

        assertEquals(EnumSet.of(Scope.RESOURCE_FILE),
                Scope.intersect(
                        EnumSet.of(Scope.RESOURCE_FILE, Scope.JAVA_FILE),
                        EnumSet.of(Scope.RESOURCE_FILE)));

        assertEquals(EnumSet.of(Scope.JAVA_FILE),
                Scope.intersect(
                        EnumSet.of(Scope.RESOURCE_FILE, Scope.JAVA_FILE),
                        EnumSet.of(Scope.JAVA_FILE)));

        assertEquals(EnumSet.of(Scope.RESOURCE_FILE),
                Scope.intersect(
                        EnumSet.of(Scope.RESOURCE_FILE),
                        EnumSet.of(Scope.RESOURCE_FILE, Scope.JAVA_FILE)));

        assertEquals(EnumSet.of(Scope.JAVA_FILE),
                Scope.intersect(
                        EnumSet.of(Scope.JAVA_FILE),
                        EnumSet.of(Scope.RESOURCE_FILE, Scope.JAVA_FILE)));

        assertTrue(Scope.intersect(
                    EnumSet.of(Scope.JAVA_FILE), EnumSet.of(Scope.RESOURCE_FILE)).isEmpty());
    }
}


text:
- lista uno
- lista dos


text:
function y = cvx_id( x )
y = cvx_id( struct2cell( x ) );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
/**
 * Fig. Fig. 16.13: Algorithms2.java
 * Collections methods addAll, frequency and disjoint
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AlgorithmsTwo {

    public static void main(String[] args)
    {
        // Initialize listOne and listTwo
        String[] colors = {"red", "white", "yellow", "blue"};
        List<String> listOne = Arrays.asList(colors);
        List<String> listTwo = new ArrayList<>();

        listTwo.add("black");
        listTwo.add("red");
        listTwo.add("green");

        System.out.print("Before addAll, listTwo contains: ");

        // Display elements in listTwo
        for (String s : listTwo)
            System.out.printf("%s ", s);

        Collections.addAll(listTwo, colors);

        System.out.printf("\nAfter addAll, listTwo contains: ");

        // Display elements in listTwo
        for (String s : listTwo)
            System.out.printf("%s ", s);

        // Get frequency of "red"
        int frequency = Collections.frequency(listTwo, "red");
        System.out.printf("\nFrequency of red in listTwo: %d\n", frequency);

        // check whether list1 and list2 have elements in common
        boolean common = Collections.disjoint(listOne, listTwo);
        System.out.printf("listOne and listTwo %s elements in common\n", (common ? "don't have" : "have"));
    }
}


text:
name: Issue
about: Please only raise an issue if you've been advised to do so after discussion. Thanks! 🙏
---

The starting point for issues should usually be a discussion...

https://github.com/encode/starlette/discussions

Possible bugs may be raised as a "Potential Issue" discussion, feature requests may be raised as an "Ideas" discussion. We can then determine if the discussion needs to be escalated into an "Issue" or not.

This will help us ensure that the "Issues" list properly reflects ongoing or needed work on the project.

---

- [ ] Initially raised as discussion #...


text:
"""Utilities for keeping track of time in a task."""

from __future__ import division
from PyQt5 import QtCore
from axopy.messaging import Transmitter, TransmitterBase

class Counter(TransmitterBase):
    """Counts to a given number then transmits a timeout event.

    Parameters
    ----------
    max_count : int
        Number of iterations to go through before transmitting the `timeout`
        event. Must be greater than 1.
    reset_on_timeout : bool, optional
        Specifies whether or not the timer should reset its count back to zero
        once the timeout event occurs. The default behavior is to reset.

    Attributes
    ----------
    count : int
        Current count.
    timeout : Transmitter
        Transmitted when ``max_count`` has been reached.

    Examples
    --------
    Basic usage:

    >>> from axopy.timing import Counter
    >>> timer = Counter(2)
    >>> timer.increment()
    >>> timer.count
    1
    >>> timer.progress
    0.5
    >>> timer.increment()
    >>> timer.count
    0
    """

    timeout = Transmitter()

    def __init__(self, max_count=1, reset_on_timeout=True):
        super(Counter, self).__init__()
        max_count = int(max_count)
        if max_count < 1:
            raise ValueError('max_count must be > 1')

        self.reset_on_timeout = reset_on_timeout

        self.max_count = max_count
        self.count = 0

    @property
    def progress(self):
        """Progress toward timeout, from 0 to 1."""
        return self.count / self.max_count

    def increment(self):
        """Increment the counter.

        If `max_count` is reached, the ``timeout`` event is transmitted. If
        `reset_on_timeout` has been set to True (default), the timer is also
        reset.
        """
        self.count += 1

        if self.count == self.max_count:
            if self.reset_on_timeout:
                self.reset()

            self.timeout.emit()

    def reset(self):
        """Resets the count to 0 to start over."""
        self.count = 0

class Timer(TransmitterBase):
    """Real-time one-shot timer.

    This is useful in situations where you want to wait for some amount of time
    and locking the timing to data acquisition updates is not important. For
    example, inserting a waiting period between trials of a task can be done by
    connecting the ``timeout`` transmitter to your task's
    :meth:`~axopy.task.Task.next_trial` method.

    Parameters
    ----------
    duration : float
        Duration of the timer, in seconds.

    Attributes
    ----------
    timeout : Transmitter
        Transmitted when the timer has finished.
    """

    timeout = Transmitter()

    def __init__(self, duration):
        super(Timer, self).__init__()
        self.duration = duration

        self._qtimer = QtCore.QTimer()
        self._qtimer.setInterval(int(1000*self.duration))
        self._qtimer.setSingleShot(True)
        self._qtimer.timeout.connect(self.timeout)

    def start(self):
        """Start the timer."""
        self._qtimer.start()

    def stop(self):
        """Stop the timer.

        If you stop the timer early, the timeout event won't be transmitted.
        """
        self._qtimer.stop()


text:
package com.github.chrisblutz.networking.packets;

import com.github.chrisblutz.networking.exceptions.Errors;
import com.github.chrisblutz.networking.exceptions.NetworkException;
import com.github.chrisblutz.networking.packets.datatypes.DataType;
import com.github.chrisblutz.networking.packets.datatypes.DataTypes;
import com.github.chrisblutz.networking.sockets.Connection;
import com.github.chrisblutz.networking.utils.ExtendedMap;

import java.util.ArrayList;
import java.util.List;

/**
 * A class that allows the transformation of {@code Packets} into
 * {@code Strings}. This can be configured using a
 * {@code PacketHandlerConfiguration}.
 *
 * @author Christopher Lutz
 */
public class PacketWriter {

    private List<Throwable> errors = new ArrayList<Throwable>();
    private PacketHandlerConfiguration config;

    /**
     * Creates a {@code PacketWriter} that uses the default
     * {@code PacketHandlerConfiguration}
     */
    public PacketWriter() {

        this(PacketHandlerConfiguration.getDefaultConfiguration());
    }

    /**
     * Creates a {@code PacketWriter} that uses a custom
     * {@code PacketHandlerConfiguration}
     *
     * @param config The {@code PacketHandlerConfiguration} that should be used
     */
    public PacketWriter(PacketHandlerConfiguration config) {

        this.config = config;
    }

    /**
     * Turns a {@code Packet} into a {@code String} following the
     * {@code PacketHandlerConfiguration} used by this {@code PacketWriter}
     *
     * @param connection The {@code Connection} that sent the request
     * @param packet     The {@code Packet} to turn into a {@code String}
     * @return The {@code String} form of the {@code Packet}
     */
    public String getPacketAsWriteableString(Connection connection, Packet packet) {

        errors.clear();

        ExtendedMap data = packet.getDataAsMap();

        String toWrite = "";

        for (int typeInt = 0; typeInt < data.typeSet().size(); typeInt++) {

            Class<?> type = data.typeSet().toArray(new Class<?>[data.typeSet().size()])[typeInt];

            DataType dataType = DataTypes.getDataType(type);

            if (dataType != null) {

                for (int i = 0; i < data.size(type); i++) {

                    String key = data.keySet(type).toArray(new String[]{})[i];

                    toWrite += DataTypes.writeType(dataType, key, data.get(key)).replace("|", PacketUtils.VERTICAL_LINE_ESCAPE);

                    if (i < data.keySet(type).size() - 1
                            || (i == data.keySet(type).size() - 1 && typeInt < data
                            .typeSet().size() - 1)) {

                        toWrite += "|";
                    }
                }

            } else {

                NullPointerException e = Errors.getMissingDataType("class", type.getName(), new NetworkException(""));

                if (config.getIgnoreErrors()) {

                    errors.add(e);

                } else {

                    throw e;
                }
            }
        }

        return toWrite;
    }

    /**
     * Gets all of the errors thrown during the previous {@code Packet} to
     * {@code String} transformation. This will be empty if {@code ignoreErrors}
     * flag in the {@code PacketHandlerConfiguration} is {@code false}.
     *
     * @return A {@code Throwable[]} containing all errors thrown during the
     * previous transformation
     */
    public Throwable[] getErrors() {

        return errors.toArray(new Throwable[]{});
    }
}


text:
package com.ajah.syndicate.data;

import lombok.EqualsAndHashCode;

import com.ajah.syndicate.FeedSourceId;

/**
 * Thrown when a feed source is requested that does not exist.
 *
 * @author Eric F. Savage <code@efsavage.com>
 */
@EqualsAndHashCode(callSuper = true)
public class FeedSourceNotFoundException extends Exception {

	private final FeedSourceId feedSourceId;

	/**
	 * Thrown when a feed source is requested by an ID that does not exist.
	 *
	 * @param feedSourceId
	 * 		FeedSource ID that was sought.
	 */
	public FeedSourceNotFoundException(final FeedSourceId feedSourceId) {
		super("id: " + feedSourceId + " not found");
		this.feedSourceId = feedSourceId;
	}

}