text:
//=================================================================================
// Name        : help_functions.h
// Version     : 1.0.0
// Copyright   : MBRDNA, Udacity
//=================================================================================

#ifndef HELP_FUNCTIONS_H_
#define HELP_FUNCTIONS_H_

#include <math.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include "measurement_package.h"

class help_functions {
public:

	//definition of one over square root of 2*pi:
	float ONE_OVER_SQRT_2PI = 1/sqrt(2*M_PI) ;

	//definition square:
	float squared(float x)
	{
	    return x*x;
	}

	/*****************************************************************************
	 * normpdf(X,mu,sigma) computes the probability function at values x using the
	 * normal distribution with mean mu and standard deviation std. x, mue and
	 * sigma must be scalar! The parameter std must be positive.
	 * The normal pdf is y=f(x;mu,std)= 1/(std*sqrt(2pi)) e[ -(x−mu)^2 / 2*std^2 ]
	*****************************************************************************/
	float normpdf(float x, float mu, float std) {
	    return (ONE_OVER_SQRT_2PI/std)*exp(-0.5*squared((x-mu)/std));
	}

	//function to normalize a vector:
	std::vector<float> normalize_vector(std::vector<float> inputVector){

		//declare sum:
		float sum = 0.0f;

		//declare and resize output vector:
		std::vector<float> outputVector ;
		outputVector.resize(inputVector.size());

		//estimate the sum:
		for (int i = 0; i < inputVector.size(); ++i) {
			sum += inputVector[i];
		}

		//normalize with sum:
		for (int i = 0; i < inputVector.size(); ++i) {
			outputVector[i] = inputVector[i]/sum ;
		}

		//return normalized vector:
		return outputVector ;
	}

	/* Reads map data from a file.
	 * @param filename Name of file containing map data.
	 */
	inline bool read_map_data(std::string filename, map& map) {

		// Get file of map:
		std::ifstream in_file_map(filename.c_str(),std::ifstream::in);
		// Return if we can't open the file.
		if (!in_file_map) {
			return false;
		}

		//declare single line of map file:
		std::string line_map;

		//run over each single line:
		while(getline(in_file_map, line_map)){

			std::istringstream iss_map(line_map);

			//declare landmark values and ID:
			float landmark_x_f;
			int id_i;

			//read data from current line to values::
			iss_map >> id_i	;
			iss_map >> landmark_x_f	;

			//declare single_landmark:
			map::single_landmark_s single_landmark_temp ;

			//set values
			single_landmark_temp.id_i = id_i ;
			single_landmark_temp.x_f  = landmark_x_f;

			//push_back in landmark list of map_1d:
			map.landmark_list.push_back(single_landmark_temp);

		}
		return true;
	}

	/* Reads measurements from a file.
	 * @param filename Name of file containing measurement  data.
	 */
	inline bool read_measurement_data(std::string filename_control,
			                          std::string filename_obs,
			                          std::vector<MeasurementPackage>& measurement_pack_list) {
	//get file of measurements:
	std::ifstream in_file_control(filename_control.c_str(),std::ifstream::in);
	if (!in_file_control) {
		return false;
	}
	//declare single line of measurement file:
	std::string line;

	int count = 1 ;

	//run over each single line:
	while(getline(in_file_control, line)){

		//declare measurement package:
		MeasurementPackage meas_package;

		std::istringstream iss(line);

		//declare position values:
		float delta_x_f;

		//read data from line to values:
		iss >> delta_x_f;

		//set control information:
		meas_package.control_s_.delta_x_f = delta_x_f ;

		//read observations for each control information:
		char str_obs[1024];

		//define file name of observations for current control/position info:
		sprintf(str_obs,"%sobservations_%06i.txt", filename_obs.c_str(), count);
		std::string in_file_name_observation = std::string(str_obs);

		//get file of observations:
		std::ifstream in_file_observation(in_file_name_observation.c_str(),
				                          std::ifstream::in);
		if (!in_file_observation) {
			return false;
		}

		std::string line_obs;

		//run over each single line:
		while(getline(in_file_observation, line_obs)){

			std::istringstream iss_obs(line_obs);

			//declare observation values:
			float distance_f;

			//read data from line to values:
			iss_obs >> distance_f;

			//set observation information:
			meas_package.observation_s_.distance_f.push_back(distance_f);
		}
		//push_back single package in measurement list:
		measurement_pack_list.push_back(meas_package);

		//increase counter for observation files:
		count++;
	}
	return true;
	}

	inline bool compare_data(std::string filename_gt,
			                 std::vector<float>& result_vec) {
	/*****************************************************************************
	 *  print/compare results:												   *
	 *****************************************************************************/
	//get GT data:
	//define file name of map:

		std::vector<float> gt_vec;

		//get file of map:
		std::ifstream in_file_gt(filename_gt.c_str(),std::ifstream::in);

		//declare single line of map file:
		std::string line_gt;

		//run over each single line:
		while(getline(in_file_gt, line_gt)){

			std::istringstream iss_gt(line_gt);
			float gt_value;

			//read data from current line to values::
			iss_gt >> gt_value	;
			gt_vec.push_back(gt_value);

		}
		float error_sum;
		float belief_sum;
		error_sum  = 0.0f;
		belief_sum = 0.0f;
		std::cout <<"..................................................."<< std::endl;
	    std::cout <<"...............----> Results <----................."<< std::endl;
		std::cout <<"..................................................."<< std::endl;

		for (int i = 0; i <  result_vec.size(); ++i){
			error_sum+= (gt_vec[i]-result_vec[i])*(gt_vec[i]-result_vec[i]);
			belief_sum+= result_vec[i] ;
			std::cout << std::fixed << std::setprecision(5) <<"bel_x="<< i <<":" << "\t"
					  << result_vec[i]<<"\t"
					  << "ground truth:" << "\t"
					  << gt_vec[i]<<"\t" << std::endl ;
		}
		std::cout <<"..................................................."<< std::endl;
		std::cout << std::fixed << std::setprecision(5)<< "sum bel:"    << "\t" << belief_sum <<std::endl;
		std::cout <<"..................................................."<< std::endl;
		std::cout << std::fixed << std::setprecision(5)<< "sqrt error sum:     " << "\t" << sqrt((error_sum)) <<std::endl;
		std::cout <<"..................................................."<< std::endl;
		std::cout <<"..................................................."<< std::endl;
		return true;

	}

};

#endif /* HELP_FUNCTIONS_H_ */


text:
/// <reference path='../all.d.ts' />
/**
 * Container Module for the OpenDataHub Application
 * Contains the submodules and some basic logic
 */
module odh {
    'use strict';

    angular
        .module('openDataHub.main', [
            'angularFileUpload'
        ]);
}

redpajama_set_name: RedPajamaGithub


text:
A personal website made using the Flask framework for Python

# Using

 Python

 Flask

 Postgres

 Bootstrap (theme https://bootswatch.com/cyborg/)

# 1. Installation & Requirements

 Clone the tool if you have git installed.

 Git Installation Guide:

Windows - https://git-scm.com/download/win

Linux - https://git-scm.com/download/linux

Then run these command in the Command Prompt or Terminal.

```
git clone https://github.com/Daan4/website.git
cd website
pip install -r requirements.txt
```

         OR

 Download from the link: https://github.com/Daan4/website/archive/master.zip

Then, run these command in the Command Prompt or Terminal.

```
cd website/
pip install -r requirements.txt
```

# 2. Usage:

 Setup postgresql database (utf8 encoding, match username, pass & db name with the config settings)

 Setup website_config.py and config.py based on the given example config

 i. Run the python file (db_create.py)

 ii. Run the python file (run.py)

 Or type the command in terminal/command prompt:

```
python db_create.py
python run.py
```


text:
from .xcconfig_item_base import xcconfig_item_base
from .xcconfig_include import xcconfig_include
from .xcconfig_comment import xcconfig_comment
from .xcconfig_kv import xcconfig_kv

def xcconfig_line_type(line):
    type = 'EMPTY';
    if line != None:
        if line.startswith('//') == True:
            type = 'COMMENT';
        elif line.startswith('#include ') == True:
            type = 'INCLUDE';
        else:
            offset = xcconfig_kv.FindKeyValueAssignmentOffset(line, 0);
            if offset > 0 and offset < len(line):
                type = 'KV';
    return type;

XCCONGIF_LINE_TYPE_DICT = {
    'COMMENT': xcconfig_comment,
    'INCLUDE': xcconfig_include,
    'KV': xcconfig_kv,
};

def xcconfig_line_resolver(line, type):
    global XCCONGIF_LINE_TYPE_DICT;
    if type in XCCONGIF_LINE_TYPE_DICT.keys():
        return (True, XCCONGIF_LINE_TYPE_DICT[type]);
    else:
        return (False, None);


text:
'use strict';

let path = require('path');
let srcPath = path.join(__dirname, '/../src/');
let $ = require('jquery');

let baseConfig = require('./base');

// Add needed plugins here
let BowerWebpackPlugin = require('bower-webpack-plugin');

module.exports = {
  devtool: 'eval',
  module: {
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'isparta-instrumenter-loader',
        include: [
          path.join(__dirname, '/../src')
        ]
      }
    ],
    loaders: [
      {
        test: /\.(png|jpg|gif|woff|woff2|css|sass|scss|less|styl)$/,
        loader: 'null-loader'
      },
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        include: [].concat(
          baseConfig.additionalPaths,
          [
            path.join(__dirname, '/../src'),
            path.join(__dirname, '/../test')
          ]
        )
      }
    ]
  },
  resolve: {
    extensions: [ '', '.js', '.jsx' ],
    alias: {
      fn: srcPath + 'fn/',
      actions: srcPath + 'actions/',
      helpers: path.join(__dirname, '/../test/helpers'),
      components: srcPath + 'components/',
      sources: srcPath + 'sources/',
      stores: srcPath + 'stores/',
      styles: srcPath + 'styles/',
      config: srcPath + 'config/' + process.env.REACT_WEBPACK_ENV
    }
  },
  plugins: [
    new BowerWebpackPlugin({
      searchResolveModulesDirectories: false
    })
  ]
};


text:
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('contenttypes', '0002_remove_content_type_name'),
    ]

    operations = [
        migrations.CreateModel(
            name='Rating',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('count', models.PositiveIntegerField(default=0)),
                ('total', models.PositiveIntegerField(default=0)),
                ('average', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=6)),
                ('object_id', models.PositiveIntegerField(blank=True, null=True)),
                ('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType')),
            ],
            options={
                'unique_together': {('content_type', 'object_id')},
            },
        ),
        migrations.CreateModel(
            name='UserRating',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('ip', models.GenericIPAddressField(blank=True, null=True)),
                ('score', models.PositiveSmallIntegerField()),
                ('rating', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='user_ratings', to='star_ratings.Rating')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'unique_together': {('user', 'rating')},
            },
        ),
    ]


text:
package org.sewas.util;

import org.sewas.domain.model.*;

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

/**
 * Created by sebastian on 25/05/17.
 */
public class MatchBuilder {
    private int MatchID;
    private List<org.sewas.domain.model.Goal> Goal = new ArrayList<Goal>();
    private Team Team1;
    private Team Team2;
    private int NumberOfViewers;
    private org.sewas.domain.model.Group Group;
    private List<MatchResult> matchResults = new ArrayList<MatchResult>();
    private Boolean isMatchFinished = true;

    public MatchBuilder()
    {}

    public MatchBuilder withMatchID(int MatchID)
    {
        this.MatchID = MatchID;
        return this;
    }

    public MatchBuilder withNumberOfViewers(int NumberOfViewers)
    {
        this.NumberOfViewers = NumberOfViewers;
        return this;
    }

    public MatchBuilder withTeam1(Team team)
    {
        this.Team1 = team;
        return this;
    }

    public MatchBuilder withTeam2(Team team)
    {
        this.Team2 = team;
        return this;
    }

    public MatchBuilder withGroup(Group group)
    {
        this.Group = group;
        return this;
    }

    public MatchBuilder withGoal(Goal goal)
    {
        this.Goal.add(goal);
        return this;
    }

    public MatchBuilder withResult(MatchResult matchResult)
    {
        this.matchResults.add(matchResult);
        return this;
    }

    public MatchBuilder isFinished(Boolean isMatchFinished) {
        this.isMatchFinished = isMatchFinished;
        return this;
    }

    public Match build()
    {
        Match m = new Match();
        m.setGoal(this.Goal);
        m.setTeam1(this.Team1);
        m.setTeam2(this.Team2);
        m.setNumberOfViewers(this.NumberOfViewers);
        m.setMatchID(this.MatchID);
        m.setGroup(this.Group);
        m.setMatchResults(this.matchResults);
        m.setMatchIsFinished(this.isMatchFinished);

        return m;
    }
}


text:
package be.gerard.core.service.dao;

import be.gerard.core.service.BaseTest;
import be.gerard.core.service.model.ApplicationInstanceRecord;
import be.gerard.core.service.model.ApplicationRecord;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * UserDaoTest
 *
 * @author bartgerard
 * @version 0.0.1
 */
public class ApplicationInstanceDaoTest extends BaseTest {

    @Autowired
    private ApplicationInstanceDao applicationInstanceDao;

    @Test
    public void test() {
        ApplicationRecord applicationRecord = new ApplicationRecord(APP_KEY);

        ApplicationInstanceRecord applicationInstanceRecord = new ApplicationInstanceRecord(applicationRecord, REFERENCE, PASSWORD);
        applicationInstanceRecord.addIp(IP);
        applicationInstanceRecord.addMac(MAC);
        applicationInstanceDao.saveAndFlush(applicationInstanceRecord);

        ApplicationInstanceRecord applicationInstanceRecord1 = applicationInstanceDao.findByApplicationAndReference(applicationRecord, REFERENCE);
        Assert.assertTrue("application.ips does not contain ip", applicationInstanceRecord1.isIpAllowed(IP));
        Assert.assertTrue("application.macs does not contain mac", applicationInstanceRecord1.isMacAllowed(MAC));

        ApplicationInstanceRecord applicationInstanceRecord2 = applicationInstanceDao.findByApplicationAndReference(applicationRecord.getKey(), REFERENCE);
        Assert.assertNotNull("application not found", applicationInstanceRecord2);
    }

}


text:
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from scipy.stats import linregress

from mri_tools.plots.layouts import SquareGridLayout
from mri_tools.plots.widgets import DiscreteSlider

__author__ = 'Robbert Harms'
__date__ = "2015-08-17"
__maintainer__ = "Robbert Harms"
__email__ = "robbert.harms@maastrichtuniversity.nl"

class ScatterDataInterface(object):

    def get_x_data(self, dimension=0):
        """Get the scatter data on the x axis

        Args:
            dimension (int): optional support for multi dimensional data

        Returns:
            ndarray: the data on the x axis
        """

    def get_y_data(self, dimension=0):
        """Get the scatter data on the y axis

        Args:
            dimension (int): optional support for multi dimensional data

        Returns:
            ndarray: the data on the y axis
        """

    def get_x_label(self):
        """Get the label on the x axis

        Returns:
            str: the label on the x axis
        """

    def get_y_label(self):
        """Get the label on the y axis

        Returns:
            str: the label on the y axis
        """

    def get_title(self):
        """Get the title of this scatter data

        Returns:
            str: the title of this scatter data
        """

    def get_nmr_dimensions(self):
        """Get the number of available dimensions.

        Returns:
            int: the available number of dimensions available
        """

class SimpleScatterData(ScatterDataInterface):

    def __init__(self, x_data, y_data, x_label, y_label, title):
        self._x_data = x_data
        self._y_data = y_data
        self._x_label = x_label
        self._y_label = y_label
        self._title = title

        if len(x_data.shape) != len(y_data.shape):
            raise ValueError('The x and y data should have the same number of dimensions.')

    def get_x_data(self, dimension=0):
        if self.get_nmr_dimensions() > 0:
            if dimension >= self._x_data.shape[1]:
                return self._x_data[:, -1]
            return self._x_data[:, dimension]
        return self._x_data

    def get_y_data(self, dimension=0):
        if self.get_nmr_dimensions() > 0:
            if dimension >= self._y_data.shape[1]:
                return self._y_data[:, -1]
            return self._y_data[:, dimension]
        return self._y_data

    def get_x_label(self):
        return self._x_label

    def get_y_label(self):
        return self._y_label

    def get_title(self):
        return self._title

    def get_nmr_dimensions(self):
        if len(self._x_data.shape) > 1:
            return self._x_data.shape[1]
        return 1

class ScatterDataInfo(object):

    def __init__(self, scatter_data_list, plot_titles):
        """All the information (including meta info) about the scatter data

        Args:
            scatter_data_list (list of ScatterDataInterface): the scatter data elements
            plot_titles (list of str): the titles of the dimensions
            nmr_dimensions (int): the default dimension
        """
        self._scatter_data_list = scatter_data_list
        self._plot_titles = plot_titles
        self._nmr_dimensions = max([sd.get_nmr_dimensions() for sd in scatter_data_list])

    def get_nmr_dimensions(self):
        """Get the number of supported dimensions.

        Returns:
            int: the number of dimensions
        """
        return self._nmr_dimensions

    def get_plot_title(self, dimension):
        """Get the title of this plot in the given dimension

        Args:
            dimension (int): the dimension from which we want the plot title

        Returns:
            str: the plot title
        """
        return self._plot_titles[dimension]

    def get_nmr_plots(self):
        """Get the number of plots we will display

        Returns:
            int: the number of plots
        """
        return len(self._scatter_data_list)

    def get_x_data(self, plot_ind, dimension=None):
        return self._scatter_data_list[plot_ind].get_x_data(dimension=dimension)

    def get_y_data(self, plot_ind, dimension=None):
        return self._scatter_data_list[plot_ind].get_y_data(dimension=dimension)

    def get_x_label(self, plot_ind):
        return self._scatter_data_list[plot_ind].get_x_label()

    def get_y_label(self, plot_ind):
        return self._scatter_data_list[plot_ind].get_y_label()

    def get_title(self, plot_ind):
        return self._scatter_data_list[plot_ind].get_title()

class ScatterPlots(object):

    def __init__(self, scatter_info, placement=None):
        """Create scatter plots of the given scatter data items.

        Args:
            scatter_info (ScatterDataInfo): the scatter data information
            placement (PlacementInterface): the placement options
        """
        self._scatter_info = scatter_info
        self.font_size = None
        self._figure = plt.figure(figsize=(18, 16))
        self.placement = placement or SquareGridLayout()
        self.show_titles = True
        self.dimension = 0
        self._dimension_slider = None
        self._updating_sliders = False
        self._show_sliders = True

    def show(self, dimension=0, show_titles=True, to_file=None, block=True, maximize=False, show_sliders=True):
        """Plot all the scatterplots.

        Args:
            dimension (int):
                The dimension to display
            show_titles (boolean): if we want to display the titles per scatter plot
            to_file (string, optional, default None):
                If to_file is not None it is supposed to be a filename where the image will be saved.
                If not set to None, nothing will be displayed, the results will directly be saved.
                Already existing items will be overwritten.
            block (boolean): If we want to block after calling the plots or not. Set this to False if you
                do not want the routine to block after drawing. In doing so you manually need to block.
            maximize (boolean): if we want to display the window maximized or not
            show_sliders (boolean): if we want to display the sliders
        """
        self.dimension = dimension
        self.show_titles = show_titles
        self._show_sliders = show_sliders

        self._setup()

        if maximize:
            mng = plt.get_current_fig_manager()
            mng.window.showMaximized()

        if to_file:
            plt.savefig(to_file)
            plt.close()
        else:
            plt.draw()
            if block:
                plt.show(True)

    def set_dimension(self, val):
        val = round(val)
        if not self._updating_sliders:
            self._updating_sliders = True
            self.dimension = int(round(val))

            if self.dimension > self._scatter_info.get_nmr_dimensions():
                self.dimension = self._scatter_info.get_nmr_dimensions()

            self._dimension_slider.set_val(val)
            self._rerender_maps()
            self._updating_sliders = False

    def _setup(self):
        if self.font_size:
            matplotlib.rcParams.update({'font.size': self.font_size})

        if self._show_sliders:
            ax = self._figure.add_axes([0.25, 0.008, 0.5, 0.01], axisbg='Wheat')
            self._dimension_slider = DiscreteSlider(
                ax, 'Volume', 0, self._scatter_info.get_nmr_dimensions() - 1,
                valinit=self.dimension, valfmt='%i', color='DarkSeaGreen', closedmin=True, closedmax=False)

            self._dimension_slider.on_changed(self.set_dimension)

        self._rerender_maps()

    def _rerender_maps(self):
        bb_min, bb_max = _get_bounding_box(self._scatter_info, self.dimension)

        for ind in range(self._scatter_info.get_nmr_plots()):
            axis = self.placement.get_axis(ind, self._scatter_info.get_nmr_plots())
            vf = axis.scatter(self._scatter_info.get_x_data(ind, dimension=self.dimension),
                              self._scatter_info.get_y_data(ind, dimension=self.dimension))

            axis.plot(np.arange(bb_min, bb_max, 0.01), np.arange(bb_min, bb_max, 0.01), 'k')

            slope, intercept, _, _, _ = linregress(self._scatter_info.get_x_data(ind, dimension=self.dimension),
                                                   self._scatter_info.get_y_data(ind, dimension=self.dimension))
            line_x_range = np.arange(bb_min, bb_max, 0.01)
            line_y_range = line_x_range * slope + intercept

            pos = np.where(np.logical_and(bb_min <= line_y_range, line_y_range<= bb_max))
            line_x_range = line_x_range[pos]
            line_y_range = line_y_range[pos]

            plt.plot(line_x_range, line_y_range, 'b')

            plt.xlabel(self._scatter_info.get_x_label(ind))
            plt.ylabel(self._scatter_info.get_y_label(ind))

            if self.show_titles:
                plt.title(self._scatter_info.get_plot_title(ind))

            plt.subplots_adjust(hspace=.3)

        self._figure.suptitle(self._scatter_info.get_plot_title(self.dimension))

        self._figure.canvas.draw()

        mng = plt.get_current_fig_manager()
        mng.canvas.set_window_title(self._scatter_info.get_plot_title(self.dimension))

class MultiROIScatterPlots(object):

    def __init__(self, scatter_info, placement=None):
        """Create scatter plots of the given scatter data items.

        Args:
            scatter_info (ScatterDataInfo): the scatter data information
            placement (PlacementInterface): the placement options
        """
        self._scatter_info = scatter_info
        self.font_size = None
        self._figure = plt.figure(figsize=(18, 16))
        self.placement = placement or SquareGridLayout()
        self.show_titles = True
        self.dimensions = []
        self._dimension_slider = None
        self._updating_sliders = False
        self._show_sliders = True
        self._legend_plot_options = {}

    def show(self, dimensions, show_titles=True, to_file=None, block=True, maximize=False, show_sliders=True,
             legend_plot_options=None):
        """Plot all the scatterplots with multiple dimensions per plot

        Args:
            dimensions (list of int):
                The dimensions to overlap on each other
            show_titles (boolean): if we want to display the titles per scatter plot
            to_file (string, optional, default None):
                If to_file is not None it is supposed to be a filename where the image will be saved.
                If not set to None, nothing will be displayed, the results will directly be saved.
                Already existing items will be overwritten.
            block (boolean): If we want to block after calling the plots or not. Set this to False if you
                do not want the routine to block after drawing. In doing so you manually need to block.
            maximize (boolean): if we want to display the window maximized or not
            show_sliders (boolean): if we want to display the sliders
            legend_plot_options (dict): the varargs for the legend, per plot
        """
        self.dimensions = dimensions
        self.show_titles = show_titles
        self._show_sliders = show_sliders
        self._legend_plot_options = legend_plot_options or {}
        self._setup()

        if maximize:
            mng = plt.get_current_fig_manager()
            mng.window.showMaximized()

        if to_file:
            plt.savefig(to_file)
            plt.close()
        else:
            plt.draw()
            if block:
                plt.show(True)

    def _rerender_maps(self):
        bb_min, bb_max = self._get_bounding_box()

        for ind in range(self._scatter_info.get_nmr_plots()):
            axis = self.placement.get_axis(ind, self._scatter_info.get_nmr_plots())
            axis.plot(np.arange(bb_min, bb_max, 0.01), np.arange(bb_min, bb_max, 0.01), 'k')

            color_cycle = iter([color['color'] for color in list(matplotlib.rcParams['axes.prop_cycle'])])

            for dimension in self.dimensions:
                color = next(color_cycle)

                vf = axis.scatter(self._scatter_info.get_x_data(ind, dimension=dimension),
                                  self._scatter_info.get_y_data(ind, dimension=dimension), c=color)

                slope, intercept, _, _, _ = linregress(self._scatter_info.get_x_data(ind, dimension=dimension),
                                                       self._scatter_info.get_y_data(ind, dimension=dimension))

                line_x_range = np.arange(bb_min, bb_max, 0.01)
                line_y_range = line_x_range * slope + intercept

                pos = np.where(np.logical_and(bb_min <= line_y_range, line_y_range<= bb_max))
                line_x_range = line_x_range[pos]
                line_y_range = line_y_range[pos]

                plt.plot(line_x_range, line_y_range, color, label=self._scatter_info.get_plot_title(dimension))

            plt.xlabel(self._scatter_info.get_x_label(ind))
            plt.ylabel(self._scatter_info.get_y_label(ind))

            if self.show_titles:
                plt.title(self._scatter_info.get_plot_title(ind))

            plt.subplots_adjust(hspace=.3)

            legend_options = {}
            if ind in self._legend_plot_options:
                legend_options.update(self._legend_plot_options[ind])
            axis.legend(**legend_options)

        title = ', '.join(map(self._scatter_info.get_plot_title, self.dimensions))

        self._figure.suptitle(title)
        self._figure.canvas.draw()

        mng = plt.get_current_fig_manager()
        mng.canvas.set_window_title(title)

    def _get_bounding_box(self):
        min_list = []
        max_list = []
        for dimension in self.dimensions:
            bb_min, bb_max = _get_bounding_box(self._scatter_info, dimension)
            min_list.append(bb_min)
            max_list.append(bb_max)
        return max(min_list), min(max_list)

    def _setup(self):
        if self.font_size:
            matplotlib.rcParams.update({'font.size': self.font_size})
        self._rerender_maps()

def _get_bounding_box(scatter_info, dimension):
    """Get the bounding box for a scatter plot.

    Args:
        scatter_info (ScatterInfo): the information about the scatter plots
        dimension (int): which dimension we want to show
    """
    min_list = []
    max_list = []

    for ind in range(scatter_info.get_nmr_plots()):
        line_min = min(np.min(scatter_info.get_x_data(ind, dimension=dimension)),
                       np.min(scatter_info.get_y_data(ind, dimension=dimension)))
        line_max = max(np.max(scatter_info.get_x_data(ind, dimension=dimension)),
                       np.max(scatter_info.get_y_data(ind, dimension=dimension)))

        min_list.append(line_min)
        max_list.append(line_max)

    minimum = float(np.around(min(min_list), decimals=2))
    maximum = float(np.around(max(max_list), decimals=2))

    return max(minimum - 0.1, 0), min(maximum + 0.1, 1)


text:
package com.lovecws.mumu.system.service.impl;

import com.lovecws.mumu.common.core.enums.PublicEnum;
import com.lovecws.mumu.common.core.page.PageBean;
import com.lovecws.mumu.common.core.page.PageParam;
import com.lovecws.mumu.system.dao.SysExportModelDao;
import com.lovecws.mumu.system.entity.SysExportModel;
import com.lovecws.mumu.system.service.SysExportModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=true)
public class SysExportModelServiceImpl implements SysExportModelService {

	@Autowired
	private SysExportModelDao sysExportModelDao;

	@Override
	public PageBean<SysExportModel> listPage(String modelName, int pageNum, int pageSize) {
		PageParam pageParam=new PageParam(pageNum, pageSize);
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("modelName", modelName);
		paramMap.put("ddlStatus", PublicEnum.NORMAL.value());
		return sysExportModelDao.listPage(pageParam, paramMap);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public void deleteById(String modelId) {
		sysExportModelDao.delete(modelId);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public void addExportModel(SysExportModel exportModel) {
		exportModel.setCreateTime(new Date());
		exportModel.setModelStatus(String.valueOf(PublicEnum.NORMAL.value()));
		sysExportModelDao.insert(exportModel);
	}

	@Override
	public SysExportModel getSysExportModelById(String modelId) {
		return sysExportModelDao.getById(modelId);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public void updateSysExportModel(SysExportModel exportModel) {
		exportModel.setEditTime(new Date());
		sysExportModelDao.update(exportModel);
	}

	@Override
	public List<SysExportModel> queryExportModelByCondition(String modelName) {
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("modelName", modelName);
		map.put("modelStatus", PublicEnum.NORMAL.value());
		return sysExportModelDao.listByColumn(map);
	}

}


text:
using System;
using System.Reflection;

namespace Enigma.Serialization.Reflection
{
    public class AcquirePropertyMetadataArgs
    {
        private readonly Type _type;
        private readonly PropertyInfo _property;
        private readonly Arguments _args;

        public UInt32? Index { get; set; }

        public AcquirePropertyMetadataArgs(Type type, PropertyInfo property)
        {
            _type = type;
            _property = property;
            _args = new Arguments();
        }

        public Type Type
        {
            get { return _type; }
        }

        public PropertyInfo Property
        {
            get { return _property; }
        }

        public Arguments Args { get { return _args; } }
    }
}


text:
/** Automatically generated file. DO NOT MODIFY */
package edu.mtu.citizenscience.thunderbay;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
<?php

declare (strict_types=1);
namespace PHPStan\Type\PHPUnit;

use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeWithClassName;
use RectorPrefix20210615\PHPUnit\Framework\MockObject\Builder\InvocationMocker;
use RectorPrefix20210615\PHPUnit\Framework\MockObject\MockObject;
class MockObjectDynamicReturnTypeExtension implements \PHPStan\Type\DynamicMethodReturnTypeExtension
{
    public function getClass() : string
    {
        return \RectorPrefix20210615\PHPUnit\Framework\MockObject\MockObject::class;
    }
    public function isMethodSupported(\PHPStan\Reflection\MethodReflection $methodReflection) : bool
    {
        return $methodReflection->getName() === 'expects';
    }
    public function getTypeFromMethodCall(\PHPStan\Reflection\MethodReflection $methodReflection, \PhpParser\Node\Expr\MethodCall $methodCall, \PHPStan\Analyser\Scope $scope) : \PHPStan\Type\Type
    {
        $type = $scope->getType($methodCall->var);
        if (!$type instanceof \PHPStan\Type\IntersectionType) {
            return new \PHPStan\Type\ObjectType(\RectorPrefix20210615\PHPUnit\Framework\MockObject\Builder\InvocationMocker::class);
        }
        $mockClasses = \array_values(\array_filter($type->getTypes(), function (\PHPStan\Type\Type $type) : bool {
            return !$type instanceof \PHPStan\Type\TypeWithClassName || $type->getClassName() !== \RectorPrefix20210615\PHPUnit\Framework\MockObject\MockObject::class;
        }));
        if (\count($mockClasses) !== 1) {
            return new \PHPStan\Type\ObjectType(\RectorPrefix20210615\PHPUnit\Framework\MockObject\Builder\InvocationMocker::class);
        }
        return new \PHPStan\Type\Generic\GenericObjectType(\RectorPrefix20210615\PHPUnit\Framework\MockObject\Builder\InvocationMocker::class, $mockClasses);
    }
}


text:
class Redbox::Style < ActiveRecord::Base
  establish_connection 'redbox'
  self.table_name = 'shop_styles'

  has_and_belongs_to_many :products
end


text:
package com.github.sd4324530.fastweixin.message.req;

public final class ScanCodeEvent extends BaseEvent {

	private String eventKey;
	private String scanType;
	private String scanResult;

    public ScanCodeEvent(String eventKey, String scanType, String scanResult) {
        super();
        this.eventKey = eventKey;
        this.scanType = scanType;
        this.scanResult = scanResult;
    }

	public String getEventKey() {
		return eventKey;
	}

	public void setEventKey(String eventKey) {
		this.eventKey = eventKey;
	}

	public String getScanType() {
		return scanType;
	}

	public void setScanType(String scanType) {
		this.scanType = scanType;
	}

	public String getScanResult() {
		return scanResult;
	}

	public void setScanResult(String scanResult) {
		this.scanResult = scanResult;
	}

	@Override
    public String toString() {
        return "ScanCodeEvent [eventKey=" + eventKey + ", scanType=" + scanType + ", scanResult=" + scanResult + ", toUserName=" + toUserName
                + ", fromUserName=" + fromUserName + ", createTime="
                + createTime + ", msgType=" + msgType + "]";
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
//
// This file is part of BasicLTI4Moodle
//
// BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
// consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
// based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
// specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
// are already supporting or going to support BasicLTI. This project Implements the consumer
// for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
// BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
// at the GESSI research group at UPC.
// SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
// by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
// Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
//
// BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
// of the Universitat Politecnica de Catalunya http://www.upc.edu
// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu.

require_once("../../config.php");
require_once($CFG->dirroot.'/mod/lti/lib.php');

$id = required_param('id', PARAM_INT);   // Course id.

$course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);

require_login($course);
$PAGE->set_pagelayout('incourse');

$params = array(
    'context' => context_course::instance($course->id)
);
$event = \mod_lti\event\course_module_instance_list_viewed::create($params);
$event->add_record_snapshot('course', $course);
$event->trigger();

$PAGE->set_url('/mod/lti/index.php', array('id' => $course->id));
$pagetitle = strip_tags($course->shortname.': '.get_string("modulenamepluralformatted", "lti"));
$PAGE->set_title($pagetitle);
$PAGE->set_heading($course->fullname);

echo $OUTPUT->header();

// Print the main part of the page.
echo $OUTPUT->heading(get_string("modulenamepluralformatted", "lti"));

// Get all the appropriate data.
if (! $basicltis = get_all_instances_in_course("lti", $course)) {
    notice(get_string('noltis', 'lti'), "../../course/view.php?id=$course->id");
    die;
}

// Print the list of instances (your module will probably extend this).
$timenow = time();
$strname = get_string("name");
$usesections = course_format_uses_sections($course->format);

$table = new html_table();
$table->attributes['class'] = 'generaltable mod_index';

if ($usesections) {
    $strsectionname = get_string('sectionname', 'format_'.$course->format);
    $table->head  = array ($strsectionname, $strname);
    $table->align = array ("center", "left");
} else {
    $table->head  = array ($strname);
}

foreach ($basicltis as $basiclti) {
    if (!$basiclti->visible) {
        // Show dimmed if the mod is hidden.
        $link = "coursemodule\">$basiclti->name";
    } else {
        // Show normal if the mod is visible.
        $link = "coursemodule\">$basiclti->name";
    }

    if ($usesections) {
        $table->data[] = array (get_section_name($course, $basiclti->section), $link);
    } else {
        $table->data[] = array ($link);
    }
}

echo "
";

echo html_writer::table($table);

// Finish the page.
echo $OUTPUT->footer();


text:
require 'spec_helper'
describe(Rain::Config) do
  let(:config) { Rain::Config.new File.dirname(__FILE__) }

  it 'can get a yaml file' do
    expect(config.yaml_file).not_to be_empty
  end

  it 'is a indifferent hash' do
    expect(config.versions).to be_a(ActiveSupport::HashWithIndifferentAccess)
  end
end


text:
import Data.List
import Data.List.Split
import Control.Arrow

anagramCount :: String -> Int
anagramCount s = if length s `mod` 2 /= 0 then -1 else length $ a \\ b
  where [a, b] = chunksOf (length s `div` 2) s

main :: IO ()
main = do
  _ <- getLine
  interact $ lines >>> map (show . anagramCount) >>> unlines


text:
module.exports = {
  debug : false,
  slackChannel : "#football",
  serverPort : 8080,
  pingInteralInMilliseconds : 1000 * 60, // server main loop interval. 6 hours
  postBeforeTheMatch : true,
  postAfterTheMatch : true,
  preMatchWindowInMinutes: "in 5 minutes", // moment.js humanize expression
  postMatchWindowInHours: "2 hours ago" // moment.js humanize expression
};


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:orientation="vertical">
            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar"
                />

            <FrameLayout
                android:id="@+id/frgmContent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/menu_main"
        />

</android.support.v4.widget.DrawerLayout>


text:
""" The interface of a workbench editor. """
# standard library imports
import uuid

# Enthought library imports.
from traits.api import Any, Bool, Event, VetoableEvent, Vetoable, \
    HasTraits, Instance, Interface
from traits.api import provides

# Local imports.
from .i_workbench_part import IWorkbenchPart, MWorkbenchPart

class IEditor(IWorkbenchPart):
    """ The interface of a workbench editor. """

    # The optional command stack.
    command_stack = Instance('apptools.undo.api.ICommandStack')

    # Is the object that the editor is editing 'dirty' i.e., has it been
    # modified but not saved?
    dirty = Bool(False)

    # The object that the editor is editing.
    #
    # The framework sets this when the editor is created.
    obj = Any

    #### Editor Lifecycle Events ##############################################

    # Fired when the editor is closing.
    closing = VetoableEvent

    # Fired when the editor is closed.
    closed = Event

    #### Methods ##############################################################

    def close(self):
        """ Close the editor.

        This method is not currently called by the framework itself as the user
        is normally in control of the editor lifecycle. Call this if you want
        to control the editor lifecycle programmatically.

        """

@provides(IEditor)
class MEditor(MWorkbenchPart):
    """ Mixin containing common code for toolkit-specific implementations. """
    #### 'IEditor' interface ##################################################

    # The optional command stack.
    command_stack = Instance('apptools.undo.api.ICommandStack')

    # Is the object that the editor is editing 'dirty' i.e., has it been
    # modified but not saved?
    dirty = Bool(False)

    # The object that the editor is editing.
    #
    # The framework sets this when the editor is created.
    obj = Any

    #### Editor Lifecycle Events ##############################################

    # Fired when the editor is opening.
    opening = VetoableEvent

    # Fired when the editor has been opened.
    open = Event

    # Fired when the editor is closing.
    closing = Event(VetoableEvent)

    # Fired when the editor is closed.
    closed = Event

    ###########################################################################
    # 'object' interface.
    ###########################################################################

    def __str__(self):
        """ Return an informal string representation of the object. """

        return 'Editor(%s)' % self.id

    ###########################################################################
    # 'IWorkbenchPart' interface.
    ###########################################################################

    def _id_default(self):
        """ Trait initializer. """

        # If no Id is specified then use a random uuid
        # this gaurantees (barring *really* unusual cases) that there are no
        # collisions between the ids of editors.
        return uuid.uuid4().hex

    ###########################################################################
    # 'IEditor' interface.
    ###########################################################################

    def close(self):
        """ Close the editor. """

        if self.control is not None:
            self.closing = event = Vetoable()
            if not event.veto:
                self.window.close_editor(self)

                self.closed = True

        return

    #### Initializers #########################################################

    def _command_stack_default(self):
        """ Trait initializer. """

        # We make sure the undo package is entirely optional.
        try:
            from apptools.undo.api import CommandStack
        except ImportError:
            return None

        return CommandStack(undo_manager=self.window.workbench.undo_manager)

#### EOF ######################################################################


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>angular-spa-auth basic example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        Home
        Public
        Login
        Private Page
        Logout

    You can open Chrome DevTools to see console.info outputs


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__short_fscanf_multiply_82_goodB2G.cpp
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-82_goodB2G.tmpl.cpp
*/
/*
 * @description
 * CWE: 191 Integer Underflow
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Set data to a small, non-zero number (negative two)
 * Sinks: multiply
 *    GoodSink: Ensure there will not be an underflow before multiplying data by 2
 *    BadSink : If data is negative, multiply by 2, which can cause an underflow
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE191_Integer_Underflow__short_fscanf_multiply_82.h"

namespace CWE191_Integer_Underflow__short_fscanf_multiply_82
{

void CWE191_Integer_Underflow__short_fscanf_multiply_82_goodB2G::action(short data)
{
    if(data < 0) /* ensure we won't have an overflow */
    {
        /* FIX: Add a check to prevent an underflow from occurring */
        if (data > (SHRT_MIN/2))
        {
            short result = data * 2;
            printIntLine(result);
        }
        else
        {
            printLine("data value is too small to perform multiplication.");
        }
    }
}

}
#endif /* OMITGOOD */


text:
> [出处](https://www.jianshu.com/p/dabc0c6d083e)

- 用户在WiFi环境下下载的高清图,下次在蜂窝网络状态下打开应用也应显示高清图,而不是去下载缩略图
- 移动网络环境下仍然显示高清图
- 用户处于离线状态时候,合理处理业务

### 存在 `bug` 版本

```
- setItem:(CustomItem *)item
{
    _item = item;

     // 占位图片
    UIImage *placeholder = [UIImage imageNamed:@"placeholderImage"];

    // 从内存\沙盒缓存中获得原图,
    UIImage *originalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:item.originalImage];
    if (originalImage) { // 如果内存\沙盒缓存有原图,那么就直接显示原图(不管现在是什么网络状态)
        self.imageView.image = originalImage;
    } else { // 内存\沙盒缓存没有原图
        AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
        if (mgr.isReachableViaWiFi) { // 在使用Wifi, 下载原图
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];
        } else if (mgr.isReachableViaWWAN) { // 在使用手机自带网络
            //     用户的配置项假设利用NSUserDefaults存储到了沙盒中
            //    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"alwaysDownloadOriginalImage"];
            //    [[NSUserDefaults standardUserDefaults] synchronize];
#warning 从沙盒中读取用户的配置项:在3G\4G环境是否仍然下载原图
            BOOL alwaysDownloadOriginalImage = [[NSUserDefaults standardUserDefaults] boolForKey:@"alwaysDownloadOriginalImage"];
            if (alwaysDownloadOriginalImage) { // 下载原图
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];
            } else { // 下载小图
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.thumbnailImage] placeholderImage:placeholder];
            }
        } else { // 没有网络
            UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:item.thumbnailImage];
            if (thumbnailImage) { // 内存\沙盒缓存中有小图
                self.imageView.image = thumbnailImage;
            } else { // 处理离线状态,而且有没有缓存时的情况
                self.imageView.image = placeholder;
            }
        }
    }
}

```

### 详细分析

- UITableViewCell的缓存机制,一个展示 list

	- 没有cell被推出屏幕,此时`缓存池为空`
	- 当有一个cell被推到屏幕之外时,系统会自动将这个cell放入自动缓存池,依旧存在对应的数据模型

> `BUG 场景 `当用户所处环境WiFi网速不够快(不能立即将图片下载完毕),而在上述代码,在WiFi环境下又是下载高清大图。所以需要一定的时间来完成下载。而就在此时,用户不愿等,想看看上次打开App时显示的图片,此时用户会滑到处于下面的cell来查看。注意:此时,上面的cell下载图片操作并没有暂停,还在处于下载图片状态中。当用户在查看上次打开App的显示图片时(上次打开App下载完成的图片,SDWebImage会帮我们缓存,不用下载),而正好需要显示上次打开App时的图片的cell是利用tableView重用机制而从缓存池中拿出来的cell,等到处于上面的cell的高清大图已经下载好了的时候,SDWebImage默认做法是,立马把下载好的图片设置给ImageView,所以我们这时候会在底下的显示的cell显示上面的图片,造成数据错乱,这是非常严重的BUG

```

- setItem:(CustomItem *)item
{
    _item = item;

  // 占位图片
    UIImage *placeholder = [UIImage imageNamed:@"placeholderImage"];

    // 从内存\沙盒缓存中获得原图
    UIImage *originalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:item.originalImage];
    if (originalImage) { // 如果内存\沙盒缓存有原图,那么就直接显示原图(不管现在是什么网络状态)
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];
    } else { // 内存\沙盒缓存没有原图
        AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
        if (mgr.isReachableViaWiFi) { // 在使用Wifi, 下载原图
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];
        } else if (mgr.isReachableViaWWAN) { // 在使用手机自带网络
            //     用户的配置项假设利用NSUserDefaults存储到了沙盒中
            //    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"alwaysDownloadOriginalImage"];
            //    [[NSUserDefaults standardUserDefaults] synchronize];
#warning 从沙盒中读取用户的配置项:在3G\4G环境是否仍然下载原图
            BOOL alwaysDownloadOriginalImage = [[NSUserDefaults standardUserDefaults] boolForKey:@"alwaysDownloadOriginalImage"];
            if (alwaysDownloadOriginalImage) { // 下载原图
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];
            } else { // 下载小图
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.thumbnailImage] placeholderImage:placeholder];
            }
        } else { // 没有网络
            UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:item.thumbnailImage];
            if (thumbnailImage) { // 内存\沙盒缓存中有小图
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.thumbnailImage] placeholderImage:placeholder];
            } else {
                [self.imageView sd_setImageWithURL:nil placeholderImage:placeholder];
            }
        }
    }
}

```


text:
package com.github.junitrunner.spring;

import static org.hamcrest.CoreMatchers.*;

import java.util.Arrays;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.annotation.IfProfileValue;

public class SpringRunnerTest {

    @Test
    public void shouldProcessIfProfileValue() throws Exception {

        System.setProperty("b", "y");
        SpringRunner unit = new SpringRunner(A.class);
        MockRunNotifier notifier = new MockRunNotifier();
        unit.run(notifier);

        Assert.assertThat(notifier.getCalls(), is(Arrays.asList("fireTestIgnored")));
    }

    @IfProfileValue(name = "b", value="x")
    public static class A {

        @Test
        public void x() {
        }
    }
}


text:
package org.helm.notation2.tools;

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

import org.helm.chemtoolkit.CTKException;
import org.helm.notation2.Monomer;
import org.helm.notation2.MonomerFactory;
import org.helm.notation2.exception.ChemistryException;
import org.helm.notation2.exception.HELM2HandledException;
import org.helm.notation2.exception.MonomerException;
import org.helm.notation2.exception.MonomerLoadingException;
import org.helm.notation2.exception.RNAUtilsException;
import org.helm.notation2.parser.exceptionparser.NotationException;
import org.helm.notation2.parser.notation.HELM2Notation;
import org.helm.notation2.parser.notation.annotation.AnnotationNotation;
import org.helm.notation2.parser.notation.connection.ConnectionNotation;
import org.helm.notation2.parser.notation.grouping.GroupingNotation;
import org.helm.notation2.parser.notation.polymer.MonomerNotation;
import org.helm.notation2.parser.notation.polymer.MonomerNotationGroup;
import org.helm.notation2.parser.notation.polymer.MonomerNotationGroupElement;
import org.helm.notation2.parser.notation.polymer.MonomerNotationGroupMixture;
import org.helm.notation2.parser.notation.polymer.MonomerNotationGroupOr;
import org.helm.notation2.parser.notation.polymer.MonomerNotationList;
import org.helm.notation2.parser.notation.polymer.MonomerNotationUnit;
import org.helm.notation2.parser.notation.polymer.MonomerNotationUnitRNA;
import org.helm.notation2.parser.notation.polymer.PolymerNotation;
import org.jdom2.JDOMException;

/**
 * ChangeObjects, class to provide simple methods to change the HELM2Notation
 * objects
 *
 * @author hecht
 */
public final class ChangeObjects {

	/**
	 * method to add an annotation at a specific position of the HELM2Notation
	 *
	 * @param notation
	 *            new annotation
	 * @param position
	 *            position of the new annotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void addAnnotation(final AnnotationNotation notation, final int position,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfAnnotations().add(position, notation);
	}

	/**
	 * method to change an annotation at the position of the HELM2Notation
	 *
	 * @param notation
	 *            new changed annotation
	 * @param position
	 *            position of the changed annotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void changeAnnotation(final AnnotationNotation notation, final int position,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfAnnotations().set(position, notation);
	}

	/**
	 * method to delete the annotation at the specific position of the
	 * HELM2Notation
	 *
	 * @param position
	 *            position of the to be deleted annotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void deleteAnnotation(final int position, final HELM2Notation helm2notation) {
		helm2notation.getListOfAnnotations().remove(position);
	}

	/**
	 * method to delete all annotations of the HELM2Notation
	 *
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void deleteAllAnnotations(final HELM2Notation helm2notation) {
		helm2notation.getListOfAnnotations().clear();
	}

	/**
	 * method to add a new connection at the position of the HELM2Notation
	 *
	 * @param notation
	 *            new ConnectionNotation
	 * @param position
	 *            position of the new ConnectionNotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void addConnection(final ConnectionNotation notation, final int position,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfConnections().add(position, notation);
	}

	/**
	 * method to change a connection at the position of the HELM2Notation
	 *
	 * @param position
	 *            position of the changed Connection
	 * @param notation
	 *            to be changed ConnectionNotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void changeConnection(final int position, final ConnectionNotation notation,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfConnections().set(position, notation);
	}

	/**
	 * method to delete the connection at the specific position of the
	 * HELM2Notation
	 *
	 * @param position
	 *            of the to deleted connection
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void deleteConnection(final int position, final HELM2Notation helm2notation) {
		helm2notation.getListOfConnections().remove(position);
	}

	/**
	 * method to add an annotation to a connection of the HELM2Notation
	 *
	 * @param position
	 *            position of the connection
	 * @param annotation
	 *            new annotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void addAnnotationToConnection(final int position, final String annotation,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfConnections().get(position).setAnnotation(annotation);
	}

	/**
	 * method to delete all connections of the HELM2Notation
	 *
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void deleteAllConnections(final HELM2Notation helm2notation) {
		helm2notation.getListOfConnections().clear();
	}

	/**
	 * method to add a group to the grouping section of the HELM2Notation
	 *
	 * @param notation
	 *            new group
	 * @param position
	 *            position of the new group
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void addGroup(final GroupingNotation notation, final int position,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfGroupings().add(position, notation);
	}

	/**
	 * method to change a group of the HELM2Notation
	 *
	 * @param notation
	 *            new group
	 * @param position
	 *            position of the to be changed group
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void changeGroup(final GroupingNotation notation, final int position,
			final HELM2Notation helm2notation) {
		helm2notation.getListOfGroupings().set(position, notation);
	}

	/**
	 * method to delete a group at a specific position of the HELM2Notation
	 *
	 * @param position
	 *            position of the to be deleted group
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void deleteGroup(final int position, final HELM2Notation helm2notation) {
		helm2notation.getListOfGroupings().remove(position);
	}

	/**
	 * method to delete all groups of the HELM2Notation
	 *
	 * @param helm2notation
	 *            input HELM2Notation
	 */
	public final static void deleteAllGroups(final HELM2Notation helm2notation) {
		helm2notation.getListOfGroupings().clear();
	}

	/**
	 * method to add an annotation to a PolymerNotation
	 *
	 * @param polymer
	 *            PolymerNotation
	 * @param annotation
	 *            new annotation
	 * @return PolymerNotation with the annotation
	 */
	public final static PolymerNotation addAnnotationToPolymer(final PolymerNotation polymer, final String annotation) {
		if (polymer.getAnnotation() != null) {
			return new PolymerNotation(polymer.getPolymerID(), polymer.getPolymerElements(),
					polymer.getAnnotation() + " | " + annotation);
		}
		return new PolymerNotation(polymer.getPolymerID(), polymer.getPolymerElements(), annotation);
	}

	/**
	 * method to remove a current annotation of a PolymerNotation
	 *
	 * @param polymer
	 *            PolymerNotation
	 * @return PolymerNotation with no annotation
	 */
	public final static PolymerNotation removeAnnotationOfPolmyer(PolymerNotation polymer) {
		return new PolymerNotation(polymer.getPolymerID(), polymer.getPolymerElements(), null);
	}

	/**
	 * method to add a new MonomerNotation to a PolymerNotation
	 *
	 * @param position
	 *            position of the new MonomerNotation
	 * @param polymer
	 *            PolymerNotation
	 * @param monomerNotation
	 *            new MonomerNotation
	 * @return PolymerNotation with the new MonomerNotation
	 */
	public final static PolymerNotation addMonomerNotation(int position, PolymerNotation polymer,
			MonomerNotation monomerNotation) {
		polymer.getPolymerElements().getListOfElements().add(position, monomerNotation);
		return polymer;
	}

	/**
	 * method to change the MonomerNotation on the specific position
	 *
	 * @param position
	 *            position of the changed MonomerNotation
	 * @param polymer
	 *            PolymerNotation
	 * @param not
	 *            changed MonomerNotation
	 */
	public final static void changeMonomerNotation(int position, PolymerNotation polymer, MonomerNotation not) {
		polymer.getPolymerElements().getListOfElements().set(position, not);
	}

	/**
	 * method to delete a MonomerNotation at a specific position of the
	 * PolymerNotation
	 *
	 * @param position
	 *            position of the to be deleted MonomerNotation
	 * @param polymer
	 *            PolymerNotation
	 * @throws NotationException
	 *             if the generated PolymerNotation has no elements after
	 *             deleting the MonomerNotation
	 */
	public final static void deleteMonomerNotation(int position, PolymerNotation polymer) throws NotationException {
		MonomerNotation monomerNotation = polymer.getPolymerElements().getListOfElements().get(position);
		if (polymer.getPolymerElements().getListOfElements().size() == 1) {
			throw new NotationException(monomerNotation.toString()
					+ " can't be removed. Polymer has to have at least one Monomer Notation");
		}
		polymer.getPolymerElements().getListOfElements().remove(monomerNotation);
	}

	/**
	 * method to add an annotation to a MonomerNotation
	 *
	 * @param polymer
	 *            PolymerNotation
	 * @param position
	 *            position of the monomerNotation
	 * @param annotation
	 *            new annotation
	 */
	public final static void addAnnotationToMonomerNotation(PolymerNotation polymer, int position, String annotation) {
		polymer.getPolymerElements().getListOfElements().get(position).setAnnotation(annotation);
	}

	/**
	 * method to set the count of a MonomerNotation
	 *
	 * @param polymer
	 *            PolymerNotation
	 * @param position
	 *            position of the MonomerNotation
	 * @param count
	 *            new count of the MonomerNotation
	 */
	public final static void addCountToMonomerNotation(PolymerNotation polymer, int position, String count) {
		polymer.getPolymerElements().getListOfElements().get(position).setCount(count);
	}

	/**
	 * method to delete the annotation of a MonomerNotation
	 *
	 * @param polymer
	 *            PolymerNotation
	 * @param position
	 *            position of the MonomerNotation
	 */
	public final static void deleteAnnotationFromMonomerNotation(PolymerNotation polymer, int position) {
		polymer.getPolymerElements().getListOfElements().get(position).setAnnotation(null);
	}

	/**
	 * method to set the count of a MonomerNotation to default (=1)
	 *
	 * @param polymer
	 *            PolymerNotation
	 * @param position
	 *            position of the MonomerNotation
	 */
	public final static void setCountToDefault(PolymerNotation polymer, int position) {
		polymer.getPolymerElements().getListOfElements().get(position).setCount("1");
	}

	/**
	 * method to change the PolymerNotation at a specific position of the
	 * HELM2Notation
	 *
	 * @param position
	 *            position of the PolymerNotation
	 * @param polymer
	 *            new PolymerNotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */

	public final static void changePolymerNotation(int position, PolymerNotation polymer, HELM2Notation helm2notation) {
		helm2notation.getListOfPolymers().set(position, polymer);
	}

	/**
	 * method to delete the PolymerNotation at a specific position of the
	 * HELM2Notation
	 *
	 * @param position
	 *            position of the PolymerNotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */

	public final static void deletePolymerNotation(int position, HELM2Notation helm2notation) {
		helm2notation.getListOfPolymers().remove(position);
	}

	/**
	 * method to add a PolymerNotation at a specific position of the
	 * HELM2Notation
	 *
	 * @param position
	 *            position of the PolymerNotation
	 * @param polymer
	 *            new PolymerNotation
	 * @param helm2notation
	 *            input HELM2Notation
	 */

	public final static void addPolymerNotation(int position, PolymerNotation polymer, HELM2Notation helm2notation) {
		helm2notation.getListOfPolymers().add(position, polymer);
	}

	/**
	 * method to replace the MonomerID with the new MonomerID for a given
	 * polymer type
	 *
	 * @param helm2notation
	 *            HELM2Notation
	 * @param polymerType
	 *            String of the polymer type
	 * @param existingMonomerID
	 *            old MonomerID
	 * @param newMonomerID
	 *            new MonomerID
	 * @throws NotationException
	 *             if notation was not valid
	 * @throws MonomerException
	 *             if monomer is not valid
	 * @throws ChemistryException
	 *             if chemistry engine could not be initialized
	 * @throws CTKException
	 *             general ChemToolKit exception passed to HELMToolKit
	 * @throws IOException IO error
	 * @throws JDOMException jdome error
	 *
	 */
	public final static void replaceMonomer(HELM2Notation helm2notation, String polymerType, String existingMonomerID,
			String newMonomerID) throws NotationException, MonomerException,
					ChemistryException, CTKException, IOException, JDOMException {
		validateMonomerReplacement(polymerType, existingMonomerID, newMonomerID);
		/*
		 * if(newMonomerID.length()> 1){ if( !( newMonomerID.startsWith("[") &&
		 * newMonomerID.endsWith("]"))){ newMonomerID = "[" + newMonomerID +
		 * "]"; } }
		 */
		for (int i = 0; i < helm2notation.getListOfPolymers().size(); i++) {
			if (helm2notation.getListOfPolymers().get(i).getPolymerID().getType().equals(polymerType)) {
				for (int j = 0; j < helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements()
						.size(); j++) {
					MonomerNotation monomerNotation = replaceMonomerNotation(
							helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().get(j),
							existingMonomerID, newMonomerID);
					if (monomerNotation != null) {
						helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().set(j,
								monomerNotation);
					}
				}
			}
		}
	}

	/**
	 * method to replace the MonomerNotation having the MonomerID with the new
	 * MonomerID
	 *
	 * @param monomerNotation
	 *            given monomer notation
	 * @param existingMonomerID
	 *            existing monomer id
	 * @param newMonomerID
	 *            new monomer id
	 * @return MonomerNotation, if it had the old MonomerID, null otherwise
	 * @throws NotationException
	 *             if new monomer id is not valid
	 * @throws ChemistryException
	 *             if chemistry engine can not be initialized
	 * @throws CTKException
	 *             if it contains an invalid smiles
	 * @throws MonomerLoadingException
	 *             if monomers can not be loaded
	 */
	public final static MonomerNotation replaceMonomerNotation(MonomerNotation monomerNotation,
			String existingMonomerID, String newMonomerID)
					throws NotationException, ChemistryException, CTKException, MonomerLoadingException {
		/* Nucleotide */
		if (monomerNotation instanceof MonomerNotationUnitRNA) {
			List<String> result = generateIDForNucleotide(((MonomerNotationUnitRNA) monomerNotation), existingMonomerID,
					newMonomerID);
			if (result.get(1) != null) {
				MonomerNotationUnitRNA newObject = new MonomerNotationUnitRNA(result.get(0), monomerNotation.getType());
				newObject.setCount(monomerNotation.getCount());
				if (monomerNotation.isAnnotationTrue()) {
					newObject.setAnnotation(monomerNotation.getAnnotation());
				}
				return newObject;
			}
		} else if (monomerNotation instanceof MonomerNotationUnit) {
			/* Simple MonomerNotationUnit */
			if (monomerNotation.getUnit().equals(existingMonomerID)) {
				return produceMonomerNotationUnitWithOtherID(monomerNotation, newMonomerID);
			}
		} else if (monomerNotation instanceof MonomerNotationList) {
			/* MonomerNotationList */
			monomerNotation = replaceMonomerNotationList(((MonomerNotationList) monomerNotation), existingMonomerID,
					newMonomerID);
			if (monomerNotation != null) {
				return monomerNotation;
			}
		} else if (monomerNotation instanceof MonomerNotationGroup) {
			/* MonomerNotatationGroup */
			monomerNotation = replaceMonomerNotationGroup(((MonomerNotationGroup) monomerNotation), existingMonomerID,
					newMonomerID);
			if (monomerNotation != null) {
				return monomerNotation;
			}
		} else {
			throw new NotationException("Unknown MonomerNotation Type " + monomerNotation.getClass());
		}

		return null;

	}

	/**
	 * method to replace the MonomerNotationGroup having the MonomerID with the
	 * new MonomerID
	 *
	 * @param monomerNotation
	 *            the to replace monomernotationgroup
	 * @param existingMonomerID
	 *            the to replace existing monomer id of the monomernotationgroup
	 * @param newMonomerID
	 *            the new monomerid
	 * @return MonomerNotationGroup, if it had the old MonomerID, null otherwise
	 * @throws NotationException
	 *             if the new monomer id is not valid
	 */
	public final static MonomerNotationGroup replaceMonomerNotationGroup(MonomerNotationGroup monomerNotation,
			String existingMonomerID, String newMonomerID) throws NotationException {
		MonomerNotationGroup newObject = null;
		boolean hasChanged = false;
		StringBuilder sb = new StringBuilder();
		String id = "";
		for (MonomerNotationGroupElement object : monomerNotation.getListOfElements()) {
			if (object.getMonomerNotation().getUnit().equals(existingMonomerID)) {
				hasChanged = true;
				id = generateGroupElement(newMonomerID, object.getValue());
			} else {
				id = generateGroupElement(object.getMonomerNotation().getUnit(), object.getValue());
			}
			if (monomerNotation instanceof MonomerNotationGroupOr) {
				sb.append(id + ",");
			} else {
				sb.append(id + "+");
			}

		}
		if (hasChanged) {
			sb.setLength(sb.length() - 1);
			if (monomerNotation instanceof MonomerNotationGroupOr) {
				newObject = new MonomerNotationGroupOr(sb.toString(), monomerNotation.getType());
			} else {
				newObject = new MonomerNotationGroupMixture(sb.toString(), monomerNotation.getType());
			}
		}
		return newObject;
	}

	/**
	 * method to replace the MonomerNotationUnit having the MonomerID with the
	 * new MonomerID
	 *
	 * @param monomerNotation
	 *            given monomer notation
	 * @param newID
	 *            new monomer id
	 * @return MonomerNotationUnit
	 * @throws NotationException
	 *             if new id is not valid
	 */
	public final static MonomerNotationUnit produceMonomerNotationUnitWithOtherID(MonomerNotation monomerNotation,
			String newID) throws NotationException {
		MonomerNotationUnit result = new MonomerNotationUnit(newID, monomerNotation.getType());
		if (monomerNotation.isAnnotationTrue()) {
			result.setAnnotation(monomerNotation.getAnnotation());
		}
		result.setCount(monomerNotation.getCount());
		return result;
	}

	/**
	 * method to replace the MonomerNotationList having the MonomerID with the
	 * new MonomerID
	 *
	 * @param object
	 *            MonomerNotationList to change
	 * @param existingMonomerID
	 *            monomer to change
	 * @param newMonomerID
	 *            new monomer
	 * @return MonomerNotationList, if it had the old MonomerID, null otherwise
	 * @throws NotationException
	 *             if notation is not valid
	 * @throws ChemistryException
	 *             if chemistry could not be initialized
	 * @throws CTKException
	 *             general ChemToolKit exception passed to HELMToolKit
	 * @throws MonomerLoadingException
	 *             could not load monomers from source
	 */
	public final static MonomerNotationList replaceMonomerNotationList(MonomerNotationList object,
			String existingMonomerID, String newMonomerID)
					throws NotationException, ChemistryException, CTKException, MonomerLoadingException {
		MonomerNotationList newObject = null;
		boolean hasChanged = false;
		StringBuilder sb = new StringBuilder();
		String id = "";
		for (MonomerNotation element : object.getListofMonomerUnits()) {
			if (element instanceof MonomerNotationUnitRNA) {
				List<String> result = generateIDForNucleotide(((MonomerNotationUnitRNA) element), existingMonomerID,
						newMonomerID);
				id = result.get(0);
				if (result.get(1) != null) {
					hasChanged = true;
				}
			} else {
				if (element.getUnit().equals(existingMonomerID)) {
					hasChanged = true;
					id = generateIDMonomerNotation(newMonomerID, element.getCount(), element.getAnnotation());
				} else {
					id = generateIDMonomerNotation(element.getUnit(), element.getCount(), element.getAnnotation());
				}

			}
			sb.append(id + ".");
		}
		if (hasChanged) {
			sb.setLength(sb.length() - 1);
			newObject = new MonomerNotationList(sb.toString(), object.getType());
			newObject.setCount(object.getCount());
			if (object.isAnnotationTrue()) {
				newObject.setAnnotation(object.getAnnotation());

			}
		}

		return newObject;

	}

	/**
	 * method to generate the MonomerNotation in String format
	 *
	 * @param id
	 *            id of the MonomerNotation
	 * @param count
	 *            Count of the MonomerNotation
	 * @param annotation
	 *            Annotation of the MonomerNotation
	 * @return MonomerNotation in String format
	 */
	private final static String generateIDMonomerNotation(String id, String count, String annotation) {
		if (id.length() > 1) {
			id = "[" + id + "]";
		}
		String result = id;
		try {
			if (!(Integer.parseInt(count) == 1)) {
				result += "'" + count + "'";
			}
		} catch (NumberFormatException e) {
			result += "'" + count + "'";
		}
		if (annotation != null) {
			result += "\"" + annotation + "\"";
		}
		return result;
	}

	/**
	 * method to generate the MonomerNotation for a RNA
	 *
	 * @param id
	 *            id of the MonomerNotation
	 * @param count
	 *            Count of the MonomerNotation
	 * @param annotation
	 *            Annotation of the MonomerNotation
	 * @return MonomerNotation in String format
	 * @throws MonomerLoadingException
	 * @throws ChemistryException
	 * @throws CTKException
	 */
	private final static String generateIDRNA(String id, String count, String annotation)
			throws MonomerLoadingException, ChemistryException, CTKException {
		String result = id;
		if (result.startsWith("[") && result.endsWith("]")) {
			result = id.substring(1, id.length() - 1);
		}
		if (MonomerFactory.getInstance().getMonomerStore().getMonomer("RNA", result).getMonomerType()
				.equals(Monomer.BRANCH_MOMONER_TYPE)) {
			if (id.length() > 1) {
				result = "[" + id + "]";
			}
			result = "(" + result + ")";
		} else {
			if (id.length() > 1) {
				result = "[" + id + "]";
			}
		}

		try {
			if (!(Integer.parseInt(count) == 1)) {
				result += "'" + count + "'";
			}
		} catch (NumberFormatException e) {
			result += "'" + count + "'";
		}
		if (annotation != null) {
			result += "\"" + annotation + "\"";
		}
		return result;
	}

	/**
	 * method to replace the MonomerNotationUnitRNA having the MonomerID with
	 * the new MonomerID
	 *
	 * @param object
	 *            MonomerNotationUnitRNA
	 * @param existingMonomerID
	 * @param newMonomerID
	 * @return List of MonomerNotationUnitRNA in String format and the
	 *         information if the MonomerNotationUnitRNA has to be changed
	 * @throws MonomerLoadingException
	 * @throws ChemistryException
	 * @throws CTKException
	 */
	private final static List<String> generateIDForNucleotide(MonomerNotationUnitRNA object, String existingMonomerID,
			String newMonomerID) throws MonomerLoadingException, ChemistryException, CTKException {
		List<String> result = new ArrayList<String>();
		String hasChanged = null;
		StringBuilder sb = new StringBuilder();
		String id = "";
		for (MonomerNotation element : object.getContents()) {
			if (element.getUnit().equals(existingMonomerID)) {
				hasChanged = "";
				id = generateIDRNA(newMonomerID, element.getCount(), element.getAnnotation());
			} else {
				id = generateIDRNA(element.getUnit(), element.getCount(), element.getAnnotation());
			}
			sb.append(id);
		}
		try {
			if (!(Integer.parseInt(object.getCount()) == 1)) {
				sb.append("'" + object.getCount() + "'");
			}
		} catch (NumberFormatException e) {
			sb.append("'" + object.getCount() + "'");
		}
		if (object.getAnnotation() != null) {
			sb.append("\"" + object.getAnnotation() + "\"");
		}
		result.add(sb.toString());
		result.add(hasChanged);
		return result;
	}

	/**
	 * method to generate the MonomerNotationGroupElement in String format
	 *
	 * @param id
	 * @param list
	 * @return MonomerNotationGroupElement in String format
	 */
	private static String generateGroupElement(String id, List<Double> list) {
		StringBuilder sb = new StringBuilder();

		if (list.size() == 1) {
			if (list.get(0) == -1.0) {
				sb.append(id + ":");
				sb.append("?" + "-");
			} else if (list.get(0) == 1.0) {
				sb.append(id + ":");
			} else {
				sb.append(id + ":" + list.get(0) + "-");
			}
		} else {
			sb.append(id + ":");
			for (Double item : list) {
				sb.append(item + "-");
			}
		}

		sb.setLength(sb.length() - 1);
		return sb.toString();
	}

	private static boolean validateMonomerReplacement(String polymerType, String existingMonomerID, String newMonomerID)
			throws MonomerException, IOException, JDOMException, NotationException, ChemistryException, CTKException {

		if (null == polymerType || polymerType.length() == 0) {
			throw new NotationException("Polymer type is required for monomer replacement");
		}

		if (null == existingMonomerID || existingMonomerID.length() == 0) {
			throw new NotationException("Existing monomer ID is required for monomer replacement");
		}

		if (null == newMonomerID || newMonomerID.length() == 0) {
			throw new NotationException("New monomer ID is required for monomer replacement");
		}
		Map<String, Monomer> monomers = MonomerFactory.getInstance().getMonomerStore().getMonomers(polymerType);

		if (null == monomers || monomers.size() == 0) {
			throw new NotationException("Unknown polymer type [" + polymerType + "] found");
		}

		if (!monomers.containsKey(existingMonomerID)) {
			throw new NotationException(
					"Existing monomer ID [" + existingMonomerID + "] is invalid in polymer type " + polymerType);
		}

		if (!monomers.containsKey(newMonomerID)) {
			throw new NotationException(
					"New monomer ID [" + newMonomerID + "] is invalid in polymer type " + polymerType);
		}

		Monomer existingMonomer = monomers.get(existingMonomerID);
		Monomer newMonomer = monomers.get(newMonomerID);

		if (polymerType.equals(Monomer.NUCLIEC_ACID_POLYMER_TYPE)) {
			if (existingMonomer.getMonomerType().equals(newMonomer.getMonomerType())) {
				if (existingMonomer.getMonomerType().equals(Monomer.BACKBONE_MOMONER_TYPE)) {
					if (!existingMonomer.getNaturalAnalog().equals(newMonomer.getNaturalAnalog())) {
						throw new NotationException("Existing monomer natural analog ["
								+ existingMonomer.getNaturalAnalog() + "] and new monomer natural analog ["
								+ newMonomer.getNaturalAnalog() + "] are different");
					}
				}
			} else {
				throw new NotationException("Existing monomer type [" + existingMonomer.getMonomerType()
						+ "] and new monomer type [" + newMonomer.getMonomerType() + "] are different");
			}
		}

		if (!newMonomer.attachmentEquals(existingMonomer)) {
			throw new NotationException("Existing monomer attachment [" + existingMonomer.getAttachmentListString()
					+ "] and new monomer attachement [" + newMonomer.getAttachmentListString() + "] are different");
		}

		return true;
	}

	/**
	 * This function replaces smiles in complex notation with temporary ids
	 *
	 * @param helm2notation
	 *            given helm2 notation
	 * @throws NotationException
	 *             if notation is not valid
	 * @throws ChemistryException
	 *             if chemistry engine can not be initialized
	 * @throws HELM2HandledException
	 *             if it contains HELM2 specific features, so that it can not be
	 *             casted to HELM1 Format
	 * @throws CTKException
	 *             general ChemToolKit exception passed to HELMToolKit
	 * @throws MonomerLoadingException
	 *             if monomers can not be loaded
	 * @throws JDOMException
	 *             if smiles can not be replace with the temporary ids
	 */
	public static final void replaceSMILESWithTemporaryIds(HELM2Notation helm2notation) throws NotationException,
			HELM2HandledException, ChemistryException, CTKException, MonomerLoadingException, JDOMException {
		for (int i = 0; i < helm2notation.getListOfPolymers().size(); i++) {
			/* First save intern smiles to the MonomerFactory */
			MethodsMonomerUtils.getListOfHandledMonomers(helm2notation.getListOfPolymers().get(i).getListMonomers());

			for (int j = 0; j < helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements()
					.size(); j++) {
				MonomerNotation monomerNotation = replaceSMILESWithTemporaryIdsMonomerNotation(
						helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().get(j));
				if (monomerNotation != null) {
					helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().set(j,
							monomerNotation);
				}
			}
		}

	}

	/**
	 * @param monomerNotation
	 * @return
	 * @throws NotationException
	 * @throws IOException
	 * @throws JDOMException
	 * @throws ChemistryException
	 * @throws CTKException
	 * @throws MonomerLoadingException
	 */
	private static MonomerNotation replaceSMILESWithTemporaryIdsMonomerNotation(MonomerNotation monomerNotation)
			throws NotationException, ChemistryException, CTKException, MonomerLoadingException, JDOMException {
		/* Nucleotide */
		if (monomerNotation instanceof MonomerNotationUnitRNA) {
			List<String> result = ChangeObjects.generateIDForNucleotide(((MonomerNotationUnitRNA) monomerNotation));
			if (result.get(1) != null) {
				MonomerNotationUnitRNA newObject = new MonomerNotationUnitRNA(result.get(0), monomerNotation.getType());
				newObject.setCount(monomerNotation.getCount());
				if (monomerNotation.isAnnotationTrue()) {
					newObject.setAnnotation(monomerNotation.getAnnotation());
				}
				return newObject;
			}
		} else if (monomerNotation instanceof MonomerNotationUnit) {
			/* Simple MonomerNotationUnit */
			return ChangeObjects.produceMonomerNotationUnitWithOtherID(monomerNotation);
		} else if (monomerNotation instanceof MonomerNotationList) {
			/* MonomerNotationList */
			monomerNotation = replaceMonomerNotationList(((MonomerNotationList) monomerNotation));
			if (monomerNotation != null) {
				return monomerNotation;
			}
		} else if (monomerNotation instanceof MonomerNotationGroup) {
			/* MonomerNotatationGroup */
			monomerNotation = ChangeObjects.replaceMonomerNotationGroup(((MonomerNotationGroup) monomerNotation));
			if (monomerNotation != null) {
				return monomerNotation;
			}
		} else {
			throw new NotationException("Unknown MonomerNotation Type " + monomerNotation.getClass());
		}

		return null;
	}

	/**
	 * @param monomerNotationGroup
	 * @return
	 * @throws JDOMException
	 * @throws NotationException
	 * @throws ChemistryException
	 * @throws CTKException
	 * @throws MonomerLoadingException
	 */
	private static MonomerNotation replaceMonomerNotationGroup(MonomerNotationGroup monomerNotationGroup)
			throws NotationException, JDOMException, ChemistryException, CTKException, MonomerLoadingException {
		MonomerNotationGroup newObject = null;
		boolean hasChanged = false;
		StringBuilder sb = new StringBuilder();
		String id = "";
		for (MonomerNotationGroupElement object : monomerNotationGroup.getListOfElements()) {
			String newID = ChangeObjects.produceID(object.getMonomerNotation().getUnit(),
					object.getMonomerNotation().getType());
			if (newID != null) {
				newID = "[" + newID + "]";
				hasChanged = true;
				id = generateGroupElement(newID, object.getValue());
			} else {
				id = generateGroupElement(object.getMonomerNotation().getUnit(), object.getValue());
			}
			if (monomerNotationGroup instanceof MonomerNotationGroupOr) {
				sb.append(id + ",");
			} else {
				sb.append(id + "+");
			}

		}
		if (hasChanged) {
			sb.setLength(sb.length() - 1);
			if (monomerNotationGroup instanceof MonomerNotationGroupOr) {
				newObject = new MonomerNotationGroupOr(sb.toString(), monomerNotationGroup.getType());
			} else {
				newObject = new MonomerNotationGroupMixture(sb.toString(), monomerNotationGroup.getType());
			}
		}
		return newObject;
	}

	/**
	 * @param monomerNotationList
	 * @return
	 * @throws JDOMException
	 * @throws NotationException
	 * @throws ChemistryException
	 * @throws CTKException
	 * @throws MonomerLoadingException
	 */
	private static MonomerNotation replaceMonomerNotationList(MonomerNotationList monomerNotationList)
			throws NotationException, JDOMException, ChemistryException, CTKException, MonomerLoadingException {
		MonomerNotationList newObject = null;
		boolean hasChanged = false;
		StringBuilder sb = new StringBuilder();
		String id = "";
		for (MonomerNotation element : monomerNotationList.getListofMonomerUnits()) {
			if (element instanceof MonomerNotationUnitRNA) {
				List<String> result = ChangeObjects.generateIDForNucleotide(((MonomerNotationUnitRNA) element));
				id = result.get(0);
				if (result.get(1) != null) {
					hasChanged = true;
				}
			} else {
				String newID = ChangeObjects.produceID(element.getUnit(), element.getType());
				if (newID != null) {
					hasChanged = true;
					id = generateIDMonomerNotation(newID, element.getCount(), element.getAnnotation());
				} else {
					id = generateIDMonomerNotation(element.getUnit(), element.getCount(), element.getAnnotation());
				}

			}
			sb.append(id + ".");
		}
		if (hasChanged) {
			sb.setLength(sb.length() - 1);
			newObject = new MonomerNotationList(sb.toString(), monomerNotationList.getType());
			newObject.setCount(monomerNotationList.getCount());
			if (monomerNotationList.isAnnotationTrue()) {
				newObject.setAnnotation(monomerNotationList.getAnnotation());

			}
		}

		return newObject;
	}

	/**
	 * @param monomerNotation
	 * @return
	 * @throws NotationException
	 * @throws ChemistryException
	 * @throws CTKException
	 * @throws MonomerLoadingException
	 */
	private static MonomerNotation produceMonomerNotationUnitWithOtherID(MonomerNotation monomerNotation)
			throws NotationException, ChemistryException, CTKException, MonomerLoadingException {
		String newID = ChangeObjects.produceID(monomerNotation.getUnit(), monomerNotation.getType());
		if (newID != null) {
			MonomerNotationUnit result = new MonomerNotationUnit(newID, monomerNotation.getType());
			if (monomerNotation.isAnnotationTrue()) {
				result.setAnnotation(monomerNotation.getAnnotation());
			}
			result.setCount(monomerNotation.getCount());
			return result;
		} else {
			return null;
		}
	}

	/**
	 * @param monomerNotationUnitRNA
	 * @return
	 * @throws MonomerLoadingException
	 * @throws ChemistryException
	 * @throws CTKException
	 */
	private static List<String> generateIDForNucleotide(MonomerNotationUnitRNA monomerNotationUnitRNA)
			throws MonomerLoadingException, ChemistryException, CTKException {
		List<String> result = new ArrayList<String>();
		String hasChanged = null;
		StringBuilder sb = new StringBuilder();
		String id = "";
		for (MonomerNotation element : monomerNotationUnitRNA.getContents()) {
			String newID = ChangeObjects.produceID(element.getUnit(), element.getType());

			if (newID != null) {
				hasChanged = "";
				id = generateIDRNA(newID, element.getCount(), element.getAnnotation());
			} else {
				id = generateIDRNA(element.getUnit(), element.getCount(), element.getAnnotation());
			}
			sb.append(id);
		}
		try {
			if (!(Integer.parseInt(monomerNotationUnitRNA.getCount()) == 1)) {
				sb.append("'" + monomerNotationUnitRNA.getCount() + "'");
			}
		} catch (NumberFormatException e) {
			sb.append("'" + monomerNotationUnitRNA.getCount() + "'");
		}
		if (monomerNotationUnitRNA.getAnnotation() != null) {
			sb.append("\"" + monomerNotationUnitRNA.getAnnotation() + "\"");
		}
		result.add(sb.toString());
		result.add(hasChanged);
		return result;
	}

	private static String produceID(String oldID, String polymerType)
			throws MonomerLoadingException, ChemistryException, CTKException {
		HELM2NotationUtils.LOG.debug("SMILES string?: " + oldID);
		if (oldID.startsWith("[") && oldID.endsWith("]")) {
			oldID = oldID.substring(1, oldID.length() - 1);
		}
		if (MonomerFactory.getInstance().getMonomerStore().getMonomer(polymerType, oldID) == null) {
			return MonomerFactory.getInstance().getSmilesMonomerDB().get(oldID).getAlternateId();
		} else {
			return null;
		}
	}

	/**
	 * this method will automatically add base pair info into notation only if
	 * it contains two RNA polymer notations and there is no base pairing info
	 *
	 * @param helm2notation
	 *            HELM2Notation object
	 * @throws NotationException
	 *             if notation is not valid
	 * @throws RNAUtilsException
	 *             if the polymer is not a RNA/DNA
	 * @throws HELM2HandledException
	 *             if it contains HELM2 specific features, so that it can not be
	 *             casted to HELM1 Format
	 * @throws org.helm.notation2.exception.NotationException
	 *             if notation is not valid
	 * @throws ChemistryException
	 *             if chemistry engine can not be initialized
	 */
	public static void hybridize(HELM2Notation helm2notation) throws NotationException, RNAUtilsException,
			HELM2HandledException, org.helm.notation2.exception.NotationException, ChemistryException {
		if (HELM2NotationUtils.getAllBasePairConnections(helm2notation.getListOfConnections()).isEmpty()
				&& HELM2NotationUtils.getRNAPolymers(helm2notation.getListOfPolymers()).size() == 2) {
			List<ConnectionNotation> connections = RNAUtils.hybridize(
					HELM2NotationUtils.getRNAPolymers(helm2notation.getListOfPolymers()).get(0),
					HELM2NotationUtils.getRNAPolymers(helm2notation.getListOfPolymers()).get(1));
			for (ConnectionNotation connection : connections) {
				addConnection(connection, helm2notation.getListOfConnections().size(), helm2notation);
			}
		}
	}

}


text:
mkdir build
cd build

cmake \
  -DCMAKE_INSTALL_PREFIX=$PREFIX \
  -DCMAKE_INSTALL_LIBDIR="lib" \
  -DBUILD_TESTING=OFF \
  -DBUILD_SHARED_LIBS=ON \
  -DLAPACKE=ON \
  ..

make -j${CPU_COUNT}
make install


text:
function register() {

  $.ajax({
		type: "POST",
		url: USERS,
		data: {
			email: document.getElementById("email").value,
			password: document.getElementById("password").value
		},
		success: function( data, textStatus, xhr ) {
			window.location = HOME;
		},
		error: function( xhr, textStatus, msg ) {
			console.log("PROVIDE A REAL ERROR MESSAGE");
		},
		datatype: "json"
	});

} // register

// login
function login() {

  $.ajax({
		type: "POST",
		url: AUTH,
		data: {
			email: document.getElementById("email").value,
			password: document.getElementById("password").value
		},
		success: function( data, textStatus, xhr ) {
			window.location = HOME;
		},
		error: function( xhr, textStatus, msg ) {
			alert("Invalid credentials.");
		},
		datatype: "json"
	});

} // login

// logout
function logout() {

  $.ajax({
		type: "DELETE",
		url: AUTH,
		success: function( data, textStatus, xhr ) {
			window.location = WWW;
		},
		error: function( xhr, textStatus, msg ) {
			console.log("PROVIDE A REAL ERROR MESSAGE");
		},
		datatype: "json"
	});

} // logout


text:
set -euo pipefail

grafana-server --config=/usr/local/etc/grafana/grafana.ini --homepath /usr/local/share/grafana cfg:default.paths.logs=/usr/local/var/log/grafana cfg:default.paths.data=/usr/local/var/lib/grafana cfg:default.paths.plugins=/usr/local/var/lib/grafana/plugins &

telegraf -config telegraf.conf &

influxd &

influxd -config influxdb.generated.conf


text:
<?php

namespace Users;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Users\Model\Users;
use Users\Model\UsersTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class Module
{

    public function onBootstrap(MvcEvent $e)
    {
        $e->getApplication()->getServiceManager()->get('translator');
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Users\Model\UsersTable' => function($sm) {
                    $tableGateway = $sm->get('UsersTableGateway');
                    $table = new UsersTable($tableGateway);
                    return $table;
                },
                'Users\Model\Users' => function($sm) {
                    $adapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $users = new \Users\Model\Users();
                    $users->setDbAdapter($adapter);
                    return $users;
                },
                'UsersTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Users());
                    return new TableGateway('system_users', $dbAdapter, null, $resultSetPrototype);
                },
            ),
        );
    }

}


text:
package com.example.dell.mytextapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.dell.mytextapplication.circlemenu.view.CircleImageView;
import com.example.dell.mytextapplication.circlemenu.view.CircleLayout;
import com.example.dell.mytextapplication.circlemenu.view.CircleLayout.OnItemClickListener;
import com.example.dell.mytextapplication.circlemenu.view.CircleLayout.OnItemSelectedListener;
import com.example.dell.mytextapplication.online.WebVideo;
import com.example.dell.mytextapplication.util.AppLog;

import android.content.Intent;

import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements OnItemSelectedListener, OnItemClickListener {
    TextView selectedTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AppLog.enableLogging(true);
        CircleLayout circleMenu = (CircleLayout)findViewById(R.id.main_circle_layout);
        circleMenu.setOnItemSelectedListener(this);
        circleMenu.setOnItemClickListener(this);

        selectedTextView = (TextView)findViewById(R.id.main_selected_textView);
        selectedTextView.setText(((CircleImageView)circleMenu.getSelectedItem()).getName());
    }

    @Override
    public void onItemSelected(View view, int position, long id, String name) {
        selectedTextView.setText(name);
    }

    @Override
    public void onItemClick(View view, int position, long id, String name) {
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.start_app) + " " + name, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        switch(position){
            case 0:
                intent.setClass(MainActivity.this, JieVideo.class);
                startActivity(intent);
                break;
            case 2:
                intent.setClass(MainActivity.this, WebVideo.class);
                startActivity(intent);
                break;
        }
    }

}