text:
package ru.r2cloud.device;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.r2cloud.Lifecycle;
import ru.r2cloud.model.BandFrequency;
import ru.r2cloud.model.BandFrequencyComparator;
import ru.r2cloud.model.DeviceConfiguration;
import ru.r2cloud.model.DeviceConnectionStatus;
import ru.r2cloud.model.DeviceStatus;
import ru.r2cloud.model.IQData;
import ru.r2cloud.model.Observation;
import ru.r2cloud.model.ObservationRequest;
import ru.r2cloud.model.ObservationStatus;
import ru.r2cloud.model.RotatorStatus;
import ru.r2cloud.model.Transmitter;
import ru.r2cloud.predict.PredictOreKit;
import ru.r2cloud.satellite.IObservationDao;
import ru.r2cloud.satellite.ObservationFactory;
import ru.r2cloud.satellite.ObservationRequestComparator;
import ru.r2cloud.satellite.OverlappedTimetable;
import ru.r2cloud.satellite.RotatorService;
import ru.r2cloud.satellite.Schedule;
import ru.r2cloud.satellite.ScheduledObservation;
import ru.r2cloud.satellite.SequentialTimetable;
import ru.r2cloud.satellite.TransmitterFilter;
import ru.r2cloud.satellite.decoder.DecoderService;
import ru.r2cloud.satellite.reader.IQReader;
import ru.r2cloud.util.Clock;
import ru.r2cloud.util.NamingThreadFactory;
import ru.r2cloud.util.SafeRunnable;
import ru.r2cloud.util.ThreadPoolFactory;
import ru.r2cloud.util.Util;

public abstract class Device implements Lifecycle {

	private static final Logger LOG = LoggerFactory.getLogger(Device.class);
	public static final Long PARTIAL_TOLERANCE_MILLIS = 60 * 4 * 1000L;

	private final String id;
	private final List<Transmitter> scheduledTransmitters = new ArrayList<>();
	private final TransmitterFilter filter;
	private final Schedule schedule;
	private final int numberOfConcurrentObservations;
	private final ThreadPoolFactory threadpoolFactory;
	private final Object sdrServerLock = new Object();
	private final Clock clock;
	private final RotatorService rotatorService;
	private final IObservationDao observationDao;
	private final DecoderService decoderService;
	private final DeviceConfiguration deviceConfiguration;

	private Long currentBandFrequency = null;
	private int numberOfObservationsOnCurrentBand = 0;
	private ScheduledExecutorService startThread = null;
	private ScheduledExecutorService stopThread = null;

	protected Device(String id, TransmitterFilter filter, int numberOfConcurrentObservations, ObservationFactory observationFactory, ThreadPoolFactory threadpoolFactory, Clock clock, DeviceConfiguration deviceConfiguration, IObservationDao observationDao, DecoderService decoderService,
			PredictOreKit predict, Schedule schedule) {
		this.id = id;
		this.filter = filter;
		this.numberOfConcurrentObservations = numberOfConcurrentObservations;
		this.threadpoolFactory = threadpoolFactory;
		this.clock = clock;
		if (deviceConfiguration.getRotatorConfiguration() != null) {
			this.rotatorService = new RotatorService(deviceConfiguration.getRotatorConfiguration(), predict, threadpoolFactory, clock);
		} else {
			this.rotatorService = null;
		}
		this.observationDao = observationDao;
		this.decoderService = decoderService;
		this.deviceConfiguration = deviceConfiguration;
		if (schedule != null) {
			this.schedule = schedule;
		} else {
			if (numberOfConcurrentObservations == 1) {
				this.schedule = new Schedule(new SequentialTimetable(PARTIAL_TOLERANCE_MILLIS), observationFactory);
			} else {
				this.schedule = new Schedule(new OverlappedTimetable(PARTIAL_TOLERANCE_MILLIS), observationFactory);
			}
		}
	}

	public synchronized boolean tryTransmitter(Transmitter transmitter) {
		if (!filter.accept(transmitter)) {
			return false;
		}
		scheduledTransmitters.add(transmitter);
		return true;
	}

	private void schedule(ObservationRequest req, Transmitter transmitter) {
		// write some device-specific parameters
		req.setGain(deviceConfiguration.getGain());
		req.setBiast(deviceConfiguration.isBiast());
		req.setRtlDeviceId(deviceConfiguration.getRtlDeviceId());
		req.setPpm(deviceConfiguration.getPpm());
		req.setSdrServerConfiguration(deviceConfiguration.getSdrServerConfiguration());
		req.setSampleRate(transmitter.getInputSampleRate());
		LOG.info("[{}] scheduled next pass for {}. start: {} end: {}", id, transmitter, new Date(req.getStartTimeMillis()), new Date(req.getEndTimeMillis()));
		IQReader reader = createReader(req, transmitter);
		Runnable readTask = new SafeRunnable() {

			@Override
			public void safeRun() {
				IQData data;
				Observation observation = new Observation(req);
				observation.setStatus(ObservationStatus.RECEIVING_DATA);
				// do not use lock for multiple concurrent observations
				if (numberOfConcurrentObservations > 1) {
					synchronized (sdrServerLock) {
						while (currentBandFrequency != null && currentBandFrequency != req.getCenterBandFrequency()) {
							try {
								sdrServerLock.wait();
							} catch (InterruptedException e) {
								Thread.currentThread().interrupt();
								return;
							}
						}
						if (clock.millis() > req.getEndTimeMillis()) {
							LOG.info("[{}] observation time passed. skip {}", req.getId(), transmitter);
							return;
						}
						if (currentBandFrequency == null) {
							currentBandFrequency = req.getCenterBandFrequency();
							LOG.info("starting observations on {} hz", currentBandFrequency);
						}
						numberOfObservationsOnCurrentBand++;
					}
					// insert only when it actually started on the device
					observationDao.insert(observation);
					try {
						data = reader.start();
					} catch (InterruptedException e) {
						LOG.info("[{}] reader was terminated", req.getId());
						observationDao.cancel(observation);
						Thread.currentThread().interrupt();
						return;
					} finally {
						synchronized (sdrServerLock) {
							numberOfObservationsOnCurrentBand--;
							if (numberOfObservationsOnCurrentBand <= 0) {
								LOG.info("no more observations on: {} hz", currentBandFrequency);
								currentBandFrequency = null;
							}
							sdrServerLock.notifyAll();
						}
					}
				} else {
					if (clock.millis() > req.getEndTimeMillis()) {
						LOG.info("[{}] observation time passed. skip {}", req.getId(), transmitter);
						return;
					}
					observationDao.insert(observation);
					try {
						data = reader.start();
					} catch (InterruptedException e) {
						observationDao.cancel(observation);
						Thread.currentThread().interrupt();
						return;
					}
				}

				if (data == null || data.getDataFile() == null) {
					observationDao.cancel(observation);
					return;
				}
				// actual start/end might be different
				observation.setStartTimeMillis(data.getActualStart());
				observation.setEndTimeMillis(data.getActualEnd());
				observation.setStatus(ObservationStatus.RECEIVED);

				File dataFile = observationDao.update(observation, data.getDataFile());
				if (dataFile == null) {
					return;
				}

				synchronized (Device.this) {
					if (startThread == null) {
						return;
					}

					decoderService.run(dataFile, req);
				}

			}
		};
		synchronized (this) {
			if (startThread == null) {
				return;
			}
			long current = clock.millis();
			Future<?> startFuture = startThread.schedule(readTask, req.getStartTimeMillis() - current, TimeUnit.MILLISECONDS);
			Future<?> rotatorFuture = null;
			if (rotatorService != null) {
				rotatorFuture = rotatorService.schedule(req, current, startFuture);
			}
			Runnable completeTask = new SafeRunnable() {

				@Override
				public void safeRun() {
					reader.complete();
				}
			};
			Future<?> stopRtlSdrFuture = stopThread.schedule(completeTask, req.getEndTimeMillis() - current, TimeUnit.MILLISECONDS);
			schedule.assignTasksToSlot(req.getId(), new ScheduledObservation(startFuture, stopRtlSdrFuture, completeTask, rotatorFuture));
		}
	}

	public void reschedule() {
		synchronized (sdrServerLock) {
			currentBandFrequency = null;
			numberOfObservationsOnCurrentBand = 0;
		}
		synchronized (this) {
			if (scheduledTransmitters.isEmpty()) {
				LOG.info("[{}] no available satellites for this device", id);
				return;
			}
			long current = clock.millis();
			List<ObservationRequest> newSchedule = schedule.createInitialSchedule(scheduledTransmitters, current);
			for (ObservationRequest cur : newSchedule) {
				Transmitter fullSatelliteInfo = findById(cur.getTransmitterId());
				if (fullSatelliteInfo == null) {
					LOG.error("unable to find full transmitter info for schedule observation: {}", cur.getId());
					continue;
				}
				schedule(cur, fullSatelliteInfo);
			}
			if (numberOfConcurrentObservations > 1) {
				logBandsForSdrServer(scheduledTransmitters);
			}
		}
	}

	private void logBandsForSdrServer(List<Transmitter> allSatellites) {
		LOG.info("[{}] active bands are:", id);
		Set<BandFrequency> unique = new HashSet<>();
		for (Transmitter cur : allSatellites) {
			unique.add(cur.getFrequencyBand());
		}
		List<BandFrequency> sorted = new ArrayList<>(unique);
		Collections.sort(sorted, BandFrequencyComparator.INSTANCE);
		for (BandFrequency cur : sorted) {
			LOG.info("  {} - {}", cur.getLower(), cur.getUpper());
		}
	}

	public abstract IQReader createReader(ObservationRequest req, Transmitter satellite);

	@Override
	public void stop() {
		// cancel all tasks and complete active sdr readers
		schedule.cancelAll();
		if (rotatorService != null) {
			rotatorService.stop();
		}
		Util.shutdown(startThread, threadpoolFactory.getThreadPoolShutdownMillis());
		Util.shutdown(stopThread, threadpoolFactory.getThreadPoolShutdownMillis());
		startThread = null;
		LOG.info("[{}] device stopped", id);
	}

	@Override
	public void start() {
		if (startThread != null) {
			return;
		}
		startThread = threadpoolFactory.newScheduledThreadPool(numberOfConcurrentObservations, new NamingThreadFactory("sch-start"));
		stopThread = threadpoolFactory.newScheduledThreadPool(1, new NamingThreadFactory("sch-stop"));
		if (rotatorService != null) {
			rotatorService.start();
		}
		LOG.info("[{}] device started", id);
	}

	public ObservationRequest startImmediately(Transmitter transmitter) {
		long startTime = clock.millis();
		ObservationRequest closest = schedule.findFirstByTransmitterId(transmitter.getId(), startTime);
		if (closest == null) {
			return null;
		}
		long endTime = startTime + (closest.getEndTimeMillis() - closest.getStartTimeMillis());
		List<ObservationRequest> requests = schedule.findObservations(startTime, endTime);
		for (ObservationRequest cur : requests) {
			completeImmediately(cur.getId());
		}
		ObservationRequest movedTo = schedule.moveObservation(closest, startTime);
		if (movedTo == null) {
			return null;
		}
		schedule(closest, transmitter);
		return closest;
	}

	public boolean completeImmediately(String observationId) {
		ScheduledObservation previous = schedule.cancel(observationId);
		if (previous == null) {
			return false;
		}
		stopThread.submit(previous.getCompleteTask());
		return true;
	}

	public ObservationRequest findFirstByTransmitter(Transmitter transmitter) {
		// schedule can be shared. thus containing observations from different
		// transmitters
		if (!filter.accept(transmitter)) {
			return null;
		}
		return schedule.findFirstByTransmitterId(transmitter.getId(), clock.millis());
	}

	public ObservationRequest enableTransmitter(Transmitter transmitter) {
		if (!tryTransmitter(transmitter)) {
			return null;
		}
		List<ObservationRequest> batch = schedule.getByTransmitterId(transmitter.getId());
		if (batch.isEmpty()) {
			batch = schedule.addToSchedule(transmitter, clock.millis());
			if (batch.isEmpty()) {
				return null;
			}

			for (ObservationRequest cur : batch) {
				schedule(cur, transmitter);
			}
		}

		// return first
		Collections.sort(batch, ObservationRequestComparator.INSTANCE);
		return batch.get(0);
	}

	public List<ObservationRequest> findScheduledObservations() {
		List<ObservationRequest> result = new ArrayList<>();
		for (Transmitter cur : scheduledTransmitters) {
			result.addAll(schedule.getByTransmitterId(cur.getId()));
		}
		return result;
	}

	public synchronized void disableTransmitter(Transmitter transmitter) {
		if (removeTransmitter(transmitter.getId())) {
			reschedule();
			LOG.info("[{}] rescheduled", id);
		}
	}

	private Transmitter findById(String id) {
		for (Transmitter cur : scheduledTransmitters) {
			if (cur.getId().equals(id)) {
				return cur;
			}
		}
		return null;
	}

	public synchronized void removeAllTransmitters() {
		for (Transmitter cur : scheduledTransmitters) {
			schedule.cancelByTransmitter(cur.getId());
		}
		scheduledTransmitters.clear();
	}

	private boolean removeTransmitter(String id) {
		boolean removed = false;
		Iterator<Transmitter> it = scheduledTransmitters.iterator();
		while (it.hasNext()) {
			Transmitter cur = it.next();
			if (cur.getId().equalsIgnoreCase(id)) {
				removed = true;
				it.remove();
				break;
			}
		}
		return removed;
	}

	public DeviceStatus getStatus() {
		DeviceStatus result = new DeviceStatus();
		result.setConfig(deviceConfiguration);
		if (rotatorService != null) {
			result.setRotatorStatus(rotatorService.getStatus());
		} else {
			RotatorStatus rotatorStatus = new RotatorStatus();
			rotatorStatus.setStatus(DeviceConnectionStatus.DISABLED);
			result.setRotatorStatus(rotatorStatus);
		}
		return result;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: cpu/base_dyn_inst.hh File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

File List

File Members

cpu/base_dyn_inst.hh File Reference
Defines a dynamic instruction context. More...

#include <bitset>

#include <list>

#include <string>

#include <queue>

#include "arch/utility.hh"

#include "base/trace.hh"

#include "config/the_isa.hh"

#include "cpu/checker/cpu.hh"

#include "cpu/o3/comm.hh"

#include "cpu/exec_context.hh"

#include "cpu/exetrace.hh"

#include "cpu/inst_seq.hh"

#include "cpu/op_class.hh"

#include "cpu/static_inst.hh"

#include "cpu/translation.hh"

#include "mem/packet.hh"

#include "sim/byteswap.hh"

#include "sim/fault_fwd.hh"

#include "sim/system.hh"

#include "sim/tlb.hh"

Go to the source code of this file.

Classes

class  	BaseDynInst< Impl >

union  	BaseDynInst< Impl >::Result

Detailed Description

Defines a dynamic instruction context.

Definition in file base_dyn_inst.hh.
<address style="align: right;">
Generated on Fri Apr 17 12:39:06 2015 for gem5 by  doxygen 1.4.7</address>

redpajama_set_name: RedPajamaGithub


text:
Coodit Symfony2 Sandbox
========================

Go to your local sandbox `/app_dev.php`.


text:
package org.apache.airavata.client.impl;

import org.apache.airavata.client.api.OutputDataSettings;

public class ApplicationOutputDataSettingsImpl implements OutputDataSettings {
	private String nodeId;
	private String outputDataDirectory;
	private String dataRegistry;
	private Boolean dataPersistent;

	public ApplicationOutputDataSettingsImpl(String nodeId) {
		this(nodeId, null,null,null);
	}

	public ApplicationOutputDataSettingsImpl(String nodeId, String outputDataDirectory, String dataRegistryUrl, Boolean dataPersistent) {
		setNodeId(nodeId);
		setOutputDataDirectory(outputDataDirectory);
		setDataRegistryUrl(dataRegistryUrl);
		setDataPersistent(dataPersistent);
	}

	@Override
	public String getOutputDataDirectory() {
		return outputDataDirectory;
	}

	@Override
	public String getDataRegistryUrl() {
		return dataRegistry;
	}

	@Override
	public Boolean isDataPersistent() {
		return dataPersistent;
	}

	@Override
	public void setOutputDataDirectory(String outputDataDirectory) {
		this.outputDataDirectory=outputDataDirectory;
	}

	@Override
	public void setDataRegistryUrl(String dataRegistryUrl) {
		this.dataRegistry=dataRegistryUrl;
	}

	@Override
	public void setDataPersistent(Boolean isDataPersistance) {
		this.dataPersistent=isDataPersistance;
	}

	@Override
	public void resetOutputDataDirectory() {
		this.outputDataDirectory=null;
	}

	@Override
	public void resetDataRegistryUrl() {
		this.dataRegistry=null;
	}

	@Override
	public void resetDataPersistent() {
		this.dataPersistent=null;
	}

	@Override
	public String getNodeId() {
		return nodeId;
	}

	@Override
	public void setNodeId(String nodeId) {
		this.nodeId=nodeId;
	}

}


text:
package com.fatcoder.cordova.stomp;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Represents all the data in a STOMP frame.
 *
 * @author chirino
 */
public class StompFrame {// implements Command {

	public static final byte[] NO_DATA = new byte[] {};

	private String action;
	private Map<String, String> headers = new HashMap<String, String>();
	private byte[] content = NO_DATA;

	public static void main(String[] args) {

		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("destination", "A");
		StompFrame frame = new StompFrame("UNSUBSCRIBE", headers);
		System.out.print("-------------------");
		System.out.print(frame.format());
	}

	public StompFrame(String command) {
		this(command, null, null);
	}

	public StompFrame(String command, Map<String, String> headers) {
		this(command, headers, null);
	}

	public StompFrame(String command, Map<String, String> headers, byte[] data) {
		this.action = command;
		if (headers != null)
			this.headers = headers;
		if (data != null)
			this.content = data;
	}

	public StompFrame() {
	}

	public String getAction() {
		return action;
	}

	public void setAction(String command) {
		this.action = command;
	}

	public byte[] getContent() {
		return content;
	}

	public String getBody() {
		try {
			return new String(content, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return new String(content);
		}
	}

	public void setContent(byte[] data) {
		this.content = data;
	}

	public Map<String, String> getHeaders() {
		return headers;
	}

	public void setHeaders(Map<String, String> headers) {
		this.headers = headers;
	}

	//
	// Methods in the Command interface
	//
	public int getCommandId() {
		return 0;
	}

	// public Endpoint getFrom() {
	// return null;
	// }
	//
	// public Endpoint getTo() {
	// return null;
	// }

	public boolean isBrokerInfo() {
		return false;
	}

	public boolean isMessage() {
		return false;
	}

	public boolean isMessageAck() {
		return false;
	}

	public boolean isMessageDispatch() {
		return false;
	}

	public boolean isMessageDispatchNotification() {
		return false;
	}

	public boolean isResponse() {
		return false;
	}

	public boolean isResponseRequired() {
		return false;
	}

	public boolean isShutdownInfo() {
		return false;
	}

	public boolean isConnectionControl() {
		return false;
	}

	public boolean isWireFormatInfo() {
		return false;
	}

	public void setCommandId(int value) {
	}

	// public void setFrom(Endpoint from) {
	// }
	//
	// public void setResponseRequired(boolean responseRequired) {
	// }
	//
	// public void setTo(Endpoint to) {
	// }
	//
	// public Response visit(CommandVisitor visitor) throws Exception {
	// return null;
	// }

	public byte getDataStructureType() {
		return 0;
	}

	public boolean isMarshallAware() {
		return false;
	}

	public String toString() {
		return format(true);
	}

	public String format() {
		return format(false);
	}

	public String format(boolean forLogging) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(getAction());
		buffer.append("\n");
		Map headers = getHeaders();
		for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			buffer.append(entry.getKey());
			buffer.append(":");
			if (forLogging
					&& entry.getKey().toString().toLowerCase()
							.contains(Stomp.Headers.Connect.PASSCODE)) {
				buffer.append("*****");
			} else {
				buffer.append(entry.getValue());
			}
			buffer.append("\n");
		}
		buffer.append("\n");
		if (getContent() != null) {
			try {
				String contentString = new String(getContent(), "UTF-8");
				// if (forLogging) {
				// contentString = MarshallingSupport.truncate64(contentString);
				// }
				buffer.append(contentString);
			} catch (Throwable e) {
				buffer.append(Arrays.toString(getContent()));
			}
		}
		return buffer.toString();
	}
}


text:
layout: default
title: History
permalink: /History/
---
### History

Michael Knoedler (1823–1878), 1859. Photo: Courtesy Getty Research Institute, Los Angeles.

The Gallery was originally established as a branch of Paris' Goupil et Cie Gallery. However, the founder, Michel Knoedler, quickly realized the potential of the American market. He decided to capitalize on it, buying out Goupil's New York branch after ten years. The newly formed Knoedler Gallery transitioned from specializing in French Salon paintings, the crux of the art market industry, to exploring the relatively new field of Old Masters and American artists. With notable clients such as [the Astors](http://www.britannica.com/topic/Astor-family), [the Vanderbilts](https://en.wikipedia.org/wiki/Vanderbilt_family), [J.P. Morgan](http://www.themorgan.org/about/pierpont-morgan-collector/1), [Henry Clay Frick](http://www.frick.org/collection/history/henry_clay_frick) and others, [Knoedler stock books](http://primo.getty.edu/GRI:GETTY_ALMA21129976460001551) read like a veritable who's who of late 19th- and early 20th-century American society.

### Influence

It's hard to overestimate the influence the gallery had on the burgeoning art market in New York and throughout the country. While the Knoedler Gallery was not alone in changing the landscape of the art market (see also [Duveen](http://primo.getty.edu/GRI:GETTY_ALMA21124730440001551)), it was easily the major supplier to the United States.

### Records

The gallery's records constitute the history of taste, the art market, collecting, patronage, artists and works of art throughout the world. After the closure of the gallery in the early 2010's the Getty Research Institute (GRI) acquired all of the stock books. Previously, the archive was housed in the New York office, inaccessible and not widely available for study. Once acquired, the GRI began processing and readying the archive for digitization. As of June 2015, six out of the eleven series of archives are online, free and open to pursue for future scholarship and reference.

### Dealer Stock Book Database

In the fall of 2014, the Getty Research Institute's Project for the Study of Collecting and Provenance launched the Knoedler section of the Dealer Stock Book Database that previously included only Goupil. Hand-written entries from stock books one through six have been transcribed by Provenance Index editors and carefully enhanced with subject classifications. Artists, sellers, and buyers are standardized according to an authority database. Every day, hundreds of records are created or edited with extensive metadata. This resource allows for numerous research opportunities.


text:
from pydons import MatStruct
import numpy as np
import random

MAX_INT = 1000000
MAX_FLOAT = 1e9
REL_THRESH = 1e-12

def sgn():
    return random.randint(0, 1) * 2 - 1

def randint(abs_min=1):
    return random.randint(abs_min, MAX_INT) * sgn()

def randfloat(abs_min=REL_THRESH, abs_max=MAX_FLOAT):
    return (random.random() + abs_min) * abs_max * sgn()

def test_diff_self():
    d = MatStruct()

    d.field_a = 'field a'
    d.field_b = 10
    d.field_c = np.random.rand(3, 4)

    ddiff = d.diff(d)

    assert ddiff.diff_norm == 0
    assert ddiff.diff_max == 0
    assert ddiff.diff_uncomparable == 0

def test_diff_numbers():
    d = MatStruct()
    d.int = randint(1)
    d.float = randfloat()

    dd = MatStruct()
    dd.int = randint(1)
    dd.float = randfloat()

    ddiff = d.diff(dd, rel_norm_thold=REL_THRESH)

    assert ddiff.int == abs(float(d.int - dd.int)) / abs(d.int)
    assert ddiff.float == abs(d.float - dd.float) / abs(d.float)
    assert ddiff.diff_norm == (ddiff.int + ddiff.float) / 2
    assert ddiff.diff_max == max(ddiff.int, ddiff.float)
    assert ddiff.diff_uncomparable == 0

def test_diff_small_numbers():
    d = MatStruct()
    d.int = 0
    d.float = randfloat(0, 0.9 * REL_THRESH)

    dd = MatStruct()
    dd.int = randint(1)
    dd.float = randfloat()

    ddiff = d.diff(dd)

    assert ddiff.int == abs(float(d.int - dd.int))
    assert ddiff.float == abs(d.float - dd.float)
    assert ddiff.diff_norm == (ddiff.int + ddiff.float) / 2
    assert ddiff.diff_max == max(ddiff.int, ddiff.float)
    assert ddiff.diff_uncomparable == 0


text:
<?php

// $Id$

import('search.SearchFileParser');

class SearchHelperParser extends SearchFileParser {

	/** @var $type string Type should match an index[$type] setting in the "search" section of config.inc.php */
	var $type;

	function SearchHelperParser($type, $filePath) {
		parent::SearchFileParser($filePath);
		$this->type = $type;
	}

	function open() {
		$prog = Config::getVar('search', 'index[' . $this->type . ']');

		if (isset($prog)) {
			$exec = sprintf($prog, escapeshellcmd($this->getFilePath()));
			$this->fp = @popen($exec, 'r');
			return $this->fp ? true : false;
		}

		return false;
	}

	function close() {
		pclose($this->fp);
	}
}

?>


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

package com.google.api.ads.admanager.jaxws.v202211;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ProgrammaticError.Reason.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="ProgrammaticError.Reason">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="AUDIENCE_EXTENSION_NOT_SUPPORTED"/>
 *     <enumeration value="AUTO_EXTENSION_DAYS_NOT_SUPPORTED"/>
 *     <enumeration value="VIDEO_NOT_SUPPORTED"/>
 *     <enumeration value="ROADBLOCKING_NOT_SUPPORTED"/>
 *     <enumeration value="INVALID_CREATIVE_ROTATION"/>
 *     <enumeration value="INVALID_LINE_ITEM_TYPE"/>
 *     <enumeration value="INVALID_COST_TYPE"/>
 *     <enumeration value="SIZE_NOT_SUPPORTED"/>
 *     <enumeration value="ZERO_COST_PER_UNIT_NOT_SUPPORTED"/>
 *     <enumeration value="CANNOT_UPDATE_FIELD_FOR_APPROVED_LINE_ITEMS"/>
 *     <enumeration value="CANNOT_CREATE_LINE_ITEM_FOR_APPROVED_ORDER"/>
 *     <enumeration value="CANNOT_UPDATE_BACKFILL_WEB_PROPERTY_FOR_APPROVED_LINE_ITEMS"/>
 *     <enumeration value="COST_PER_UNIT_TOO_LOW"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "ProgrammaticError.Reason")
@XmlEnum
public enum ProgrammaticErrorReason {

    /**
     *
     *                 Audience extension is not supported by programmatic line items.
     *
     *
     */
    AUDIENCE_EXTENSION_NOT_SUPPORTED,

    /**
     *
     *                 Auto extension days is not supported by programmatic line items.
     *
     *
     */
    AUTO_EXTENSION_DAYS_NOT_SUPPORTED,

    /**
     *
     *                 Video is currently not supported.
     *
     *
     */
    VIDEO_NOT_SUPPORTED,

    /**
     *
     *                 Roadblocking is not supported by programmatic line items.
     *
     *
     */
    ROADBLOCKING_NOT_SUPPORTED,

    /**
     *
     *                 Programmatic line items do not support {@link CreativeRotationType#SEQUENTIAL}.
     *
     *
     */
    INVALID_CREATIVE_ROTATION,

    /**
     *
     *                 Programmatic line items only support {@link LineItemType#STANDARD} and
     *                 {@link LineItemType#SPONSORSHIP} if the relevant feature is on.
     *
     *
     */
    INVALID_LINE_ITEM_TYPE,

    /**
     *
     *                 Programmatic line items only support {@link CostType#CPM}.
     *
     *
     */
    INVALID_COST_TYPE,

    /**
     *
     *                 Programmatic line items only support a creative size that is supported by AdX.
     *                 The list of supported sizes is maintained based on the list published in the help docs:
     *
     *                 https://support.google.com/adxseller/answer/1100453
     *
     *
     */
    SIZE_NOT_SUPPORTED,

    /**
     *
     *                 Zero cost per unit is not supported by programmatic line items.
     *
     *
     */
    ZERO_COST_PER_UNIT_NOT_SUPPORTED,

    /**
     *
     *                 Some fields cannot be updated on approved line items.
     *
     *
     */
    CANNOT_UPDATE_FIELD_FOR_APPROVED_LINE_ITEMS,

    /**
     *
     *                 Creating a new line item in an approved order is not allowed.
     *
     *
     */
    CANNOT_CREATE_LINE_ITEM_FOR_APPROVED_ORDER,

    /**
     *
     *                 Cannot change backfill web property for a programmatic line item whose order has been
     *                 approved.
     *
     *
     */
    CANNOT_UPDATE_BACKFILL_WEB_PROPERTY_FOR_APPROVED_LINE_ITEMS,

    /**
     *
     *                 Cost per unit is too low. It has to be at least 0.005 USD.
     *
     *
     */
    COST_PER_UNIT_TOO_LOW,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static ProgrammaticErrorReason fromValue(String v) {
        return valueOf(v);
    }

}


text:
import urlparse, urllib

__all__ = ['Query', 'URL']

class Query(object):
    """ Parses passed query string with urlparse.parse_qs and provides
    mapping methods for updating query parameters.

    Interpolates query with urllib.urlencode.
    """

    def __init__(self, query=''):
        self._params = urlparse.parse_qs(query)

    def __repr__(self):
        return repr(self._params)

    def __str__(self):
        return urllib.urlencode(self._params, doseq=True)

    def __getitem__(self, item):
        val = self._params[item]
        if isinstance(val, list) and len(val) == 1:
            return val[0]
        else:
            return val

    def __setitem__(self, item, val):
        if not isinstance(val, list):
            val = [val]
        self._params[item] = val

    def __iter__(self):
        for k in self._params:
            yield self._params[k]

    def __len__(self):
        return len(self._params)

    def keys(self):
        return self._params.keys()

    def update(self, mapping):
        # TODO validation of values in mapping, they must not be nested mappings
        self._params.update(mapping)

class URL(object):
    """Parses passed URL with urlparse.urlparse, exposes writable
    attributes named after urlparse.ParseResult fields:
    - scheme
    - netloc
    - path
    - params
    - query
    - fragment

    query attribute is Query instance.
    """

    _fields = urlparse.ParseResult._fields

    def __init__(self, url):
        for field, value in zip(self._fields, urlparse.urlparse(url)):
            setattr(self, field, value)

    @property
    def query(self):
        return self._query

    @query.setter
    def query(self, value):
        if isinstance(value, Query):
            self._query = value
        else:
            self._query = Query(value)

    def __str__(self):
        return urlparse.urlunparse(str(s) for s in self)

    def __getitem__(self, field_idx):
        if isinstance(field_idx, slice):
            return [getattr(self, field) for field in self._fields[field_idx]]
        else:
            return getattr(self, self._fields[field_idx])

    def __setitem__(self, field_idx, val):
        if isinstance(field_idx, slice):
            for field in self._fields[field_idx]:
                setattr(self, field, val)
        else:
            setattr(self, self._fields[field_idx], val)

    def __iter__(self):
        for field in self._fields:
            yield getattr(self, field)

    def __len__(self):
        return len(self._fields)


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/product_trmm_111.dir/product_trmm.cpp.o"
  "product_trmm_111.pdb"
  "product_trmm_111"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/product_trmm_111.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
title: Backend modules searchbackend
category: architecture
authors: amuller
wiki_category: Architecture
wiki_title: Backend modules searchbackend
wiki_revision_count: 2
wiki_last_updated: 2013-02-13
---

# Backend modules searchbackend

**Introduction:** searchbackend implements the search bar at the top of the GUI. You may search for entities and their relationships in a domain specific language, which is translated into an appropriate SQL query. In addition to being used to implement the search bar, the module is used to display the GUI's main tabs. The user can see the query that was ran when a tab was clicked.

For more information see [Introducing_Entity_Search](Development/Introducing_Entity_Search).


text:
using CustomerManager.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace CustomerManager.Repository
{
    public class CustomerManagerContext : DbContext
    {
        public CustomerManagerContext()
        {
            Configuration.ProxyCreationEnabled = false;
            Configuration.LazyLoadingEnabled = false;
        }

        // DEVELOPMENT ONLY: initialize the database
        static CustomerManagerContext()
        {
            Database.SetInitializer(new CustomerManagerDatabaseInitializer());
        }

        public DbSet<Customer> Customers { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<State> States { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VineScript.Binding;
using VineScript.Core;

namespace VineScript.Lib
{
    public class Date
    {
        [VineBinding]
        public static VineVar CurrentDateTime()
        {
            return DateTime.Now.ToString();
        }

        [VineBinding]
        public static VineVar CurrentDateTime(string format)
        {
            return DateTime.Now.ToString(format);
        }

        [VineBinding]
        public static VineVar CurrentDate()
        {
            return DateTime.Today.ToShortDateString();
        }

        [VineBinding]
        public static VineVar CurrentDateLong()
        {
            return DateTime.Today.ToLongDateString();
        }

        [VineBinding]
        public static VineVar CurrentTime()
        {
            return DateTime.Now.ToShortTimeString();
        }

        [VineBinding]
        public static VineVar CurrentTimeLong()
        {
            return DateTime.Now.ToLongTimeString();
        }

        [VineBinding]
        public static VineVar MonthDay()
        {
            return DateTime.Today.Day;
        }

        [VineBinding]
        public static VineVar Weekday()
        {
            return DateTime.Today.DayOfWeek.ToString();
        }
    }
}


text:
package org.bndtools.rt.http.test;

import java.util.concurrent.atomic.AtomicBoolean;

import junit.framework.TestCase;

public abstract class AbstractDelayedTest extends TestCase {

	private static final AtomicBoolean initialised = new AtomicBoolean(false);

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		boolean needToWait = initialised.compareAndSet(false, true);
		if (needToWait) {
			System.out.println("Tests1 waiting 3 seconds for system to settle.");
			Thread.sleep(3000);
			System.out.println("Waiting done, proceeding with tests");
		}
	}

}


text:
package uk.ac.ebi.subs.api.services;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import uk.ac.ebi.subs.data.component.Submitter;
import uk.ac.ebi.subs.data.component.Team;
import uk.ac.ebi.subs.data.status.SubmissionStatusEnum;
import uk.ac.ebi.subs.repository.model.Submission;
import uk.ac.ebi.subs.repository.model.SubmissionStatus;
import uk.ac.ebi.subs.repository.repos.SubmissionRepository;
import uk.ac.ebi.subs.validator.data.SingleValidationResult;
import uk.ac.ebi.subs.validator.data.ValidationResult;
import uk.ac.ebi.subs.validator.data.structures.GlobalValidationStatus;
import uk.ac.ebi.subs.validator.data.structures.SingleValidationResultStatus;
import uk.ac.ebi.subs.validator.data.structures.ValidationAuthor;
import uk.ac.ebi.subs.validator.repository.ValidationResultRepository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

/**
 * Created by karoly on 11/07/2017.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@EnableMongoRepositories(basePackageClasses = { ValidationResultRepository.class, SubmissionRepository.class })
@EnableAutoConfiguration
@SpringBootTest(classes = ValidationResultService.class)
public class ValidationResultServiceTest {

    @Autowired
    private ValidationResultRepository validationResultRepository;

    @Autowired
    private SubmissionRepository submissionRepository;

    private ValidationResultService validationResultService;

    private static String SUCCESSFUL_SUBMISSION_ID = "1111";
    private static String SUBMISSION_WITH_UNFINISHED_VALIDATION_ID = "2222";
    private static String SUBMISSION_WITH_NOT_PASSED_VALIDATION_ID = "3333";
    private static String SUCCESSFUL_SUBMISSION_STATUS_ID = "5678";
    private static String NOT_PASSED_SUBMISSION_STATUS_ID = "8765";
    private static int SIZE_OF_ENTITIES_BY_VALID_SUBMISSION_ID = 5;
    private static String[] ENTITY_UUIDS = {"11", "22", "33", "44", "55", "66", "77", "88"};

    @Before
    public void setup() {
        validationResultRepository = spy(ValidationResultRepository.class);
        submissionRepository = mock(SubmissionRepository.class);

        validationResultService = new ValidationResultServiceImpl(validationResultRepository, submissionRepository);

        when(validationResultRepository.findAllBySubmissionId(eq(SUCCESSFUL_SUBMISSION_ID)))
                .thenReturn(generateValidationResults(SIZE_OF_ENTITIES_BY_VALID_SUBMISSION_ID, SUCCESSFUL_SUBMISSION_ID)
        );
    }

    @Test
    public void whenSubmissionIdIsValidThanGotBackAListOfValidationResults() {
        assertThat(validationResultService.getValidationResultBySubmissionId(SUCCESSFUL_SUBMISSION_ID).size(),
                is(equalTo(SIZE_OF_ENTITIES_BY_VALID_SUBMISSION_ID)));
    }

    @Test
    public void whenValidationNotFinishedShouldReturnFalse() {
        Submission submission_with_not_finished_validation = createSubmission(SUBMISSION_WITH_UNFINISHED_VALIDATION_ID, SUCCESSFUL_SUBMISSION_STATUS_ID);

        when(submissionRepository.findBySubmissionStatusId(SUCCESSFUL_SUBMISSION_STATUS_ID))
                .thenReturn(submission_with_not_finished_validation);

        assertThat(validationResultService.isValidationFinishedAndPassed(submission_with_not_finished_validation.getSubmissionStatus().getId()),
                    is(equalTo(false)));
    }

    @Test
    public void whenValidationFinishedButNotAllPassedShouldReturnFalse() {
        Submission submission_with_not_passed_validation = createSubmission(SUBMISSION_WITH_NOT_PASSED_VALIDATION_ID, NOT_PASSED_SUBMISSION_STATUS_ID);

        List<ValidationResult> results = generateValidationResults(1, SUBMISSION_WITH_NOT_PASSED_VALIDATION_ID);
        addSingleValidationResult(results.get(0), ValidationAuthor.Taxonomy, SingleValidationResultStatus.Pass);
        addSingleValidationResult(results.get(0), ValidationAuthor.Biosamples, SingleValidationResultStatus.Error);
        results.get(0).setValidationStatus(GlobalValidationStatus.Complete);

        when(submissionRepository.findBySubmissionStatusId(NOT_PASSED_SUBMISSION_STATUS_ID))
                .thenReturn(submission_with_not_passed_validation);
        when(validationResultRepository.findAllBySubmissionId(eq(SUBMISSION_WITH_NOT_PASSED_VALIDATION_ID)))
                .thenReturn(results);

        assertThat(validationResultService.isValidationFinishedAndPassed(submission_with_not_passed_validation.getSubmissionStatus().getId()),
                is(equalTo(false)));
    }

    @Test
    public void whenValidationFinishedAndAllPassedShouldReturnTrue() {
        Submission submission_with_successful_validation = createSubmission(SUCCESSFUL_SUBMISSION_ID, SUCCESSFUL_SUBMISSION_STATUS_ID);

        List<ValidationResult> results = generateValidationResults(1, SUCCESSFUL_SUBMISSION_ID);
        addSingleValidationResult(results.get(0), ValidationAuthor.Taxonomy, SingleValidationResultStatus.Pass);
        addSingleValidationResult(results.get(0), ValidationAuthor.Biosamples, SingleValidationResultStatus.Pass);
        results.get(0).setValidationStatus(GlobalValidationStatus.Complete);

        when(submissionRepository.findBySubmissionStatusId(SUCCESSFUL_SUBMISSION_STATUS_ID))
                .thenReturn(submission_with_successful_validation);
        when(validationResultRepository.findAllBySubmissionId(eq(SUCCESSFUL_SUBMISSION_ID)))
                .thenReturn(results);

        assertThat(validationResultService.isValidationFinishedAndPassed(submission_with_successful_validation.getSubmissionStatus().getId()),
                is(equalTo(true)));

    }

    private List<ValidationResult> generateValidationResults(int numberOfValidationResults, String submissionId) {
        Map<ValidationAuthor, List<SingleValidationResult>> validationAuthorListMap = new HashMap<>();
        validationAuthorListMap.put(ValidationAuthor.Taxonomy, new ArrayList<>());
        validationAuthorListMap.put(ValidationAuthor.Biosamples, new ArrayList<>());

        List<ValidationResult> results = new ArrayList<>();
        for (int i = 0; i < numberOfValidationResults; i++) {
            ValidationResult validationResult = new ValidationResult();
            validationResult.setUuid(UUID.randomUUID().toString());
            validationResult.setExpectedResults(validationAuthorListMap);
            validationResult.setVersion(1);
            validationResult.setSubmissionId(submissionId);
            validationResult.setEntityUuid(ENTITY_UUIDS[i]);
            validationResult.setValidationStatus(GlobalValidationStatus.Pending);

            results.add(validationResult);
        }

        return results;
    }

    private void addSingleValidationResult(ValidationResult validationResult, ValidationAuthor validationAuthor,
                                           SingleValidationResultStatus validationStatus) {
        SingleValidationResult singleValidationResult = new SingleValidationResult(validationAuthor, validationResult.getEntityUuid());
        singleValidationResult.setValidationStatus(validationStatus);

        validationResult.getExpectedResults().put(validationAuthor, Collections.singletonList(singleValidationResult));
    }

    private Submission createSubmission(String submissionId, String submissionStatusId) {
        Submission submission = new Submission();
        submission.setId(submissionId);
        submission.setSubmitter(Submitter.build("submitter@email.com"));
        submission.setVersion(1L);
        submission.setTeam(Team.build("team name"));

        SubmissionStatus submissionStatus = new SubmissionStatus();
        submissionStatus.setStatus(SubmissionStatusEnum.Draft);
        submissionStatus.setId(submissionStatusId);

        submission.setSubmissionStatus(submissionStatus);

        return submission;
    }
}


text:
extern crate uni;

use uni::io::Read;
use uni::io::stdin;

use uni::string::String;

#[start]
fn main(_: isize, _: *const *const u8) -> isize {
    println!("Reading terminal to echo what you type");

    loop {
        let mut v = vec![0; 10];

        let stdin = stdin();
        let mut stdin_locked = stdin.lock();

        stdin_locked.read(&mut v[..]).unwrap();

        println!("Read: {}", String::from_utf8(v).unwrap());
    }
}


text:
<!DOCTYPE html>

    <title>Test MediaSource behavior when the decoder is starved.</title>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
    <meta name="timeout" content="long">
    <link rel="author" title="Alicia Boya García" href="mailto:aboya@igalia.com"/>