text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io.subutai.common.util;

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;

import com.google.common.base.Preconditions;

/**
 * Service Locator allows to locate OSGi services by interface
 */
public class ServiceLocator
{

    /**
     * Returns service by Interface
     *
     * @param clazz Service Interface class to look up for
     *
     * @return service reference
     */
    public static <T> T getServiceOrNull( Class<T> clazz )
    {
        Preconditions.checkNotNull( clazz, "Class is null" );

        // get bundle instance via the OSGi Framework Util class
        BundleContext ctx = FrameworkUtil.getBundle( clazz ).getBundleContext();
        if ( ctx != null )
        {
            ServiceReference serviceReference = ctx.getServiceReference( clazz.getName() );
            if ( serviceReference != null )
            {
                Object service = ctx.getService( serviceReference );
                if ( clazz.isInstance( service ) )
                {
                    return clazz.cast( service );
                }
            }
        }

        return null;
    }

    public static <T> T lookup( Class<T> clazz )
    {
        T service = getServiceOrNull( clazz );

        if ( service == null )
        {
            throw new IllegalStateException( String.format( "Failed to lookup %s service", clazz.getSimpleName() ) );
        }

        return service;
    }

    /**
     * Returns service by Interface
     *
     * @param clazz - Service Interface class to look up for
     *
     * @return - service reference
     */

    public <T> T getService( Class<T> clazz )
    {
        return lookup( clazz );
    }
}

redpajama_set_name: RedPajamaGithub


text:
%Centralizar verticalmente.
\newenvironment{midpage}{\vspace*{\fill}}{\vspace*{\fill}}
%Centralizar horizontalmente.
\newenvironment{midline}{\hspace*{\fill}}{\hspace*{\fill}}
\documentclass[12pts]{article}
\usepackage[utf8]{inputenc}
%Pacote para colocar cor no código.
\usepackage{color}
\definecolor{light-gray}{gray}{0.95}
%Pacote para inserir código.
\usepackage{listings}
\lstset{
    numbers=left,
    tabsize=2,
    backgroundcolor=\color{light-gray},
}\title{
	Prática de Eletrônica Digital 1 - (119466)
	\singlespacing
		Turma E (Unb - Gama)
	\singlespacing
	\begin{midpage}
	\begin {large}
		Relatório Experimento 5
		\singlespace
		Circuitos Multiplexadores e Demultiplexadores
	\end {large}
	\end{midpage}
}
\date{Outubro 04, 2016}
\usepackage{indentfirst}
\usepackage{setspace}
\usepackage{verbatim}
\usepackage[pdftex]{hyperref}
\usepackage{graphicx}
\begin{document}
\maketitle
%\vspace{100 mm}
\begin{center}

\begin{tabular}{|c|l|r|}
\hline
Nome & Matrícula & Assinatura\\
\hline

Arthur Temporim & 14/0016759 & \\
\hline
Eduardo Nunes & 14/0056189 & \\

\hline
\end{tabular}

\end{center}

\newpage

\section{Sumário}

\begin{itemize}
	\item Introdução
	\singlespacing
	\item Experimentos
	\singlespacing
	\item Discussão
	\singlespacing
	\item Conclusões
	\singlespacing
	\item Referências Bibliograficas
	\singlespacing
	%\item Diagramas esquemáticos
\end{itemize}

\newpage

\section{Introdução}
\iffalse
Introdução, indicando a delimitação do tema, apresentando a justificativa descrevendo o propósito do relatório.
\fi

\section{Experimentos}
\iffalse
Parte Experimental, descrevendo os passos realizados, dificuldades e soluções para os problemas encontrados. Aqui, deve-se apresentar uma descrição dos resultados encontrados em forma de figuras, gráficos e tabelas.
\fi

	Neste relatório é apresentado o resultado dos experimentos realizados na aula prática de eletrônica digital 1. São apresentados o código VHDL assim como as saidas em forma de onda e o diagrama do circuito.

\subsection{Experimento 01}
\singlespacing
	O primeiro experimento tratou-se de projetar e simular um circuito que implemente a função: f(A,B,C) = !AB + !ABC + ABC. Utilizando um multiplexidor de quatro entradas e uma saída (Mux 4:1).

	Acompanham abaixo o código VHDL, diagrama do circuito e a saída em forma de onda:

\clearpage
\subsection{Código VHDL}
\lstinputlisting[language=vhdl]{projetos/projeto1/projeto1.vhd}

\clearpage
\subsection{Diagrama Esquemático}
\begin{figure}[!htb]
  \centering
  \includegraphics[scale=0.45]{imagens/circuito1}
  \caption{Esquemático projeto 1- Ise Design Suite 14.7}
  \label{figRotulo}
\end{figure}

\newpage
\subsection{Diagrama de Onda}

\begin{figure}[!htb]
  \centering
  \includegraphics[scale=0.35]{imagens/onda1}
  \caption{Diagrama de ondas projeto 1- Ise Design Suite 14.7}
  \label{figRotulo}
\end{figure}
\newpage

\subsection{Experimento 02}
	O segundo experimento tratou-se de projetar e simular um circuito que implemente a mesma função do experiemnto 01. Utilizando um Demux:2, Mux:2 e uma porta OR.

\clearpage
\subsection{Código VHDL}
\lstinputlisting[language=vhdl]{projetos/projeto2/projeto2.vhd}

\clearpage
\subsection{Diagrama Esquemático versão 1}
\begin{figure}[!htb]
  \centering
  \includegraphics[scale=0.45]{imagens/esquematico2}
  \caption{Esquemático projeto 2 V1 - Ise Design Suite 14.7}
  \label{figRotulo}
\end{figure}

\newpage
\subsection{Diagrama Esquemático versão 2}
\begin{figure}[!htb]
  \centering
  \includegraphics[scale=0.45]{imagens/esquematico22}
  \caption{Esquemático projeto 2 V2 - Ise Design Suite 14.7}
  \label{figRotulo}
\end{figure}

\subsection{Diagrama de Onda}

\begin{figure}[!htb]
  \centering
  \includegraphics[scale=0.35]{imagens/onda2}
  \caption{Diagrama de ondas Projeto 2 V2 - Ise Design Suite 14.7}
  \label{figRotulo}
\end{figure}
\newpage

\section{Discussão}
\iffalse
Discussão sobre os resultados encontrados, comentando detalhadamente as medições realizadas e dando a devida interpretação destas, informando se os objetivos da experimento foram alcançados. Esta é uma das partes mais importantes do relatório: aqui, há oportunidade para expressar os conhecimentos adquiridos na prática e fazer a interrelação com os fundamentos teóricos.
\fi

        Neste quinto relatório foi possível realizar o primeiro experimento com êxito. Porém, em relação ao segundo experimento tivemos dificuldade na implementação do circuito pois o código em VHDL não correspondia ao resultado esperado quando verificado o diagrama em forma de onda. Para solucionar foi utilizado mais um \textit{signal} e as atribuições para a saida foram feitas fora do \textit{process}.

        A solução que alcançou o resultado esperado é a referente à \textbf{versão 2}. Pode-se observar que a implementação do circuito é abstraída para um multiplexador após a implementação do circuito.

\section{Conclusões}
\iffalse
Conclusões, mostrando os êxitos e eventuais problemas encontrados na realização do experimento, indicando as limitações, apresentando recomendações e/ou sugestões.
\fi

Com a realização deste experimento foi possível adquirir conhecimento a respeito de multiplexador e demultiplexador. Suas incríveis funcionalidades e reaproveitamento de circuitos com um auxílio de \textit{clocks}.

\section{Referências Bibliográficas}
\iffalse
Referencias Bibliográficas, relacionadas e citadas de acordo com as normas da ABNT.
\fi
Prática de Eletrônica Digital I 2016.2 professores Henrique Marra Taira Menegaz,Leonardo Aguayo, Lourdes Mattos Brasil, Marcus Vinícius Chaffim Costa, Mariana Costa Bernardes Matias. UnB - FGA Agosto de 2015.

\iffalse
\section{Diagramas Esquemáticos}
Diagramas Esquemáticos. Todos os diagramas devem ser inseridos ao final do relatório em páginas separadas do texto, indicando a identificação do circuito, autor, revisor, versão e datas relevantes.
\fi
\newpage

\end{document}


text:
package org.n0pe.asadmin.commands;

import org.apache.commons.lang.StringUtils;
import org.n0pe.asadmin.AbstractAsAdminCmd;
import org.n0pe.asadmin.Util;

public class Set
    extends AbstractAsAdminCmd
{

    private String property;
    private String value;

    public Set( String propertyName, String propertyValue )
    {
        property = propertyName;
        value = propertyValue;
    }

    public boolean needCredentials()
    {
        return false;
    }

    public String getActionCommand()
    {
        return "set";
    }

    public String[] getParameters()
    {
        if( StringUtils.isEmpty( property ) || StringUtils.isEmpty( value ) )
        {
            throw new IllegalStateException();
        }
        return new String[]
            {
                property + "=" + Util.quoteCommandArgument( value )
            };
    }

}


text:
<!DOCTYPE html>

	<title>Login</title>
	<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/pagestyle.css') }}">

				{% if username %}

Hello! {{ username }}

				{% endif %}

Home

Help

				{% if accType == 'admin' %}

Edit thresholds

Add new user

Delete user

Show all account details

				{% endif %}
				{% if accType == 'doctor' %}

Notifications

        {% endif %}
				{% if accType == 'patient' %}

Add new entry

New MCQ Entry

Upload Photo

Suggest a MCQ

        {% endif %}
				{% if username %}

Logout

				{% endif %}

			<form action="" method="POST">

						Username
						<input type="text" name="username">

						Password
						<input type="password" name="password">

							<input class="button second" type="submit" name="submit" value="Login">

			</form>
			{% if error %}

Error! {{ error }}

			{% endif %}

	Developed by Vivek, Piyush, Chaitanya


text:
using ACBr.Net.DFe.Core.Attributes;
using ACBr.Net.DFe.Core.Serializer;
using PropertyChanged;

namespace ACBr.Net.Sat
{
	/// <summary>
	/// Class ImpostoPISST. This class cannot be inherited.
	/// </summary>
	[ImplementPropertyChanged]
	public sealed class ImpostoPisSt
	{
		#region Propriedades

		/// <summary>
		/// Gets or sets the v bc.
		/// </summary>
		/// <value>The v bc.</value>
		[DFeElement(TipoCampo.De2, "vBC", Id = "R02", Min = 3, Max = 15, Ocorrencia = Ocorrencia.Obrigatoria)]
		public decimal VBc { get; set; }

		/// <summary>
		/// Gets or sets the p pis.
		/// </summary>
		/// <value>The p pis.</value>
		[DFeElement(TipoCampo.De4, "pPIS", Id = "R03", Min = 5, Max = 5, Ocorrencia = Ocorrencia.Obrigatoria)]
		public decimal PPis { get; set; }

		/// <summary>
		/// Gets or sets the q bc product.
		/// </summary>
		/// <value>The q bc product.</value>
		[DFeElement(TipoCampo.De4, "qBCProd", Id = "R04", Min = 1, Max = 16, Ocorrencia = Ocorrencia.MaiorQueZero)]
		public decimal QBcProd { get; set; }

		/// <summary>
		/// Gets or sets the v aliq product.
		/// </summary>
		/// <value>The v aliq product.</value>
		[DFeElement(TipoCampo.De4, "vAliqProd", Id = "R05", Min = 5, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)]
		public decimal VAliqProd { get; set; }

		/// <summary>
		/// Gets or sets the v pis.
		/// </summary>
		/// <value>The v pis.</value>
		[DFeElement(TipoCampo.De2, "vPIS", Id = "R06", Min = 1, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)]
		public decimal VPis { get; set; }

		#endregion Propriedades

		#region Methods

		/// <summary>
		/// Shoulds the serialize v bc.
		/// </summary>
		/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
		private bool ShouldSerializeVBc()
		{
			return VAliqProd == 0;
		}

		/// <summary>
		/// Shoulds the serialize ppis.
		/// </summary>
		/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
		private bool ShouldSerializePPis()
		{
			return VAliqProd == 0;
		}

		#endregion Methods
	}
}


text:
package com.example.usage.recycler;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.example.usage.R;
import com.example.usage.recycler.BasicRecyclerViewContract.PresentationModel;
import com.example.usage.recycler.BasicRecyclerViewContract.Presenter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class BasicRecyclerViewActivity extends AppCompatActivity implements BasicRecyclerViewAdapter.ItemClickListener {

    private BasicRecyclerViewAdapter adapter;

    private Presenter presenter;

    private List<PresentationModel> items;

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

        RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setAdapter(adapter = new BasicRecyclerViewAdapter(this, this));

        // Setting layout manager in XML layout files is recommended.
        // recycler.setLayoutManager(new LinearLayoutManager(this));

        presenter = new BasicRecyclerViewPresenter(new MvpView());

        Map<String, Serializable> state = null;
        if (savedInstanceState != null) {
            state = new HashMap<>();
            for (String key : Presenter.STATE_KEYS) {
                state.put(key, savedInstanceState.getSerializable(key));
            }
        }

        presenter.init(state);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        for (Entry<String, Serializable> entry : presenter.prepareState().entrySet()) {
            outState.putSerializable(entry.getKey(), entry.getValue());
        }

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onItemClicked(int position, String id) {
        presenter.hit(position, id);
    }

    private class MvpView implements BasicRecyclerViewContract.View {

        @Override
        public void showData(List<PresentationModel> items) {
            adapter.setData(BasicRecyclerViewActivity.this.items = items);
        }

        @Override
        public void updateHits(int position, int hits) {
            items.get(position).hits = hits;
            // or adapter.updateHits(position, hits), so the view don't have to manipulate data.
            adapter.notifyItemChanged(position);
        }

        @Override
        public void showTotalHits(int hits) {
            String message = String.format("Totoal HITS: %d !!", hits);
            Toast.makeText(BasicRecyclerViewActivity.this, message, Toast.LENGTH_SHORT).show();
        }

    }

}


text:
package co.tinyqs.tinyredis;

/**
 * A pairing between a redis LUA script and its SHA hash.
 */
public class ScriptSHAPair
{
    private final String script;
    private final String SHA;
    public ScriptSHAPair(String script, String sHA)
    {
        super();
        this.script = script;
        SHA = sHA;
    }
    public String getScript()
    {
        return script;
    }
    public String getSHA()
    {
        return SHA;
    }

}


text:
package org.onehippo.repository.mock;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;

import javax.jcr.Binary;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;

import org.apache.jackrabbit.util.ISO8601;

/**
 * Mock version of a {@link Value}.
 */
public class MockValue implements Value {

    private int type;
    private String stringifiedValue;
    private Binary binary;

    @SuppressWarnings("unused")
    public MockValue() {
        // used by JAXB
    }

    public MockValue(String stringifiedValue) {
        this(PropertyType.STRING, stringifiedValue);
    }

    public MockValue(Binary binaryValue) {
        this.type = PropertyType.BINARY;
        this.binary = binaryValue;
    }

    public MockValue(int type, String stringifiedValue) {
        this.type = type;
        this.stringifiedValue = stringifiedValue;
    }

    public MockValue(Value value) throws RepositoryException {
        this.type = value.getType();

        switch (type) {
            case PropertyType.STRING: {
                this.stringifiedValue = value.getString();
                break;
            }
            case PropertyType.DATE: {
                this.stringifiedValue = ISO8601.format(value.getDate());
                break;
            }
            case PropertyType.BOOLEAN: {
                this.stringifiedValue = Boolean.toString(value.getBoolean());
                break;
            }
            case PropertyType.LONG: {
                this.stringifiedValue = Long.toString(value.getLong());
                break;
            }
            case PropertyType.DOUBLE: {
                this.stringifiedValue = Double.toString(value.getDouble());
                break;
            }
            case PropertyType.DECIMAL: {
                this.stringifiedValue = value.getDecimal().toString();
                break;
            }
            case PropertyType.BINARY: {
                this.binary = value.getBinary();
                break;
            }
            case PropertyType.NAME: {
                this.stringifiedValue = value.getString();
                break;
            }
            case PropertyType.URI: {
                this.stringifiedValue = value.getString();
                break;
            }
            default: {
                throw new UnsupportedOperationException("Unsupported type, " + type + ". Only primitive number/string values are currently supported.");
            }
        }
    }

    @Override
    public int getType() {
        return type;
    }

    @Override
    public String getString() throws ValueFormatException {
        checkNotBinary();
        return stringifiedValue;
    }

    private void checkNotBinary() throws ValueFormatException {
        if (binary != null) {
            throw new ValueFormatException("Binary value cannot be converted to a string");
        }
    }

    @Override
    public Calendar getDate() throws ValueFormatException {
        checkNotBinary();
        try {
            Calendar date = ISO8601.parse(stringifiedValue);

            if (date == null) {
                throw new ValueFormatException("Invalid date format (ISO8601). " + stringifiedValue);
            }

            return date;
        } catch (Exception e) {
            throw new ValueFormatException(e);
        }
    }

    @Override
    public boolean getBoolean() throws ValueFormatException {
        checkNotBinary();
        try {
            return Boolean.parseBoolean(stringifiedValue);
        } catch (Exception e) {
            throw new ValueFormatException(e);
        }
    }

    @Override
    public long getLong() throws ValueFormatException {
        checkNotBinary();
        try {
            return Long.parseLong(stringifiedValue);
        } catch (Exception e) {
            throw new ValueFormatException(e);
        }
    }

    @Override
    public double getDouble() throws ValueFormatException {
        checkNotBinary();
        try {
            return Double.parseDouble(stringifiedValue);
        } catch (Exception e) {
            throw new ValueFormatException(e);
        }
    }

    @Override
    public BigDecimal getDecimal() throws ValueFormatException {
        checkNotBinary();
        try {
            return new BigDecimal(stringifiedValue);
        } catch (Exception e) {
            throw new ValueFormatException(e);
        }
    }

    @Override
    public InputStream getStream() throws RepositoryException {
        throw new UnsupportedOperationException("Use #getBinary instead");
    }

    @Override
    public Binary getBinary() throws RepositoryException {
        if (binary != null) {
            return binary;
        }
        throw new RepositoryException("Value is not binary");
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        } else if (o instanceof MockValue) {
            MockValue other = (MockValue) o;
            if (stringifiedValue != null) {
                return stringifiedValue.equals(other.stringifiedValue);
            } else {
                return binary.equals(other.binary);
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        if (stringifiedValue != null) {
            return stringifiedValue.hashCode();
        }
        return binary.hashCode();
    }

    @Override
    public String toString() {
        StringBuffer result = new StringBuffer(super.toString());
        result.append(";{type: ").append(type);
        if (stringifiedValue != null) {
            result.append(", '").append(stringifiedValue).append("'");
        }
        result.append("}");
        return result.toString();
    }
}


text:
define([
    'underscore',
    'backbone',
    'common',
    'app/models/device'
], function(_, Backbone, Common, Device) {
    'use strict';

    var DevicesCollection = Backbone.Collection.extend({
        model: Device,
        url: function () {
            return Common.getUrl({name: 'devices'});
        }
    });

    return DevicesCollection;
});


text:
package com.intellij.openapi.vcs.changes;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.ThreeState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.File;
import java.util.Collection;
import java.util.List;

public abstract class ChangeListManager implements ChangeListModification {
  @NotNull
  public static ChangeListManager getInstance(@NotNull Project project) {
    return project.getComponent(ChangeListManager.class);
  }

  public abstract void scheduleUpdate();

  @Deprecated
  public abstract void scheduleUpdate(boolean updateUnversionedFiles);

  public abstract void invokeAfterUpdate(@NotNull Runnable afterUpdate,
                                         @NotNull InvokeAfterUpdateMode mode,
                                         @Nullable String title,
                                         @Nullable ModalityState state);

  @Deprecated
  public abstract void invokeAfterUpdate(@NotNull Runnable afterUpdate,
                                         @NotNull InvokeAfterUpdateMode mode,
                                         @Nullable String title,
                                         @Nullable Consumer<VcsDirtyScopeManager> dirtyScopeManager,
                                         @Nullable ModalityState state);

  public abstract int getChangeListsNumber();

  @NotNull
  public List<LocalChangeList> getChangeListsCopy() {
    return getChangeLists();
  }

  @NotNull
  public abstract List<LocalChangeList> getChangeLists();

  @NotNull
  public abstract Collection<Change> getAllChanges();

  /**
   *  Currently active change list.
   *  @see #setDefaultChangeList(String)
   *  @see #setDefaultChangeList(LocalChangeList)
   */
  @NotNull
  public abstract LocalChangeList getDefaultChangeList();

  @NotNull
  public abstract String getDefaultListName();

  @NotNull
  public abstract List<File> getAffectedPaths();

  @NotNull
  public abstract List<VirtualFile> getAffectedFiles();

  /**
   * @return if a file belongs to some changelist
   */
  public abstract boolean isFileAffected(@NotNull VirtualFile file);

  @Nullable
  public abstract LocalChangeList findChangeList(String name);

  @Nullable
  public abstract LocalChangeList getChangeList(String id);

  @NotNull
  public abstract List<LocalChangeList> getChangeLists(@NotNull Change change);

  @NotNull
  public abstract List<LocalChangeList> getChangeLists(@NotNull VirtualFile file);

  @Nullable
  public abstract LocalChangeList getChangeList(@NotNull Change change);

  @Nullable
  public abstract LocalChangeList getChangeList(@NotNull VirtualFile file);

  @Nullable
  public abstract String getChangeListNameIfOnlyOne(Change[] changes);

  @Nullable
  public abstract Change getChange(@NotNull VirtualFile file);

  @Nullable
  public abstract Change getChange(FilePath file);

  @NotNull
  public abstract FileStatus getStatus(@NotNull VirtualFile file);

  public abstract boolean isUnversioned(VirtualFile file);

  @NotNull
  public abstract Collection<Change> getChangesIn(@NotNull VirtualFile dir);

  @NotNull
  public abstract Collection<Change> getChangesIn(@NotNull FilePath path);

  @NotNull
  public abstract ThreeState haveChangesUnder(@NotNull VirtualFile vf);

  @Nullable
  public abstract AbstractVcs getVcsFor(@NotNull Change change);

  public abstract void addChangeListListener(@NotNull ChangeListListener listener, @NotNull Disposable disposable);

  public abstract void addChangeListListener(@NotNull ChangeListListener listener);

  public abstract void removeChangeListListener(@NotNull ChangeListListener listener);

  public abstract void registerCommitExecutor(@NotNull CommitExecutor executor);

  @NotNull
  public abstract List<CommitExecutor> getRegisteredExecutors();

  public abstract void commitChanges(@NotNull LocalChangeList changeList, @NotNull List<Change> changes);

  public abstract void scheduleAutomaticEmptyChangeListDeletion(@NotNull LocalChangeList list);

  public abstract void scheduleAutomaticEmptyChangeListDeletion(@NotNull LocalChangeList list, boolean silently);

  @NotNull
  public abstract IgnoredFileBean[] getFilesToIgnore();

  public abstract boolean isIgnoredFile(@NotNull VirtualFile file);

  public abstract void setFilesToIgnore(@NotNull IgnoredFileBean... ignoredFiles);

  public abstract void addFilesToIgnore(@NotNull IgnoredFileBean... ignoredFiles);

  public abstract void addDirectoryToIgnoreImplicitly(@NotNull String path);

  public abstract void removeImplicitlyIgnoredDirectory(@NotNull String path);

  @NotNull
  public abstract List<VirtualFile> getModifiedWithoutEditing();

  @Nullable
  public abstract String getSwitchedBranch(@NotNull VirtualFile file);

  @Nullable
  public abstract String isFreezed();

  public abstract boolean isFreezedWithNotification(@Nullable String modalTitle);

  @Deprecated // used in TeamCity
  public abstract void reopenFiles(@NotNull List<FilePath> paths);

  @TestOnly
  public abstract boolean ensureUpToDate(boolean canBeCanceled);
}


text:
package org.hibernate.envers.test.entities.components.relations;

import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.envers.test.entities.StrTestEntity;

/**
 * @author Adam Warski (adam at warski dot org)
 */
@Embeddable
@Table(name = "ManyToOneCompEmb")
public class ManyToOneComponent {
	@ManyToOne
    private StrTestEntity entity;

    private String data;

	public ManyToOneComponent(StrTestEntity entity, String data) {
        this.entity = entity;
        this.data = data;
    }

    public ManyToOneComponent() {
    }

	public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

	public StrTestEntity getEntity() {
		return entity;
	}

	public void setEntity(StrTestEntity entity) {
		this.entity = entity;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		ManyToOneComponent that = (ManyToOneComponent) o;

		if (data != null ? !data.equals(that.data) : that.data != null) return false;
		if (entity != null ? !entity.equals(that.entity) : that.entity != null) return false;

		return true;
	}

	@Override
	public int hashCode() {
		int result = entity != null ? entity.hashCode() : 0;
		result = 31 * result + (data != null ? data.hashCode() : 0);
		return result;
	}

	public String toString() {
        return "ManyToOneComponent(str1 = " + data + ")";
    }
}


text:
"""
Usage: py2deb [OPTIONS] ...

Convert Python packages to Debian packages according to the given
command line options (see below). The command line arguments are the
same as accepted by the `pip install' command because py2deb invokes
pip during the conversion process. This means you can name the
package(s) to convert on the command line but you can also use
`requirement files' if you prefer.

If you want to pass command line options to pip (e.g. because you want
to use a custom index URL or a requirements file) then you will need
to tell py2deb where the options for py2deb stop and the options for
pip begin. In such cases you can use the following syntax:

  $ py2deb -r /tmp -- -r requirements.txt

So the `--' marker separates the py2deb options from the pip options.

Supported options:

  -c, --config=FILENAME

    Load a configuration file. Because the command line arguments are processed
    in the given order, you have the choice and responsibility to decide if
    command line options override configuration file options or vice versa.
    Refer to the documentation for details on the configuration file format.

    The default configuration files /etc/py2deb.ini and ~/.py2deb.ini are
    automatically loaded if they exist. This happens before environment
    variables and command line options are processed.

    Can also be set using the environment variable $PY2DEB_CONFIG.

  -r, --repository=DIRECTORY

    Change the directory where *.deb archives are stored. Defaults to
    the system wide temporary directory (which is usually /tmp). If
    this directory doesn't exist py2deb refuses to run.

    Can also be set using the environment variable $PY2DEB_REPOSITORY.

  --use-system-package=PYTHON_PACKAGE_NAME,DEBIAN_PACKAGE_NAME

    Exclude a Python package (the name before the comma) from conversion and
    replace references to the Python package with a specific Debian package
    name. This allows you to use system packages for specific Python
    requirements.

  --name-prefix=PREFIX

    Set the name prefix used during the name conversion from Python to
    Debian packages. Defaults to `python'. The name prefix and package
    names are always delimited by a dash.

    Can also be set using the environment variable $PY2DEB_NAME_PREFIX.

  --no-name-prefix=PYTHON_PACKAGE_NAME

    Exclude a Python package from having the name prefix applied
    during the package name conversion. This is useful to avoid
    awkward repetitions.

  --rename=PYTHON_PACKAGE_NAME,DEBIAN_PACKAGE_NAME

    Override the package name conversion algorithm for the given pair
    of package names. Useful if you don't agree with the algorithm :-)

  --install-prefix=DIRECTORY

    Override the default system wide installation prefix. By setting
    this to anything other than `/usr' or `/usr/local' you change the
    way py2deb works. It will build packages with a file system layout
    similar to a Python virtual environment, except there will not be
    a Python executable: The packages are meant to be loaded by
    modifying Python's module search path. Refer to the documentation
    for details.

    Can also be set using the environment variable $PY2DEB_INSTALL_PREFIX.

  --install-alternative=LINK,PATH

    Use Debian's `update-alternatives' system to add an executable
    that's installed in a custom installation prefix (see above) to
    the system wide executable search path. Refer to the documentation
    for details.

  --python-callback=EXPRESSION

    Set a Python callback to be called during the conversion process. Refer to
    the documentation for details about the use of this feature and the syntax
    of EXPRESSION.

    Can also be set using the environment variable $PY2DEB_CALLBACK.

  --report-dependencies=FILENAME

    Add the Debian relationships needed to depend on the converted
    package(s) to the given control file. If the control file already
    contains relationships the additional relationships will be added
    to the control file; they won't overwrite existing relationships.

  -y, --yes

    Instruct pip-accel to automatically install build time dependencies
    where possible. Refer to the pip-accel documentation for details.

    Can also be set using the environment variable $PY2DEB_AUTO_INSTALL.

  -v, --verbose

    Make more noise :-).

  -h, --help

    Show this message and exit.
"""

# Standard library modules.
import getopt
import logging
import os
import sys

# External dependencies.
import coloredlogs
from deb_pkg_tools.control import patch_control_file
from humanfriendly.terminal import usage, warning

# Modules included in our package.
from py2deb.converter import PackageConverter

# Initialize a logger.
logger = logging.getLogger(__name__)

def main():
    """Command line interface for the ``py2deb`` program."""
    # Configure terminal output.
    coloredlogs.install()
    try:
        # Initialize a package converter.
        converter = PackageConverter()
        # Parse and validate the command line options.
        options, arguments = getopt.getopt(sys.argv[1:], 'c:r:yvh', [
            'config=', 'repository=', 'use-system-package=', 'name-prefix=',
            'no-name-prefix=', 'rename=', 'install-prefix=',
            'install-alternative=', 'python-callback=', 'report-dependencies=',
            'yes', 'verbose', 'help',
        ])
        control_file_to_update = None
        for option, value in options:
            if option in ('-c', '--config'):
                converter.load_configuration_file(value)
            elif option in ('-r', '--repository'):
                converter.set_repository(value)
            elif option == '--use-system-package':
                python_package_name, _, debian_package_name = value.partition(',')
                converter.use_system_package(python_package_name, debian_package_name)
            elif option == '--name-prefix':
                converter.set_name_prefix(value)
            elif option == '--no-name-prefix':
                converter.rename_package(value, value)
            elif option == '--rename':
                python_package_name, _, debian_package_name = value.partition(',')
                converter.rename_package(python_package_name, debian_package_name)
            elif option == '--install-prefix':
                converter.set_install_prefix(value)
            elif option == '--install-alternative':
                link, _, path = value.partition(',')
                converter.install_alternative(link, path)
            elif option == '--python-callback':
                converter.set_python_callback(value)
            elif option == '--report-dependencies':
                control_file_to_update = value
                if not os.path.isfile(control_file_to_update):
                    msg = "The given control file doesn't exist! (%s)"
                    raise Exception(msg % control_file_to_update)
            elif option in ('-y', '--yes'):
                converter.set_auto_install(True)
            elif option in ('-v', '--verbose'):
                coloredlogs.increase_verbosity()
            elif option in ('-h', '--help'):
                usage(__doc__)
                return
            else:
                assert False, "Unhandled option!"
    except Exception as e:
        warning("Failed to parse command line arguments: %s", e)
        sys.exit(1)
    # Convert the requested package(s).
    try:
        if arguments:
            archives, relationships = converter.convert(arguments)
            if relationships and control_file_to_update:
                patch_control_file(control_file_to_update, dict(depends=relationships))
        else:
            usage(__doc__)
    except Exception:
        logger.exception("Caught an unhandled exception!")
        sys.exit(1)


text:
/***************************************************************************
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

/*
	this class holds some properties of the car
*/

#ifndef _MYCAR_H_
#define _MYCAR_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <tgf.h>
#include <track.h>
#include <car.h>
#include <raceman.h>
#include <robot.h>
#include <robottools.h>
#include <math.h>
#include "trackdesc.h"
#include "pathfinder.h"
#include "linalg.h"

class Pathfinder;
class PathSeg;

class AbstractCar
{
	public:
		AbstractCar() {};
		~AbstractCar() {};
		inline tCarElt* getCarPtr() { return me; }
		inline v3d* getCurrentPos() { return &currentpos; }
		inline v3d* getDir() { return &dir; }
		inline double getSpeedSqr() { return speedsqr; }
		inline double getSpeed() { return speed; }
		inline int getCurrentSegId() { return currentsegid; }

	protected:
		inline void setCarPtr(tCarElt* car) { me = car; }
		inline void updateDir() { dir.x = cos(me->_yaw); dir.y = sin(me->_yaw); dir.z = 0.0; }
		inline void updatePos() { currentpos.x = me->_pos_X; currentpos.y = me->_pos_Y; currentpos.z = me->_pos_Z - cgh; }
		inline void updateSpeedSqr() { speedsqr = (me->_speed_x)*(me->_speed_x) + (me->_speed_y)*(me->_speed_y) + (me->_speed_z)*(me->_speed_z); }
		inline void updateSpeed() { speed = sqrt(speedsqr); }
		inline void initCGh() { cgh = GfParmGetNum(me->_carHandle, SECT_CAR, PRM_GCHEIGHT, NULL, 0.0); }

		tCarElt* me;
		v3d currentpos;
		v3d dir;
		double speedsqr;
		double speed;
		int currentsegid;

	private:
		double cgh;			/* height of center of gravity */
};

class MyCar : public AbstractCar
{
	public:
		/* possible behaviours */
		enum {
			INSANE = 0, PUSH = 1, NORMAL = 2, CAREFUL = 3, SLOW = 4, START = 5
		};

		static const double PATHERR;			/* if derror > PATHERR we take actions to come back to the path [m] */
		static const double CORRLEN;			/* CORRLEN * derror is the length of the correction [m] */
		static const double TURNTOL;			/* tolerance for end backing up [m] */
		static const double TURNSPEED;			/* if speed lower than this you can back up [m/s] */
		static const double MARGIN;				/* security margin from track border [m] */
		static const double STABLESPEED;		/* we brake currentspeed/stablespeed if car seems unstable [m/s] */
		static const double TIMETOCATCH;		/* when do we start thinking about overtaking [s]*/
		static const double MINOVERTAKERANGE;	/* minimum length for overtaking [m] */
		static const double OVERTAKERADIUS;		/* min allowed radius to start overtaking [m] */
		static const double OVERTAKEDIST;		/* planned distance of CG's while overtaking [m] */
		static const double OVERTAKEMINDIST;	/* minimal distance of CG's while overtaking [m] */
		static const double OVERTAKEANGLE;		/* [-] radians */
		static const double OVERTAKEMARGIN;		/* [m] */
		static const double MAXALLOWEDPITCH;	/* [-] radians */
		static const double FLYSPEED;			/* speed where antifly checking gets activated [m/s] */
		static const double OVERLAPSTARTDIST;	/* distance where we start to check the need to let pass the opponent */
		static const double OVERLAPPASSDIST;	/* distance smaller than that and waiting long enough -> let him pass */
		static const double OVERLAPWAITTIME;	/* minimal waiting time before we consider let him pass */
		static const double LAPBACKTIMEPENALTY; /* penalty if i am able to "lap back" [s] */
		static const double TCL_SLIP;			/* [m/s] range [0..10] */
		static const double TCL_RANGE;			/* [m/s] range [0..10] */
		static const double SHIFT;				/* [-] (% of rpmredline) */
		static const double SHIFT_MARGIN;		/* [m/s] */
		static const double MAX_SPEED;			/* [m/s] */
		static const double MAX_FUEL_PER_METER;	/* [liter/m] fuel consumtion */
		static const double LOOKAHEAD_MAX_ERROR;/* [m] */
		static const double LOOKAHEAD_FACTOR;	/* [-] */

		/* data for behavior */
		int bmode;
		double behaviour[6][12];
		int MAXDAMMAGE;									/* if dammage > MAXDAMMAGE then we plan a pit stop [-] */
		double DIST;									/* minimal distance to other cars [m] */
		double MAXRELAX;								/* to avoid skidding (0..0.99) [-] */
		double MAXANGLE;								/* biggest allowed angle to the path [deg] */
		double ACCELINC;								/* increment/decrement for acceleration [-] */
		double SPEEDSQRFACTOR;							/* multiplier for speedsqr */
		double GCTIME;									/* minimal time between gear changes */
		double ACCELLIMIT;								/* maximal allowed acceleration */
		double PATHERRFACTOR;							/* if derror > PATHERR*PATHERRFACTOR we compute a corrected path [-] */
		double CARWIDTH;								/* width of the car [m] */
		double CARLEN;									/* length of the car [m] */
		double AEROMAGIC;								/* aerodynamic lift factor [-] */
		double CFRICTION;								/* friction "magic" coefficient [-] */

		/* static data */
		double cgcorr_b;
		double ca;
		double cw;

		/* dynamic data */
		double mass;
		int destsegid;
		double trtime;

		TrackSegment* currentseg;
		TrackSegment* destseg;
		PathSeg* currentpathseg;
		PathSeg* destpathseg;

		int undamaged;
		double lastfuel;
		double fuelperlap;
		double lastpitfuel;

		double turnaround;
		int tr_mode;
		double accel;
		bool fuelchecked;
		bool startmode;

		double derror;			/* distance to desired trajectory */

		MyCar(TrackDesc* track, tCarElt* car, tSituation *situation);
		~MyCar();

		void info(void);
		void update(TrackDesc* track, tCarElt* car, tSituation *situation);
		void loadBehaviour(int id);
		double querySlipSpeed(tCarElt* car);
		double queryAcceleration(tCarElt * car, double speed);
		inline double getDeltaPitch() { return deltapitch; }
		inline double getWheelBase() { return wheelbase; }
		inline double getWheelTrack() { return wheeltrack; }
		inline double getErrorSgn() { return derrorsgn; }
		inline Pathfinder* getPathfinderPtr() { return pf; }

	private:
		enum { DRWD = 0, DFWD = 1, D4WD = 2 };

		int drivetrain;			/* RWD, FWD or 4WD */
		double carmass;			/* mass of car without fuel */
		double deltapitch;		/* angle between road and car */
		double wheelbase;
		double wheeltrack;
		double derrorsgn;		/* on which side of the trajectory am i left -1 or 1 right */

		Pathfinder* pf;

		void updateCa();
		void updateDError();
		void initCarGeometry();
};

class OtherCar: public AbstractCar
{
	public:
		void init(TrackDesc* itrack, tCarElt* car, tSituation *situation);
		void update(void);

	private:
		TrackDesc* track;
		double dt;
};

#endif // _MYCAR_H_


text:
int main()
{
    base::LapTimer timer;
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    timer.lap("slept 1");
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    timer.lap("slept 2");

    for (const auto& lap : timer.laps()) {
        std::cout << lap.first.to_localtime_string()
                  << " -> " << lap.second
                  << std::endl;
    }
    return 0;
}


text:
Marionette.Region.Dialog = Marionette.Region.extend({
    onShow: function(view){
       this.listenTo(view, 'dialog:close', this.closeDailog);

        var _this = this;
        this.$el.dialog({
            modal: true,
            title: view.title,
            width: 'auto',
            close: function(e, ui){
                _this.closeDialog();
            }
        });
    },

    closeDialog: function(){
        this.stopListening();
        this.close();
        this.$el.dialog('destroy');
    }
})


text:
'use strict';

module.exports = {
    set: function (v) {
        this.setProperty('table-layout', v);
    },
    get: function () {
        return this.getPropertyValue('table-layout');
    },
    enumerable: true
};


text:
package org.simpleframework.xml.strategy;

import java.util.Map;

import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.NodeMap;
import org.simpleframework.xml.stream.OutputNode;

/**
 * The Strategy interface represents a strategy that can be
 * used to resolve and load the Class objects that compose
 * a serializable object. A strategy implementation will make use of the
 * provided attribute node map to extract details that can be used to
 * determine what type of object must be used.
 *

 *
 *    <xml version="1.0">
 *    <example class="some.example.Demo">
 *       <integer>2</integer>
 *    </example>
 *
 *

 * The above example shows how the default strategy augments elements
 * with "class" attributes that describe the type that should be used
 * to instantiate a field when an object is deserialized. So looking at
 * the above example the root element would be a "some.example.Demo".
 *

 * Custom Strategy implementations give the persister a
 * chance to intercept the class loading and type resolution for XML
 * documents. It also opens up the possibility for class versioning.
 * To establish contextual information a Map object can be
 * used. The map object is a transient object that is created and used
 * for the duration of a single operation of the persister.
 *
 * @author Niall Gallagher
 *
 * @see org.simpleframework.xml.core.Persister
 */
public interface Strategy {

   /**
    * This is used to resolve and load a class for the given element.
    * The class should be of the same type or a subclass of the class
    * specified. It can be resolved using the details within the
    * provided XML node map, if the details used do not represent any
    * serializable values they should be removed so as not to disrupt
    * the deserialization process. For example the default strategy
    * removes all "class" attributes from the given node map.
    *
    * @param type this is the type of the root element expected
    * @param node this is the node map used to resolve an override
    * @param map this is used to maintain contextual information
    *
    * @return the value that should be used to describe the instance
    *
    * @throws Exception thrown if the class cannot be resolved
    */
   Value read(Type type, NodeMap<InputNode> node, Map map) throws Exception;

   /**
    * This is used to attach attribute values to the given node
    * map during the serialization process. This method allows
    * the strategy to augment the XML document so that it can be
    * deserialized using a similar strategy. For example the
    * default strategy adds a "class" attribute to the node map.
    *
    * @param type this is the declared class for the field used
    * @param value this is the instance variable being serialized
    * @param node this is the node map used to represent the value
    * @param map this is used to maintain contextual information
    *
    * @return this returns true if serialization is complete
    *
    * @throws Exception thrown if the details cannot be set
    */
   boolean write(Type type, Object value, NodeMap<OutputNode> node, Map map) throws Exception;

}


text:
#ifndef SHARE_VM_GC_IMPLEMENTATION_PARALLELSCAVENGE_PARALLELSCAVENGEHEAP_HPP
#define SHARE_VM_GC_IMPLEMENTATION_PARALLELSCAVENGE_PARALLELSCAVENGEHEAP_HPP

#include "gc_implementation/parallelScavenge/objectStartArray.hpp"
#include "gc_implementation/parallelScavenge/psGCAdaptivePolicyCounters.hpp"
#include "gc_implementation/parallelScavenge/psOldGen.hpp"
#include "gc_implementation/parallelScavenge/psPermGen.hpp"
#include "gc_implementation/parallelScavenge/psYoungGen.hpp"
#include "gc_implementation/shared/gcPolicyCounters.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "utilities/ostream.hpp"

class AdjoiningGenerations;
class GCTaskManager;
class PSAdaptiveSizePolicy;
class GenerationSizer;
class CollectorPolicy;

class ParallelScavengeHeap : public CollectedHeap {
  friend class VMStructs;
 private:
  static PSYoungGen* _young_gen;
  static PSOldGen*   _old_gen;
  static PSPermGen*  _perm_gen;

  // Sizing policy for entire heap
  static PSAdaptiveSizePolicy* _size_policy;
  static PSGCAdaptivePolicyCounters*   _gc_policy_counters;

  static ParallelScavengeHeap* _psh;

  size_t _perm_gen_alignment;
  size_t _young_gen_alignment;
  size_t _old_gen_alignment;

  GenerationSizer* _collector_policy;

  inline size_t set_alignment(size_t& var, size_t val);

  // Collection of generations that are adjacent in the
  // space reserved for the heap.
  AdjoiningGenerations* _gens;

  static GCTaskManager*          _gc_task_manager;      // The task manager.

 protected:
  static inline size_t total_invocations();
  HeapWord* allocate_new_tlab(size_t size);

 public:
  ParallelScavengeHeap() : CollectedHeap() {
    set_alignment(_perm_gen_alignment, intra_heap_alignment());
    set_alignment(_young_gen_alignment, intra_heap_alignment());
    set_alignment(_old_gen_alignment, intra_heap_alignment());
  }

  // For use by VM operations
  enum CollectionType {
    Scavenge,
    MarkSweep
  };

  ParallelScavengeHeap::Name kind() const {
    return CollectedHeap::ParallelScavengeHeap;
  }

CollectorPolicy* collector_policy() const { return (CollectorPolicy*) _collector_policy; }
  // GenerationSizer* collector_policy() const { return _collector_policy; }

  static PSYoungGen* young_gen()     { return _young_gen; }
  static PSOldGen* old_gen()         { return _old_gen; }
  static PSPermGen* perm_gen()       { return _perm_gen; }

  virtual PSAdaptiveSizePolicy* size_policy() { return _size_policy; }

  static PSGCAdaptivePolicyCounters* gc_policy_counters() { return _gc_policy_counters; }

  static ParallelScavengeHeap* heap();

  static GCTaskManager* const gc_task_manager() { return _gc_task_manager; }

  AdjoiningGenerations* gens() { return _gens; }

  // Returns JNI_OK on success
  virtual jint initialize();

  void post_initialize();
  void update_counters();
  // The alignment used for the various generations.
  size_t perm_gen_alignment()  const { return _perm_gen_alignment; }
  size_t young_gen_alignment() const { return _young_gen_alignment; }
  size_t old_gen_alignment()  const { return _old_gen_alignment; }

  // The alignment used for eden and survivors within the young gen
  // and for boundary between young gen and old gen.
  size_t intra_heap_alignment() const { return 64 * K; }

  size_t capacity() const;
  size_t used() const;

  // Return "true" if all generations (but perm) have reached the
  // maximal committed limit that they can reach, without a garbage
  // collection.
  virtual bool is_maximal_no_gc() const;

  // Return true if the reference points to an object that
  // can be moved in a partial collection.  For currently implemented
  // generational collectors that means during a collection of
  // the young gen.
  virtual bool is_scavengable(const void* addr);

  // Does this heap support heap inspection? (+PrintClassHistogram)
  bool supports_heap_inspection() const { return true; }

  size_t permanent_capacity() const;
  size_t permanent_used() const;

  size_t max_capacity() const;

  // Whether p is in the allocated part of the heap
  bool is_in(const void* p) const;

  bool is_in_reserved(const void* p) const;
  bool is_in_permanent(const void *p) const {    // reserved part
    return perm_gen()->reserved().contains(p);
  }

#ifdef ASSERT
  virtual bool is_in_partial_collection(const void *p);
#endif

  bool is_permanent(const void *p) const {    // committed part
    return perm_gen()->is_in(p);
  }

  inline bool is_in_young(oop p);        // reserved part
  inline bool is_in_old_or_perm(oop p);  // reserved part

  // Memory allocation.   "gc_time_limit_was_exceeded" will
  // be set to true if the adaptive size policy determine that
  // an excessive amount of time is being spent doing collections
  // and caused a NULL to be returned.  If a NULL is not returned,
  // "gc_time_limit_was_exceeded" has an undefined meaning.

  HeapWord* mem_allocate(size_t size,
                         bool is_noref,
                         bool is_tlab,
                         bool* gc_overhead_limit_was_exceeded);
  HeapWord* failed_mem_allocate(size_t size, bool is_tlab);

  HeapWord* permanent_mem_allocate(size_t size);
  HeapWord* failed_permanent_mem_allocate(size_t size);

  // Support for System.gc()
  void collect(GCCause::Cause cause);

  // This interface assumes that it's being called by the
  // vm thread. It collects the heap assuming that the
  // heap lock is already held and that we are executing in
  // the context of the vm thread.
  void collect_as_vm_thread(GCCause::Cause cause);

  // These also should be called by the vm thread at a safepoint (e.g., from a
  // VM operation).
  //
  // The first collects the young generation only, unless the scavenge fails; it
  // will then attempt a full gc.  The second collects the entire heap; if
  // maximum_compaction is true, it will compact everything and clear all soft
  // references.
  inline void invoke_scavenge();
  inline void invoke_full_gc(bool maximum_compaction);

  size_t large_typearray_limit() { return FastAllocateSizeLimit; }

  bool supports_inline_contig_alloc() const { return !UseNUMA; }

  HeapWord** top_addr() const { return !UseNUMA ? young_gen()->top_addr() : (HeapWord**)-1; }
  HeapWord** end_addr() const { return !UseNUMA ? young_gen()->end_addr() : (HeapWord**)-1; }

  void ensure_parsability(bool retire_tlabs);
  void accumulate_statistics_all_tlabs();
  void resize_all_tlabs();

  size_t unsafe_max_alloc();

  bool supports_tlab_allocation() const { return true; }

  size_t tlab_capacity(Thread* thr) const;
  size_t unsafe_max_tlab_alloc(Thread* thr) const;

  // Can a compiler initialize a new object without store barriers?
  // This permission only extends from the creation of a new object
  // via a TLAB up to the first subsequent safepoint.
  virtual bool can_elide_tlab_store_barriers() const {
    return true;
  }

  virtual bool card_mark_must_follow_store() const {
    return false;
  }

  // Return true if we don't we need a store barrier for
  // initializing stores to an object at this address.
  virtual bool can_elide_initializing_store_barrier(oop new_obj);

  // Can a compiler elide a store barrier when it writes
  // a permanent oop into the heap?  Applies when the compiler
  // is storing x to the heap, where x->is_perm() is true.
  virtual bool can_elide_permanent_oop_store_barriers() const {
    return true;
  }

  void oop_iterate(OopClosure* cl);
  void object_iterate(ObjectClosure* cl);
  void safe_object_iterate(ObjectClosure* cl) { object_iterate(cl); }
  void permanent_oop_iterate(OopClosure* cl);
  void permanent_object_iterate(ObjectClosure* cl);

  HeapWord* block_start(const void* addr) const;
  size_t block_size(const HeapWord* addr) const;
  bool block_is_obj(const HeapWord* addr) const;

  jlong millis_since_last_gc();

  void prepare_for_verify();
  void print() const;
  void print_on(outputStream* st) const;
  virtual void print_gc_threads_on(outputStream* st) const;
  virtual void gc_threads_do(ThreadClosure* tc) const;
  virtual void print_tracing_info() const;

  void verify(bool allow_dirty, bool silent, bool /* option */);

  void print_heap_change(size_t prev_used);

  // Resize the young generation.  The reserved space for the
  // generation may be expanded in preparation for the resize.
  void resize_young_gen(size_t eden_size, size_t survivor_size);

  // Resize the old generation.  The reserved space for the
  // generation may be expanded in preparation for the resize.
  void resize_old_gen(size_t desired_free_space);

  // Save the tops of the spaces in all generations
  void record_gen_tops_before_GC() PRODUCT_RETURN;

  // Mangle the unused parts of all spaces in the heap
  void gen_mangle_unused_area() PRODUCT_RETURN;

  // Call these in sequential code around the processing of strong roots.
  class ParStrongRootsScope : public MarkingCodeBlobClosure::MarkScope {
  public:
    ParStrongRootsScope();
    ~ParStrongRootsScope();
  };
};

inline size_t ParallelScavengeHeap::set_alignment(size_t& var, size_t val)
{
  assert(is_power_of_2((intptr_t)val), "must be a power of 2");
  var = round_to(val, intra_heap_alignment());
  return var;
}

#endif // SHARE_VM_GC_IMPLEMENTATION_PARALLELSCAVENGE_PARALLELSCAVENGEHEAP_HPP


text:
'use strict';

import {isPromiseCanceledError} from 'vs/base/common/errors';
import URI from 'vs/base/common/uri';
import {ISearchService, QueryType} from 'vs/platform/search/common/search';
import {IWorkspaceContextService, IWorkspace} from 'vs/platform/workspace/common/workspace';
import {Remotable, IThreadService} from 'vs/platform/thread/common/thread';
import {IEventService} from 'vs/platform/event/common/event';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {ITextFileService} from 'vs/workbench/parts/files/common/files';
import {ICommonCodeEditor} from 'vs/editor/common/editorCommon';
import {bulkEdit, IResourceEdit} from 'vs/editor/common/services/bulkEdit';
import {TPromise} from 'vs/base/common/winjs.base';
import {fromRange} from 'vs/workbench/api/common/extHostTypeConverters';
import {Uri, CancellationToken} from 'vscode';

export class ExtHostWorkspace {

	private static _requestIdPool = 0;

	private _proxy: MainThreadWorkspace;
	private _workspacePath: string;

	constructor( @IThreadService threadService: IThreadService, workspacePath:string) {
		this._proxy = threadService.getRemotable(MainThreadWorkspace);
		this._workspacePath = workspacePath;
	}

	getPath(): string {
		return this._workspacePath;
	}

	getRelativePath(pathOrUri: string|Uri): string {

		let path: string;
		if (typeof pathOrUri === 'string') {
			path = pathOrUri;
		} else {
			path = pathOrUri.fsPath;
		}

		if (this._workspacePath && this._workspacePath.length < path.length) {
			// return relative(workspacePath, path);
			return path.substring(this._workspacePath.length);
		}

		return path;
	}

	findFiles(include: string, exclude: string, maxResults?: number, token?: CancellationToken): Thenable<Uri[]> {
		const requestId = ExtHostWorkspace._requestIdPool++;
		const result = this._proxy.$startSearch(include, exclude, maxResults, requestId);
		if (token) {
			token.onCancellationRequested(() => this._proxy.$cancelSearch(requestId));
		}
		return result;
	}

	saveAll(includeUntitled?: boolean): Thenable<boolean> {
		return this._proxy.$saveAll(includeUntitled);
	}

	appyEdit(edit: vscode.WorkspaceEdit): TPromise<boolean> {

		let resourceEdits: IResourceEdit[] = [];

		let entries = edit.entries();
		for (let entry of entries) {
			let [uri, edits] = entry;

			for (let edit of edits) {
				resourceEdits.push({
					resource: <URI>uri,
					newText: edit.newText,
					range: fromRange(edit.range)
				});
			}
		}

		return this._proxy.$applyWorkspaceEdit(resourceEdits);
	}
}

@Remotable.MainContext('MainThreadWorkspace')
export class MainThreadWorkspace {

	private _activeSearches: { [id: number]: TPromise<Uri[]> } = Object.create(null);
	private _searchService: ISearchService;
	private _workspace: IWorkspace;
	private _textFileService: ITextFileService;
	private _editorService:IWorkbenchEditorService;
	private _eventService:IEventService;

	constructor( @ISearchService searchService: ISearchService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITextFileService textFileService,
		@IWorkbenchEditorService editorService,
		@IEventService eventService) {

		this._searchService = searchService;
		this._workspace = contextService.getWorkspace();
		this._textFileService = textFileService;
		this._editorService = editorService;
		this._eventService = eventService;
	}

	$startSearch(include: string, exclude: string, maxResults: number, requestId: number): Thenable<Uri[]> {

		if (!this._workspace) {
			return;
		}

		const search = this._searchService.search({
			rootResources: [this._workspace.resource],
			type: QueryType.File,
			maxResults,
			includePattern: { [include]: true },
			excludePattern: { [exclude]: true },
		}).then(result => {
			return result.results.map(m => m.resource);
		}, err => {
			if (!isPromiseCanceledError(err)) {
				return TPromise.wrapError(err);
			}
		});

		this._activeSearches[requestId] = search;
		const onDone = () => delete this._activeSearches[requestId];
		search.done(onDone, onDone);

		return search;
	}

	$cancelSearch(requestId: number): Thenable<boolean> {
		const search = this._activeSearches[requestId];
		if (search) {
			delete this._activeSearches[requestId];
			search.cancel();
			return TPromise.as(true);
		}
	}

	$saveAll(includeUntitled?: boolean): Thenable<boolean> {
		return this._textFileService.saveAll(includeUntitled).then(result => {
			return result.results.every(each => each.success === true);
		});
	}

	$applyWorkspaceEdit(edits: IResourceEdit[]): TPromise<boolean> {

		let codeEditor: ICommonCodeEditor;
		let editor = this._editorService.getActiveEditor();
		if (editor) {
			let candidate = <ICommonCodeEditor> editor.getControl();
			if (typeof candidate.getEditorType === 'function') {
				// enough proof
				codeEditor = candidate;
			}
		}

		return bulkEdit(this._eventService, this._editorService, codeEditor, edits)
			.then(() => true);
	}
}


text:
/*!
  \class SoLightModel SoLightModel.h Inventor/nodes/SoLightModel.h
  \brief The SoLightModel class is a node for specifying the model for geometry lighting.
  \ingroup nodes

  Use nodes of this type to set up how lighting should affect
  subsequent geometry in the scene.

  <b>FILE FORMAT/DEFAULTS:</b>
  \code
    LightModel {
        model PHONG
    }
  \endcode
*/

// *************************************************************************

#include <Inventor/actions/SoCallbackAction.h>

#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/elements/SoOverrideElement.h>
#include <Inventor/elements/SoGLLazyElement.h>
#include <Inventor/elements/SoLightModelElement.h>

#include "nodes/SoSubNodeP.h"

// *************************************************************************

/*!
  \enum SoLightModel::Model
  Enumerates available light models.
*/
/*!
  \var SoLightModel::Model SoLightModel::BASE_COLOR

  Use the current diffuse material color for subsequent geometry, and
  do not let any lightsources influence the appearance of the
  rendering primitives.
*/
/*!
  \var SoLightModel::Model SoLightModel::PHONG

  Use Phong-style shading for the geometry.
*/

/*!
  \var SoSFEnum SoLightModel::model

  Lightmodel to use. Defaults to SoLightModel::PHONG.
*/

// *************************************************************************

SO_NODE_SOURCE(SoLightModel);

/*!
  Constructor.
*/
SoLightModel::SoLightModel(void)
{
  SO_NODE_INTERNAL_CONSTRUCTOR(SoLightModel);

  SO_NODE_ADD_FIELD(model, (SoLightModel::PHONG));
  SO_NODE_DEFINE_ENUM_VALUE(Model, BASE_COLOR);
  SO_NODE_DEFINE_ENUM_VALUE(Model, PHONG);
  SO_NODE_SET_SF_ENUM_TYPE(model, Model);
}

/*!
  Destructor.
*/
SoLightModel::~SoLightModel()
{
}

// Doc from superclass.
void
SoLightModel::initClass(void)
{
  SO_NODE_INTERNAL_INIT_CLASS(SoLightModel, SO_FROM_INVENTOR_1);

  SO_ENABLE(SoCallbackAction, SoLazyElement);
  SO_ENABLE(SoGLRenderAction, SoGLLazyElement);

  SO_ENABLE(SoCallbackAction, SoLightModelElement);
  SO_ENABLE(SoGLRenderAction, SoLightModelElement);
}

// Doc from superclass.
void
SoLightModel::GLRender(SoGLRenderAction * action)
{
  SoLightModel::doAction(action);
}

// Doc from superclass.
void
SoLightModel::doAction(SoAction * action)
{
  if (!model.isIgnored()
      && !SoOverrideElement::getLightModelOverride(action->getState())) {
    SoLazyElement::setLightModel(action->getState(),
                                 (int32_t) this->model.getValue());
    if (this->isOverride()) {
      SoOverrideElement::setLightModelOverride(action->getState(), this, TRUE);
    }
  }
}

// Doc from superclass.
void
SoLightModel::callback(SoCallbackAction * action)
{
  SoLightModel::doAction(action);
}


text:
//
//  PxRuntimeHelper.h
//  PxCore OpenSource
//
//  Created by Jonathan Cichon on 18.02.13.
//

#import <Foundation/Foundation.h>
#import <objc/message.h>
#import <objc/runtime.h>

/**
 Returns the concrete class of a property.

 If the return-type is primitive or _id_ **nil** is returned. If the return-type is primitive, the isPrimitive parameter is set to **YES**.
 */
Class property_getReturnClass(objc_property_t property, BOOL *isPrimitive);

#pragma mark - ARC Fuckup Helpers
static inline unsigned char *pointerFromObject(void *object) {
    return (unsigned char *)object;
}

static inline void *pointerToInstanceVariable(id object, char *variableName) {
    Ivar instanceVar = class_getInstanceVariable([object class], variableName);
    if (!instanceVar) {
        return nil;
    }
    return (__bridge void *)object + ivar_getOffset(instanceVar);
}


text:
<?php

namespace App\Models;

use Artesaos\Defender\Traits\HasDefender;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable,
        Authorizable,
        CanResetPassword,
        HasDefender;

    protected $table = 'users';

    protected $fillable = [
        'name',
        'email',
        'password',
        'verification_token'
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'verification_token',
        'verified'
    ];

    /**
     * Confirm the user.
     *
     * @return void
     */
    public function confirmEmail()
    {
        $this->verified = true;
        $this->verification_token = null;
        $this->save();
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Mém. Soc. Linn. Paris 1:303. 1822

#### Original name
null

### Remarks
null


text:
<?php
namespace Siegelion\Storage\Persistence\Entity;

/**
 * @Entity
 * @Table(name="producttype")
 */
class Producttype
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     */
    public $producttypeid;

    /**
     * @Column(type="string")
     */
    public $name;

    /**
     * @Column(type="text")
     */
    public $description;

    /**
     * Get producttypeid
     *
     * @return integer
     */
    public function getProducttypeid()
    {
        return $this->producttypeid;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}


text:
from pact.enums import DAY_SLOTS_BY_TIME, PACT_REGIMEN_CHOICES, DAY_SLOTS_BY_IDX, DOT_ART, DOT_NONART, CASE_ART_REGIMEN_PROP, CASE_NONART_REGIMEN_PROP

#def calculate_regimen_caseblock(self):
#    """
#    Forces all labels to be reset back to the labels set on the patient document.
#
#    patient document trumps casedoc in this case.
#    """
#    update_ret = {}
#    for prop_fmt in ['dot_a_%s', 'dot_n_%s']:
#        if prop_fmt[4] == 'a':
#            code_arr = get_regimen_code_arr(self.art_regimen)
#            update_ret['artregimen'] = str(len(code_arr)) if len(code_arr) > 0 else ""
#        elif prop_fmt[4] == 'n':
#            code_arr = get_regimen_code_arr(self.non_art_regimen)
#            update_ret['nonartregimen'] = str(len(code_arr)) if len(code_arr) > 0 else ""
#        digit_strings = ["zero", 'one', 'two', 'three','four']
#        for x in range(1,5):
#            prop_prop = prop_fmt % digit_strings[x]
#            if x > len(code_arr):
#                update_ret[prop_prop] = ''
#            else:
#                update_ret[prop_prop] = str(code_arr[x-1])
#    return update_ret

type_keys = {DOT_ART: 'dot_a_%s', DOT_NONART: 'dot_n_%s'}
digit_strings = ['one', 'two', 'three', 'four']

def regimen_dict_from_choice(key_type, regimen_string):
    """
    Given a regimen string, "morning,noon,evening" return a dict of the appropriate update values
    of the casedoc of this representation

    key_type is ART or NONART

    so if art will return 'artregimen': <int>, "dot_a_one": 0, "dot_a_two": "1", etc
    if nonartregimen it'll be 'nonartregimen' and dot_n_one, etc.
    """

    assert key_type in type_keys.keys(), 'the key_type must be ART or NONART'

    #ensure regimen_string is in PACT_REGIMEN_CHOICES_DICT
    #get integer day slot from DAY_SLOTS_BY_TIME[str]
    if len(regimen_string) > 0:
        regimen_split = regimen_string.split(',')
        regimen_freq = len(regimen_split)
    else:
        regimen_freq = 0
        regimen_split = []

    day_key_prefix = type_keys[key_type]
    if key_type == DOT_ART:
        key_type_string = CASE_ART_REGIMEN_PROP
    elif key_type == DOT_NONART:
        key_type_string = CASE_NONART_REGIMEN_PROP
    ret = { key_type_string: str(regimen_freq) }
    for x in range(0, 4):
        if x < regimen_freq:
            ret[day_key_prefix % digit_strings[x]] = str(DAY_SLOTS_BY_TIME.get(regimen_split[x], None))
        else:
            ret[day_key_prefix % digit_strings[x]] = ""
    return ret

def regimen_string_from_doc(drug_type, doc_dict):
    """
    For a dict of doc properties and a given drug_type (ART, NONART), calculate/confirm the
    regimen string of the times of doses.
    """
    assert drug_type in type_keys.keys(), "the drug type must be art or nonart"
    prefix = type_keys[drug_type]

    if drug_type == DOT_ART:
        try:
            freq = int(doc_dict.get(CASE_ART_REGIMEN_PROP, ''))
        except ValueError:
            return None
    elif drug_type == DOT_NONART:
        try:
            freq = int(doc_dict.get(CASE_NONART_REGIMEN_PROP, ''))
        except ValueError:
            return None

    props = []
    for digit in digit_strings:
        key = prefix % digit
        prop = doc_dict.get(key, '')
        if prop != '' and prop is not None:
            try:
                props.append(int(prop))
            except:
                pass

    return string_from_regimen_props(freq, props=props, suppress_errors=True)

def string_from_regimen_props(freq, props=[], suppress_errors=False):
    """
    For a given set of properties, (dot_a_one, etc...)

    return the comma separated string of the regimen frequency/dose times
    morning,noon,evening...etc
    """
    str_props = []
    for prop in props:
        if prop == "" or prop is None:
            break
        str_props.append(DAY_SLOTS_BY_IDX[prop])

    if len(str_props) == freq:
        return ','.join(str_props)
    else:
        message = "Error, frequency %d given does not match properties %s" % (freq, props)
        if suppress_errors:
            return message
        else:
            raise Exception(message)


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">

  <meta name="description" content="Holden Lee's Research Notebook">
  <meta name="author" content="Holden Lee">

  <title>Alignment for advanced machine learning systems</title>

  <link href="../../../../bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <link href="../../../../css/blog.css" rel="stylesheet">
  <link href="../../../../css/default.css" rel="stylesheet">

  <link href="../../../../footnotes/css/footnotes.css" rel="stylesheet">

  <link href="../../../../collapsible_lists/css/collapsible.css" rel="stylesheet">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          Toggle navigation

        </button>
        Notebook

Home

Sitemap

Alignment for advanced machine learning systems

Posted: 2017-02-01
          , Modified: 2017-02-01

Tags: ai safety, machine learning

Increasing safety by reducing autonomy

Increasing safety without reducing autonomy

Paper

Presentation

6 problems

Inductive ambiguity identification

Other research agenda

Article

new agenda is intended to help more in scenarios where advanced AI is relatively near and relatively directly descended from contemporary ML techniques, while our agent foundations agenda is more agnostic about when and how advanced AI will be developed.

Where the agent foundations agenda can be said to follow the principle "start with the least well-understood long-term AI safety problems, since those seem likely to require the most work and are the likeliest to seriously alter our understanding of the overall problem space," the concrete problems agenda follows the principle "start with the long-term AI safety problems that are most applicable to systems today, since those problems are the easiest to connect to existing work by the AI research community."

Increasing safety by reducing autonomy

Inductive ambiguity identification: How can we train ML systems to detect and notify us of cases where the classification of test data is highly under-determined from the training data?

Robust human imitation: How can we design and train ML systems to effectively imitate humans who are engaged in complex and difficult tasks?

Informed oversight: How can we train a reinforcement learning system to take actions that aid an intelligent overseer, such as a human, in accurately assessing the system's performance?

Ambiguity identification helps:

We could reduce risk somewhat by building systems that are still reasonably smart and autonomous, but will pause to consult operators in cases where their actions are especially high-risk. Ambiguity identification is one approach to fleshing out which scenarios are "high-risk"

vs. human imitation.

In practice, however, ambiguity identification is probably too mild a restriction on its own, and strict human imitation probably isn't efficiently implementable. Informed oversight considers more moderate approaches to keeping humans in the loop.

Increasing safety without reducing autonomy

Generalizable environmental goals: How can we create systems that robustly pursue goals defined in terms of the state of the environment, rather than defined directly in terms of their sensory data?

Conservative concepts: How can a classifier be trained to develop useful concepts that exclude highly atypical examples and edge cases?

Impact measures: What sorts of regularizers incentivize a system to pursue its goals with minimal side effects?

Mild optimization: How can we design systems that pursue their goals "without trying too hard"-stopping when the goal has been pretty well achieved, as opposed to expending further resources searching for ways to achieve the absolute optimum expected score?

Averting instrumental incentives: How can we design and train systems such that they robustly lack default incentives to manipulate and deceive their operators, compete for scarce resources, etc.?

ambiguity-identifying learners are designed to predict potential ways they might run into edge cases and defer to human operators in those cases, conservative learners are designed to err in a safe direction in edge cases.

Ex. cooking the cat.

Paper

Right kind of objective function (value specification), vs. avoid unintended consequences even with imperfect objective function (error tolerance)

Codify "without doing anything drastic."

Obstacles: values of humans hard to pin down, and intelligent system wants to ensure continued existence

Solutions must be applicable to advanced AI systems. Ignorance is an unsatisfactory solution.

Extreme guarantees: "after time t, make 0 significant mistakes."

Improving a system's capability may make it exploit loopholes and do less well in the sense we care about. (And hide it from the creator)

Know when past experience provides insufficient evidence to make a decision.

Ex. distinguish between Soviet and US tanks - Soviet tanks were taken on sunny day.

Recognize underspecificity and query user

Cf. robustness to distributional change.

Bayesian approaches need the right variables (features).

Non-Bayesian approaches do not identify ambiguities.

Active learning: maintain plausible hypotheses, query to rule out

Disagreement coefficient: overall probability of disagreement in local ball

Active learning usually requires simple hypothesis class, or iid test samples.

Ex. Soviets respond by making tanks to fool algorithm

Conformal predictor: give set of plasuible classifications, contain true one about 95% of time.

KWIK (knows what it knows): query human finitely many times and makes 0 critical errors. Make classification only when all remaining plausible hypotheses agree.

Only known for simple hypothesis classes

Directions

Bayesian

Extend active learning beyond iid, and more complex hypothesis classes (NN)

Relax realizability

More efficient way to represent ambiguity than set of hypotheses

Robust Human Interaction

Ambiguity identification can help by limiting autonomy

Do what a trusted human would do.

How to define objective?

Related

Inverse RL.

Max entropy criterion to convert to opt problem

May not scale because human demonstrators may not be optimizing value function (irrational).

Directions

Imitate human answers to questions (NLP).

GAN

VAE - can only imitate reversible algorithms

Informed oversight

do what a trusted human would approve given time to consider (approval directed)

But a human may have a hard time assessing behavior of even a simpler agent (ex. plagiarism easier to execute than detect)

Related

Active learning component

CIRL

cf. scalable oversight (when possibly deceptive)

Making more transparent: sparsity, gradients, influence…

Transparency by construction

Make robotics systems more transparent

Directions

Output action a and report r to help overseer evaluate. Ex. a is story

Generalizable environment goals

How to not incentivize self-fooling sensors?

Designing more elaborate sensors doesn't scale.

Instead learn environment goal

Related

Learn utility over world-states. Requires specifying (1) type of world-state, (2) prior over utilities, (3) Value-learning model relating utility functions, state transitions, and observations

Use reward perceptions as evidence of utility function rather than direct measure.

Reward hacking

Ex. (A) make sandwich vs. (B) print photo of one. (B): if move paper, then fails.

Delusion box

Take into account past leading up to state

Avoid large jumps in feature space?

Conservative concepts

AI system finds strange, undesirable edge case

Adversarial examples

Inverse RL

Generative adversarial modeling

Directions

Dimensionality reduction

Anomaly detection

What is a "conservative concept"?

Impact

Regularizer penalizing unnecessary large scale side effects but not intended side effects.

Related

Impact measure

Define null policy and state of world

Divergence between distribution and distribution of null policy. Use model-based RL

How to separate follow-on and unintended side effects?

Directions

Causal counterfactual: follow-on effects are causally downstream of goal

Query the operator

Mild

Related

Regularization

How to measure optimization?

Universal intelligence metrics

Empowerment metric

Early stopping is ad-hoc mild optimization

Satisfice reward rather than maximize. OK if find easy strategies before extreme ones.

Quantilization: select action randomly from top 1%. Justified by adversarial assumptions.

How to define measure over actions?

Directions

regularizer for intelligence

design environments with exploitable glitches

do not self-modify or outsource computation

Instrumental

Convergent instrumental objectives

Difficulty: "shut down if human wants it to shut down". Then make human not want to shut it down.

Uncertainty about goal

But if confidently wrong, would have instrumental incentives

Related

Specific designs vs. general solution?

Directions

Way of combine objective functions

No incentive to cause/prevent shift in objective function

Incentivized to preserve ability to update objective function

Reasonable beliefs about relation between actions and mechanism that causes objective function shifts.

Systems that know they are flawed.

Presentation

Video

6 problems

Actions hard to evaluate. Ex. plagiarize, steganography. Informed insight

Ambiguous test examples. Ex. train on domestic cats. Wild cats?

Imitate human behavior. Produce kind of picture a human would draw. GAN. Imitator vs. distinguisher. Does distinguisher have to be smarter than imitator? How to effectively imitate humans in complex/difficult tasks.

Difficulty specifying goals: make a sandwich. Reward hacking.

Negative side effect. 99.99999% chance. Avoid plans with high estimated impact, mild optimization, avert instrumental incentives (manipulate operators, compete for scarce resources).

Edge cases that still satisfy the goal

Inductive ambiguity identification

Draw many consistent models with data

KWIK learning. At each step output w/i epsilon, or .

Problem: realizability, only for simple hyp classes

Bayesian: Prior Q over mappings. P unknown ture prior. Perform some classification almost as well as if we already knew P. Assumption: \(\forall f, Q(f)\ge \rc k P(f)\).

Other research agenda

Agent foundations: theoretical foundations, agnostic about specific form, logical induction

Concrete problems in AI safety: empirically study as ML problems. Ex. RL act safely as explore environment.

    Built with
    Hakyll
    using
    Bootstrap,
    Disqus,
    Footnotes.js,
    Highlight.js,
    MathJax,
    and ShareThis.

<link rel="stylesheet" href="../../../../highlight/css/tomorrow-night-bright.css">


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;

namespace BenchmarkDotNet.Characteristics
{
    public abstract class CharacteristicObject<T> : CharacteristicObject
        where T : CharacteristicObject<T>, new()
    {
        protected CharacteristicObject() { }

        protected CharacteristicObject(string id) : base(id) { }

        public new T Apply(CharacteristicObject other) => (T)ApplyCore(other);

        public T Apply(params CharacteristicObject[] others)
        {
            var result = this;
            foreach (var other in others)
            {
                result.Apply(other);
            }
            return (T)result;
        }

        public T ApplyAndFreeze(CharacteristicObject other) => Apply(other).Freeze();

        public T ApplyAndFreeze(params CharacteristicObject[] others) => Apply(others).Freeze();

        public new T Freeze() => (T)FreezeCore();

        public new T UnfreezeCopy() => (T)UnfreezeCopyCore();
    }
}


text:
@class ATTextResult;

@interface NSTextView (TextGetter)

- (NSInteger)at_currentCurseLocation;

- (ATTextResult *)at_textResultOfCurrentLine;

@end


text:
import { MermaidConfig } from './config.type';
/**
 * @param text
 * @param parseError
 */
declare function parse(text: string, parseError?: Function): boolean;
/**
 *
 * @param text
 * @param parseError
 */
declare function parseAsync(text: string, parseError?: Function): Promise<boolean>;
export declare const encodeEntities: (text: string) => string;
export declare const decodeEntities: (text: string) => string;
/** @param {MermaidConfig} options */
declare function initialize(options: MermaidConfig): void;
export declare const mermaidAPI: Readonly<{
    render: (id: string, text: string, cb: (svgCode: string, bindFunctions?: ((element: Element) => void) | undefined) => void, container?: Element) => void;
    renderAsync: (id: string, text: string, cb: (svgCode: string, bindFunctions?: ((element: Element) => void) | undefined) => void, container?: Element) => Promise<void>;
    parse: typeof parse;
    parseAsync: typeof parseAsync;
    parseDirective: (p: any, statement: string, context: string, type: string) => void;
    initialize: typeof initialize;
    getConfig: () => MermaidConfig;
    setConfig: (conf: MermaidConfig) => MermaidConfig;
    getSiteConfig: () => MermaidConfig;
    updateSiteConfig: (conf: MermaidConfig) => MermaidConfig;
    reset: () => void;
    globalReset: () => void;
    defaultConfig: MermaidConfig;
}>;
export default mermaidAPI;
/**
 * ## mermaidAPI configuration defaults
 *
 * ```html
 * <script>
 *   var config = {
 *     theme: 'default',
 *     logLevel: 'fatal',
 *     securityLevel: 'strict',
 *     startOnLoad: true,
 *     arrowMarkerAbsolute: false,
 *
 *     er: {
 *       diagramPadding: 20,
 *       layoutDirection: 'TB',
 *       minEntityWidth: 100,
 *       minEntityHeight: 75,
 *       entityPadding: 15,
 *       stroke: 'gray',
 *       fill: 'honeydew',
 *       fontSize: 12,
 *       useMaxWidth: true,
 *     },
 *     flowchart: {
 *       diagramPadding: 8,
 *       htmlLabels: true,
 *       curve: 'basis',
 *     },
 *     sequence: {
 *       diagramMarginX: 50,
 *       diagramMarginY: 10,
 *       actorMargin: 50,
 *       width: 150,
 *       height: 65,
 *       boxMargin: 10,
 *       boxTextMargin: 5,
 *       noteMargin: 10,
 *       messageMargin: 35,
 *       messageAlign: 'center',
 *       mirrorActors: true,
 *       bottomMarginAdj: 1,
 *       useMaxWidth: true,
 *       rightAngles: false,
 *       showSequenceNumbers: false,
 *     },
 *     gantt: {
 *       titleTopMargin: 25,
 *       barHeight: 20,
 *       barGap: 4,
 *       topPadding: 50,
 *       leftPadding: 75,
 *       gridLineStartPadding: 35,
 *       fontSize: 11,
 *       fontFamily: '"Open Sans", sans-serif',
 *       numberSectionStyles: 4,
 *       axisFormat: '%Y-%m-%d',
 *       topAxis: false,
 *     },
 *   };
 *   mermaid.initialize(config);
 * </script>
 * ```
 */


text:
namespace mozc {

class ConnectorInterface;
class Lattice;
class POSMatcher;
class SegmenterInterface;
class SuggestionFilter;
class SuppressionDictionary;
struct Node;

// TODO(toshiyuki): write unittest for NBestGenerator.
class NBestGenerator {
 public:
  enum BoundaryCheckMode {
    // Boundary check mode.
    // For the case like;
    //   Candidate edge:      |  candidate  |
    //   Nodes:        |Node A|Node B|Node C|Node D|

    // For normal converison.
    //  Candidate boundary is strictly same as inner boundary.
    // A-B: Should be the boundary
    // B-C: Should not be the boundary
    // C-D: Should be the boundary
    STRICT = 0,

    // For resegmented segment.
    //  Check mid point only.
    // A-B: Don't care
    // B-C: Should not be the boundary
    // C-D: Don't care
    ONLY_MID,

    // For Realtime conversion ("私の名前は中野です").
    //  Check only for candidate edge.
    // A-B: Should be the boundary
    // B-C: Don't care
    // C-D: Should be the boundary
    ONLY_EDGE,
  };

  // Try to enumurate N-best results between begin_node and end_node.
  NBestGenerator(const SuppressionDictionary *suppression_dictionary,
                 const SegmenterInterface *segmenter,
                 const ConnectorInterface *connector,
                 const POSMatcher *pos_matcher,
                 const Lattice *lattice,
                 const SuggestionFilter *suggestion_filter);
  ~NBestGenerator();

  // Reset the iterator status.
  void Reset(const Node *begin_node, const Node *end_node,
             const BoundaryCheckMode mode);

  // Iterator:
  // Can obtain N-best results by calling Next() in sequence.
  bool Next(const string &original_key,
            Segment::Candidate *candidate,
            Segments::RequestType request_type);

 private:
  enum BoundaryCheckResult {
    VALID = 0,
    VALID_WEAK_CONNECTED,  // Valid but should get penalty.
    INVALID,
  };

  typedef BoundaryCheckResult (NBestGenerator::*BoundaryChecker)(
      const Node *, const Node *, bool) const;

  struct QueueElement;
  struct QueueElementComparator;

  // This is just a priority_queue of const QueueElement*, but supports
  // more operations in addition to std::priority_queue.
  class Agenda {
   public:
    Agenda() {
    }
    ~Agenda() {
    }

    const QueueElement *Top() const {
      return priority_queue_.front();
    }
    bool IsEmpty() const {
      return priority_queue_.empty();
    }
    void Clear() {
      priority_queue_.clear();
    }
    void Reserve(int size) {
      priority_queue_.reserve(size);
    }

    void Push(const QueueElement *element);
    void Pop();

   private:
    vector<const QueueElement*> priority_queue_;

    DISALLOW_COPY_AND_ASSIGN(Agenda);
  };

  int InsertTopResult(const string &original_key,
                      Segment::Candidate *candidate,
                      Segments::RequestType request_type);

  void MakeCandidate(Segment::Candidate *candidate,
                     int32 cost, int32 structure_cost, int32 wcost,
                     const vector<const Node *> &nodes) const;

  // Helper functions for Next(). Checks node boundary conditions.
  BoundaryCheckResult CheckStrict(
      const Node *lnode, const Node *rnode, bool is_edge) const;
  BoundaryCheckResult CheckOnlyMid(
      const Node *lnode, const Node *rnode, bool is_edge) const;
  BoundaryCheckResult CheckOnlyEdge(
      const Node *lnode, const Node *rnode, bool is_edge) const;

  int GetTransitionCost(const Node *lnode, const Node *rnode) const;

  // Create queue element from freelist
  const QueueElement *CreateNewElement(const Node *node,
                                       const QueueElement *next,
                                       int32 fx,
                                       int32 gx,
                                       int32 structure_gx,
                                       int32 w_gx);

  // References to relevant modules.
  const SuppressionDictionary *suppression_dictionary_;
  const SegmenterInterface *segmenter_;
  const ConnectorInterface *connector_;
  const POSMatcher *pos_matcher_;
  const Lattice *lattice_;

  const Node *begin_node_;
  const Node *end_node_;

  Agenda agenda_;
  FreeList<QueueElement> freelist_;
  vector<const Node *> nodes_;
  scoped_ptr<converter::CandidateFilter> filter_;
  bool viterbi_result_checked_;
  BoundaryCheckMode check_mode_;

  BoundaryChecker boundary_checker_;

  DISALLOW_COPY_AND_ASSIGN(NBestGenerator);
};

}  // namespace mozc

#endif  // MOZC_CONVERTER_NBEST_GENERATOR_H_


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<roles>
	<role name="RegisteredUser"/>
	<role name="Guest"/>
	<role name="Administrator"/>
	<role name="SuperAdministrator"/>
</roles>


text:
require 'spec_helper'

module Pageflow
  describe EntryDuplicate do
    describe '#create!' do
      it 'creates an entry with a title containing the original title' do
        entry = create(:entry, title: 'Some Title')

        duplicate = EntryDuplicate.of(entry).create!

        expect(duplicate).to be_persisted
        expect(duplicate.title).to include('Some Title')
      end

      it 'creates entry with same account and theming' do
        entry = create(:entry)

        duplicate = EntryDuplicate.of(entry).create!

        expect(duplicate.account).to eq(entry.account)
        expect(duplicate.theming).to eq(entry.theming)
      end

      it 'copies draft' do
        entry = create(:entry, title: 'Some Title')
        create(:chapter,
               in_main_storyline_of: entry.draft,
               title: 'Original Chapter')

        duplicate = EntryDuplicate.of(entry).create!
        chapter_titles = duplicate.draft.chapters.map(&:title)

        expect(chapter_titles).to eq(['Original Chapter'])
      end

      it 'copies memberships' do
        user = create(:user)
        entry = create(:entry, with_member: user)

        duplicate = EntryDuplicate.of(entry).create!

        expect(duplicate.users.first).to eq(user)
      end

      it 'copies enabled features' do
        entry = create(:entry, features_configuration: {fancy_page_type: true})

        duplicate = EntryDuplicate.of(entry).create!

        expect(duplicate.feature_state('fancy_page_type')).to eq(true)
      end
    end
  end
end