text:
package ca.ualberta.lexie;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class UnarchiveScreen extends ViewArchive{
	private ListView mainListView ;
	private ArrayAdapter<ToDo> listAdapter;
	public static ArrayList<ToDo> viewarchived=new ArrayList<ToDo>();
	private String ARCHIVEFILENAME="archive1.sav";
	private String FILENAME="saves8.sav";
	private ArrayList<ToDo> todolist;
	private ArrayList<ToDo> moveBackList;
	private ArrayList<Integer> positions=new ArrayList<Integer>();

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.unarchive_screen);
		moveBackList=new ArrayList<ToDo>();
		//when a list item is clicked it is added to the movebackList
		mainListView = (ListView) findViewById( R.id.unarchiveListView);
		mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			public void onItemClick(AdapterView<?> listAdapter,View v, int position, long id)
			{
				moveBackList.add(viewarchived.get(position));
				positions.add(position);
			}
		});
		//this button calls function MoveBack();
		Button move_back=(Button) findViewById(R.id.moveSelect);
		move_back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				MoveBack();
			}
		});
		//this button calls delete
		Button deleteButton=(Button) findViewById(R.id.deleteSelect);
		deleteButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				Delete();
			}
		});
	}
	//moves the items from moveBackList to todolist
	public void MoveBack(){
		for(int i=0;i<moveBackList.size();i++){
			todolist.add(moveBackList.get(i));
			viewarchived.remove(positions.get(i));
		}
		saveInFile();
		saveArchiveInFile();
		listAdapter.notifyDataSetChanged();
	}
	//deletes the selected items
	public void Delete(){
		for(int i=0;i<moveBackList.size();i++){
			viewarchived.remove(positions.get(i));
		}
		saveArchiveInFile();
		listAdapter.notifyDataSetChanged();
	}
	//this does the same thing all the other onStarts do...Go read those if you're curious
	public void onStart(){
		super.onStart();
		loadArchiveFromFile();
		loadFromFile();
		mainListView = (ListView) findViewById( R.id.unarchiveListView );
		listAdapter = new ArrayAdapter<ToDo>(this,android.R.layout.simple_list_item_checked, viewarchived);
		mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		mainListView.setAdapter( listAdapter );
	}
	//loads list viewarchived from file ARCHIVEFILENAME
	private void loadArchiveFromFile() {
		try {
			FileInputStream fis = openFileInput(ARCHIVEFILENAME);
			InputStreamReader isr = new InputStreamReader(fis);
			//from http://www.javacreed.com/simple-gson-example/
			Gson gson= new GsonBuilder().create();
			viewarchived=gson.fromJson(isr, new TypeToken <ArrayList<ToDo>>(){}.getType());
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}
}
//loads to do list from file FILENAME
private void loadFromFile() {
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
//from http://www.javacreed.com/simple-gson-example/
Gson gson= new GsonBuilder().create();
todolist=gson.fromJson(isr, new TypeToken <ArrayList<ToDo>>(){}.getType());
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
//saves todolist to file FILENAME
private void saveInFile() {
try {
FileOutputStream fos = openFileOutput(FILENAME,0);
OutputStreamWriter osw = new OutputStreamWriter(fos);
Gson gson=new GsonBuilder().create();
gson.toJson(todolist,osw);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//saves viewarchived to ARCHIVEFILENAME
private void saveArchiveInFile() {
try {
FileOutputStream fos = openFileOutput(ARCHIVEFILENAME,0);
OutputStreamWriter osw = new OutputStreamWriter(fos);
Gson gson=new GsonBuilder().create();
gson.toJson(viewarchived,osw);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


text:
<?php

/**
 * afValidatorCache form.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage form
 * @author     ##AUTHOR_NAME##
 */
class afValidatorCacheForm extends BaseafValidatorCacheForm
{
  public function configure()
  {
  }
}

redpajama_set_name: RedPajamaGithub


text:
import os
import fnmatch
import re
import subprocess
import sys
import readline
import shutil
import random
#settings_file = '%s/.mod-lang-scala' % os.getenv('HOME')

### Known config keys
maven_pom_xml_namespace = "http://maven.apache.org/POM/4.0.0"
#default_settings = {'dry_run': False, 'multi_threaded': False, 'verbose': False, 'use_colors': True}
#boolean_keys = ['dry_run', 'multi_threaded', 'verbose']

class Colors(object):
    MAGENTA = '\033[95m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    CYAN = '\033[96m'
    END = '\033[0m'
    UNDERLINE = '\033[4m'

    @staticmethod
    def magenta():
        if use_colors():
            return Colors.MAGENTA
        else:
            return ""

    @staticmethod
    def green():
        if use_colors():
            return Colors.GREEN
        else:
            return ""

    @staticmethod
    def yellow():
        if use_colors():
            return Colors.YELLOW
        else:
            return ""

    @staticmethod
    def red():
        if use_colors():
            return Colors.RED
        else:
            return ""

    @staticmethod
    def cyan():
        if use_colors():
            return Colors.CYAN
        else:
            return ""

    @staticmethod
    def end_color():
        if use_colors():
            return Colors.END
        else:
            return ""

class Levels(Colors):
    C_DEBUG = Colors.CYAN
    C_INFO = Colors.GREEN
    C_WARNING = Colors.YELLOW
    C_FATAL = Colors.RED
    C_ENDC = Colors.END

    DEBUG = "DEBUG"
    INFO = "INFO"
    WARNING = "WARNING"
    FATAL = "FATAL"

    @staticmethod
    def get_color(level):
        if use_colors():
            return getattr(Levels, "C_" + level)
        else:
            return ""

def use_colors():
    return True

#  return ('use_colors' in settings and settings['use_colors']) or ('use_colors' not in settings)

def prettyprint(message, level):
    start_color = Levels.get_color(level)
    end_color = Levels.end_color()

    print "[%s%s%s] %s" % (start_color, level, end_color, message)

def to_bool(x):
    if type(x) == bool:
        return x
    if type(x) == str:
        return {'true': True, 'false': False}.get(x.strip().lower())

def input_with_default(msg, default):
    i = raw_input(
        "%s %s[%s]%s: " % (msg, Colors.magenta(), default, Colors.end_color()))
    if i.strip() == "":
        i = default
    return i

def get_search_path(executable):
    """Retrieves a search path based on where the current executable is located.  Returns a string to be prepended to add"""
    in_bin_dir = re.compile('^.*/?bin/.*.py')
    if in_bin_dir.search(executable):
        return "./"
    else:
        return "../"

def strip_leading_dots(filename):
    return filename.strip('/. ')

def to_set(list):
    """Crappy implementation of creating a Set from a List.  To cope with older Python versions"""
    temp_dict = {}
    for entry in list:
        temp_dict[entry] = "dummy"
    return temp_dict.keys()

class GlobDirectoryWalker:
    """A forward iterator that traverses a directory tree"""

    def __init__(self, directory, pattern="*"):
        self.stack = [directory]
        self.pattern = pattern
        self.files = []
        self.index = 0

    def __getitem__(self, index):
        while True:
            try:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
            else:
                # got a filename
                fullname = os.path.join(self.directory, file)
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    self.stack.append(fullname)
                if fnmatch.fnmatch(file, self.pattern):
                    return fullname

class Git(object):
    '''Encapsulates git functionality necessary for releasing Infinispan'''
    cmd = 'git'
    # Helper functions to clean up branch lists
    @staticmethod
    def clean(e): return e.strip().replace(' ', '').replace('*', '')

    @staticmethod
    def non_empty(e): return e != None and e.strip() != ''

    @staticmethod
    def current(e): return e != None and e.strip().replace(' ', '').startswith(
        '*')

    def __init__(self, branch, tag_name, settings):
        self.settings = settings
        if not self.is_git_directory():
            raise Exception(
                'Attempting to run git outside of a repository. Current directory is %s' % os.path.abspath(
                    os.path.curdir))

        self.branch = branch
        self.tag = tag_name
        self.verbose = False
        if settings.verbose:
            self.verbose = True
        rand = '%x'.upper() % (random.random() * 100000)
        self.working_branch = '__temp_%s' % rand
        self.original_branch = self.current_branch()

    def run_git(self, opts):
        call = [self.cmd]
        if type(opts) == list:
            for o in opts:
                call.append(o)
        elif type(opts) == str:
            for o in opts.split(' '):
                if o != '':
                    call.append(o)
        else:
            raise Error("Cannot handle argument of type %s" % type(opts))
        if self.settings.verbose:
            prettyprint('Executing %s' % call, Levels.DEBUG)
        # Non-interactive shells have issues with piping, so do normal check calls
        if self.settings.non_interactive:
            return subprocess.check_call(call)
        else:
            return subprocess.Popen(
                call, stdout=subprocess.PIPE).communicate()[0].split('\n')

    def is_git_directory(self):
        if self.settings.non_interactive:
            return True
        else:
            return self.run_git('branch')[0] != ''

    def is_upstream_clone(self):
        if self.settings.non_interactive:
            return True
        else:
            r = self.run_git('remote show -n origin')
            cleaned = map(self.clean, r)

            def push(e): return e.startswith('PushURL:')

            def remove_noise(e): return e.replace('PushURL:', '')

            push_urls = map(remove_noise, filter(push, cleaned))
            return len(push_urls) == 1 and \
                   push_urls[0] == 'git@github.com:vert-x/mod-lang-scala.git'

    def clean_branches(self, raw_branch_list):
        return map(self.clean, filter(self.non_empty, raw_branch_list))

    def remote_branch_exists(self):
        """Tests whether the branch exists on the remote origin"""
        if self.settings.non_interactive:
            return True
        else:
            branches = self.clean_branches(self.run_git("branch -r"))

            def replace_origin(b): return b.replace('origin/', '')

            return self.branch in map(replace_origin, branches)

    def switch_to_branch(self):
        """Switches the local repository to the specified branch.  Creates it if it doesn't already exist."""
        if self.settings.non_interactive:
            # If non-interactive, the repo is clean, checkout directly, unless master
            # TODO: Uncomment this and make it conditional when non-master
            # self.run_git("branch %s origin/%s" % (self.branch, self.branch))
            self.run_git("checkout %s" % self.branch)
        else:
            local_branches = self.clean_branches(self.run_git("branch"))
            if self.branch not in local_branches:
                self.run_git("branch %s origin/%s" % (self.branch, self.branch))
            self.run_git("checkout %s" % self.branch)

    def create_tag_branch(self):
        '''Creates and switches to a temp tagging branch, based off the release branch.'''
        self.run_git("checkout -b %s %s" % (self.working_branch, self.branch))

    def commit(self, files, message):
        '''Commits the set of files to the current branch with a generated commit message.'''
        for f in files:
            self.run_git("add %s" % f)

        self.run_git(["commit", "-m", message])

    def tag_for_release(self):
        """Tags the current branch for release using the tag name."""
        self.run_git(["tag", "-a", "-m", "'Release Script: tag %s'" % self.tag,
                      self.tag])

    def push_tags_to_origin(self):
        '''Pushes the updated tags to origin'''
        self.run_git("push origin --tags")

    def push_master_to_origin(self):
        '''Pushes the updated tags to origin'''
        self.run_git("push origin master")

    def current_branch(self):
        """Returns the current branch you are on"""
        if (self.settings.non_interactive):
            return 'master'
        else:
            return map(self.clean, filter(self.current, self.run_git('branch')))[0]

    def cleanup(self):
        '''Cleans up any temporary branches created'''
        self.run_git("checkout %s" % self.original_branch)
        self.run_git("branch -D %s" % self.working_branch)

class DryRun(object):
    location_root = "%s/%s" % (os.getenv("HOME"), "mod-lang-scala-release-dry-run")

    def find_version(self, url):
        return os.path.split(url)[1]

    def copy(self, src, dst):
        prettyprint(
            "  DryRun: Executing %s" % ['rsync', '-rv', '--protocol=28', src,
                                        dst], Levels.DEBUG)
        try:
            os.makedirs(dst)
        except:
            pass
        subprocess.check_call(['rsync', '-rv', '--protocol=28', src, dst])

class Uploader(object):
    def __init__(self, settings):
        if settings.verbose:
            self.scp_cmd = ['scp', '-rv']
            self.rsync_cmd = ['rsync', '-rv', '--protocol=28']
        else:
            self.scp_cmd = ['scp', '-r']
            self.rsync_cmd = ['rsync', '-r', '--protocol=28']

    def upload_scp(self, fr, to, flags=[]):
        self.upload(fr, to, flags, list(self.scp_cmd))

    def upload_rsync(self, fr, to, flags=[]):
        self.upload(fr, to, flags, list(self.rsync_cmd))

    def upload(self, fr, to, flags, cmd):
        for e in flags:
            cmd.append(e)
        cmd.append(fr)
        cmd.append(to)
        subprocess.check_call(cmd)

class DryRunUploader(DryRun):
    def upload_scp(self, fr, to, flags=[]):
        self.upload(fr, to, "scp")

    def upload_rsync(self, fr, to, flags=[]):
        self.upload(fr, to.replace(':', '____').replace('@', "__"), "rsync")

    def upload(self, fr, to, type):
        self.copy(fr, "%s/%s/%s" % (self.location_root, type, to))

def build_publish(settings):
    """Builds the distribution in the current working dir"""
    sbt_commands = [['clean'], ['+ package'], ['+ publishM2']]
    if not settings.dry_run:
        sbt_commands.append(['+ publish-signed'])

    for c in sbt_commands:
        c.insert(0, 'sbt')
        prettyprint("Execute SBT command %s" % c, Levels.DEBUG)
        subprocess.check_call(c)

def get_version_pattern():
    return re.compile("^([0-9]\.[0-9])\.[0-9]", re.IGNORECASE)

def get_version_major_minor(full_version):
    pattern = get_version_pattern()
    matcher = pattern.match(full_version)
    return matcher.group(1)

def assert_python_minimum_version(major, minor):
    e = re.compile('([0-9])\.([0-9])\.([0-9]).*')
    m = e.match(sys.version)
    major_ok = int(m.group(1)) == major
    minor_ok = int(m.group(2)) >= minor
    if not (minor_ok and major_ok):
        prettyprint("This script requires Python >= %s.%s.0.  You have %s" % (
        major, minor, sys.version), Levels.FATAL)
        sys.exit(3)


text:
package br.gov.siscomex.portalunico.due.model;

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

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "DeclarationDrawbackIsencao", propOrder =
    { "goodsShipment"
})

@XmlRootElement(name="DeclarationDrawbackIsencao")
public class DeclarationDrawbackIsencao  {

  @XmlElement(name="goodsShipment", required = true)
  @ApiModelProperty(required = true, value = "")
  @Valid
  private List<GoodsShipment> goodsShipment = new ArrayList<>();
 /**
   * Get goodsShipment
   * @return goodsShipment
  **/
  @JsonProperty("goodsShipment")
  @NotNull
  public List<GoodsShipment> getGoodsShipment() {
    return goodsShipment;
  }

  public void setGoodsShipment(List<GoodsShipment> goodsShipment) {
    this.goodsShipment = goodsShipment;
  }

  public DeclarationDrawbackIsencao goodsShipment(List<GoodsShipment> goodsShipment) {
    this.goodsShipment = goodsShipment;
    return this;
  }

  public DeclarationDrawbackIsencao addGoodsShipmentItem(GoodsShipment goodsShipmentItem) {
    this.goodsShipment.add(goodsShipmentItem);
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class DeclarationDrawbackIsencao {\n");

    sb.append("    goodsShipment: ").append(toIndentedString(goodsShipment)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
package io.requery.android.sqlitex;

import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import io.requery.android.database.sqlite.SQLiteStatement;
import io.requery.android.sqlite.BasePreparedStatement;
import io.requery.android.sqlite.CursorResultSet;
import io.requery.android.sqlite.SingleResultSet;

import java.sql.ResultSet;
import java.sql.SQLException;

class SqlitexPreparedStatement extends BasePreparedStatement {

    private final SqlitexConnection connection;
    private final SQLiteStatement statement;
    private Cursor cursor;

    SqlitexPreparedStatement(SqlitexConnection connection, String sql,
                             int autoGeneratedKeys) throws SQLException {
        super(connection, sql, autoGeneratedKeys);
        this.connection = connection;
        statement = connection.getDatabase().compileStatement(sql);
    }

    @Override
    protected void bindNullOrString(int index, Object value) {
        if (value == null) {
            statement.bindNull(index);
            if (bindings != null) {
                bindings.add(null);
            }
        } else {
            String string = value.toString();
            statement.bindString(index, string);
            if (bindings != null) {
                bindings.add(string);
            }
        }
    }

    @Override
    protected void bindLong(int index, long value) {
        statement.bindLong(index, value);
        if (bindings != null) {
            bindings.add(value);
        }
    }

    @Override
    protected void bindDouble(int index, double value) {
        statement.bindDouble(index, value);
        if (bindings != null) {
            bindings.add(value);
        }
    }

    @Override
    protected void bindBlob(int index, byte[] value) {
        if (value == null) {
            statement.bindNull(index);
            if (bindings != null) {
                bindings.add(null);
            }
        } else {
            statement.bindBlob(index, value);
            if (bindings != null) {
                bindBlobLiteral(index, value);
            }
        }
    }

    @Override
    public void close() throws SQLException {
        clearParameters();
        statement.close();
        if (cursor != null) {
            cursor.close();
        }
        super.close();
    }

    @Override
    public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public ResultSet executeQuery(String sql) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void clearParameters() throws SQLException {
        statement.clearBindings();
        if (bindings != null) {
            bindings.clear();
        }
    }

    @Override
    public boolean execute() throws SQLException {
        try {
            statement.execute();
        } catch (SQLiteException e) {
            SqlitexConnection.throwSQLException(e);
        }
        return false;
    }

    @Override
    public ResultSet executeQuery() throws SQLException {
        try {
            String[] args = bindingsToArray();
            cursor = connection.getDatabase().rawQuery(sql, args);
            return queryResult = new CursorResultSet(this, cursor, false);
        } catch (SQLiteException e) {
            SqlitexConnection.throwSQLException(e);
        }
        return null;
    }

    @Override
    public int executeUpdate() throws SQLException {
        if (autoGeneratedKeys == RETURN_GENERATED_KEYS) {
            try {
                long rowId = statement.executeInsert();
                insertResult = new SingleResultSet(this, rowId);
                updateCount = 1;
            } catch (SQLiteException e) {
                SqlitexConnection.throwSQLException(e);
            }
        } else {
            try {
                updateCount = statement.executeUpdateDelete();
            } catch (SQLiteException e) {
                SqlitexConnection.throwSQLException(e);
            }
        }
        return updateCount;
    }
}


text:
/**
    Sistemas Operativos 2013-1
    shell.c
    Propósito: Desarrollar una shell básica para ejecutar tareas en primer y segundo plano

    @author Christopher Fernándes Astudillo
    @version 1.0
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <errno.h>

// Función handler que maneja la señal que envía el proceso hijo que está ejecutándose en background
void handler(int signum) {
    int status;
    pid_t pid;

    pid = waitpid(-1, &status, WNOHANG);
}

int main(int argc, char const *argv[])
{
    char *args[1<<16]; // arreglo de string que contendrá cada parámetro del comando ejecutado
    char name[1024]; // variable que guarda el input del usuario
    char *token; // token usado para hacer split al input del usuario
    int i=1; // contador para ir completando el arreglo de parámetros
    pid_t pid; // pid para el fork
    int background = 0; // variable flag que indica si se está ejecutando un proceso en background

    printf("\x1B[33mCtrl+c para salir\x1B[0m\n");

    signal(SIGCHLD, handler); // señal para las tareas hijas en background que terminan

    while (1) {
        memset(args, 0, sizeof args); // limpia el arreglo de parámetros
        i = 1; // contador inicializado en 1
        printf("\x1B[31m > \x1B[0m");
        fgets(name, 1024, stdin); // obteniendo input del usuario

        if (strcmp(name, "\n") == 0) // se vuelve a ejecutar el while si el input es solo un salto de linea
            continue;

        // se limpia el último char basura del input
        size_t ln = strlen(name) - 1;
        if (name[ln] == '\n')
            name[ln] = '\0';

        // split del input para guardar los parámetros
        token = strtok(name, " ");
        args[0] = name;

        background = 0; // por defecto se toma en cuenta que la tarea no será en background

        // while que registra los parámetros del comando por medio de split
        while (token != NULL) {
            token = strtok(NULL, " ");
            if (token != NULL) {
                if (strcmp(token, "&") == 0) // si existe un & es porque la tarea será ejecutada en background
                {
                    background = 1;
                } else { // de lo contrario, se siguen guardando los parámetros
                    args[i] = token;
                    i++;
                }
            }
        }

        // Aquí viene el fork
        pid = fork();

        if (pid == 0) { // si es el hijo
            if (background == 1) // si el usuario eligió tarea en background
                printf("[%d: On background]\n", getpid()); // se notifica el pid de la tarea en background
            if (execvp(args[0], args)) { // se ejecuta el comando
                puts(strerror(errno));
            }
            exit(0); // termina de manera exitosa
        } else if (pid == -1) { // error de fork
            printf("Fork error.\n");
            return -1; // retorna error
        }

        if (background == 0) // si la tarea no se ejecutará en background, entonces se espera el waitpid
            waitpid(pid, NULL , 0);
    }

    return 0;
}


text:
package org.carlspring.strongbox.converters.configuration;

import org.carlspring.strongbox.forms.configuration.NugetRepositoryConfigurationForm;
import org.carlspring.strongbox.yaml.configuration.repository.NugetRepositoryConfigurationDto;

import org.springframework.core.convert.converter.Converter;

public enum NugetRepositoryConfigurationConverter
        implements Converter<NugetRepositoryConfigurationForm, NugetRepositoryConfigurationDto>
{

    INSTANCE;

    @Override
    public NugetRepositoryConfigurationDto convert(NugetRepositoryConfigurationForm form)
    {
        NugetRepositoryConfigurationDto configuration = new NugetRepositoryConfigurationDto();
        configuration.setFeedVersion(form.getFeedVersion());
        configuration.setRemoteFeedPageSize(form.getRemoteFeedPageSize());

        return configuration;
    }
}


text:
require 'spec_helper'

describe HL7::Message::Segment do
  describe 'length' do

    it "should return the length of the elements" do
      segment = HL7::Message::Segment.new "MSA|AR|ZZ9380 ERR"
      segment.length.should eq 3
    end
  end

  describe 'enumerable' do
    it 'enumerates over elements' do
      seg = HL7::Message::Segment::Default.new
      segment_count = 0
      seg.each do |s|
        segment_count = segment_count + 1
      end
      segment_count.should == seg.length
    end
  end

  describe 'is_child_segment?' do
    let(:segment){ HL7::Message::Segment.new "MSA|AR|ZZ9380 ERR" }
    it "return false when is not set" do
      segment.is_child_segment?.should be false
    end
  end

  describe 'convert_to_ts' do
    let(:time_now){ DateTime.now }
    let(:formated_time){ time_now.strftime('%Y%m%d%H%M%S') }

    it "should conver to the hl7 time format" do
      HL7::Message::Segment.convert_to_ts(time_now).should eq formated_time
    end
  end
end


text:
package org.cyclops.integrateddynamics.part.aspect.read.inventory;

import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.api.part.aspect.property.IAspectProperties;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypeBoolean;

/**
 * Aspect that checks if all slots contain no item.
 * @author rubensworks
 */
public class AspectReadBooleanInventoryEmpty extends AspectReadBooleanInventoryBase {

    @Override
    protected String getUnlocalizedBooleanWorldType() {
        return "empty";
    }

    @Override
    protected ValueTypeBoolean.ValueBoolean getValue(PartTarget target, IAspectProperties properties) {
        DimPos dimPos = target.getTarget().getPos();
        TileEntity tile = dimPos.getWorld().getTileEntity(dimPos.getBlockPos());
        if(tile instanceof IInventory) {
            IInventory inventory = (IInventory) tile;
            for(int i = 0; i < inventory.getSizeInventory(); i++) {
                ItemStack itemStack = inventory.getStackInSlot(i);
                if(itemStack != null) {
                    return ValueTypeBoolean.ValueBoolean.of(false);
                }
            }
        }
        return ValueTypeBoolean.ValueBoolean.of(true);
    }
}


text:
<?php
/**
 * WP Bootstrap Navwalker
 *
 * @package WP-Bootstrap-Navwalker
 */
/*
 * Class Name: WP_Bootstrap_Navwalker
 * Plugin Name: WP Bootstrap Navwalker
 * Plugin URI:  https://github.com/wp-bootstrap/wp-bootstrap-navwalker
 * Description: A custom WordPress nav walker class to implement the Bootstrap 3 navigation style in a custom theme using the WordPress built in menu manager.
 * Author: Edward McIntyre - @twittem, WP Bootstrap, William Patton - @pattonwebz
 * Version: 3.0.3
 * Author URI: https://github.com/wp-bootstrap
 * GitHub Plugin URI: https://github.com/wp-bootstrap/wp-bootstrap-navwalker
 * GitHub Branch: master
 * License: GPL-3.0+
 * License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/
/* Check if Class Exists. */
if ( ! class_exists( 'WP_Bootstrap_Navwalker' ) ) {
	/**
	 * WP_Bootstrap_Navwalker class.
	 *
	 * @extends Walker_Nav_Menu
	 */
	class WP_Bootstrap_Navwalker extends Walker_Nav_Menu {
		/**
		 * Start Level.
		 *
		 * @see Walker::start_lvl()
		 * @since 3.0.0
		 *
		 * @access public
		 * @param mixed $output Passed by reference. Used to append additional content.
		 * @param int   $depth (default: 0) Depth of page. Used for padding.
		 * @param array $args (default: array()) Arguments.
		 * @return void
		 */
		public function start_lvl( &$output, $depth = 0, $args = array() ) {
			$indent = str_repeat( "\t", $depth );
			// find all links with an id in the output.
			preg_match_all( '/(/im', $output, $matches );
			// with pointer at end of array check if we got an ID match.
			if ( end( $matches[2] ) ) {
				// build a string to use as aria-labelledby.
				$labledby = 'aria-labelledby="' . end( $matches[2] ) . '"';
			}
			$output .= "\n$indent
\n";
		}
		/**
		 * Start El.
		 *
		 * @see Walker::start_el()
		 * @since 3.0.0
		 *
		 * @access public
		 * @param mixed $output Passed by reference. Used to append additional content.
		 * @param mixed $item Menu item data object.
		 * @param int   $depth (default: 0) Depth of menu item. Used for padding.
		 * @param array $args (default: array()) Arguments.
		 * @param int   $id (default: 0) Menu item ID.
		 * @return void
		 */
		public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
			$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
			$value = '';
			$class_names = $value;
			$classes = empty( $item->classes ) ? array() : (array) $item->classes;
			// Loop through the array and pick out any special classes that need
			// to be added to an element other than the main
.
			$extra_link_classes = array();
			$icon_class_string = '';
			foreach ( $classes as $key => $class ) {
				// test if this is a disabled link.
				if ( 'disabled' === $class ) {
					$extra_link_classes[] = 'disabled';
					unset( $classes[ $key ] );
				}
				// test for icon classes - Supports Font Awesome and Glyphicons.
				if ( 'fa' === $class || 'fa-' === substr( $class, 0, 3 ) ) {
					// Because of the abiguity of just 'fa' at the start both
					// 'fa' & 'fa-' are tested for with Font Awesome icons.
					$icon_class_string .= $class . ' ';
					unset( $classes[ $key ] );
				} elseif ( 'glyphicons' === substr( $class, 0, 10 ) ) {
					// This should be a glyphicon icon class.
					$icon_class_string .= $class . ' ';
					unset( $classes[ $key ] );
				}
			}
			$classes[] = 'menu-item-' . $item->ID;
			// BSv4 classname - as of v4-alpha.
			$classes[] = 'nav-item';
			// reasign any filtered classes back to the $classes array.
			$classes = apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args );
			$class_names = join( ' ', $classes );
			if ( $args->has_children ) {
				$class_names .= ' dropdown';
			}
			if ( in_array( 'current-menu-item', $classes, true ) || in_array( 'current-menu-parent', $classes, true ) ) {
				$class_names .= ' active';
			}
			$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
			$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args );
			$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
			$output .= $indent . '
';
			$atts = array();
			if ( empty( $item->attr_title ) ) {
				$atts['title']  = ! empty( $item->title )   ? strip_tags( $item->title ) : '';
			} else {
				$atts['title'] = $item->attr_title;
			}
			$atts['target'] = ! empty( $item->target )	? $item->target	: '';
			$atts['rel']    = ! empty( $item->xfn )		? $item->xfn	: '';
			// If item has_children add atts to a.
			if ( $args->has_children && 0 === $depth && $args->depth > 1 ) {
				$atts['href']   		= '#';
				$atts['data-toggle']	= 'dropdown';
				$atts['aria-haspopup']	= 'true';
				$atts['aria-expanded']	= 'false';
				$atts['class']			= 'dropdown-toggle nav-link';
				$atts['id']				= 'menu-item-dropdown-' . $item->ID;
			} else {
				$atts['href'] 	= ! empty( $item->url ) ? $item->url : '';
				// if we are in a dropdown then the the class .dropdown-item
				// should be used instead of .nav-link.
				if ( $depth > 0 ) {
					$atts['class']	= 'dropdown-item';
				} else {
					$atts['class']	= 'nav-link';
				}
			}
			// Loop through the array of extra link classes plucked from the
			// parent
s classes array.
			if ( ! empty( $extra_link_classes ) ) {
				foreach ( $extra_link_classes as $link_class ) {
					if ( ! empty( $link_class ) ) {
						// update $atts with the extra class link.
						$atts['class'] .= ' ' . esc_attr( $link_class );
						// if the modification is a disabled class...
						if ( 'disabled' === $link_class ) {
							// then # the link so it doesn't point anywhere.
							$atts['href'] = '#';
						}
					}
				}
			}
			$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
			$attributes = '';
			foreach ( $atts as $attr => $value ) {
				if ( ! empty( $value ) ) {
					$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
					$attributes .= ' ' . $attr . '="' . $value . '"';
				}
			}
			$item_output = $args->before;
			$item_output .= '';
			// initiate empty icon var then if we have a string containing icon classes...
			$icon_html = '';
			if ( ! empty( $icon_class_string ) ) {
				// append an  with the icon classes to what is output before links.
				$icon_html = ' ';
			}
			$item_output .= $args->link_before . $icon_html . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
			$item_output .= '';
			$item_output .= $args->after;
			$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
		}
		/**
		 * Traverse elements to create list from elements.
		 *
		 * Display one element if the element doesn't have any children otherwise,
		 * display the element and its children. Will only traverse up to the max
		 * depth and no ignore elements under that depth.
		 *
		 * This method shouldn't be called directly, use the walk() method instead.
		 *
		 * @see Walker::start_el()
		 * @since 2.5.0
		 *
		 * @access public
		 * @param mixed $element Data object.
		 * @param mixed $children_elements List of elements to continue traversing.
		 * @param mixed $max_depth Max depth to traverse.
		 * @param mixed $depth Depth of current element.
		 * @param mixed $args Arguments.
		 * @param mixed $output Passed by reference. Used to append additional content.
		 * @return null Null on failure with no changes to parameters.
		 */
		public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
			if ( ! $element ) {
				return; }
			$id_field = $this->db_fields['id'];
			// Display this element.
			if ( is_object( $args[0] ) ) {
				$args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] ); }
			parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
		}
		/**
		 * Menu Fallback
		 * =============
		 * If this function is assigned to the wp_nav_menu's fallback_cb variable
		 * and a menu has not been assigned to the theme location in the WordPress
		 * menu manager the function with display nothing to a non-logged in user,
		 * and will add a link to the WordPress menu manager if logged in as an admin.
		 *
		 * @param array $args passed from the wp_nav_menu function.
		 */
		public static function fallback( $args ) {
			if ( current_user_can( 'edit_theme_options' ) ) {
				/* Get Arguments. */
				$container = $args['container'];
				$container_id = $args['container_id'];
				$container_class = $args['container_class'];
				$menu_class = $args['menu_class'];
				$menu_id = $args['menu_id'];
				// initialize var to store fallback html.
				$fallback_output = '';
				if ( $container ) {
					$fallback_output = '<' . esc_attr( $container );
					if ( $container_id ) {
						$fallback_output = ' id="' . esc_attr( $container_id ) . '"';
					}
					if ( $container_class ) {
						$fallback_output = ' class="' . sanitize_html_class( $container_class ) . '"';
					}
					$fallback_output = '>';
				}
				$fallback_output = '
';
				$fallback_output = '
' . esc_attr( 'Add a menu', '' ) . '
';
				$fallback_output = '
';
				if ( $container ) {
					$fallback_output = '</' . esc_attr( $container ) . '>';
				}
				// if $args has 'echo' key and it's true echo, otherwise return.
				if ( array_key_exists( 'echo', $args ) && $args['echo'] ) {
					echo $fallback_output; // WPCS: XSS OK.
				} else {
					return $fallback_output;
				}
			} // End if().
		}
	}
} // End if().


text:
<?xml version='1.0' encoding='utf-8'?>
<program_description>
  <program provider="PUT" name="PROMETHEE-II_flows" version="1.0.0" displayName="PROMETHEE-II_flows" />
  <documentation>
    <description>Final flows calculated with Promethee II method as a difference of positive and negative outranking flows.</description>
    <contact><![CDATA[Magdalena Dzi?cielska <magdalenadziecielska6@gmail.com>]]></contact>
    <url>https://github.com/MagdalenaDziecielska/PrometheeDiviz</url>
    <reference>J.-P. Brans and B. Mareschal, 2005. PROMETHEE methods. In J. Figueira, S. Greco, M. Ehrgott, editors, Multiple Criteria Decision Analysis. State of the Art Surveys, 163–195. Springer, New York, USA.</reference>
  </documentation>
  <parameters>

    <input id="input1" name="alternatives" displayName="alternatives" isoptional="0">
      <documentation>
        <description>Alternatives to consider.</description>
      </documentation>
      <xmcda tag="alternatives" />
    </input>

    <input id="input2" name="positive_flow" displayName="positive flows" isoptional="0">
      <documentation>
        <description>Positive flows of given alternatives and profiles.</description>
      </documentation>
      <xmcda tag="alternativesValues" />
    </input>

    <input id="input3" name="negative_flow" displayName="negative flows" isoptional="0">
      <documentation>
        <description>Negative flows of given alternatives and profiles.</description>
      </documentation>
      <xmcda tag="alternativesValues" />
    </input>

    <input id="input5" name="categories_profiles" displayName="categories profiles" isoptional="1">
      <documentation>
        <description>Definitions of profiles (boundary or central) which should be used for classes (categories) representation.</description>
      </documentation>
      <xmcda tag="categoriesProfiles" />
    </input>

    <input id="input4" name="parameters" displayName="method parameters" isoptional="0">
      <documentation>
        <description>Parameter specifies the type of elements provided for comparison.
          Choosing 'boundary_profiles' or 'central_profiles' requires providing input file: 'categories_profiles'.</description>
      </documentation>
      <xmcda tag="programParameters"><![CDATA[

		<programParameters>
			<parameter id="comparison_with" name="comparison_with">
				<values>
					<value>
						<label>%1</label>
					</value>
				</values>
			</parameter>
		</programParameters>

      ]]></xmcda>
      <gui status="preferGUI">
        <entry id="%1" type="enum" displayName="comparison with">
          <items>
            <item id="item0">
              <description>alternatives vs alternatives</description>
              <value>alternatives</value>
            </item>
            <item id="item1">
              <description>alternatives vs boundary profiles</description>
              <value>boundary_profiles</value>
            </item>
            <item id="item2">
              <description>alternatives vs central profiles</description>
              <value>central_profiles</value>
            </item>
          </items>
          <defaultValue>item0</defaultValue>
        </entry>
      </gui>
    </input>

    <output id="output1" name="flows" displayName="flows">
      <documentation>
        <description>Result computed from the given data.</description>
      </documentation>
      <xmcda tag="alternativesValues" />
    </output>

    <output id="output2" name="messages" displayName="messages">
      <documentation>
        <description>Messages or errors generated by this module.</description>
      </documentation>
      <xmcda tag="programExecutionResult" />
    </output>

  </parameters>
</program_description>


text:
# StringMutation

## Features

Use these Array methods on a String. Each method changes original string value.

     - .map()
     - .splice()
     - .indexOf()
     - .reverse()
     - .pop()
     - .push()
     - .shift()
     - .unshift()
     - .sort()
     - .keys()
     - .countChars()

## Installation
Download `string-mutation.js` and include it in your `index.html` file.

## Getting Started
Create a new SM object

```js
SM(/*string*/);
//or
new SM(/*string*/)
```
type `.value` to access the value.

```js
console.log(SM('John Doe').value);
//=>"John Doe"
```

## Methods
**.reverse(position)**

```js
var a = SM("John Doe").reverse("");

console.log(a.value);
//=>"eoD nhoJ"

var a = SM("John Doe").reverse(" ");
//=>"Doe John"
```

**.indexOf(chr[, num])** - returns the index value of the character in a string starting from the left. When there is more than one character in a string specify the second argument (e.g. `1`(st), `2`(nd), ..).

```js
console.log(SM("John Doe").indexOf("o", 2));
//=>6
```

**.countChar(chr)** - finds amount of characters in a string.

```js
console.log(SM("John Doe drinks too much Coffee").countChar("n"));
//=>2
```
All other methods work the same as in an Array

## Example

```js
var a = SM("John Doe").splice(0, 4, "Jane");

console.log(a.value);
//=>"Jane Doe"

var a = SM("John Doe").splice(0, 4, "Jane").pop().pop().push("wane");

console.log(a.value);
//=>"Jane Dwane"

var a = SM("John Doe")
.splice(0, 4, "Jane")
.pop()
.pop()
.push("wane")
.map(function(v){
    return "{" + v + "}";
});

console.log(a.value);
//=>"{J}{a}{n}{e}{ }{D}{w}{a}{n}{e}"
```

## License
MIT


text:
package ch.unifr.pai.twice.mousecontrol.client;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ScrollPanel;

/**
 * An implementation of the mouse pointer control based on scroll. This is e.g. required for e-readers or other rather exotic devices which are not providing
 * appropriate mouse and / or touch events.
 *
 * @author Oliver Schmid
 *
 */
public class TouchPadScrollWidget extends TouchPadWidget {

	private final HTML spacer = new HTML();
	private final ScrollPanel scroller = new ScrollPanel();

	Timer updater;
	int currentScreenX;
	int currentScreenY;

	public TouchPadScrollWidget() {
		super(false);
		scroller.setHeight("100%");
		scroller.setWidth("100%");
		add(scroller);
		scroller.add(spacer);
		updater = new Timer() {

			@Override
			public void run() {
				currentScreenX = spacer.getOffsetWidth() - scroller.getHorizontalScrollPosition() - scroller.getOffsetWidth();
				currentScreenY = spacer.getOffsetHeight() - scroller.getVerticalScrollPosition() - scroller.getOffsetHeight();
			}
		};

	}

	/*
	 * (non-Javadoc)
	 * @see ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget#getX()
	 */
	@Override
	protected int getX() {
		return currentScreenX;
	}

	/*
	 * (non-Javadoc)
	 * @see ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget#getY()
	 */
	@Override
	protected int getY() {
		return currentScreenY;
	}

	/*
	 * (non-Javadoc)
	 * @see ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget#updateScreenDimensions()
	 */
	@Override
	protected void updateScreenDimensions() {
		spacer.setWidth((scroller.getOffsetWidth() + screenWidth) + "px");
		spacer.setHeight((scroller.getOffsetHeight() + screenHeight) + "px");
	}

	/*
	 * (non-Javadoc)
	 * @see ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget#start()
	 */
	@Override
	public void start() {
		super.start();
		updater.scheduleRepeating(MOVEMENTUPDATEINTERVAL);
	}

	/*
	 * (non-Javadoc)
	 * @see ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget#stop()
	 */
	@Override
	public void stop() {
		super.stop();
		updater.cancel();
	}

}


text:
package org.wandledi;

import org.xml.sax.Attributes;

/**
 *
 * @author Markus Kahl
 */
public class LocalSpells extends AbstractSpell {

    private Scroll parentScroll;
    private Scroll localScroll;

    public LocalSpells(Scroll parentScroll, Scroll localScroll) {
        this.parentScroll = parentScroll;
        this.localScroll = localScroll;
    }

    public void startTransformedElement(String label, Attributes attributes) {
        super.startTransformedElement(label, attributes);
        parentScroll.addScroll(localScroll);
    }

    public void endTransformedElement(String label) {
        parentScroll.removeScroll(localScroll);
        super.endTransformedElement(label);
    }

    @Override
    public Spell clone() {
        return new LocalSpells(parentScroll, localScroll);
    }
}


text:
import global from 'global';
import dedent from 'ts-dedent';
import { render } from 'lit-html';
// Keep `.js` extension to avoid issue with Webpack (related to export map?)
// eslint-disable-next-line import/extensions
import { isTemplateResult } from 'lit-html/directive-helpers.js';
import { simulatePageLoad, simulateDOMContentLoaded } from '@storybook/client-api';
import { RenderContext } from './types';

const { document, Node } = global;
const rootElement = document.getElementById('root');

export default function renderMain({
  storyFn,
  kind,
  name,
  showMain,
  showError,
  forceRender,
}: RenderContext) {
  const element = storyFn();

  showMain();
  if (isTemplateResult(element)) {
    // `render` stores the TemplateInstance in the Node and tries to update based on that.
    // Since we reuse `rootElement` for all stories, remove the stored instance first.
    // But forceRender means that it's the same story, so we want too keep the state in that case.
    if (!forceRender || !rootElement.querySelector('[id="root-inner"]')) {
      rootElement.innerHTML = '

';
    }
    const renderTo = rootElement.querySelector('[id="root-inner"]');

    render(element, renderTo);
    simulatePageLoad(rootElement);
  } else if (typeof element === 'string') {
    rootElement.innerHTML = element;
    simulatePageLoad(rootElement);
  } else if (element instanceof Node) {
    // Don't re-mount the element if it didn't change and neither did the story
    if (rootElement.firstChild === element && forceRender === true) {
      return;
    }

    rootElement.innerHTML = '';
    rootElement.appendChild(element);
    simulateDOMContentLoaded();
  } else {
    showError({
      title: `Expecting an HTML snippet or DOM node from the story: "${name}" of "${kind}".`,
      description: dedent`
        Did you forget to return the HTML snippet from the story?
        Use "() => <your snippet or node>" or when defining the story.
      `,
    });
  }
}


text:
#include "server.h"
#include "../util/strings.h"
#include "../util/file.h"
#include "../util/config.h"
#include "../util/log.h"
#include "../util/ip_filter.h"
#include "link.h"
#include <vector>

static DEF_PROC(ping);
static DEF_PROC(info);
static DEF_PROC(auth);
static DEF_PROC(list_allow_ip);
static DEF_PROC(add_allow_ip);
static DEF_PROC(del_allow_ip);
static DEF_PROC(list_deny_ip);
static DEF_PROC(add_deny_ip);
static DEF_PROC(del_deny_ip);

#define TICK_INTERVAL          100 // ms
#define STATUS_REPORT_TICKS    (300 * 1000/TICK_INTERVAL) // second
static const int READER_THREADS = 10;
static const int WRITER_THREADS = 1;  // 必须为1, 因为某些写操作依赖单线程

volatile bool quit = false;
volatile uint32_t g_ticks = 0;

void signal_handler(int sig){
	switch(sig){
		case SIGTERM:
		case SIGINT:{
			quit = true;
			break;
		}
		case SIGALRM:{
			g_ticks ++;
			break;
		}
	}
}

NetworkServer::NetworkServer(){
	num_readers = READER_THREADS;
	num_writers = WRITER_THREADS;

	tick_interval = TICK_INTERVAL;
	status_report_ticks = STATUS_REPORT_TICKS;

	//conf = NULL;
	serv_link = NULL;
	link_count = 0;

	fdes = new Fdevents();
	ip_filter = new IpFilter();

	// add built-in procs, can be overridden
	proc_map.set_proc("ping", "r", proc_ping);
	proc_map.set_proc("info", "r", proc_info);
	proc_map.set_proc("auth", "r", proc_auth);
	proc_map.set_proc("list_allow_ip", "r", proc_list_allow_ip);
	proc_map.set_proc("add_allow_ip",  "r", proc_add_allow_ip);
	proc_map.set_proc("del_allow_ip",  "r", proc_del_allow_ip);
	proc_map.set_proc("list_deny_ip",  "r", proc_list_deny_ip);
	proc_map.set_proc("add_deny_ip",   "r", proc_add_deny_ip);
	proc_map.set_proc("del_deny_ip",   "r", proc_del_deny_ip);

	signal(SIGPIPE, SIG_IGN);
	signal(SIGINT, signal_handler);
	signal(SIGTERM, signal_handler);
#ifndef __CYGWIN__
	signal(SIGALRM, signal_handler);
	{
		struct itimerval tv;
		tv.it_interval.tv_sec = (TICK_INTERVAL / 1000);
		tv.it_interval.tv_usec = (TICK_INTERVAL % 1000) * 1000;
		tv.it_value.tv_sec = 1;
		tv.it_value.tv_usec = 0;
		setitimer(ITIMER_REAL, &tv, NULL);
	}
#endif
}

NetworkServer::~NetworkServer(){
	//delete conf;
	delete serv_link;
	delete fdes;
	delete ip_filter;

	writer->stop();
	delete writer;
	reader->stop();
	delete reader;
}

NetworkServer* NetworkServer::init(const char *conf_file, int num_readers, int num_writers){
	if(!is_file(conf_file)){
		fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
		exit(1);
	}

	Config *conf = Config::load(conf_file);
	if(!conf){
		fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
		exit(1);
	}
	{
		std::string conf_dir = real_dirname(conf_file);
		if(chdir(conf_dir.c_str()) == -1){
			fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
			exit(1);
		}
	}
	NetworkServer* serv = init(*conf, num_readers, num_writers);
	delete conf;
	return serv;
}

NetworkServer* NetworkServer::init(const Config &conf, int num_readers, int num_writers){
	static bool inited = false;
	if(inited){
		return NULL;
	}
	inited = true;

	NetworkServer *serv = new NetworkServer();
	if(num_readers >= 0){
		serv->num_readers = num_readers;
	}
	if(num_writers >= 0){
		serv->num_writers = num_writers;
	}
	// init ip_filter
	{
		Config *cc = (Config *)conf.get("server");
		if(cc != NULL){
			std::vector<Config *> *children = &cc->children;
			std::vector<Config *>::iterator it;
			for(it = children->begin(); it != children->end(); it++){
				if((*it)->key == "allow"){
					const char *ip = (*it)->str();
					log_info("    allow %s", ip);
					serv->ip_filter->add_allow(ip);
				}
				if((*it)->key == "deny"){
					const char *ip = (*it)->str();
					log_info("    deny %s", ip);
					serv->ip_filter->add_deny(ip);
				}
			}
		}
	}

	{ // server
		const char *ip = conf.get_str("server.ip");
		int port = conf.get_num("server.port");
		if(ip == NULL || ip[0] == '\0'){
			ip = "127.0.0.1";
		}

		serv->serv_link = Link::listen(ip, port);
		if(serv->serv_link == NULL){
			log_fatal("error opening server socket! %s", strerror(errno));
			fprintf(stderr, "error opening server socket! %s\n", strerror(errno));
			exit(1);
		}
		// see UNP
		// if client send RST between server's calls of select() and accept(),
		// accept() will block until next connection.
		// so, set server socket nonblock.
		serv->serv_link->noblock();
		log_info("server listen on %s:%d", ip, port);

		std::string password;
		password = conf.get_str("server.auth");
		if(password.size() && (password.size() < 6 || password == "very-strong-password")){
			log_fatal("weak password is not allowed!");
			fprintf(stderr, "WARNING! Weak password is not allowed!\n");
			exit(1);
		}
		if(password.empty()){
			log_info("auth: off");
		}else{
			log_info("auth: on");
		}
		serv->need_auth = false;
		if(!password.empty()){
			serv->need_auth = true;
			serv->password = password;
		}
	}
	return serv;
}

void NetworkServer::serve(){
	writer = new ProcWorkerPool("writer");
	writer->start(num_writers);
	reader = new ProcWorkerPool("reader");
	reader->start(num_readers);

	ready_list_t ready_list;
	ready_list_t ready_list_2;
	ready_list_t::iterator it;
	const Fdevents::events_t *events;

	fdes->set(serv_link->fd(), FDEVENT_IN, 0, serv_link);
	fdes->set(this->reader->fd(), FDEVENT_IN, 0, this->reader);
	fdes->set(this->writer->fd(), FDEVENT_IN, 0, this->writer);

	uint32_t last_ticks = g_ticks;

	while(!quit){
		double loop_stime = millitime();

		// status report
		if((uint32_t)(g_ticks - last_ticks) >= STATUS_REPORT_TICKS){
			last_ticks = g_ticks;
			log_debug("server running, links: %d", this->link_count);
		}

		ready_list.swap(ready_list_2);
		ready_list_2.clear();

		if(!ready_list.empty()){
			// ready_list not empty, so we should return immediately
			events = fdes->wait(0);
		}else{
			events = fdes->wait(50);
		}
		if(events == NULL){
			log_fatal("events.wait error: %s", strerror(errno));
			break;
		}

		for(int i=0; i<(int)events->size(); i++){
			const Fdevent *fde = events->at(i);
			if(fde->data.ptr == serv_link){
				Link *link = accept_link();
				if(link){
					this->link_count ++;
					log_debug("new link from %s:%d, fd: %d, links: %d",
						link->remote_ip, link->remote_port, link->fd(), this->link_count);
					fdes->set(link->fd(), FDEVENT_IN, 1, link);
				}else{
					log_debug("accept return NULL");
				}
			}else if(fde->data.ptr == this->reader || fde->data.ptr == this->writer){
				ProcWorkerPool *worker = (ProcWorkerPool *)fde->data.ptr;
				ProcJob *job = nullptr;
				if(worker->pop(&job) == 0){
					log_fatal("reading result from workers error!");
					exit(0);
				}
				if(proc_result(job, &ready_list) == PROC_ERROR){
					//
				}
			}else{
				proc_client_event(fde, &ready_list);
			}
		}

		for(it = ready_list.begin(); it != ready_list.end(); it ++){
			Link *link = *it;
			if(link->error()){
				this->link_count --;
				fdes->del(link->fd());
				delete link;
				continue;
			}

			const Request *req = link->recv();
			if(req == NULL){
				log_warn("fd: %d, link parse error, delete link", link->fd());
				this->link_count --;
				fdes->del(link->fd());
				delete link;
				continue;
			}
			if(req->empty()){
				fdes->set(link->fd(), FDEVENT_IN, 1, link);
				continue;
			}

			link->active_time = millitime();

			ProcJob *job = new ProcJob();
			job->link = link;
			job->req = link->last_recv();
			int result = this->proc(job);
			if(result == PROC_THREAD){
				fdes->del(link->fd());
			}else if(result == PROC_BACKEND){
				fdes->del(link->fd());
				this->link_count --;
			}else{
				if(proc_result(job, &ready_list_2) == PROC_ERROR){
					//
				}
			}
		} // end foreach ready link

		double loop_time = millitime() - loop_stime;
		if(loop_time > 0.5){
			log_warn("long loop time: %.3f", loop_time);
		}
	}
}

Link* NetworkServer::accept_link(){
	Link *link = serv_link->accept();
	if(link == NULL){
		log_error("accept failed! %s", strerror(errno));
		return NULL;
	}
	if(!ip_filter->check_pass(link->remote_ip)){
		log_debug("ip_filter deny link from %s:%d", link->remote_ip, link->remote_port);
		delete link;
		return NULL;
	}

	link->nodelay();
	link->noblock();
	link->create_time = millitime();
	link->active_time = link->create_time;
	return link;
}

bool NetworkServer::filterCmdInfo(std::string &name) {
	if (name != "info" && name != "config get maxmemory" &&
				name != "ping" && name != "namespaces" && name != "alarm"){
		return true;
	}else {
		return false;
	}
}

int NetworkServer::proc_result(ProcJob *job, ready_list_t *ready_list){
	Link *link = job->link;
	int result = job->result;

	if(log_level() >= Logger::LEVEL_DEBUG){
		std::string command = serialize_req(*job->req);
		if (filterCmdInfo(command)){
			log_debug("w:%.3f,p:%.3f, req: %s, resp: %s",
			job->time_wait, job->time_proc,
			command.c_str(),
			serialize_req(job->resp.resp).c_str());
		}
	}
	if(job->cmd){
		job->cmd->calls += 1;

		job->cmd->time_wait += job->time_wait;
		job->cmd->time_proc += job->time_proc;
		if (job->time_proc >= time_proc_lower){
			log_info("cmd: %s, w:%.3f, p:%.3f, req: %s, resp: %s",
					job->cmd->name.data(), job->time_wait, job->time_proc,
					serialize_req(*job->req).c_str(), serialize_req(job->resp.resp).c_str());
			Locking l(&this->mutex);
			auto it = warn_cmd_list.find(job->cmd->name);

			if (it != warn_cmd_list.end()){
				it->second.tick_num += 1;
				if (it->second.time_proc < job->time_proc){
					it->second.time_proc = job->time_proc;
				}
			}else{
				warn_cmd_list[job->cmd->name] = WarnningCmd(job->cmd->name, job);
			}
		} else if (job->time_proc > 500){
			log_info("cmd: %s, w:%.3f, p:%.3f, req: %s, resp: %s",
				job->cmd->name.data(), job->time_wait, job->time_proc,
				serialize_req(*job->req).c_str(), serialize_req(job->resp.resp).c_str());
		}
	}
	delete job;

	if(result == PROC_ERROR){
		log_info("fd: %d, proc error, delete link", link->fd());
		goto proc_err;
	}

	if(!link->output->empty()){
		int len = link->write();
		//log_debug("write: %d", len);
		if(len < 0){
			log_debug("fd: %d, write: %d, delete link", link->fd(), len);
			goto proc_err;
		}
	}

	if(!link->output->empty()){
		fdes->set(link->fd(), FDEVENT_OUT, 1, link);
	}
	if(link->input->empty()){
		fdes->set(link->fd(), FDEVENT_IN, 1, link);
	}else{
		fdes->clr(link->fd(), FDEVENT_IN);
		ready_list->push_back(link);
	}
	return PROC_OK;

proc_err:
	this->link_count --;
	fdes->del(link->fd());
	delete link;
	return PROC_ERROR;
}

/*
event:
	read => ready_list OR close
	write => NONE
proc =>
	done: write & (read OR ready_list)
	async: stop (read & write)

1. When writing to a link, it may happen to be in the ready_list,
so we cannot close that link in write process, we could only
just mark it as closed.

2. When reading from a link, it is never in the ready_list, so it
is safe to close it in read process, also safe to put it into
ready_list.

3. Ignore FDEVENT_ERR

A link is in either one of these places:
	1. ready list
	2. async worker queue
So it safe to delete link when processing ready list and async worker result.
*/
int NetworkServer::proc_client_event(const Fdevent *fde, ready_list_t *ready_list){
	Link *link = (Link *)fde->data.ptr;
	if(fde->events & FDEVENT_IN){
		ready_list->push_back(link);
		if(link->error()){
			return 0;
		}
		int len = link->read();
		//log_debug("fd: %d read: %d", link->fd(), len);
		if(len <= 0){
			double serv_time = millitime() - link->create_time;
			log_debug("fd: %d, read: %d, delete link, s:%.3f", link->fd(), len, serv_time);
			link->mark_error();
			return 0;
		}
	}
	if(fde->events & FDEVENT_OUT){
		if(link->error()){
			return 0;
		}
		int len = link->write();
		if(len <= 0){
			log_debug("fd: %d, write: %d, delete link", link->fd(), len);
			link->mark_error();
			return 0;
		}
		if(link->output->empty()){
			fdes->clr(link->fd(), FDEVENT_OUT);
		}
	}
	return 0;
}

int NetworkServer::proc(ProcJob *job){
	job->serv = this;
	job->result = PROC_OK;
	job->stime = millitime();

	const Request *req = job->req;

	do{
		// AUTH
		if(this->need_auth && job->link->auth == false && req->at(0) != "auth"){
			job->resp.push_back("noauth");
			job->resp.push_back("authentication required");
			break;
		}

		Command *cmd = proc_map.get_proc(req->at(0));
		if(!cmd){
			job->resp.push_back("client_error");
			job->resp.push_back("Unknown Command: " + req->at(0).String());
			break;
		}
		job->cmd = cmd;

		if(cmd->flags & Command::FLAG_THREAD){
			if(cmd->flags & Command::FLAG_WRITE){
				writer->push(job);
			}else{
				reader->push(job);
			}
			return PROC_THREAD;
		}

		proc_t p = cmd->proc;
		job->time_wait = 1000 * (millitime() - job->stime);
		job->result = (*p)(this, job->link, *req, &job->resp);
		job->time_proc = 1000 * (millitime() - job->stime) - job->time_wait;
	}while(0);
	if(job->link->send(job->resp.resp) == -1){
		job->result = PROC_ERROR;
	}
	return job->result;
}

void NetworkServer::set_lower_time(double millitime) {
	this->time_proc_lower = millitime;
}

std::string NetworkServer::slow_cmd_list(){
	Locking(&this->mutex);
	std::string result;
	for (auto it = warn_cmd_list.cbegin(); it != warn_cmd_list.cend(); ++it){
		result.append(strprintfln("slowrequest: %s tick_num:%d, time_wait:%.0f, time_proc:%.0f",
			it->first.data(), it->second.tick_num, it->second.time_wait, it->second.time_proc));
	}
	return result;
}

void NetworkServer::clear_cmd_list(){
	Locking(&this->mutex);
	std::map<std::string, WarnningCmd> empty;
	warn_cmd_list.swap(empty);
}

/* built-in procs */

static int proc_ping(NetworkServer *net, Link *link, const Request &req, Response *resp){
	resp->push_back("ok");
	return 0;
}

static int proc_info(NetworkServer *net, Link *link, const Request &req, Response *resp){
	resp->push_back("ok");
	resp->push_back("ideawu's network server framework");
	resp->push_back("version");
	resp->push_back("1.0");
	resp->push_back("links");
	resp->add(net->link_count);
	{
		int64_t calls = 0;
		proc_map_t::iterator it;
		for(it=net->proc_map.begin(); it!=net->proc_map.end(); it++){
			Command *cmd = it->second;
			calls += cmd->calls;
		}
		resp->push_back("total_calls");
		resp->add(calls);
	}
	return 0;
}

static int proc_auth(NetworkServer *net, Link *link, const Request &req, Response *resp){
	if(req.size() != 2){
		resp->push_back("client_error");
	}else{
		if(!net->need_auth || req[1] == net->password){
			link->auth = true;
			resp->push_back("ok");
			resp->push_back("1");
		}else{
			resp->push_back("error");
			resp->push_back("invalid password");
		}
	}
	return 0;
}

#define ENSURE_LOCALHOST() do{ \
		if(strcmp(link->remote_ip, "127.0.0.1") != 0){ \
			resp->push_back("noauth"); \
			resp->push_back("this command is only available from 127.0.0.1"); \
			return 0; \
		} \
	}while(0)

static int proc_list_allow_ip(NetworkServer *net, Link *link, const Request &req, Response *resp){
	ENSURE_LOCALHOST();

	resp->push_back("ok");
	IpFilter *ip_filter = net->ip_filter;
	if(ip_filter->allow_all){
		resp->push_back("all");
	}
	std::set<std::string>::const_iterator it;
	for(it=ip_filter->allow.begin(); it!=ip_filter->allow.end(); it++){
		std::string ip = *it;
		ip = ip.substr(0, ip.size() - 1);
		resp->push_back(ip);
	}

	return 0;
}

static int proc_add_allow_ip(NetworkServer *net, Link *link, const Request &req, Response *resp){
	ENSURE_LOCALHOST();
	if(req.size() != 2){
		resp->push_back("client_error");
	}else{
		IpFilter *ip_filter = net->ip_filter;
		ip_filter->add_allow(req[1].String());
		resp->push_back("ok");
	}
	return 0;
}

static int proc_del_allow_ip(NetworkServer *net, Link *link, const Request &req, Response *resp){
	ENSURE_LOCALHOST();
	if(req.size() != 2){
		resp->push_back("client_error");
	}else{
		IpFilter *ip_filter = net->ip_filter;
		ip_filter->del_allow(req[1].String());
		resp->push_back("ok");
	}
	return 0;
}

static int proc_list_deny_ip(NetworkServer *net, Link *link, const Request &req, Response *resp){
	ENSURE_LOCALHOST();

	resp->push_back("ok");
	IpFilter *ip_filter = net->ip_filter;
	if(!ip_filter->allow_all){
		resp->push_back("all");
	}
	std::set<std::string>::const_iterator it;
	for(it=ip_filter->deny.begin(); it!=ip_filter->deny.end(); it++){
		std::string ip = *it;
		ip = ip.substr(0, ip.size() - 1);
		resp->push_back(ip);
	}

	return 0;
}

static int proc_add_deny_ip(NetworkServer *net, Link *link, const Request &req, Response *resp){
	ENSURE_LOCALHOST();
	if(req.size() != 2){
		resp->push_back("client_error");
	}else{
		IpFilter *ip_filter = net->ip_filter;
		ip_filter->add_deny(req[1].String());
		resp->push_back("ok");
	}
	return 0;
}

static int proc_del_deny_ip(NetworkServer *net, Link *link, const Request &req, Response *resp){
	ENSURE_LOCALHOST();
	if(req.size() != 2){
		resp->push_back("client_error");
	}else{
		IpFilter *ip_filter = net->ip_filter;
		ip_filter->del_deny(req[1].String());
		resp->push_back("ok");
	}
	return 0;
}


text:
	class CanControlSystem;

	// Define events
	enum {
	  doOff = 1,
	};

	// Define levels
	enum {
	  off = 1,
	};

	class CanSafetyProperties : public eeros::safety::SafetyProperties {

		public:
			CanSafetyProperties(CanControlSystem* cs);
			virtual ~CanSafetyProperties();

			// outputs
			// inputs

		private:
			CanControlSystem* controlSys;
	};

	#endif // CH_NTB_CANSAFETYPROPERTIES_HPP_


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="OxyPlot">
//   The MIT License (MIT)
//
//   Copyright (c) 2012 Oystein Bjorke
//
//   Permission is hereby granted, free of charge, to any person obtaining a
//   copy of this software and associated documentation files (the
//   "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish,
//   distribute, sublicense, and/or sell copies of the Software, and to
//   permit persons to whom the Software is furnished to do so, subject to
//   the following conditions:
//
//   The above copyright notice and this permission notice shall be included
//   in all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ExampleBrowser
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled.
                // For production applications this error handling should be replaced with something that will
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}


text:
```
$ brew install mysql
$ mysql.server start
```

#### Create db, temp user and grant privileges
```
$ sudo mysql
CREATE DATABASE ufcdb;
CREATE USER 'tempuser'@'localhost' IDENTIFIED BY 'temppassword';
GRANT ALL PRIVILEGES ON ufcdb . * TO 'tempuser'@'localhost';
FLUSH PRIVILEGES;
exit
```

#### Install dependencies
`$ pip install -r requirements.txt`

#### Save dependencies
`$ pip freeze > requirements.txt`

## Architecture

- crawler
    - multiple data sources
    - event based updates
- storage
- predictor(s)
    - featurizer
    - learner
    - verifier
        - cross-validation
        - benchmarking (against trivial predictors)


text:
/* eslint-disable mocha/no-hooks-for-single-case, mocha/no-top-level-hooks */

import '@babel/polyfill';

import { format } from 'util';
import chai from 'chai';
import Enzyme, { ReactWrapper, ShallowWrapper } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import sinonChai from 'sinon-chai';

Enzyme.configure({ adapter: new Adapter() });

function assertLength(length) {
  return function $assertLength(selector) {
    let result = this.find(selector);
    expect(result).to.have.length(length);
    return result;
  };
}

function print() {
  return this.tap((f) => console.log(f.debug()));
}

ReactWrapper.prototype.assertSingle = assertLength(1);
ShallowWrapper.prototype.assertSingle = assertLength(1);

ReactWrapper.prototype.assertNone = assertLength(0);
ShallowWrapper.prototype.assertNone = assertLength(0);

ReactWrapper.prototype.print = print;
ShallowWrapper.prototype.print = print;

chai.should();
chai.use(sinonChai);

global.expect = chai.expect;
global.assert = chai.assert;

beforeEach(() => {
  sinon.stub(console, 'error').callsFake((...args) => {
    const msg = format(...args);
    let expected = false;

    console.error.expected.forEach((about) => {
      if (msg.indexOf(about) !== -1) {
        console.error.warned[about] = true;
        expected = true;
      }
    });

    if (expected) {
      return;
    }

    console.error.threw = true;
    throw new Error(msg);
  });

  console.error.expected = [];
  console.error.warned = Object.create(null);
  console.error.threw = false;
});

afterEach(() => {
  if (!console.error.threw && console.error.expected.length) {
    expect(console.error.warned).to.have.keys(console.error.expected);
  }

  console.error.restore();
});

describe('Process environment for tests', () => {
  it('Should be development for React console warnings', () => {
    assert.notEqual(process.env.NODE_ENV, 'production');
  });
});

// Ensure all files in src folder are loaded for proper code coverage analysis
const srcContext = require.context('../src', true, /.*\.js$/);
srcContext.keys().forEach(srcContext);

const testsContext = require.context('.', true, /Spec$/);
testsContext.keys().forEach(testsContext);


text:
@interface FDModalTransition ()<UIViewControllerAnimatedTransitioning>

@end

@implementation FDModalTransition

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return self;
}
#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.6;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIView *contentView = [transitionContext containerView];
    UITabBarController *fromRootVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    // 第1个是modal
    FDTableViewController1 *fromVC = fromRootVC.childViewControllers[1];
    for (FDTableViewController1 *vc in fromVC.childViewControllers) {
        if ([vc isKindOfClass:[FDTableViewController1 class]]) {
            fromVC = vc;
        }
    }
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    //目的遮住tabBar
    UIView *coverView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    coverView.backgroundColor = [UIColor yellowColor];
    [contentView addSubview:coverView];

    UIView *tempView = [[UIView alloc] init];
    tempView.frame = [contentView convertRect:fromVC.startRect fromView:fromVC.tableView];
    tempView.backgroundColor = [UIColor groupTableViewBackgroundColor];

    UIView  *snapShotView = [fromVC.tabBarController.view snapshotViewAfterScreenUpdates:NO];
    snapShotView.frame = [contentView convertRect:fromVC.tabBarController.view.frame fromView:fromVC.tabBarController.view];

    fromVC.view.alpha = 0;
    toVC.view.alpha = 0;

    [contentView addSubview:snapShotView];
    [contentView addSubview:tempView];
    [contentView addSubview:toVC.view];

    [UIView animateWithDuration:0.2 animations:^{
        snapShotView.transform = CGAffineTransformMakeScale(0.9, 0.9);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:[self transitionDuration:transitionContext] - 0.2 animations:^{
            tempView.frame = contentView.bounds;
        } completion:^(BOOL finished) {
            [coverView removeFromSuperview];
            [tempView removeFromSuperview];
            [snapShotView removeFromSuperview];
            toVC.view.alpha = 1.0;
            fromVC.view.alpha = 1.0;
            //告诉系统动画结束
            [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
        }];

    }];
}

@end


text:
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarLint.VisualStudio.Integration.State;
using SonarLint.VisualStudio.Integration.TeamExplorer;
using SonarQube.Client.Models;

namespace SonarLint.VisualStudio.Integration.UnitTests.State
{
    [TestClass]
    public class TransferableVisualStateTests
    {
        [TestInitialize]
        public void TestInitialize()
        {
            ThreadHelper.SetCurrentThreadAsUIThread();
        }

        [TestMethod]
        public void TransferableVisualState_DefaultState()
        {
            // Arrange
            var testSubject = new TransferableVisualState();

            // Assert
            testSubject.HasBoundProject.Should().BeFalse();
            testSubject.IsBusy.Should().BeFalse();
            testSubject.ConnectedServers.Should().NotBeNull();
            testSubject.ConnectedServers.Should().BeEmpty();
        }

        [TestMethod]
        public void TransferableVisualState_BoundProjectManagement()
        {
            // Arrange
            var testSubject = new TransferableVisualState();
            var server = new ServerViewModel(new ConnectionInformation(new System.Uri("http://server")));
            var project1 = new ProjectViewModel(server, new SonarQubeProject("", ""));
            var project2 = new ProjectViewModel(server, new SonarQubeProject("", ""));

            // Act (bind to something)
            testSubject.SetBoundProject(project1);

            // Assert
            testSubject.HasBoundProject.Should().BeTrue();
            project1.IsBound.Should().BeTrue();
            project2.IsBound.Should().BeFalse();
            server.ShowAllProjects.Should().BeFalse();

            // Act (bind to something else)
            testSubject.SetBoundProject(project2);

            // Assert
            testSubject.HasBoundProject.Should().BeTrue();
            project1.IsBound.Should().BeFalse();
            project2.IsBound.Should().BeTrue();
            server.ShowAllProjects.Should().BeFalse();

            // Act(clear binding)
            testSubject.ClearBoundProject();

            // Assert
            testSubject.HasBoundProject.Should().BeFalse();
            project1.IsBound.Should().BeFalse();
            project2.IsBound.Should().BeFalse();
            server.ShowAllProjects.Should().BeTrue();
        }
    }
}


text:
// OpenPHACTS RDF Validator,
// A tool for validating and storing RDF.
//
// Copyright 2012-2013  Christian Y. A. Brenninkmeijer
// Copyright 2012-2013  University of Manchester
// Copyright 2012-2013  OpenPhacts
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package uk.ac.manchester.cs.datadesc.validator.metadata.type;

import java.math.BigInteger;
import org.openrdf.model.Literal;
import org.openrdf.model.Value;

/**
 *
 * @author Christian
 */
public class IntegerType implements MetaDataType{

    @Override
    public boolean correctType(Value value) {
        if (value instanceof Literal){
            Literal literal = (Literal)value;
            try {
                BigInteger test = literal.integerValue();
                return true;
            } catch (Exception ex) {  //NumberFormatException
                return false;
            }
        }
        return false;
    }

    @Override
    public String getCorrectType() {
        return " An Integer";
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>MathPad</title>

    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap-submenu/2.0.4/css/bootstrap-submenu.min.css" rel="stylesheet">

    <link href="https://cdn.bootcss.com/summernote/0.8.8/summernote.css" rel="stylesheet">

    <link href="https://cdn.bootcss.com/fullPage.js/2.9.5/jquery.fullpage.min.css" rel="stylesheet">

                    New

                  <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" data-submenu="" aria-expanded="false" title="Settings">

                  </button>

                       Themes

Default

Cerulean

Cosmo

Cyborg

Darkly

Flatly

Journal

Lumen

Paper

Readable

Sandstone

Simplex

Slate

Spacelab

Superhero

United

Yeti

                       Hints...

                         About...

                Math Pad

                Math Pad

                Write formatted text with LaTeX formula!

                $$f(a) = {1 \over 2\pi i}\oint_\gamma {f(z) \over z-a} dz$$

                Enjoy it!

              <button type="button" class="btn btn-default" value="$$" title="$$">

              </button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="common" title="Common"></button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="birelation" title="Relations, Ops">
                $\leq$
              </button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="sum-union" title="Derivative">$\partial$ </button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="sum-union" title="Integral">$\int$</button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="sum-union" title="Sum,mul...">$\sum$</button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="greek" title="Greek">$\beta$</button>

              <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="greek" title="More">...</button>

                           Mt

                           Fn

                           Op

                           De

                           Ar&Ft

                                <button type="button" class="btn btn-default" value="\ldots ">$\ldots$</button>
                                <button type="button" class="btn btn-default" value="\cdots ">$\cdots$</button>
                                <button type="button" class="btn btn-default" value="\vdots ">$\vdots$</button>
                                <button type="button" class="btn btn-default" value="\ddots ">$\ddots$</button>
                                <button type="button" class="btn btn-default" value="\begin{cases} a & b \\ c & d \end{cases}" title="cases">cases</button>

                                <button type="button" class="btn btn-default" value="\begin{pmatrix} a & b \\ c & d \end{pmatrix}" title="pmatrix">$\begin{pmatrix} a & b \\ c & d \end{pmatrix}$</button>
                                <button type="button" class="btn btn-default" value="\begin{pmatrix} a_{11} & \cdots & a_{1n} \\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn} \end{pmatrix}" title="pmatrix">$\begin{pmatrix} a_{11} & \cdots & a_{1n} \\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn} \end{pmatrix}$</button>

                                <button type="button" class="btn btn-default" value="\begin{bmatrix} a & b \\ c & d \end{bmatrix}" title="pmatrix">$\begin{bmatrix} a & b \\ c & d \end{bmatrix}$</button>
                                <button type="button" class="btn btn-default" value="\begin{bmatrix} a_{11} & \cdots & a_{1n} \\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn} \end{bmatrix}" title="pmatrix">$\begin{bmatrix} a_{11} & \cdots & a_{1n} \\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn} \end{bmatrix}$</button>

        <button id="printit" type="button" class="btn btn-default pull-right hidden-xs" title="Print">

        </button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

              All hints

              My hints

                      Hint
                      Code
                      Disp.

                    <textarea id="myhints-conf" type="" class="col-xs-12" style="height:100px;"></textarea>

FORMAT: (hint) ## (code) [## [display] ## [display phone]]

                       xa ## \alpha

                       sqrt ## \sqrt{ } ## sqrt

                       rq ## {-b\pm\sqrt{b^2-4ac} \over 2a} ## ## root of quadr. eq

          <input type="text" class="form-control" id="hints-filter" placeholder="filter" title="Filter hints">

        <button id="hints-btn-close" type="button" class="btn btn-default" data-dismiss="modal" style="display:inline;">Close</button> <button  id="hints-btn-save" type="button" class="btn btn-primary" data-dismiss="modal">Save</button>

           <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

             Math Pad v0.5

            Write formatted text anywhere with LaTeX formula.

           Project  Home,  Source,  Privacy,  LaTeX hints.

 Build on MathJax, Summernote, Bootstrap, jQuery, fullPage.js, store.js
        , Pretty Date, and jQuery.print.

        <address class="text-muted">
           Bo Zhuang

           bozhuang#vip.jiangnan.edu.cn

           Jiangnan University
        </address>

           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

						 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

							 Delete

            <q id="item-deleted">item-deleted</q>

              Are you sure to delete?

						 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button id="remove" type="button" class="btn btn-danger" data-dismiss="modal">Delete</button>

 						 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 							Sliding mode


text:
using System;

namespace VersionOne.ServiceHost.ConfigurationTool.UI.Interfaces {
    // TODO remove this interface
    public interface IFormController : ISettingsProvider {
        void SetCoreServiceNodesEnabled(bool enabled);
        void FailApplication(string message);

        event EventHandler BeforeSave;
    }
}


text:
#include <zephyr/kernel.h>
#include <zephyr/irq_offload.h>
#include <zsr.h>
#include <zephyr/irq.h>

#define CURR_CPU (IS_ENABLED(CONFIG_SMP) ? arch_curr_cpu()->id : 0)

static struct {
	irq_offload_routine_t fn;
	const void *arg;
} offload_params[CONFIG_MP_MAX_NUM_CPUS];

static void irq_offload_isr(const void *param)
{
	ARG_UNUSED(param);
	offload_params[CURR_CPU].fn(offload_params[CURR_CPU].arg);
}

void arch_irq_offload(irq_offload_routine_t routine, const void *parameter)
{
	IRQ_CONNECT(ZSR_IRQ_OFFLOAD_INT, 0, irq_offload_isr, NULL, 0);

	unsigned int intenable, key = arch_irq_lock();

	offload_params[CURR_CPU].fn = routine;
	offload_params[CURR_CPU].arg = parameter;

	__asm__ volatile("rsr %0, INTENABLE" : "=r"(intenable));
	intenable |= BIT(ZSR_IRQ_OFFLOAD_INT);
	__asm__ volatile("wsr %0, INTENABLE; wsr %0, INTSET; rsync"
			 :: "r"(intenable), "r"(BIT(ZSR_IRQ_OFFLOAD_INT)));
	arch_irq_unlock(key);
}