text:
package org.gridchem.client;

// XML imports.
import com.microstar.xml.XmlException;

//////////////////////////////////////////////////////////////////////////
//// PlotMLParser
/**
This class constructs a plot from specifications
in PlotML (Plot Markup Language), which is an XML language.
This class supports extends the base class to
support the subset that applies to the Plot class.
It ignores unrecognized elements in the DTD.
The class contains an instance of the Microstar Ælfred XML
parser and implements callback methods to interpret the parsed XML.
The way to use this class is to construct it with a reference to
a Plot object and then call its parse() method.

@author Edward A. Lee
@version $Id: PlotMLParser.java,v 1.2 2005/05/14 23:51:01 xli16 Exp $
@since Ptolemy II 0.4
*/
public class PlotMLParser extends PlotBoxMLParser {

    /** Construct an parser to parse commands for the specified plot object.
     *  @param plot The plot object to which to apply the commands.
     */
    public PlotMLParser(Plot plot) {
        super(plot);
    }

    /** Protected constructor allows derived classes to set _plot
     *  differently.
     */
    protected PlotMLParser() {}

    ///////////////////////////////////////////////////////////////////
    ////                         public methods                    ////

    /** End an element. This method
     *  calls the appropriate Plot methods.
     *  Ælfred will call this method at the end of each element
     *  (including EMPTY elements).
     *  @param elementName The element type name.
     */
    public void endElement(String elementName) throws Exception {
        super.endElement(elementName);

        if (elementName.equals("dataset")) {
            // Reset the default, in case it was changed for this dataset.
            ((Plot)_plot).setConnected(_connected);
        }
    }

    /** Start a document.  This method is called just before the parser
     *  attempts to read the first entity (the root of the document).
     *  It is guaranteed that this will be the first method called.
     */
    public void startDocument() {
        super.startDocument();
        _currentDataset = -1;
        _currentPointCount = 0.0;
    }

    /** Start an element.
     *  This is called at the beginning of each XML
     *  element.  By the time it is called, all of the attributes
     *  for the element will already have been reported using the
     *  attribute() method.  Unrecognized elements are ignored.
     *  @param elementName The element type name.
     *  @exception XmlException If the element produces an error
     *   in constructing the model.
     */
    public void startElement(String elementName) throws XmlException {
        try {
            // NOTE: The elements are alphabetical below...

            if (elementName.equals("barGraph")) {
                String widthSpec = (String)_attributes.get("width");
                String offsetSpec = (String)_attributes.get("offset");
                // NOTE: If only one of these is given, then the other
                // is ignored.
                if (widthSpec == null || offsetSpec == null) {
                    ((Plot)_plot).setBars(true);
                } else {
                    double width = (Double.valueOf(widthSpec)).doubleValue();
                    double offset = (Double.valueOf(offsetSpec)).doubleValue();
                    ((Plot)_plot).setBars(width, offset);
                }

            } else if (elementName.equals("dataset")) {
                String name = (String)_attributes.get("name");

                if (!((Plot)_plot).getReuseDatasets()
                        || name == null
                        || _currentDataset < 0 ) {
                    // reuseDatasets was not present or if it was,
                    // the current dataset does not have a name
                    // or we have not yet seen a dataset.
                    _currentDataset++;
                    _currentPointCount = 0.0;
                } else {
                    // reuseDatasets was set to true and name is not null.
                    int possibleDataset = ((Plot)_plot).getLegendDataset(name);
                    if (possibleDataset != -1) {
                        _currentDataset = possibleDataset;
                    } else {
                        // Did not yet have a dataset with that name.
                        _currentDataset++;
                        _currentPointCount = 0.0;
                    }
                }

                if (name != null) {
                    ((Plot)_plot).addLegend(_currentDataset, name);
                }

                String connected = (String)_attributes.get("connected");
                if (connected != null) {
                    if (connected.equals("no")) {
                        ((Plot)_plot).setConnected(false, _currentDataset);
                    } else {
                        ((Plot)_plot).setConnected(true, _currentDataset);
                    }
                }

                String marks = (String)_attributes.get("marks");
                if (marks != null) {
                    ((Plot)_plot).setMarksStyle(marks, _currentDataset);
                }

                String stems = (String)_attributes.get("stems");
                if (stems != null) {
                    if (stems.equals("yes")) {
                        ((Plot)_plot).setImpulses(true, _currentDataset);
                    } else {
                        ((Plot)_plot).setImpulses(false, _currentDataset);
                    }
                }

            } else if (elementName.equals("default")) {

                String connected = (String)_attributes.get("connected");
                if (connected.equals("yes")) {
                    ((Plot)_plot).setConnected(true);
                    _connected = true;
                } else {
                    ((Plot)_plot).setConnected(false);
                    _connected = false;
                }

                String marks = (String)_attributes.get("marks");
                if (marks != null) {
                    ((Plot)_plot).setMarksStyle(marks);
                }

                String stems = (String)_attributes.get("stems");
                if (stems.equals("no")) {
                    ((Plot)_plot).setImpulses(false);
                } else {
                    ((Plot)_plot).setImpulses(true);
                }

            } else if (elementName.equals("m")) {
                _addPoint(false, elementName);

            } else if (elementName.equals("move")) {
                _addPoint(false, elementName);

            } else if (elementName.equals("p")) {
                _addPoint(true, elementName);

            } else if (elementName.equals("point")) {
                _addPoint(true, elementName);

            } else if (elementName.equals("reuseDatasets")) {
                ((Plot)_plot).setReuseDatasets(true);
            } else {
                super.startElement(elementName);
            }
        } catch (Exception ex) {
            if (ex instanceof XmlException) {
                throw (XmlException)ex;
            } else {
                // FIXME: Temporary for debugging.
                System.err.println(ex.toString());
                ex.printStackTrace();
                String msg = "XML element \"" + elementName
                    + "\" triggers exception:\n  " + ex.toString();
                throw new XmlException(msg,
                        _currentExternalEntity(),
                        _parser.getLineNumber(),
                        _parser.getColumnNumber());
            }
        }
        // NOTE: if super is called, this gets done twice.
        // Any way to avoid it?
        _attributes.clear();
    }

    ///////////////////////////////////////////////////////////////////
    ////                         protected members                 ////

    /** The default connected state. */
    protected boolean _connected = true;

    /** The current dataset number in a "dataset" element. */
    protected int _currentDataset = -1;

    /** A count within the current dataset, in case no x value is given. */
    protected double _currentPointCount = 0.0;

    ///////////////////////////////////////////////////////////////////
    ////                         protected methods                 ////

    /** Add a point based on the current attributes.
     *  If the first argument is true, connect it to the previous point.
     *  The second argument is the element name, used for error reporting.
     *  @param connected If true, connect to the previous point.
     *  @param element The name of the element.
     */
    protected void _addPoint(boolean connected, String element)
            throws Exception {
        String xSpec = (String)_attributes.get("x");
        double x;
        if (xSpec == null) {
            // No x value given.  Use _currentPointCount.
            x = _currentPointCount;
            _currentPointCount += 1.0;
        } else {
            // NOTE: Do not use parseDouble() to maintain
            // Java 1.1 compatibility.
            x = (Double.valueOf(xSpec)).doubleValue();
        }

        String ySpec = (String)_attributes.get("y");
        _checkForNull(ySpec, "No y value for element \"" + element + "\"");
        // NOTE: Do not use parseDouble() to maintain Java 1.1 compatibility.
        double y = (Double.valueOf(ySpec)).doubleValue();

        String lowSpec = (String)_attributes.get("lowErrorBar");
        String highSpec = (String)_attributes.get("highErrorBar");
        if (lowSpec == null && highSpec == null) {
            ((Plot)_plot).addPoint(_currentDataset, x, y, connected);
        } else {
            double low, high;
            if (lowSpec != null) {
                low = (Double.valueOf(lowSpec)).doubleValue();
            } else {
                low = x;
            }
            if (highSpec != null) {
                high = (Double.valueOf(highSpec)).doubleValue();
            } else {
                high = x;
            }
            ((Plot)_plot).addPointWithErrorBars(_currentDataset, x, y,
                    low, high, connected);
        }
    }
}


text:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import Footer from "../../components/Footer";
import Navbar from "../../components/Navbar";
import Bloglist from "../../components/Bloglist";

class Home extends Component {
	componentWillMount() {
		document.title = "Joe Nyugoh";
	}
	render() {
		const blogs = this.props.blogs;
		return (

				<Navbar/>

				<Bloglist blogs={blogs}/>

				<Link to={'/admin/blogs'}>///</Link>

		);
	}
}

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

export default connect(mapStateToProps)(Home);

redpajama_set_name: RedPajamaGithub


text:
// A tiny web server that serves a static file.
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
)

var (
	port = flag.Int("port", 80, "Port number.")
)

func main() {
	flag.Parse()

	fs := http.StripPrefix("/", http.FileServer(http.Dir("/")))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "private")
		// Needed for local proxy to Kubernetes API server to work.
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type")
		// Disable If-Modified-Since so update-demo isn't broken by 304s
		r.Header.Del("If-Modified-Since")
		fs.ServeHTTP(w, r)
	})

	go log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))

	select {}
}


text:
use std::cmp::Ordering;
use std::collections::HashMap;

use reqwest;

// Use our internal types module.
use config::Configuration;
use renderer;
use types;

// Endpoint for REST communication with the Todoist.
static TODOIST_API: &'static str = "https://todoist.com/API/v7/sync";

/// Used to specify what resources to fetch from the server.
/// It should be a JSON-encoded array of strings.
///
/// Here is a list of available resource types:
/// -  labels,
/// -  projects,
/// -  items,
/// -  notes,
/// -  filters,
/// -  reminders,
/// -  locations,
/// -  user,
/// -  `live_notifications`,
/// -  collaborators,
/// - `notification_settings`
///
enum TodrResourceType {
    Items,
    Projects,
}

fn to_resource_type(resource_type: &TodrResourceType) -> String {
    let resource = match resource_type {
        TodrResourceType::Items => String::from("items"),
        TodrResourceType::Projects => String::from("projects"),
    };

    format!("[\"{}\"]", &resource)
}

fn execute_request(
    resource_type: &TodrResourceType,
) -> Result<reqwest::blocking::Response, reqwest::Error> {
    // Fetch the token from the users environment.
    let auth_token = Configuration::api_token();

    // Map the resource type to the proper string.
    let resource_string = to_resource_type(resource_type);

    // Setup the request parameters.
    //
    // See the API documentation available for the full
    // list of parameters, their values and what they do.
    //
    // Link: https://developer.todoist.com/sync/v8/?shell
    //
    let sync_token: String = "*".to_string();
    let all_data: String = "true".to_string();
    let mut params = HashMap::new();
    params.insert("token", &auth_token);
    params.insert("sync_token", &sync_token);
    params.insert("resource_types", &resource_string);
    params.insert("all_data", &all_data);

    let client = reqwest::blocking::Client::new();

    // Issue the request.
    client.get(TODOIST_API).query(&params).send()
}

//
// Request response handler implementations.
//

fn process_error(error: &reqwest::Error) {
    println!("{}", error);
}

fn common_response_handler(response: &mut reqwest::blocking::Response) {
    // Only print these traces in debug mode.
    if cfg!(debug_assertions) {
        println!("Headers:\n{:?}", response.headers());
    }
}

fn process_response_items(mut response: reqwest::blocking::Response) {
    common_response_handler(&mut response);

    let sync_state: types::SyncStruct = response
        .json()
        .expect("Failed to de-serialize JSON response");

    let mut items = sync_state.items.expect("Failed to parse items JSON");

    // Sort the items by their server order.
    let custom_sort = |a: &types::ItemStruct, b: &types::ItemStruct| {
        let item_order_sort = a.item_order.cmp(&b.item_order);
        let project_order_sort = a.project_id.cmp(&b.project_id);

        // item_order values are only unique per project, so if we want to
        // display items in the correct order we need to sort by project
        // groupings first, and then sort by item order.
        if project_order_sort == Ordering::Equal {
            item_order_sort
        } else {
            project_order_sort
        }
    };

    items.sort_by(custom_sort);

    for item in items {
        renderer::render_item(&item);
    }
}

fn process_response_projects(mut response: reqwest::blocking::Response) {
    common_response_handler(&mut response);

    let sync_state: types::SyncStruct = response
        .json()
        .expect("Failed to deserialize json response");

    // Sort the items by their server order.
    //
    let mut projects = sync_state.projects.expect("Failed to parse projects JSON");
    projects.sort_by_key(|p| p.item_order);

    for project in projects {
        renderer::render_project(&project);
    }
}

//
// Command handler implementations.
//

pub fn items_command() {
    let response = execute_request(&TodrResourceType::Items);

    match response {
        Ok(r) => process_response_items(r),
        Err(e) => process_error(&e),
    }
}

pub fn projects_command() {
    let response = execute_request(&TodrResourceType::Projects);

    match response {
        Ok(r) => process_response_projects(r),
        Err(e) => process_error(&e),
    }
}

pub fn help_command() {
    println!();
    println!("Commands:");
    println!();
    println!("  h | help  - This help message");
    println!();
    println!("  i | items - List all active todo items.");
    println!();
    println!("  p | projs - List all active projects.");
    println!();
    println!("  q | quit  - Exit the application.");
    println!();
}

pub fn unknown_command(command: &str) {
    println!("Unknown Command: {}", command);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Observ. mycol. (Havniae) 2: 196 (1818)

#### Original name
Agaricus consobrinus var. livescens Fr.

### Remarks
null


text:
"""Run active learner on classification tasks.

Supported datasets include mnist, letter, cifar10, newsgroup20, rcv1,
wikipedia attack, and select classification datasets from mldata.
See utils/create_data.py for all available datasets.

For binary classification, mnist_4_9 indicates mnist filtered down to just 4 and
9.
By default uses logistic regression but can also train using kernel SVM.
2 fold cv is used to tune regularization parameter over a exponential grid.

"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import pickle
import sys
from time import gmtime
from time import strftime

import numpy as np
from sklearn.preprocessing import normalize
from sklearn.preprocessing import StandardScaler

from absl import app
from absl import flags
from tensorflow import gfile

from sampling_methods.constants import AL_MAPPING
from sampling_methods.constants import get_AL_sampler
from sampling_methods.constants import get_wrapper_AL_mapping
from utils import utils

flags.DEFINE_string("dataset", "letter", "Dataset name")
flags.DEFINE_string("sampling_method", "margin",
                    ("Name of sampling method to use, can be any defined in "
                     "AL_MAPPING in sampling_methods.constants"))
flags.DEFINE_float(
    "warmstart_size", 0.02,
    ("Can be float or integer.  Float indicates percentage of training data "
     "to use in the initial warmstart model")
)
flags.DEFINE_float(
    "batch_size", 0.02,
    ("Can be float or integer.  Float indicates batch size as a percentage "
     "of training data size.")
)
flags.DEFINE_integer("trials", 1,
                     "Number of curves to create using different seeds")
flags.DEFINE_integer("seed", 1, "Seed to use for rng and random state")
# TODO(lisha): add feature noise to simulate data outliers
flags.DEFINE_string("confusions", "0.", "Percentage of labels to randomize")
flags.DEFINE_string("active_sampling_percentage", "1.0",
                    "Mixture weights on active sampling.")
flags.DEFINE_string(
    "score_method", "logistic",
    "Method to use to calculate accuracy.")
flags.DEFINE_string(
    "select_method", "None",
    "Method to use for selecting points.")
flags.DEFINE_string("normalize_data", "False", "Whether to normalize the data.")
flags.DEFINE_string("standardize_data", "True",
                    "Whether to standardize the data.")
flags.DEFINE_string("save_dir", "/tmp/toy_experiments",
                    "Where to save outputs")
flags.DEFINE_string("data_dir", "/tmp/data",
                    "Directory with predownloaded and saved datasets.")
flags.DEFINE_string("max_dataset_size", "15000",
                    ("maximum number of datapoints to include in data "
                     "zero indicates no limit"))
flags.DEFINE_float("train_horizon", "1.0",
                   "how far to extend learning curve as a percent of train")
flags.DEFINE_string("do_save", "True",
                    "whether to save log and results")
FLAGS = flags.FLAGS

get_wrapper_AL_mapping()

def generate_one_curve(X,
                       y,
                       sampler,
                       score_model,
                       seed,
                       warmstart_size,
                       batch_size,
                       select_model=None,
                       confusion=0.,
                       active_p=1.0,
                       max_points=None,
                       standardize_data=False,
                       norm_data=False,
                       train_horizon=0.5):
  """Creates one learning curve for both active and passive learning.

  Will calculate accuracy on validation set as the number of training data
  points increases for both PL and AL.
  Caveats: training method used is sensitive to sorting of the data so we
    resort all intermediate datasets

  Args:
    X: training data
    y: training labels
    sampler: sampling class from sampling_methods, assumes reference
      passed in and sampler not yet instantiated.
    score_model: model used to score the samplers.  Expects fit and predict
      methods to be implemented.
    seed: seed used for data shuffle and other sources of randomness in sampler
      or model training
    warmstart_size: float or int.  float indicates percentage of train data
      to use for initial model
    batch_size: float or int.  float indicates batch size as a percent of
      training data
    select_model: defaults to None, in which case the score model will be
      used to select new datapoints to label.  Model must implement fit, predict
      and depending on AL method may also need decision_function.
    confusion: percentage of labels of one class to flip to the other
    active_p: percent of batch to allocate to active learning
    max_points: limit dataset size for preliminary
    standardize_data: wheter to standardize the data to 0 mean unit variance
    norm_data: whether to normalize the data.  Default is False for logistic
      regression.
    train_horizon: how long to draw the curve for.  Percent of training data.

  Returns:
    results: dictionary of results for all samplers
    sampler_states: dictionary of sampler objects for debugging
  """
  # TODO(lishal): add option to find best hyperparameter setting first on
  # full dataset and fix the hyperparameter for the rest of the routine
  # This will save computation and also lead to more stable behavior for the
  # test accuracy

  # TODO(lishal): remove mixture parameter and have the mixture be specified as
  # a mixture of samplers strategy
  def select_batch(sampler, uniform_sampler, mixture, N, already_selected,
                   **kwargs):
    n_active = int(mixture * N)
    n_passive = N - n_active
    kwargs["N"] = n_active
    kwargs["already_selected"] = already_selected
    batch_AL = sampler.select_batch(**kwargs)
    already_selected = already_selected + batch_AL
    kwargs["N"] = n_passive
    kwargs["already_selected"] = already_selected
    batch_PL = uniform_sampler.select_batch(**kwargs)
    return batch_AL + batch_PL

  np.random.seed(seed)
  data_splits = [2./3, 1./6, 1./6]

  # 2/3 of data for training
  if max_points is None:
    max_points = len(y)
  train_size = int(min(max_points, len(y)) * data_splits[0])
  if batch_size < 1:
    batch_size = int(batch_size * train_size)
  else:
    batch_size = int(batch_size)
  if warmstart_size < 1:
    # Set seed batch to provide enough samples to get at least 4 per class
    # TODO(lishal): switch to sklearn stratified sampler
    seed_batch = int(warmstart_size * train_size)
  else:
    seed_batch = int(warmstart_size)
  seed_batch = max(seed_batch, 6 * len(np.unique(y)))

  indices, X_train, y_train, X_val, y_val, X_test, y_test, y_noise = (
      utils.get_train_val_test_splits(X,y,max_points,seed,confusion,
                                      seed_batch, split=data_splits))

  # Preprocess data
  if norm_data:
    print("Normalizing data")
    X_train = normalize(X_train)
    X_val = normalize(X_val)
    X_test = normalize(X_test)
  if standardize_data:
    print("Standardizing data")
    scaler = StandardScaler().fit(X_train)
    X_train = scaler.transform(X_train)
    X_val = scaler.transform(X_val)
    X_test = scaler.transform(X_test)
  print("active percentage: " + str(active_p) + " warmstart batch: " +
        str(seed_batch) + " batch size: " + str(batch_size) + " confusion: " +
        str(confusion) + " seed: " + str(seed))

  # Initialize samplers
  uniform_sampler = AL_MAPPING["uniform"](X_train, y_train, seed)
  sampler = sampler(X_train, y_train, seed)

  results = {}
  data_sizes = []
  accuracy = []
  selected_inds = range(seed_batch)

  # If select model is None, use score_model
  same_score_select = False
  if select_model is None:
    select_model = score_model
    same_score_select = True

  n_batches = int(np.ceil((train_horizon * train_size - seed_batch) *
                          1.0 / batch_size)) + 1
  for b in range(n_batches):
    n_train = seed_batch + min(train_size - seed_batch, b * batch_size)
    print("Training model on " + str(n_train) + " datapoints")

    assert n_train == len(selected_inds)
    data_sizes.append(n_train)

    # Sort active_ind so that the end results matches that of uniform sampling
    partial_X = X_train[sorted(selected_inds)]
    partial_y = y_train[sorted(selected_inds)]
    score_model.fit(partial_X, partial_y)
    if not same_score_select:
      select_model.fit(partial_X, partial_y)
    acc = score_model.score(X_test, y_test)
    accuracy.append(acc)
    print("Sampler: %s, Accuracy: %.2f%%" % (sampler.name, accuracy[-1]*100))

    n_sample = min(batch_size, train_size - len(selected_inds))
    select_batch_inputs = {
        "model": select_model,
        "labeled": dict(zip(selected_inds, y_train[selected_inds])),
        "eval_acc": accuracy[-1],
        "X_test": X_val,
        "y_test": y_val,
        "y": y_train
    }
    new_batch = select_batch(sampler, uniform_sampler, active_p, n_sample,
                             selected_inds, **select_batch_inputs)
    selected_inds.extend(new_batch)
    print('Requested: %d, Selected: %d' % (n_sample, len(new_batch)))
    assert len(new_batch) == n_sample
    assert len(list(set(selected_inds))) == len(selected_inds)

  # Check that the returned indice are correct and will allow mapping to
  # training set from original data
  assert all(y_noise[indices[selected_inds]] == y_train[selected_inds])
  results["accuracy"] = accuracy
  results["selected_inds"] = selected_inds
  results["data_sizes"] = data_sizes
  results["indices"] = indices
  results["noisy_targets"] = y_noise
  return results, sampler

def main(argv):
  del argv

  if not gfile.Exists(FLAGS.save_dir):
    try:
      gfile.MkDir(FLAGS.save_dir)
    except:
      print(('WARNING: error creating save directory, '
             'directory most likely already created.'))

  save_dir = os.path.join(
      FLAGS.save_dir,
      FLAGS.dataset + "_" + FLAGS.sampling_method)
  do_save = FLAGS.do_save == "True"

  if do_save:
    if not gfile.Exists(save_dir):
      try:
        gfile.MkDir(save_dir)
      except:
        print(('WARNING: error creating save directory, '
               'directory most likely already created.'))
    # Set up logging
    filename = os.path.join(
        save_dir, "log-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) + ".txt")
    sys.stdout = utils.Logger(filename)

  confusions = [float(t) for t in FLAGS.confusions.split(" ")]
  mixtures = [float(t) for t in FLAGS.active_sampling_percentage.split(" ")]
  all_results = {}
  max_dataset_size = None if FLAGS.max_dataset_size == "0" else int(
      FLAGS.max_dataset_size)
  normalize_data = FLAGS.normalize_data == "True"
  standardize_data = FLAGS.standardize_data == "True"
  X, y = utils.get_mldata(FLAGS.data_dir, FLAGS.dataset)
  starting_seed = FLAGS.seed

  for c in confusions:
    for m in mixtures:
      for seed in range(starting_seed, starting_seed + FLAGS.trials):
        sampler = get_AL_sampler(FLAGS.sampling_method)
        score_model = utils.get_model(FLAGS.score_method, seed)
        if (FLAGS.select_method == "None" or
            FLAGS.select_method == FLAGS.score_method):
          select_model = None
        else:
          select_model = utils.get_model(FLAGS.select_method, seed)
        results, sampler_state = generate_one_curve(
            X, y, sampler, score_model, seed, FLAGS.warmstart_size,
            FLAGS.batch_size, select_model, c, m, max_dataset_size,
            standardize_data, normalize_data, FLAGS.train_horizon)
        key = (FLAGS.dataset, FLAGS.sampling_method, FLAGS.score_method,
               FLAGS.select_method, m, FLAGS.warmstart_size, FLAGS.batch_size,
               c, standardize_data, normalize_data, seed)
        sampler_output = sampler_state.to_dict()
        results["sampler_output"] = sampler_output
        all_results[key] = results
  fields = [
      "dataset", "sampler", "score_method", "select_method",
      "active percentage", "warmstart size", "batch size", "confusion",
      "standardize", "normalize", "seed"
  ]
  all_results["tuple_keys"] = fields

  if do_save:
    filename = ("results_score_" + FLAGS.score_method +
                "_select_" + FLAGS.select_method +
                "_norm_" + str(normalize_data) +
                "_stand_" + str(standardize_data))
    existing_files = gfile.Glob(os.path.join(save_dir, filename + "*.pkl"))
    filename = os.path.join(save_dir,
                            filename + "_" + str(1000+len(existing_files))[1:] + ".pkl")
    pickle.dump(all_results, gfile.GFile(filename, "w"))
    sys.stdout.flush_file()

if __name__ == "__main__":
  app.run(main)


text:
package org.robolectric;

import javax.annotation.Generated;

import org.robolectric.annotation.processing.objects.Dummy;
import org.robolectric.annotation.processing.objects.ParameterizedDummy;
import org.robolectric.annotation.processing.shadows.ShadowDummy;
import org.robolectric.annotation.processing.shadows.ShadowParameterizedDummy;
import org.robolectric.bytecode.RobolectricInternals;
import org.robolectric.bytecode.ShadowWrangler;

@Generated("org.robolectric.annotation.processing.RoboProcessor")
public class RobolectricBase {

  public static final Class<?>[] DEFAULT_SHADOW_CLASSES = {
    ShadowDummy.class,
    ShadowParameterizedDummy.class
  };

  public static ShadowDummy shadowOf(Dummy actual) {
    return (ShadowDummy) shadowOf_(actual);
  }

  public static <T, N extends Number> ShadowParameterizedDummy<T,N> shadowOf(ParameterizedDummy<T,N> actual) {
    return (ShadowParameterizedDummy)<T,N> shadowOf_(actual);
  }

  public static void reset() {
    ShadowDummy.resetter_method();
  }

  public static ShadowWrangler getShadowWrangler() {
    return ((ShadowWrangler) RobolectricInternals.getClassHandler());
  }

  @SuppressWarnings({"unchecked"})
  public static <P, R> P shadowOf_(R instance) {
    return (P) getShadowWrangler().shadowOf(instance);
  }
}


text:
from __future__ import division,print_function
import math, os, json, sys, re
import pickle
#import cPickle as pickle
from glob import glob
import numpy as np
from matplotlib import pyplot as plt
from operator import itemgetter, attrgetter, methodcaller
from collections import OrderedDict
import itertools
from itertools import chain

import pandas as pd
import PIL
from PIL import Image
from numpy.random import random, permutation, randn, normal, uniform, choice
from numpy import newaxis
import scipy
from scipy import misc, ndimage
from scipy.ndimage.interpolation import zoom
from scipy.ndimage import imread
from sklearn.metrics import confusion_matrix
import bcolz
from sklearn.preprocessing import OneHotEncoder
from sklearn.manifold import TSNE

from IPython.lib.display import FileLink

import theano
from theano import shared, tensor as T
from theano.tensor.nnet import conv2d, nnet
from theano.tensor.signal import pool

import keras
from keras import backend as K
from keras.utils.data_utils import get_file
from keras.utils import np_utils
from keras.utils.np_utils import to_categorical
from keras.models import Sequential, Model
from keras.layers import Input, Embedding, Reshape, merge, LSTM, Bidirectional
from keras.layers import TimeDistributed, Activation, SimpleRNN, GRU
from keras.layers.core import Flatten, Dense, Dropout, Lambda
from keras.regularizers import l2, activity_l2, l1, activity_l1
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD, RMSprop, Adam
from keras.utils.layer_utils import layer_from_config
from keras.metrics import categorical_crossentropy, categorical_accuracy
from keras.layers.convolutional import *
from keras.preprocessing import image, sequence
from keras.preprocessing.text import Tokenizer

from vgg16 import *
from vgg16bn import *
np.set_printoptions(precision=4, linewidth=100)

to_bw = np.array([0.299, 0.587, 0.114])
def gray(img):
    return np.rollaxis(img,0,3).dot(to_bw)
def to_plot(img):
    return np.rollaxis(img, 0, 3).astype(np.uint8)
def plot(img):
    plt.imshow(to_plot(img))

def floor(x):
    return int(math.floor(x))
def ceil(x):
    return int(math.ceil(x))

def plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):
    if type(ims[0]) is np.ndarray:
        ims = np.array(ims).astype(np.uint8)
        if (ims.shape[-1] != 3):
            ims = ims.transpose((0,2,3,1))
    f = plt.figure(figsize=figsize)
    for i in range(len(ims)):
        sp = f.add_subplot(rows, len(ims)//rows, i+1)
        if titles is not None:
            sp.set_title(titles[i], fontsize=18)
        plt.imshow(ims[i], interpolation=None if interp else 'none')

def do_clip(arr, mx):
    clipped = np.clip(arr, (1-mx)/1, mx)
    return clipped/clipped.sum(axis=1)[:, np.newaxis]

def get_batches(dirname, gen=image.ImageDataGenerator(), shuffle=True, batch_size=4, class_mode='categorical',
                target_size=(224,224)):
    return gen.flow_from_directory(dirname, target_size=target_size,
            class_mode=class_mode, shuffle=shuffle, batch_size=batch_size)

def onehot(x):
    return to_categorical(x)

def wrap_config(layer):
    return {'class_name': layer.__class__.__name__, 'config': layer.get_config()}

def copy_layer(layer): return layer_from_config(wrap_config(layer))

def copy_layers(layers): return [copy_layer(layer) for layer in layers]

def copy_weights(from_layers, to_layers):
    for from_layer,to_layer in zip(from_layers, to_layers):
        to_layer.set_weights(from_layer.get_weights())

def copy_model(m):
    res = Sequential(copy_layers(m.layers))
    copy_weights(m.layers, res.layers)
    return res

def insert_layer(model, new_layer, index):
    res = Sequential()
    for i,layer in enumerate(model.layers):
        if i==index: res.add(new_layer)
        copied = layer_from_config(wrap_config(layer))
        res.add(copied)
        copied.set_weights(layer.get_weights())
    return res

def adjust_dropout(weights, prev_p, new_p):
    scal = (1-prev_p)/(1-new_p)
    return [o*scal for o in weights]

def get_data(path, target_size=(224,224)):
    batches = get_batches(path, shuffle=False, batch_size=1, class_mode=None, target_size=target_size)
    return np.concatenate([batches.next() for i in range(batches.nb_sample)])

def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    (This function is copied from the scikit docs.)
    """
    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    print(cm)
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

def save_array(fname, arr):
    c=bcolz.carray(arr, rootdir=fname, mode='w')
    c.flush()

def load_array(fname):
    return bcolz.open(fname)[:]

def mk_size(img, r2c):
    r,c,_ = img.shape
    curr_r2c = r/c
    new_r, new_c = r,c
    if r2c>curr_r2c:
        new_r = floor(c*r2c)
    else:
        new_c = floor(r/r2c)
    arr = np.zeros((new_r, new_c, 3), dtype=np.float32)
    r2=(new_r-r)//2
    c2=(new_c-c)//2
    arr[floor(r2):floor(r2)+r,floor(c2):floor(c2)+c] = img
    return arr

def mk_square(img):
    x,y,_ = img.shape
    maxs = max(img.shape[:2])
    y2=(maxs-y)//2
    x2=(maxs-x)//2
    arr = np.zeros((maxs,maxs,3), dtype=np.float32)
    arr[floor(x2):floor(x2)+x,floor(y2):floor(y2)+y] = img
    return arr

def vgg_ft(out_dim):
    vgg = Vgg16()
    vgg.ft(out_dim)
    model = vgg.model
    return model

def vgg_ft_bn(out_dim):
    vgg = Vgg16BN()
    vgg.ft(out_dim)
    model = vgg.model
    return model

def get_classes(path):
    batches = get_batches(path+'train', shuffle=False, batch_size=1)
    val_batches = get_batches(path+'valid', shuffle=False, batch_size=1)
    test_batches = get_batches(path+'test', shuffle=False, batch_size=1)
    return (val_batches.classes, batches.classes, onehot(val_batches.classes), onehot(batches.classes),
        val_batches.filenames, batches.filenames, test_batches.filenames)

def split_at(model, layer_type):
    layers = model.layers
    layer_idx = [index for index,layer in enumerate(layers)
                 if type(layer) is layer_type][-1]
    return layers[:layer_idx+1], layers[layer_idx+1:]

class MixIterator(object):
    def __init__(self, iters):
        self.iters = iters
        self.multi = type(iters) is list
        if self.multi:
            self.N = sum([it[0].N for it in self.iters])
        else:
            self.N = sum([it.N for it in self.iters])

    def reset(self):
        for it in self.iters: it.reset()

    def __iter__(self):
        return self

    def next(self, *args, **kwargs):
        if self.multi:
            nexts = [[next(it) for it in o] for o in self.iters]
            n0s = np.concatenate([n[0] for n in o])
            n1s = np.concatenate([n[1] for n in o])
            return (n0, n1)
        else:
            nexts = [next(it) for it in self.iters]
            n0 = np.concatenate([n[0] for n in nexts])
            n1 = np.concatenate([n[1] for n in nexts])
            return (n0, n1)


text:
gfile = "genotypes.txt" # genotype data
mfile = "markers.txt"   # list of markers, in order
ffile = "families.txt"  # family information
ofile = "data.gen"      # output file

def read_markers (filename)
  File.open(filename).readlines.map {|str| str.strip}
end

class Person
  attr_accessor :family, :id, :dad, :mom, :sex, :famid, :gen
  def initialize (family, id, dad, mom, sex)
    @family = family
    @id = id
    @dad = dad
    @mom = mom
    @sex = sex
    @sex = "0" if @sex == "2" # convert from 1/2 to 1/0
    @famid = "#{family}-#{id}"
    @gen = {}
  end
end

# read family info and return a hash of people
def read_families (filename)
  file = File.open(filename)
  file.readline # header row
  people = {}
  file.readlines.each do |line|
    vals = line.strip.split(/\s+/) # strip removes leading and ending white space
    person = Person.new(*vals)     # *vals makes vals elements separate arguments
    people[person.famid] = person
  end
  people
end

# clean up string - > genotype
def parse_genotype (string)
  string = string.gsub(/\s/, "")
  string = "0/0" if string == ""
  string.sub(/\//, " ")
end

# read genotype data, fill in genotypes within people hash
def read_genotypes (filename, people)
  file = File.open(filename)

  header = file.readline.strip.split(/\s+/)
  header.shift # omit the first field, "Marker"

  file.readlines.each do |line|
    marker = line[0..8].gsub(/\s/, "")
    line = line[9..-1]
    header.each_with_index do |person, i|
      start = i*7
      people[person].gen[marker] = parse_genotype line[start..(start+6)]
    end
  end
end

# distinct families
def get_families (people)
  people.keys.map {|id| id.split(/\-/)[0]}.uniq
end

# people within a family
def get_family_members (people, family)
  people.select { |key,person| person.family == family }
end

def write_genfile (filename, people, markers)
  file = File.open(filename, "w")

  families = get_families(people)
  file.write("#{families.length}\n")

  file.write("#{markers.length}\n")
  markers.each {|marker| file.write(marker + "\n") }

  families.each do |family|
    file.write("#{family}\n")
    members = get_family_members(people, family)
    file.write("#{members.length}\n")

    members.each do |key,person|
      file.write("#{person.id} #{person.mom} #{person.dad} #{person.sex}\n")

      markers.each do |marker|
        file.write(person.gen[marker] + " ")
      end
      file.write("\n")
    end
  end
end

# read the data
markers = read_markers(mfile)
people = read_families(ffile)
read_genotypes(gfile, people)

# write the data
write_genfile(ofile, people, markers)


text:
from pyvisdk.thirdparty import Enum

DistributedVirtualPortgroupPortgroupType = Enum(
    'earlyBinding',
    'ephemeral',
    'lateBinding',

)


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package org.apache.hadoop.hbase.thrift (HBase 0.98.7-hadoop2 API)</title>
<meta name="date" content="2014-10-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.apache.hadoop.hbase.thrift

Packages that use org.apache.hadoop.hbase.thrift

Package
Description

org.apache.hadoop.hbase.thrift

Provides an HBase Thrift
service.

org.apache.hadoop.hbase.thrift2

Provides an HBase Thrift
service.

Classes in org.apache.hadoop.hbase.thrift used by org.apache.hadoop.hbase.thrift

Class and Description

CallQueue.Call

IncrementCoalescerMBean

MetricsThriftServerSource

Interface of a class that will export metrics about Thrift to hadoop's metrics2.

MetricsThriftServerSourceFactory

Factory that will be used to create metrics sources for the two diffent types of thrift servers.

TBoundedThreadPoolServer.Args

ThriftMetrics

This class is for maintaining the various statistics of thrift server
 and publishing them through the metrics interfaces.

ThriftMetrics.ThriftServerType

ThriftServerRunner.HBaseHandler

The HBaseHandler is a glue object that connects Thrift RPC calls to the
 HBase client API primarily defined in the HBaseAdmin and HTable objects.

ThriftServerRunner.ResultScannerWrapper

Classes in org.apache.hadoop.hbase.thrift used by org.apache.hadoop.hbase.thrift2

Class and Description

ThriftMetrics

This class is for maintaining the various statistics of thrift server
 and publishing them through the metrics interfaces.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 The Apache Software Foundation. All rights reserved.


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>R-Index</title>
<meta name="date" content="2015-10-13">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A D E F I L M P R S

R

reflectAttributeValues(int, ReflectedAttributes, byte[]) - Method in class edu.nps.moves.RprFomFederateAmbassador

RprFomFederate - Class in edu.nps.moves

The RrpFomFederate is an example federate that uses the RPR-FOM.

RprFomFederate() - Constructor for class edu.nps.moves.RprFomFederate

RprFomFederateAmbassador - Class in edu.nps.moves

RprFomFederateAmbassador(RprFomFederate) - Constructor for class edu.nps.moves.RprFomFederateAmbassador

RUN_SYNC_POINT - Static variable in class edu.nps.moves.RprFomFederate

runFederate(String, short) - Method in class edu.nps.moves.RprFomFederate

This is the main simulation loop.

A D E F I L M P R S

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    using Google.Api.Gax;
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using lro = Google.LongRunning;

    /// Generated snippets.
    public sealed class AllGeneratedInterconnectsClientSnippets
    {
        /// Snippet for Delete
        public void DeleteRequestObject()
        {
            // Snippet: Delete(DeleteInterconnectRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            DeleteInterconnectRequest request = new DeleteInterconnectRequest
            {
                RequestId = "",
                Interconnect = "",
                Project = "",
            };
            // Make the request
            lro::Operation<Operation, Operation> response = interconnectsClient.Delete(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = interconnectsClient.PollOnceDelete(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for DeleteAsync
        public async Task DeleteRequestObjectAsync()
        {
            // Snippet: DeleteAsync(DeleteInterconnectRequest, CallSettings)
            // Additional: DeleteAsync(DeleteInterconnectRequest, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            DeleteInterconnectRequest request = new DeleteInterconnectRequest
            {
                RequestId = "",
                Interconnect = "",
                Project = "",
            };
            // Make the request
            lro::Operation<Operation, Operation> response = await interconnectsClient.DeleteAsync(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await interconnectsClient.PollOnceDeleteAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for Delete
        public void Delete()
        {
            // Snippet: Delete(string, string, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            // Make the request
            lro::Operation<Operation, Operation> response = interconnectsClient.Delete(project, interconnect);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = interconnectsClient.PollOnceDelete(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for DeleteAsync
        public async Task DeleteAsync()
        {
            // Snippet: DeleteAsync(string, string, CallSettings)
            // Additional: DeleteAsync(string, string, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            // Make the request
            lro::Operation<Operation, Operation> response = await interconnectsClient.DeleteAsync(project, interconnect);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await interconnectsClient.PollOnceDeleteAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for Get
        public void GetRequestObject()
        {
            // Snippet: Get(GetInterconnectRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            GetInterconnectRequest request = new GetInterconnectRequest
            {
                Interconnect = "",
                Project = "",
            };
            // Make the request
            Interconnect response = interconnectsClient.Get(request);
            // End snippet
        }

        /// Snippet for GetAsync
        public async Task GetRequestObjectAsync()
        {
            // Snippet: GetAsync(GetInterconnectRequest, CallSettings)
            // Additional: GetAsync(GetInterconnectRequest, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            GetInterconnectRequest request = new GetInterconnectRequest
            {
                Interconnect = "",
                Project = "",
            };
            // Make the request
            Interconnect response = await interconnectsClient.GetAsync(request);
            // End snippet
        }

        /// Snippet for Get
        public void Get()
        {
            // Snippet: Get(string, string, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            // Make the request
            Interconnect response = interconnectsClient.Get(project, interconnect);
            // End snippet
        }

        /// Snippet for GetAsync
        public async Task GetAsync()
        {
            // Snippet: GetAsync(string, string, CallSettings)
            // Additional: GetAsync(string, string, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            // Make the request
            Interconnect response = await interconnectsClient.GetAsync(project, interconnect);
            // End snippet
        }

        /// Snippet for GetDiagnostics
        public void GetDiagnosticsRequestObject()
        {
            // Snippet: GetDiagnostics(GetDiagnosticsInterconnectRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest
            {
                Interconnect = "",
                Project = "",
            };
            // Make the request
            InterconnectsGetDiagnosticsResponse response = interconnectsClient.GetDiagnostics(request);
            // End snippet
        }

        /// Snippet for GetDiagnosticsAsync
        public async Task GetDiagnosticsRequestObjectAsync()
        {
            // Snippet: GetDiagnosticsAsync(GetDiagnosticsInterconnectRequest, CallSettings)
            // Additional: GetDiagnosticsAsync(GetDiagnosticsInterconnectRequest, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest
            {
                Interconnect = "",
                Project = "",
            };
            // Make the request
            InterconnectsGetDiagnosticsResponse response = await interconnectsClient.GetDiagnosticsAsync(request);
            // End snippet
        }

        /// Snippet for GetDiagnostics
        public void GetDiagnostics()
        {
            // Snippet: GetDiagnostics(string, string, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            // Make the request
            InterconnectsGetDiagnosticsResponse response = interconnectsClient.GetDiagnostics(project, interconnect);
            // End snippet
        }

        /// Snippet for GetDiagnosticsAsync
        public async Task GetDiagnosticsAsync()
        {
            // Snippet: GetDiagnosticsAsync(string, string, CallSettings)
            // Additional: GetDiagnosticsAsync(string, string, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            // Make the request
            InterconnectsGetDiagnosticsResponse response = await interconnectsClient.GetDiagnosticsAsync(project, interconnect);
            // End snippet
        }

        /// Snippet for Insert
        public void InsertRequestObject()
        {
            // Snippet: Insert(InsertInterconnectRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            InsertInterconnectRequest request = new InsertInterconnectRequest
            {
                RequestId = "",
                Project = "",
                InterconnectResource = new Interconnect(),
            };
            // Make the request
            lro::Operation<Operation, Operation> response = interconnectsClient.Insert(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = interconnectsClient.PollOnceInsert(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for InsertAsync
        public async Task InsertRequestObjectAsync()
        {
            // Snippet: InsertAsync(InsertInterconnectRequest, CallSettings)
            // Additional: InsertAsync(InsertInterconnectRequest, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            InsertInterconnectRequest request = new InsertInterconnectRequest
            {
                RequestId = "",
                Project = "",
                InterconnectResource = new Interconnect(),
            };
            // Make the request
            lro::Operation<Operation, Operation> response = await interconnectsClient.InsertAsync(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await interconnectsClient.PollOnceInsertAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for Insert
        public void Insert()
        {
            // Snippet: Insert(string, Interconnect, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            Interconnect interconnectResource = new Interconnect();
            // Make the request
            lro::Operation<Operation, Operation> response = interconnectsClient.Insert(project, interconnectResource);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = interconnectsClient.PollOnceInsert(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for InsertAsync
        public async Task InsertAsync()
        {
            // Snippet: InsertAsync(string, Interconnect, CallSettings)
            // Additional: InsertAsync(string, Interconnect, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            Interconnect interconnectResource = new Interconnect();
            // Make the request
            lro::Operation<Operation, Operation> response = await interconnectsClient.InsertAsync(project, interconnectResource);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await interconnectsClient.PollOnceInsertAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for List
        public void ListRequestObject()
        {
            // Snippet: List(ListInterconnectsRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            ListInterconnectsRequest request = new ListInterconnectsRequest
            {
                OrderBy = "",
                Project = "",
                Filter = "",
                ReturnPartialSuccess = false,
            };
            // Make the request
            PagedEnumerable<InterconnectList, Interconnect> response = interconnectsClient.List(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Interconnect item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (InterconnectList page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Interconnect item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Interconnect> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Interconnect item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListAsync
        public async Task ListRequestObjectAsync()
        {
            // Snippet: ListAsync(ListInterconnectsRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            ListInterconnectsRequest request = new ListInterconnectsRequest
            {
                OrderBy = "",
                Project = "",
                Filter = "",
                ReturnPartialSuccess = false,
            };
            // Make the request
            PagedAsyncEnumerable<InterconnectList, Interconnect> response = interconnectsClient.ListAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Interconnect item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((InterconnectList page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Interconnect item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Interconnect> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Interconnect item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for List
        public void List()
        {
            // Snippet: List(string, string, int?, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            // Make the request
            PagedEnumerable<InterconnectList, Interconnect> response = interconnectsClient.List(project);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Interconnect item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (InterconnectList page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Interconnect item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Interconnect> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Interconnect item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListAsync
        public async Task ListAsync()
        {
            // Snippet: ListAsync(string, string, int?, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            // Make the request
            PagedAsyncEnumerable<InterconnectList, Interconnect> response = interconnectsClient.ListAsync(project);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Interconnect item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((InterconnectList page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Interconnect item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Interconnect> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Interconnect item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for Patch
        public void PatchRequestObject()
        {
            // Snippet: Patch(PatchInterconnectRequest, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            PatchInterconnectRequest request = new PatchInterconnectRequest
            {
                RequestId = "",
                Interconnect = "",
                Project = "",
                InterconnectResource = new Interconnect(),
            };
            // Make the request
            lro::Operation<Operation, Operation> response = interconnectsClient.Patch(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = interconnectsClient.PollOncePatch(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for PatchAsync
        public async Task PatchRequestObjectAsync()
        {
            // Snippet: PatchAsync(PatchInterconnectRequest, CallSettings)
            // Additional: PatchAsync(PatchInterconnectRequest, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            PatchInterconnectRequest request = new PatchInterconnectRequest
            {
                RequestId = "",
                Interconnect = "",
                Project = "",
                InterconnectResource = new Interconnect(),
            };
            // Make the request
            lro::Operation<Operation, Operation> response = await interconnectsClient.PatchAsync(request);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await interconnectsClient.PollOncePatchAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for Patch
        public void Patch()
        {
            // Snippet: Patch(string, string, Interconnect, CallSettings)
            // Create client
            InterconnectsClient interconnectsClient = InterconnectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            Interconnect interconnectResource = new Interconnect();
            // Make the request
            lro::Operation<Operation, Operation> response = interconnectsClient.Patch(project, interconnect, interconnectResource);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = interconnectsClient.PollOncePatch(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }

        /// Snippet for PatchAsync
        public async Task PatchAsync()
        {
            // Snippet: PatchAsync(string, string, Interconnect, CallSettings)
            // Additional: PatchAsync(string, string, Interconnect, CancellationToken)
            // Create client
            InterconnectsClient interconnectsClient = await InterconnectsClient.CreateAsync();
            // Initialize request argument(s)
            string project = "";
            string interconnect = "";
            Interconnect interconnectResource = new Interconnect();
            // Make the request
            lro::Operation<Operation, Operation> response = await interconnectsClient.PatchAsync(project, interconnect, interconnectResource);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = await interconnectsClient.PollOncePatchAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
    }
}


text:
package com.tinkerpop.blueprints.pgm.impls.rdf.impls;

import com.tinkerpop.blueprints.BaseTest;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class MemoryStoreRdfGraphTest extends BaseTest {

    public void testConstructMemoryStore() {
        new MemoryStoreRdfGraph();
    }
}


text:
namespace Cars.Tests.JustMock
{
    using Cars.Models;

    public class CarChild : Car
    {
        // not big deal but have constructor
        public CarChild(int id = 0, string make = null, string model = null, int year = 0)
        {
            this.Id = id;
            this.Make = make;
            this.Model = model;
            this.Year = year;
        }
    }
}


text:
require '2017-04-24-preview/generated/azure_mgmt_consumption'
require '2017-11-30/generated/azure_mgmt_consumption'
require '2017-12-30-preview/generated/azure_mgmt_consumption'
require '2018-01-31/generated/azure_mgmt_consumption'
require '2018-03-31/generated/azure_mgmt_consumption'
require '2018-05-31/generated/azure_mgmt_consumption'
require '2018-06-30/generated/azure_mgmt_consumption'
require '2018-11-01-preview/generated/azure_mgmt_consumption'
require '2019-04-01-preview/generated/azure_mgmt_consumption'
require '2019-05-01/generated/azure_mgmt_consumption'
require '2019-05-01-preview/generated/azure_mgmt_consumption'
require '2019-06-01/generated/azure_mgmt_consumption'
require '2019-10-01/generated/azure_mgmt_consumption'
require 'profiles/latest/consumption_latest_profile_client'


text:
require 'json'

class Order
  class SellOrBuyNotGivenError < StandardError; end
  class UnitHasAlreadyGivenError < StandardError; end

  attr_reader :price, :unit

  def initialize(price, unit)
    @price = price
    @unit = unit
  end

  def to_h
    {
      price: @price,
      unit: @unit,
      sell_or_buy: sell_or_buy
    }
  end

  def to_json
    to_h.to_json
  end

  def bid_or_ask
    case sell_or_buy&.to_sym
    when :sell
      :bid
    when :buy
      :ask
    else
      raise SellOrBuyNotGivenError
    end
  end

  def buy?
    raise NotImplementedError
  end

  def sell?
    raise NotImplementedError
  end

  def unit=(units)
    raise UnitHasAlreadyGivenError if @unit
    @unit = units
  end

  class << self
    def create_from_json(json_string)
      j = JSON.parse(json_string, symbolize_names: true)
      klass = get_sell_or_buy_class_by_name(j[:sell_or_buy])
      klass.new(j[:price], j[:unit])
    end

    def verbs
      raise NotImplementedError
    end

    def all_verbs
      [Order::Buy.verbs, Order::Sell.verbs].flatten
    end

    private

    def get_sell_or_buy_class_by_name(sell_or_buy)
      case sell_or_buy&.to_sym
      when :sell
        Order::Sell
      when :buy
        Order::Buy
      else
        raise SellOrBuyNotGivenError
      end
    end
  end
end


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="robots" content="noindex, nofollow">

  <title>Check out our top YA books for Refugee Week 2018 – Suffolk Libraries</title>

	<meta name="twitter:card" content="summary_large_image">
	<meta name="twitter:site" content="@suffolklibrary">
	<meta name="twitter:title" content="Check out our top YA books for Refugee Week 2018">
	<meta name="twitter:description" content="18 - 24 June 2018 is Refugee Week. We've picked out some of our best Young Adult titles about displacement.">
	<meta name="twitter:image" content="/images/featured/featured-young-adult-refugee-week-2018.jpg">
	<meta name="twitter:image:alt" content="Now is the Time for Running, After Tomorrow, Asylum">

  <link rel="stylesheet" href="/css/style.css">
	<link rel="preload" as="font" type="font/woff2" href="/fonts/source-sans-pro-v11-latin-regular.woff2">
	<link rel="preload" as="font" type="font/woff2" href="/fonts/source-sans-pro-v11-latin-italic.woff2">
	<link rel="preload" as="font" type="font/woff2" href="/fonts/source-sans-pro-v11-latin-700.woff2">

Skip to content

Skip to navigation menu

💳 You can now pay online.
	Pay charges now →

Donate

Join

Login

Search

Home

eLibrary

Online events

Help

Contact

    Home

      → New suggestions

      → Young adult

      → Check out our top YA books for Refugee Week 2018

Check out our top YA books for Refugee Week 2018

  Written by Sophie Green · Published Jun 18, 2018

Boy 87, by Ele Fountain

"Shif is just an ordinary schoolboy who loves chess and playing with his best friend. But, one day, he is forced to leave home to avoid conscription into the army. He embarks on an epic journey, in which he encounters dangers and cruelties - and great acts of human kindness - as he bravely makes his way to a future he can only imagine."

The Bone Sparrow, by Zana Fraillon

"Subhi is a refugee. Born in a detention centre, all he knows of the world is that he's at least 19 fence diamonds high, that the nice jackets never stay long, and at night the sea finds its way to his tent, bringing with it unusual treasures. Bringing him Jimmie.

"Jimmie lives on the Outside. Carrying a notebook that she's unable to read and wearing a sparrow made out of bone around her neck - both talismans of her family's past and the mother she's lost - she strikes up an unlikely friendship with Subhi across the fence. As he reads aloud the tale of how Jimmie's family came to be, both children discover the importance of their own stories in writing their futures."

Welcome to Nowhere, by Elizabeth Laird

"12-year-old Omar and his brothers and sisters were born and raised in the beautiful and bustling city of Bosra, Syria. Omar doesn't care about politics - all he wants is to grow up to become a successful businessman who will take the world by storm. But when his clever older brother, Musa, gets mixed up with some young political activists, everything changes. Before long, bombs are falling, people are dying, and Omar and his family have no choice but to flee their home with only what they can carry.

"Yet no matter how far they run, the shadow of war follows them - until they have no other choice than to attempt the dangerous journey to escape their homeland altogether. But where do you go when you can't go home?"

A Dangerous Crossing, by Jane Mitchell

"Ghalib doesn't want to leave his home in Syria. But the city has become too dangerous, and his family has no choice but to flee. Together they make their way through Syria to the Turkish border, where Ghalib gets separated from his family. Stricken with grief and fear, fighting cold, pain and hunger, he manages to make it to a refugee camp in Turkey.

"Ghalib is safe for now, but life in a refugee camp is wretched and hopeless, and this boy's journey in search of safety is far from over."

Salt to the Sea, by Ruta Sepetys

"It's early 1945 and a group of people trek across Germany, bound together by their desperation to reach the ship that can take them away from the war-ravaged land. Four young people, each haunted by their own dark secret, narrate their unforgettable stories.

"This novel is based on a true story from the Second World War. When the German ship the Wilhelm Gustloff was sunk in port in early 1945 it had over 9000 civilian refugees, including children, on board. Nearly all were drowned."

Read Ann's review of Salt to the Sea →

Alpha: Abidjan to Gare du Nord, by Bessora, Barroux & Sarah Ardizzone (trans.)

"Alpha Coulibaly is emblematic of the refugee crisis today - just one of millions on the move, at the mercy of people traffickers, endlessly frustrated, endangered and exploited as he attempts to rejoin his family already in Europe. With a visa, Alpha's journey would take a matter of hours; without one he is adrift for 18 months. Along the way he meets an unforgettable cast of characters, each one giving another human face to the crisis."

After Tomorrow, by Gillian Cross

"Money is worthless. Armed robbers roam the streets. No one is safe. Matt and his little brother, Taco, escape through the Channel Tunnel. Their mother said they would be safe on the other side. She was wrong."

Now is the Time for Running, by Michael Williams

"Meet Deo, a great footballer and a fierce protector of his older brother. When the soldiers come, they destroy the only home they've ever known. Now, Deo has nothing but his brother, and a football stuffed with billions of worthless dollars. And so starts their journey to find their father."

The Bombs That Brought Us Together, by Brian Conaghan

"14-year-old Charlie Law has lived in Little Town, on the border with Old Country, all his life. He knows the rules: no going out after dark; no drinking; no litter; no fighting. You don't want to get on the wrong side of the people who run Little Town.

"When he meets Pavel Duda, a refugee from Old Country, the rules start to get broken. Then the bombs come, and the soldiers from Old Country, and Little Town changes for ever. Sometimes, to keep the people you love safe, you have to do bad things. As Little Town's rules crumble, Charlie is sucked into a dangerous game. There's a gun, and a bad man, and his closest friend, and his dearest enemy. Charlie Law wants to keep everyone happy, even if it kills him. And maybe it will."

The Weight of Water, by Sarah Crossan

"Armed with a suitcase and an old laundry bag filled with clothes, Kasienka and her mother leave Poland and head for the UK to find her father. Life is lonely for Kasienka. At home her mother's heart is breaking and at school Kasienka finds it impossible to make new friends."

Here I Stand: stories that stand for freedom, by Amnesty International (ed.)

"A varied and thought-provoking collection of short stories and poems for teens with a conscience, with striking cover illustrations by award-winning children's laureate Chris Riddell. With contributions from Frances Hardinge, Sarah Crossan, Matt Haig, Neil Gaiman and many more."

Read Emma's review of Here I Stand →

Jackdaw Summer, by David Almond

"Every summer Liam and Max roam the wild countryside of Northumberland - but this year things are different. One hot summer's day a jackdaw leads the two boys into an ancient farm house where they find a baby, wrapped in a blanket, with a scribbled note pinned to it."

Refugee Boy, by Benjamin Zephaniah

"A victim of the war between Ethiopia and Eritrea, Alem finds himself alone in England, abandoned by his parents. This story charts his fate as he is moved from children's home to foster home, and in and out of court hearings."

Asylum, by Rachel Anderson

"15-year-old Sunday wanted was a country that was democratic and respectful of human life, but all Rosa wants is somewhere safe, away from the bad things of the past. Through the eyes of these two young asylum seekers, this story explores ideas of Britain and belonging."

Threads, by Sophia Bennett

"Nonie, Edie and Jenny are best friends with very individual tastes. But when the three friends meet a young African refugee called Crow, sketching a dress at the Victoria and Albert Museum, they discover a common passion and somehow find a way to make all of their dreams come true."

Mosi's War, by Cathy McPhail

"Patrick is happy living with his mum. Then Patrick meets Mosi, a quiet, polite boy who, along with his parents, is waiting for his asylum application to be processed. He discovers Mosi is terrified of someone. But who is it?

"Patrick and Mosi strike up an unlikely friendship. In trying to help each other, they will face situations that are both terrifying and dangerous. And Patrick will find out that there is much, much more to Mosi than at first appears."

The Jungle, by Pooja Puri

"Mico has left his family, his home, his future. Setting out in search of a better life, he instead finds himself navigating one of the world's most inhospitable environments - the Jungle. For Mico, just one of many 'unaccompanied children', the Calais refugee camp has a wildness, a brutality all of its own."

Sophie Green

I work for the Suffolk Libraries stock team. I also write children's fiction, short stories and comedy. Visit my website.

About our Young Adult section

Book reviews, reading suggestions and blog posts from our staff and young adult readers. Want to write for our website? Email us at help@suffolklibraries.co.uk.

More Young adult

New Young Adult books for March 2020

Wranglestone by Darren Charlton

Recommended Young Adult titles to mark LGBT History Month 2020

With the Fire on High by Elizabeth Acevedo

New Young Adult books for February 2020

The Poet X by Elizabeth Acevedo

Find your new favourite book with the 2020 Read for Empathy YA book collection

The Deathless Girls by Kiran Millwood Hargrave

The Beautiful by Renée Ahdieh

Feast your eyes on our stunning Young Adult comic books

More suggestions

Fiction

Audiobooks

Films & DVDs

eLibrary picks

Children's books

Young adult

Non-fiction

Music

Meet the Author interviews

Articles

 Health and wellbeing

Reviews

Book club favourites

Keep updated

Get the latest suggestions, releases and reviews delivered straight to you.

Email newsletter

Facebook

Twitter

Instagram

Do it online

Search & reserve

Login & renew

eLibrary

Get a library card

Support your library

We're a charity that makes life in Suffolk better for thousands of people.

Donate

Contact us

01473 351249

help@suffolklibraries.co.uk

Social media

Facebook

YouTube

Twitter

Instagram

LinkedIn

Email newsletter

Sections

eLibrary

Libraries

Mobile & home service

Help using the service

Recommendations & reviews

Events & activities

Research & reference

Parents, carers & children

Teachers & home educators

Health & wellbeing

Help with reading & literacy

Work & benefits

Business & room hire

BLOC

Music & Drama Library

News

Jobs

Volunteering

About us

Privacy & cookies

Find out what cookies we use and how we use your data: our privacy policies.

Privacy notice for job applicants

Suffolk Libraries HMRC charity number XT34476. Registered company number IP031542.