text:
import { ConnectionOptions, createConnection } from "typeorm";
import * as ts from "typescript";
import * as yn from "yn";
import * as path from "path"
import IGenerationOptions, {
    getDefaultGenerationOptions
} from "../../src/IGenerationOptions";
import IConnectionOptions from "../../src/IConnectionOptions";
import MssqlDriver from "../../src/drivers/MssqlDriver";
import MariaDbDriver from "../../src/drivers/MariaDbDriver";
import PostgresDriver from "../../src/drivers/PostgresDriver";
import OracleDriver from "../../src/drivers/OracleDriver";
import MysqlDriver from "../../src/drivers/MysqlDriver";
import { assertUnreachable } from "../../src/Utils";

export function getGenerationOptions(resultsPath: string): IGenerationOptions {
    const retVal = getDefaultGenerationOptions();
    retVal.resultsPath = resultsPath;
    return retVal;
}

export async function createMSSQLModels(
    filesOrgPath: string
): Promise<IConnectionOptions> {
    const driver = new MssqlDriver();
    const connectionOptions = getTomgConnectionOptions("mssql");
    await driver.ConnectToServer(connectionOptions);
    connectionOptions.databaseNames = [String(process.env.MSSQL_Database)];

    if (await driver.CheckIfDBExists(String(process.env.MSSQL_Database))) {
        await driver.DropDB(String(process.env.MSSQL_Database));
    }
    await driver.CreateDB(String(process.env.MSSQL_Database));
    await driver.DisconnectFromServer();

    const connOpt: ConnectionOptions = {
        database: String(process.env.MSSQL_Database),
        host: String(process.env.MSSQL_Host),
        password: String(process.env.MSSQL_Password),
        type: "mssql",
        username: String(process.env.MSSQL_Username),
        port: Number(process.env.MSSQL_Port),
        dropSchema: true,
        synchronize: false,
        entities: [path.resolve(filesOrgPath, "*.ts")],
        name: "mssql"
    };

    const schemas = "dbo,sch1,sch2";
    const conn = await createConnection(connOpt);
    const queryRunner = conn.createQueryRunner();
    await Promise.all(
        schemas.split(",").map(sch => queryRunner.createSchema(sch, true))
    );
    await conn.synchronize();

    if (conn.isConnected) {
        await conn.close();
    }

    return connectionOptions;
}

export async function createPostgresModels(
    filesOrgPath: string
): Promise<IConnectionOptions> {
    const driver = new PostgresDriver();
    const connectionOptions = getTomgConnectionOptions("postgres");
    await driver.ConnectToServer(connectionOptions);
    connectionOptions.databaseNames = [String(process.env.POSTGRES_Database)];

    if (await driver.CheckIfDBExists(String(process.env.POSTGRES_Database))) {
        await driver.DropDB(String(process.env.POSTGRES_Database));
    }
    await driver.CreateDB(String(process.env.POSTGRES_Database));
    await driver.DisconnectFromServer();

    const connOpt: ConnectionOptions = {
        database: String(process.env.POSTGRES_Database),
        host: String(process.env.POSTGRES_Host),
        password: String(process.env.POSTGRES_Password),
        type: "postgres",
        username: String(process.env.POSTGRES_Username),
        port: Number(process.env.POSTGRES_Port),
        dropSchema: true,
        synchronize: false,
        entities: [path.resolve(filesOrgPath, "*.ts")],
        name: "postgres"
    };

    const schemas = "public,sch1,sch2";
    const conn = await createConnection(connOpt);
    const queryRunner = conn.createQueryRunner();
    await Promise.all(
        schemas.split(",").map(sch => queryRunner.createSchema(sch, true))
    );
    await conn.synchronize();

    if (conn.isConnected) {
        await conn.close();
    }

    return connectionOptions;
}

export async function createSQLiteModels(
    filesOrgPath: string
): Promise<IConnectionOptions> {
    const connectionOptions = getTomgConnectionOptions("sqlite");

    const connOpt: ConnectionOptions = {
        database: String(process.env.SQLITE_Database),
        type: "sqlite",
        dropSchema: true,
        synchronize: false,
        entities: [path.resolve(filesOrgPath, "*.ts")],
        name: "sqlite"
    };

    const conn = await createConnection(connOpt);
    await conn.synchronize();

    if (conn.isConnected) {
        await conn.close();
    }

    return connectionOptions;
}

export async function createMysqlModels(
    filesOrgPath: string
): Promise<IConnectionOptions> {
    const driver = new MysqlDriver();
    const connectionOptions = getTomgConnectionOptions("mysql");
    await driver.ConnectToServer(connectionOptions);

    if (await driver.CheckIfDBExists(String(process.env.MYSQL_Database))) {
        await driver.DropDB(String(process.env.MYSQL_Database));
    }
    await driver.CreateDB(String(process.env.MYSQL_Database));
    await driver.DisconnectFromServer();

    const connOpt: ConnectionOptions = {
        database: String(process.env.MYSQL_Database),
        host: String(process.env.MYSQL_Host),
        password: String(process.env.MYSQL_Password),
        type: "mysql",
        username: String(process.env.MYSQL_Username),
        port: Number(process.env.MYSQL_Port),
        dropSchema: true,
        synchronize: true,
        entities: [path.resolve(filesOrgPath, "*.ts")],
        name: "mysql"
    };
    const conn = await createConnection(connOpt);

    if (conn.isConnected) {
        await conn.close();
    }

    return connectionOptions;
}
export async function createMariaDBModels(
    filesOrgPath: string
): Promise<IConnectionOptions> {
    const driver = new MariaDbDriver();
    const connectionOptions = getTomgConnectionOptions("mariadb");
    await driver.ConnectToServer(connectionOptions);

    if (await driver.CheckIfDBExists(String(process.env.MARIADB_Database))) {
        await driver.DropDB(String(process.env.MARIADB_Database));
    }
    await driver.CreateDB(String(process.env.MARIADB_Database));
    await driver.DisconnectFromServer();

    const connOpt: ConnectionOptions = {
        database: String(process.env.MARIADB_Database),
        host: String(process.env.MARIADB_Host),
        password: String(process.env.MARIADB_Password),
        type: "mariadb",
        username: String(process.env.MARIADB_Username),
        port: Number(process.env.MARIADB_Port),
        dropSchema: true,
        synchronize: true,
        entities: [path.resolve(filesOrgPath, "*.ts")],
        name: "mariadb"
    };
    const conn = await createConnection(connOpt);

    if (conn.isConnected) {
        await conn.close();
    }

    return connectionOptions;
}

export async function createOracleDBModels(
    filesOrgPath: string
): Promise<IConnectionOptions> {
    const driver = new OracleDriver();

    const connectionOptions = getTomgConnectionOptions("oracle");

    await driver.ConnectToServer(connectionOptions);
    connectionOptions.user = String(process.env.ORACLE_Username);
    connectionOptions.password = String(process.env.ORACLE_Password);

    if (await driver.CheckIfDBExists(String(process.env.ORACLE_Username))) {
        await driver.DropDB(String(process.env.ORACLE_Username));
    }
    await driver.CreateDB(String(process.env.ORACLE_Username));
    await driver.DisconnectFromServer();

    const connOpt: ConnectionOptions = {
        database: String(process.env.ORACLE_Database),
        sid: String(process.env.ORACLE_Database),
        host: String(process.env.ORACLE_Host),
        password: String(process.env.ORACLE_Password),
        type: "oracle",
        username: String(process.env.ORACLE_Username),
        port: Number(process.env.ORACLE_Port),
        synchronize: true,
        entities: [path.resolve(filesOrgPath, "*.ts")],
        name: "oracle"
    };
    const conn = await createConnection(connOpt);

    if (conn.isConnected) {
        await conn.close();
    }

    return connectionOptions;
}

export function compileTsFiles(
    fileNames: string[],
    options: ts.CompilerOptions
): boolean {
    const program = ts.createProgram(fileNames, options);
    const emitResult = program.emit();
    let compiledWithoutErrors = true;
    const preDiagnostics = ts.getPreEmitDiagnostics(program);

    const allDiagnostics = [...preDiagnostics, ...emitResult.diagnostics];

    allDiagnostics.forEach(diagnostic => {
        const lineAndCharacter = diagnostic.file!.getLineAndCharacterOfPosition(
            diagnostic.start!
        );
        const message = ts.flattenDiagnosticMessageText(
            diagnostic.messageText,
            "\n"
        );
        console.log(
            `${diagnostic.file!.fileName} (${lineAndCharacter.line +
            1},${lineAndCharacter.character + 1}): ${message}`
        );
        compiledWithoutErrors = false;
    });

    return compiledWithoutErrors;
}

export function getEnabledDbDrivers(): IConnectionOptions["databaseType"][] {
    const dbDrivers: IConnectionOptions["databaseType"][] = [];
    if (process.env.SQLITE_Skip === "0") {
        dbDrivers.push("sqlite");
    }
    if (process.env.POSTGRES_Skip === "0") {
        dbDrivers.push("postgres");
    }
    if (process.env.MYSQL_Skip === "0") {
        dbDrivers.push("mysql");
    }
    if (process.env.MARIADB_Skip === "0") {
        dbDrivers.push("mariadb");
    }
    if (process.env.MSSQL_Skip === "0") {
        dbDrivers.push("mssql");
    }
    if (process.env.ORACLE_Skip === "0") {
        dbDrivers.push("oracle");
    }
    return dbDrivers;
}

export function createModelsInDb(
    dbDriver: string,
    filesOrgPathJS: string
): Promise<IConnectionOptions> {
    switch (dbDriver) {
        case "sqlite":
            return createSQLiteModels(filesOrgPathJS);
        case "postgres":
            return createPostgresModels(filesOrgPathJS);
        case "mysql":
            return createMysqlModels(filesOrgPathJS);
        case "mariadb":
            return createMariaDBModels(filesOrgPathJS);
        case "mssql":
            return createMSSQLModels(filesOrgPathJS);
        case "oracle":
            return createOracleDBModels(filesOrgPathJS);
        default:
            console.log(`Unknown engine type`);
            throw new Error("Unknown engine type");
    }
}

export function getTomgConnectionOptions(dbType: IConnectionOptions["databaseType"]): IConnectionOptions {
    switch (dbType) {
        case "mssql":
            return {
                host: String(process.env.MSSQL_Host),
                port: Number(process.env.MSSQL_Port),
                databaseNames: ["master"],
                user: String(process.env.MSSQL_Username),
                password: String(process.env.MSSQL_Password),
                databaseType: "mssql",
                schemaNames: ["dbo","sch1","sch2"],
                ssl: yn(process.env.MSSQL_SSL, { default: false }),
                skipTables: [],
                onlyTables: []
            };
        case "mariadb":
            return {
                host: String(process.env.MARIADB_Host),
                port: Number(process.env.MARIADB_Port),
                databaseNames: [String(process.env.MARIADB_Database)],
                user: String(process.env.MARIADB_Username),
                password: String(process.env.MARIADB_Password),
                databaseType: "mariadb",
                schemaNames: ["ignored"],
                ssl: yn(process.env.MARIADB_SSL, { default: false }),
                skipTables: [],
                onlyTables: []
            };
        case "mysql":
            return {
                host: String(process.env.MYSQL_Host),
                port: Number(process.env.MYSQL_Port),
                databaseNames: [String(process.env.MYSQL_Database)],
                user: String(process.env.MYSQL_Username),
                password: String(process.env.MYSQL_Password),
                databaseType: "mysql",
                schemaNames: ["ignored"],
                ssl: yn(process.env.MYSQL_SSL, { default: false }),
                skipTables: [],
                onlyTables: []
            };
        case "oracle":
            return {
                host: String(process.env.ORACLE_Host),
                port: Number(process.env.ORACLE_Port),
                databaseNames: [String(process.env.ORACLE_Database)],
                user: String(process.env.ORACLE_UsernameSys),
                password: String(process.env.ORACLE_PasswordSys),
                databaseType: "oracle",
                schemaNames: [String(process.env.ORACLE_Username)],
                ssl: yn(process.env.ORACLE_SSL, { default: false }),
                skipTables: [],
                onlyTables: []
            };
        case "postgres":
            return {
                host: String(process.env.POSTGRES_Host),
                port: Number(process.env.POSTGRES_Port),
                databaseNames: ["postgres"],
                user: String(process.env.POSTGRES_Username),
                password: String(process.env.POSTGRES_Password),
                databaseType: "postgres",
                schemaNames: ["public","sch1","sch2"],
                ssl: yn(process.env.POSTGRES_SSL, { default: false }),
                skipTables: ["spatial_ref_sys"],
                onlyTables: []
            };
        case "sqlite": return {
            host: "",
            port: 0,
            databaseNames: [String(process.env.SQLITE_Database)],
            user: "",
            password: "",
            databaseType: "sqlite",
            schemaNames: [""],
            ssl: false,
            skipTables: [],
            onlyTables: []
        };
        default:
            return assertUnreachable(dbType);
    }

}


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require("./baChartistChart.component"));
//# sourceMappingURL=index.js.map

redpajama_set_name: RedPajamaGithub


text:
package org.immopoly.android.helper;

public class TrackingManager {

	public static final String UA_ACCOUNT = "UA-25341313-1";

	// Page views, basicly Activities where you can do events
	public static final String VIEW_SIGNUP = "signup";
	public static final String VIEW_REGISTER = "register";
	public static final String VIEW_LOGIN = "login";
	public static final String VIEW_MAP = "map";
	public static final String VIEW_EXPOSE = "expose";
	public static final String VIEW_HISTORY = "history";
	public static final String VIEW_SHARE = "share";
	public static final String VIEW_ITEMS = "actionItems";
	public static final String VIEW_PORTFOLIO_LIST = "portfolioList";
	public static final String VIEW_PORTFOLIO_MAP = "portfolioMap";
	public static final String VIEW_PROFILE = "profile";
	public static final String VIEW_SETTINGS = "settings";
	public static final String VIEW_HELP = "help";
	public static final String VIEW_HIGHSCORE_OVERALL = "highscoreOverall";
	public static final String VIEW_HIGHSCORE_MONTH = "highscoreMonth";
	public static final String VIEW_HIGHSCORE_RELEAS_TESTER = "highscoreReleaseTester";
	public static final String VIEW_WEB_VIEW_DIALOG = "webviewDialog";
	public static final String VIEW_FIRST_AID = "firstAid";
	public static final String VIEW_ACTION_ITEM_SPY = "actionItemSpye";

	public static final String CATEGORY_CLICKS = "clicks";
	public static final String CATEGORY_SCROLL = "scroll";
	public static final String CATEGORY_ALERT_EXPOSE_TAKEN = "alert";
	public static final String CATEGORY_CLICKS_IN_WEBSITE = "click_in_website";
	public static final String CATEGORY_SHAREBUTTON = "click_on_share_button";

	public static final String ACTION_SHARE = "share";
	public static final String ACTION_VIEW = "view";
	public static final String ACTION_ERROR = "error";
	public static final String ACTION_EXPOSE = "tookExpose";
	public static final String ACTION_TOOK_EXPOSE = "tookExpose";
	public static final String ACTION_RELEASED_EXPOSE = "releasedExpose";
	public static final String ACTION_CONTACT = "clickWebviewContact";
	public static final String ACTION_FIRST_AID = "firstAid";
	public static final String ACTION_SEARCH = "search";
	public static final String ACTION_BADGE = "badge";

	public static final String LABEL_TRY = "try";
	public static final String LABEL_RELEASE = "release";
	public static final String LABEL_POSITIVE = "positive";
	public static final String LABEL_NEGATIVE = "negative";
	public static final String LABEL_IMAGES = "image";
	public static final String LABEL_IMAGES_DETAILS = "imagesDetails";
	public static final String LABEL_CHANGE_TO_REGISTER_FROM_LOGIN = "changeFromRegisterToLogin";
	public static final String LABEL_CHANGE_TO_LOGIN_FROM_REGISTER = "changeFromLoginToRegister";
	public static final String LABEL_BACK_INSIDE_IMMOSCOUT_WEBSITE = "clickBackInsideImmoscoutWebsite";
	public static final String LABEL_HUD_POPUP = "showHudPopup";
	public static final String LABEL_EXPOSE_PORTFOLIO = "openExposeFromPortfolio";
	public static final String LABEL_EXPOSE_MAP = "openExposeFromMap";
	public static final String LABEL_DISABLED = "disabled";
	public static final String LABEL_ENABLED = "enabled";
	public static final String LABEL_REFRESH = "refresh";
	public static final String LABEL_VIEW = "view";

}


text:
import os
import sys
import urllib2

def main(output_dir):
  # Create opener.
  opener = urllib2.OpenerDirector()
  opener.add_handler(urllib2.ProxyHandler())
  opener.add_handler(urllib2.UnknownHandler())
  opener.add_handler(urllib2.HTTPHandler())
  opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  opener.add_handler(urllib2.HTTPSHandler())
  opener.add_handler(urllib2.HTTPErrorProcessor())

  # Iterate over the files in the docs directory and copy them, as appropriate.
  for root, dirs, files in os.walk('.'):
    for file_name in files:
      if file_name.endswith('.soy') and not file_name.startswith('__'):
        # Strip the './' prefix, if appropriate.
        if root.startswith('./'):
          root = root[2:]

        # Construct the URL where the .soy file is being served.
        soy_file = file_name
        html_file = root + '/' + soy_file[:-len('.soy')] + '.html'
        url = 'http://localhost:9811/' + html_file

        # Fetch url and copy its contents to output_dir.
        req = urllib2.Request(url)
        res = opener.open(req)
        html = res.read()
        copy_to_output_dir(html_file, output_dir, html)
      elif (file_name.endswith('.css') or
            file_name.endswith('.js') or
            file_name.endswith('.png')):
        #  Copy the static resource to output_dir.
        relative_path = os.path.join(root, file_name)
        with open(relative_path) as resource_file:
          resource = resource_file.read()
          copy_to_output_dir(relative_path, output_dir, resource)

def copy_to_output_dir(path, output_dir, content):
  # Make sure that the directory for the destination path exists.
  last_slash = path.rfind('/')
  if last_slash != -1:
    output_subdir = os.path.join(output_dir, path[:last_slash])
    if not os.path.exists(output_subdir):
      os.makedirs(output_subdir)

  # Copy the file.
  output_file = os.path.join(output_dir, path)
  with open(output_file, 'w') as f:
    f.write(content)

if __name__ == '__main__':
  output_dir = sys.argv[1]
  main(output_dir)


text:
        {% image mascot.png class:'img-responsive' %}

4 a 11 Fevereiro

Universidade do Minho - CP2 B2

          Semana da Engenharia Informática

Organização

              {% image 'logos/cesium.png' class:'img-responsive' %}


text:
require "spec_helper"

describe Redistat::Options do

  before(:each) do
    @helper = OptionsHelper.new
    @helper.parse_options(:wtf => 'dude', :foo => 'booze')
  end

  it "should #parse_options" do
    @helper.options[:hello].should == 'world'
    @helper.options[:foo].should == 'booze'
    @helper.options[:wtf].should == 'dude'
    @helper.raw_options.should_not have_key(:hello)
  end

  it "should create option_accessors" do
    @helper.hello.should == 'world'
    @helper.hello('woooo')
    @helper.hello.should == 'woooo'
  end

end

class OptionsHelper
  include Redistat::Options

  option_accessor :hello

  def default_options
    { :hello => 'world',
      :foo => 'bar' }
  end

end


text:
var HotDeploy = function() {

	/*
	 * VARIABLES
	 */
    var div = null;
    var a = null;
    var span = null;
    var currentRequest = null;

	/*
	 * INITIALIZATION
	 */
	var init = function () {

        div = $('#hot-deploy');
        span = $('span',div);
        a = $('a',div);

        a.click(function(event){
            event.preventDefault();
            refresh();
        });

	};

	var refresh = function() {
        if(currentRequest != null) return;

        div.addClass('wait');
        span.text('Please Wait...');
        a.hide();

        if(div.hasClass('off')) {

            div.removeClass('off');

            currentRequest = $.ajax({
                type: 'GET',
                url: 'hotdeploy/refresh/',
                complete: function(res, status) {
                    if (status == "success" || status == "notmodified" ) {
                        div.removeClass('wait').addClass('off');
                        span.text('Pre-Compiled Mode');
                        a.show();
                    }
                    currentRequest = null;
                },
                error: function(req, err) {
                    console_log(req.responseText.stripHtml());
                    $(document).trigger('show_error', 'Error refreshing context');
                }
            });

        }
	};

	$(document).ready( function() {
		init();
	});

}();


text:
#include "cifsglob.h"

struct smb_version_operations smb21_operations = {
};

struct smb_version_values smb21_values = {
	.version_string = SMB21_VERSION_STRING,
};


text:
package org.apache.zeppelin.conf;

import junit.framework.Assert;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

import java.net.MalformedURLException;
import java.util.List;

public class ZeppelinConfigurationTest {
  @Before
  public void clearSystemVariables() {
    System.clearProperty(ConfVars.ZEPPELIN_NOTEBOOK_DIR.getVarName());
  }

  @Test
  public void getAllowedOrigins2Test() throws MalformedURLException, ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/test-zeppelin-site2.xml"));
    List<String> origins = conf.getAllowedOrigins();
    Assert.assertEquals(2, origins.size());
    Assert.assertEquals("http://onehost:8080", origins.get(0));
    Assert.assertEquals("http://otherhost.com", origins.get(1));
  }

  @Test
  public void getAllowedOrigins1Test() throws MalformedURLException, ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/test-zeppelin-site1.xml"));
    List<String> origins = conf.getAllowedOrigins();
    Assert.assertEquals(1, origins.size());
    Assert.assertEquals("http://onehost:8080", origins.get(0));
  }

  @Test
  public void getAllowedOriginsNoneTest() throws MalformedURLException, ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
    List<String> origins = conf.getAllowedOrigins();
    Assert.assertEquals(1, origins.size());
  }

  @Test
  public void isWindowsPathTestTrue() throws ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
    Boolean isIt = conf.isWindowsPath("c:\\test\\file.txt");
    Assert.assertTrue(isIt);
  }

  @Test
  public void isWindowsPathTestFalse() throws ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
    Boolean isIt = conf.isWindowsPath("~/test/file.xml");
    Assert.assertFalse(isIt);
  }

  @Test
  public void getNotebookDirTest() throws ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
    String notebookLocation = conf.getNotebookDir();
    Assert.assertEquals("notebook", notebookLocation);
  }

  @Test
  public void isNotebookPublicTest() throws ConfigurationException {

    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
    boolean isIt = conf.isNotebookPublic();
    assertTrue(isIt);
  }

  @Test
  public void getPathTest() throws ConfigurationException {
    System.setProperty(ConfVars.ZEPPELIN_HOME.getVarName(), "/usr/lib/zeppelin");
    ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
    Assert.assertEquals("/usr/lib/zeppelin", conf.getZeppelinHome());
    Assert.assertEquals("/usr/lib/zeppelin/conf", conf.getConfDir());
  }
}


text:
package com.orland0m.rpi.middleware;

import com.orland0m.rpi.access.local.LocalPinAccessor;
import com.orland0m.rpi.access.rest.RestConfig;
import com.orland0m.rpi.middleware.exception.AccessorDownException;
import com.orland0m.rpi.middleware.exception.PinBusyException;
import com.orland0m.rpi.middleware.pin.InputPin;
import com.orland0m.rpi.middleware.pin.OutputPin;
import com.orland0m.rpi.middleware.pin.PinAccessor;
import com.orland0m.rpi.middleware.pin.WiringPi;

/**
 * Middleware class used to have transparent access to GPIO. This class
 * can use a local pin accessor or a REST based PIN accessor
 *
 * @author Orlando Miramontes <https://github.com/orland0m>
 */
public class RpiController implements PinAccessor {
    /*! Middleware object for pin access */
    private PinAccessor middleware;

    public RpiController(RestConfig config) {
        // Will create a rest based pin accessor
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Initializes a controller object that uses a local pin accessor
     */
    public RpiController() {
        middleware = new LocalPinAccessor();
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#shutdown()
     */
    @Override
    public void shutdown()
    throws IllegalArgumentException, PinBusyException, AccessorDownException, AccessorDownException,
        AccessorDownException, AccessorDownException {
        middleware.shutdown();
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#isDown()
     */
    @Override
    public boolean isDown() {
        return middleware.isDown();
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getInPin(int)
     */
    @Override
    public InputPin getInPin(int physicalPinNumber)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getInPin(physicalPinNumber);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getInGpio(int)
     */
    @Override
    public InputPin getInGpio(int gpioNumber)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getInGpio(gpioNumber);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getInGpio(java.lang.String)
     */
    @Override
    public InputPin getInGpio(String gpioName)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getInGpio(gpioName);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getInGpio(com.orland0m.rpi.middleware.pin.WiringPi)
     */
    @Override
    public InputPin getInGpio(WiringPi gpio)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getInGpio(gpio);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getOutPin(int)
     */
    @Override
    public OutputPin getOutPin(int physicalPinNumber) throws IllegalArgumentException,
        PinBusyException {
        return middleware.getOutPin(physicalPinNumber);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getOutGpio(int)
     */
    @Override
    public OutputPin getOutGpio(int gpioNumber)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getOutGpio(gpioNumber);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getOutGpio(java.lang.String)
     */
    @Override
    public OutputPin getOutGpio(String gpioName)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getOutGpio(gpioName);
    }

    /* (non-Javadoc)
     * @see com.orland0m.rpi.middleware.pin.PinAccessor#getOutGpio(com.orland0m.rpi.middleware.pin.WiringPi)
     */
    @Override
    public OutputPin getOutGpio(WiringPi gpio)  throws IllegalArgumentException, PinBusyException,
        AccessorDownException, AccessorDownException {
        return middleware.getOutGpio(gpio);
    }
}


text:
function [mNewDis, mNewMst, vRearrangedVert, vNewRoot, mNewExist] = incVat3(a,mDis, mExist, mMst, mNewPtsDis, bVisualise)
% incVat()
% Updates an existing Vat image with the new points described in mRNew.
% The new points are added sequentially to the end.
%
% INPUT:
% mDis      - (n by n), dissimilarity matrix.
% mExist    - (n by n), existence matrix.
% vMst      - Minimum spanning tree, 1 by n, with each entry denoting the parent of
%           the corresponding vertex.  Root vertex has entry '0'.
% mNewPtsDis     - New distances to existing points and all new points.  Dimensions
%           should be n' by (new points number), where n' = n + new points
%           number.
% rootVert  - Root vertex.
% bVisualise    - Whether to visualise the updated MST.
%
% OUTPUT:
% mNewDis   - Updated distance measure with the new distances.
% vNewMst   - Updated MST.
% vRearrangedVerts - Ordered set of vertices (used for VAT display).
%

    old = size(mDis,1);
    new = size(mNewPtsDis,1);

    mDis = mDis/a;
    mTemp = mNewPtsDis(1:old,:)/a;
    mTemp2 = mNewPtsDis((old+1):new,:);
    mTempRow = [mTemp',mTemp2];
    mTempCol = [mDis,mTemp];
    mNewVis = [mTempCol;mTempRow];

    mDis = a*mDis;
    mNewMst = mMst;
    mNewDis = mDis;
    mNewExist = mExist;
    oldSize = size(mMst,1);
    mNewPtsExist = ones((size(mExist,1)+size(mNewPtsDis,2)),size(mNewPtsDis,2));

    mNewTempDis = a * mNewPtsDis(1:old,:);
    mNewTempDis2 = mNewPtsDis((old+1):new,:);
    mNewPtsDis = [mNewTempDis;mNewTempDis2];

    % add each new vertex
    for p = 1 : size(mNewPtsDis,2)
        vNewPtsDis = mNewPtsDis( 1:(oldSize+p-1), p);
        vNewPtsExist = mNewPtsExist(1:(oldSize+p-1), p);
        [mNewMst,vNewRoot,mNewExist,mNewDis] = insertVertVat(mNewDis, mNewExist, vNewPtsExist, vNewPtsDis, mNewMst);
        %[mNewMst,mNewDis,mNewExist,vNewRoot] = insertVertVatNonRecursive(mNewDis, vNewPtsExist, vNewPtsDis, mNewMst,mNewExist);
        %mNewMst = insertVertVatNonRecursive(mNewDis, vNewPtsExist, vNewPtsDis, mNewMst, rootVert);

        %mNewDis = cat(1, mNewDis, vNewPtsDis');
        %mNewDis = cat(2, mNewDi4es, [vNewPtsDis; 0]);
    end

    %
    % construct the rearraned vertices by traversing the updated MST
    %

    vRearrangedVert = zeros(1, size(mNewMst,1));

    % traverse the tree
%     qPriority = pq_create(length(vNewMst));
    javaComparator = PriorityComparator;
    qPriority = java.util.PriorityQueue(size(mNewMst,1), javaComparator);
%     pq_push(qPriority, rootVert, 0);
    qPriority.add({0, vNewRoot});
    vTraversed = false(1, size(mNewMst,1));
    currIndex = 1;

%     while size(qPriority) > 0
    while qPriority.size() > 0
%         [currVert, ~] = pq_pop(qPriority);
        vHead = qPriority.poll();
        currVert = vHead(2);
        vTraversed(currVert) = true;
        vRearrangedVert(currIndex) = currVert;
        % find children + parents
        vNeighs = find(mNewMst(currVert,:));
%         vNeighs = find(vNewMst == currVert);
%         parentVert = vNewMst(currVert);
%         if parentVert ~= 0
%             vNeighs = [vNeighs parentVert];
%         end

        for v = 1 : length(vNeighs)
            neighVert = vNeighs(v);
            if ~vTraversed(neighVert)
%                 pq_push(qPriority, neighVert, mNewDis(currVert, neighVert));
                qPriority.add({mNewDis(currVert, neighVert), neighVert});
            end
        end

        currIndex = currIndex + 1;
    end

    if bVisualise
       figure;
       colormap(gray);
       imagesc(mNewVis(vRearrangedVert, vRearrangedVert));
    end

end % end of function


text:
require "spec_helper"

module Pemilu
	describe Candidate do
		describe "new" do
			let(:candidate) { Pemilu::Candidate.new(
				id: 1,
        name: "bayu aldi yansyah",
        gender: "L",
        religion: "ISLAM",
        birthplace: "Nganjuk",
        date_of_birth: "07 Oktober 1996",
        marital_status: "Di PHPin",
        name_of_couples: "Pevita Pearce",
        number_of_children: 100,
        village: "Keloposepuluh",
        sub_district: "Sukodono",
        district: "Sidoarjo",
        province: {
          "id" => 2,
          "name" => "Jawa Timur"
          },
        electoral_district: {
          "id" => 20,
          "name" => "Sidoarjo"
          },
        election_year: 2014,
        legislative_body: "DPR",
        party: "Partai Asolole jos!",
        ordinal: 1,
        picture: "hhtp://foto.jpg",
        educations: [{
					"id" => 9,
					"ringkasan" => "Test"
				}],
        jobs: [{
					"id" => 9,
					"ringkasan" => "Test"
				}],
        organizations: [{
					"id" => 9,
					"ringkasan" => "Test"
				}] ) }

			it "should return Pemilu::Candidate object and have correct details" do
        candidate.should be_a(Pemilu::Candidate)
				expect(candidate.id).to eq(1)
				expect(candidate.name).to eq("bayu aldi yansyah")
				expect(candidate.gender).to eq("L")
				expect(candidate.religion).to eq("ISLAM")
				expect(candidate.birthplace).to eq("Nganjuk")
				expect(candidate.date_of_birth).to eq("07 Oktober 1996")
				expect(candidate.marital_status).to eq("Di PHPin")
				expect(candidate.name_of_couples).to eq("Pevita Pearce")
				expect(candidate.number_of_children).to eq(100)
				expect(candidate.number_of_children).to eq(100)
				expect(candidate.village).to eq("Keloposepuluh")
				expect(candidate.sub_district).to eq("Sukodono")
				expect(candidate.district).to eq("Sidoarjo")
				expect(candidate.province["id"]).to eq(2)
				expect(candidate.province["name"]).to eq("Jawa Timur")
				expect(candidate.electoral_district["id"]).to eq(20)
				expect(candidate.electoral_district["name"]).to eq("Sidoarjo")
				expect(candidate.election_year).to eq(2014)
				expect(candidate.legislative_body).to eq("DPR")
				expect(candidate.party).to eq("Partai Asolole jos!")
				expect(candidate.ordinal).to eq(1)
				expect(candidate.picture).to eq("hhtp://foto.jpg")
				expect(candidate.educations.class).to eq(Array)
        expect(candidate.jobs.class).to eq(Array)
        expect(candidate.organizations.class).to eq(Array)
			end

		end
	end
end


text:
class Ability
  include CanCan::Ability

  def initialize(user)
    if user.is_admin?
      can :manage, Humpyard::Page
      can :manage, Humpyard::Element
    else
      can :read, Humpyard::Page
    end
  end
end


text:
.. .. meta::
   :description: Migration guide to Hasura v0.15
   :keywords: hasura, v0.15, migration guide, migration

.. _migration-v0_15:

Moving to Hasura platform v0.15 from an older version
=====================================================

.. toctree::
  :maxdepth: 1

  terminologies
  workflow
  hasura-cli
  auth-api


text:
@assert typeof((4, false, [])) == Tuple{Int64, Bool, Array{Any, 1}}
@assert isa(false, Union{Int64, Bool, Array{Any, 1}})

# 1 component type
@assert typeof((5,)) == Tuple{Int64}
@assert isa(false, Union{Bool})
@assert Bool != Tuple{Bool}           # Because false != (false,)
@assert Bool == Union{Bool}           # Do you see why?

# No component types
@assert typeof(()) == Tuple{}


text:
      <ion-content>
        <ion-radio class="line-b size-12 radio-label" ng-repeat="altCurrency in altCurrencyList" ng-value="altCurrency.isoCode" ng-model="currentCurrency"
          ng-click="save(altCurrency)">{{altCurrency.name}}
        </ion-radio>
        <ion-infinite-scroll
          ng-if="!listComplete"
          on-infinite="loadMore()"
          distance="1%">
        </ion-infinite-scroll>
      </ion-content>


text:
using System.Reflection;
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;

namespace NetOffice.ExcelApi
{
	/// <summary>
	/// Interface IXmlMap
	/// SupportByVersion Excel, 11,12,14,15,16
	/// </summary>
	[SupportByVersion("Excel", 11,12,14,15,16)]
	[EntityType(EntityType.IsInterface)]
 	public class IXmlMap : COMObject
	{
		#pragma warning disable

		#region Type Information

        /// <summary>
        /// Instance Type
        /// </summary>
		[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
        public override Type InstanceType
        {
            get
            {
                return LateBindingApiWrapperType;
            }
        }

        private static Type _type;

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public static Type LateBindingApiWrapperType
        {
            get
            {
                if (null == _type)
                    _type = typeof(IXmlMap);
                return _type;
            }
        }

        #endregion

		#region Ctor

		/// <param name="factory">current used factory core</param>
		/// <param name="parentObject">object there has created the proxy</param>
		/// <param name="proxyShare">proxy share instead if com proxy</param>
		public IXmlMap(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
		public IXmlMap(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
		{

		}

        ///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public IXmlMap(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public IXmlMap(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
		{

		}

		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public IXmlMap(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
		{
		}

		///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public IXmlMap(ICOMObject replacedObject) : base(replacedObject)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public IXmlMap() : base()
		{
		}

		/// <param name="progId">registered progID</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public IXmlMap(string progId) : base(progId)
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Application Application
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlCreator Creator
		{
			get
			{
				return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// Unknown COM Proxy
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16), ProxyResult]
		public object Parent
		{
			get
			{
				return Factory.ExecuteReferencePropertyGet(this, "Parent");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public string _Default
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "_Default");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public string Name
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "Name");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "Name", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool IsExportable
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "IsExportable");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool ShowImportExportValidationErrors
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "ShowImportExportValidationErrors");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "ShowImportExportValidationErrors", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool SaveDataSourceDefinition
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "SaveDataSourceDefinition");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "SaveDataSourceDefinition", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool AdjustColumnWidth
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "AdjustColumnWidth");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "AdjustColumnWidth", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool PreserveColumnFilter
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "PreserveColumnFilter");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "PreserveColumnFilter", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool PreserveNumberFormatting
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "PreserveNumberFormatting");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "PreserveNumberFormatting", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get/Set
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public bool AppendOnImport
		{
			get
			{
				return Factory.ExecuteBoolPropertyGet(this, "AppendOnImport");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "AppendOnImport", value);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public string RootElementName
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "RootElementName");
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.XmlNamespace RootElementNamespace
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.XmlNamespace>(this, "RootElementNamespace", NetOffice.ExcelApi.XmlNamespace.LateBindingApiWrapperType);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.XmlSchemas Schemas
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.XmlSchemas>(this, "Schemas", NetOffice.ExcelApi.XmlSchemas.LateBindingApiWrapperType);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.XmlDataBinding DataBinding
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.XmlDataBinding>(this, "DataBinding", NetOffice.ExcelApi.XmlDataBinding.LateBindingApiWrapperType);
			}
		}

		/// <summary>
		/// SupportByVersion Excel 12, 14, 15, 16
		/// Get
		/// </summary>
		[SupportByVersion("Excel", 12,14,15,16)]
		public NetOffice.ExcelApi.WorkbookConnection WorkbookConnection
		{
			get
			{
				return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.WorkbookConnection>(this, "WorkbookConnection", NetOffice.ExcelApi.WorkbookConnection.LateBindingApiWrapperType);
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public Int32 Delete()
		{
			return Factory.ExecuteInt32MethodGet(this, "Delete");
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="url">string url</param>
		/// <param name="overwrite">optional object overwrite</param>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlImportResult Import(string url, object overwrite)
		{
			return Factory.ExecuteEnumMethodGet<NetOffice.ExcelApi.Enums.XlXmlImportResult>(this, "Import", url, overwrite);
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="url">string url</param>
		[CustomMethod]
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlImportResult Import(string url)
		{
			return Factory.ExecuteEnumMethodGet<NetOffice.ExcelApi.Enums.XlXmlImportResult>(this, "Import", url);
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="xmlData">string xmlData</param>
		/// <param name="overwrite">optional object overwrite</param>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlImportResult ImportXml(string xmlData, object overwrite)
		{
			return Factory.ExecuteEnumMethodGet<NetOffice.ExcelApi.Enums.XlXmlImportResult>(this, "ImportXml", xmlData, overwrite);
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="xmlData">string xmlData</param>
		[CustomMethod]
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlImportResult ImportXml(string xmlData)
		{
			return Factory.ExecuteEnumMethodGet<NetOffice.ExcelApi.Enums.XlXmlImportResult>(this, "ImportXml", xmlData);
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="url">string url</param>
		/// <param name="overwrite">optional object overwrite</param>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlExportResult Export(string url, object overwrite)
		{
			return Factory.ExecuteEnumMethodGet<NetOffice.ExcelApi.Enums.XlXmlExportResult>(this, "Export", url, overwrite);
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="url">string url</param>
		[CustomMethod]
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlExportResult Export(string url)
		{
			return Factory.ExecuteEnumMethodGet<NetOffice.ExcelApi.Enums.XlXmlExportResult>(this, "Export", url);
		}

		/// <summary>
		/// SupportByVersion Excel 11, 12, 14, 15, 16
		/// </summary>
		/// <param name="data">string data</param>
		[SupportByVersion("Excel", 11,12,14,15,16)]
		public NetOffice.ExcelApi.Enums.XlXmlExportResult ExportXml(out string data)
		{
			ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true);
			data = string.Empty;
			object[] paramsArray = Invoker.ValidateParamsArray(data);
			object returnItem = Invoker.MethodReturn(this, "ExportXml", paramsArray, modifiers);
			data = paramsArray[0] as string;
			int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
			return (NetOffice.ExcelApi.Enums.XlXmlExportResult)intReturnItem;
		}

		#endregion

		#pragma warning restore
	}
}


text:
<!DOCTYPE html>

    <title th:text="${page_title}">Home</title>
    <meta charset="UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-touch-fullscreen" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="default"/>

    <meta name="theme-color" content="#673AB7">
    <meta name="msapplication-navbutton-color" content="#673AB7">
    <meta name="apple-mobile-web-app-status-bar-style" content="#673AB7">

    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>

    <link rel="manifest" th:href="@{/js/manifest.json}">

    <link rel="shortcut icon" href="/img/icon.png" />

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Muli:300,400,500,700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
    <link th:href="@{/webjars/mui/packages/cdn/css/mui.min.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/css/vendor/bootstrap.min.css}" rel="stylesheet"/>
    <link th:href="@{/css/vendor/bootstrap-extended.min.css}" type="text/css" rel="stylesheet"/>
    <link th:href="@{/css/vendor/components.min.css}" type="text/css" rel="stylesheet"/>
    <link th:href="@{/css/vendor/vertical-menu.css}" type="text/css" rel="stylesheet"/>
    <link th:href="@{/css/elements.css}" type="text/css" rel="stylesheet"/>
    <link th:href="@{/css/styles.css}" type="text/css" rel="stylesheet"/>

                Terms of Services |
                Privacy Policy |
                code View Source |
                Developers


text:
import util
import random

########################
#   Helper Functions   #
########################

# Returns a copy of the sentence with extra outer parentheses removed if they exist.
# The general structure of this algorithm is from Gareth Rees on stackoverflow.com:
# http://stackoverflow.com/questions/4284991/parsing-nested-parentheses-in-python-grab-content-by-level
def stripOuterParens(sentence):
    if sentence == "": return sentence
    start = 0
    end = len(sentence)
    stack = []
    pairs = {}
    for i, char in enumerate(sentence):
        if char == '(':
            stack.append(i)
        elif char == ')' and stack:
            pairs[stack.pop()] = i
    for i in range(0, end):
        if i not in pairs.keys() or pairs[i] != (end - 1):
            return sentence[start : end]
        start = i + 1
        end = pairs[i]
    raise Exception("Execution should never reach here.")

# Returns True if the parentheses in the string are balanced and False otherwise.
def parensBalanced(string):
    stack = []
    for i, char in enumerate(string):
        if char == '(':
            stack.append(i)
        elif char == ')':
            if not stack: return False
            stack.pop()
    if stack: return False
    return True

# Returns (isImplication, antecedent, consequent) where:
#   * isImplication is a boolean specifying whether statement has an outermost implication
#   * antecedent is the antecedent of such an implication if it exists
#   * consequent is the consequent of such an implication if it exists
def processImplication(sentence):
    imp_index = sentence.find(" -> ")
    # Scans the string, looking for "phi -> psi" were phi and psi are properly formatted.
    # Takes the first example found since implications generally bind to the left.
    while imp_index > 0:
        antecedent = sentence[:(imp_index)]
        consequent = sentence[(imp_index + 4):]
        if '(' in antecedent or ')' in antecedent:
            if not parensBalanced(antecedent):
                imp_index += 4 + sentence[(imp_index + 4):].find(" -> ")
                continue
            antecedent = stripOuterParens(antecedent.strip())
        if '(' in consequent or ')' in consequent:
            if not parensBalanced(consequent):
                imp_index += 4 + sentence[(imp_index + 4):].find(" -> ")
                continue
            consequent = stripOuterParens(consequent.strip())
        return (True, antecedent, consequent)
    return (False, None, None)

################################################
#   Fitch Proof Search Problem Formalization   #
################################################

# Defines finding a proof in the Fitch system as a search problem
# SearchProblem class from CS221: Artificial Intelligence assignment 3: Text Reconstruction
class FitchProblem(util.SearchProblem):
    # @param premises = list [] of statements using the supplied symbolic conventions
    # @param goal = a statement to be proved, written using the supplied symbolic convenctions
    def __init__(self, premises, goal, symbolSet, statementSet, connectiveSet):
        self.premises = premises
        self.goal = goal
        self.symbols = symbolSet
        self.statementSet = statementSet
        self.connectiveSet = connectiveSet

    # Defines the start state of the search graph given the premises, goal, and symbols
    # The start state is a proof consisting only of premises at assumption level 0.
    def startState(self):
        # A state is defined by a list of tuples, each tuple containing a true statement, its justification, and its proof depth
        statements = []
        for premise in self.premises:
            statements.append((premise, "Premise", 0))
        # The full form of a state is tuple([list of statement, justification, depth tuples], sub-proof level).
        # Subproof level is initially 0.
        return (tuple(statements), 0)

    # Defines the end state of the search graph
    # The end state is defined to be any proof which contains the goal as a non-premise at sub-proof level 0
    def isEnd(self, state):
        statements = list(state[0])
        if len(statements) == 0: return False
        lastStatement = statements[len(statements) - 1]
        # For a state to be the end state, must contain the goal and be at base level (not in a subproof)
        if lastStatement[0] == self.goal and lastStatement[1] != "Premise" and lastStatement[2] == 0:
            return True
        return False

    # Defines the successor state and costs of the given state, represnting a partial proof
    # Successor states are a proof with an added set of lines generated by using one of the Fitch
    # rules of inference.
    # The proof generator only considers proof steps on symbols contained in the symbol set.
    # For the prototype, all paths will have the same cost.
    #
    # @return a list of possible (action, newState, cost) tuples representing successor states.
    #   The return type is:    list of (string, [(sentence, justification, depth), (sentence, justification, depth), etc.], int) tuples
    def succAndCost(self, state):

        # Occassionally prints the current state being searched (for testing)
        '''
        if random.random() > 0.9995:
            print state
        '''

        results = []
        allStatements = list(state[0])      # (sentence, justification, depth) tuples
        proofDepth = state[1]               # the subproof depth of the last statement in the proof
        whitespace = ""
        for _ in range(proofDepth):
            whitespace += "  "

        # Extract the statements that matter from the list of all statements made in the proof so far
        # This includes all statements at level 0 and anything in the scope of the current subproof
        # Also makes a list of the sentences alone to help check whether we're being redundent
        statements = []
        sentences = []
        maxDepthAllowed = proofDepth
        for i, statement in reversed(list(enumerate(allStatements))):
            depth = statement[2]
            if depth < maxDepthAllowed:
                maxDepthAllowed -= 1
            elif depth > maxDepthAllowed:
                continue
            statements.append(statement)
            sentences.append(statement[0])
        # Puts all the statements back into the correct ordering
        statements.reverse()

        # An edge case of sorts: if we already have the answer but as a premise, just reiterate it and move on.
        if self.goal in sentences:
            succStatements = list(state[0])
            succStatements.append((self.goal, "R", state[1]))
            succState = (tuple(succStatements), state[1])
            results.append((whitespace + "Reiteration: " + self.goal, succState, 1))
            return results

        # Assumptions
        def Acost(depth):
            if depth <= 2: return max(1, depth)
            return 2**(depth)
        # Bias argument allows adjustment of cost if, say, we know the assumption is probably a good idea.
        def addAssumption(symbol, bias = 1):
            cost = Acost(state[1] + 1) * bias
            succStatements = list(state[0])
            succStatements.append((symbol, "A", state[1] + 1))
            succState = (tuple(succStatements), state[1] + 1)
            A_whitespace = "  " + whitespace
            results.append((A_whitespace + "Assumption: " + symbol, succState, cost))

        # Tries to assume the opposite (of a non-implication) or the antecedent (of an implication)
        isImplication = False
        assumedSomething = False
        for sentence in self.statementSet:
            if len(allStatements) <= len(self.statementSet) and sentence != self.goal:
                if "->" in sentence:
                    isImplication, antecedent, consequent = processImplication(sentence)
                    if isImplication:
                        if sentence not in sentences:
                            addAssumption(sentence, 0.25)
                            assumedSomething = True
                        if antecedent not in sentences:
                            addAssumption(antecedent, 0.25)
                            assumedSomething = True

                # The following ended up being too specific a strategy for the general problem, so I've omitted it.
                '''
                if not isImplication:
                    if ("&&" in sentence or "||" in sentence or "->" in sentence):
                        addAssumption("~(" + sentence + ")", 0.75)
                        assumedSomething = True
                    else:
                        addAssumption("~" + sentence, 0.75)
                        assumedSomething = True
                '''

        # Assumptions of single propositional constants and their negations
        for symbol in self.symbols:
            cost = 3 if assumedSomething else 1
            addAssumption(symbol, cost)
            addAssumption("~" + symbol, cost)

        # Used for And Introduction and And Elimination
        if "&&" in self.connectiveSet:
            atoms = set()
            conjuncts = set()

        # Used for Or Elimination
        if "||" in self.connectiveSet:
            disjuncts = set()

        # Gathers implications -- Used for Negation Introduction (and Or Elimination, if applicable)
        phi_to_psi = {}                 # Dict from string to list(string) representing phi to all psi
        phi_to_not_psi = {}             # Dict from string to list(string) representing phi to all not psi

        # Most of the rules of inference are covered or prepped for within this for loop.
        for statement in statements:

            if "&&" in self.connectiveSet:
                # And Introduction
                sentence = statement[0]
                atoms.add(sentence)

                # And Elimination
                sentenceCopy = statement[0]
                and_index = sentenceCopy.find(" && ")
                while and_index != -1:
                    conjunct = sentenceCopy[:(and_index)]
                    # If the parentheses are balanced in the string it is assumed to be a proper conjunct
                    if parensBalanced(conjunct):
                        conjuncts.add(conjunct)
                    sentenceCopy = sentenceCopy[(and_index + 4):]
                    and_index = sentenceCopy.find(" && ")
                # Loop and a half
                conjunct = sentenceCopy
                if conjunct != "":
                    if parensBalanced(conjunct):
                        conjuncts.add(conjunct)

            if "||" in self.connectiveSet:
                # Or Introduction
                sentence = statement[0]
                def addDisjunction(disjunction):
                    # The cost below determines the efficiency of the algorithm to a large degree
                    cost = 1 if (disjunction == self.goal) else len(disjunction)
                    succStatements = list(state[0])
                    succStatements.append((disjunction, "OI", state[1]))
                    succState = (tuple(succStatements), state[1])
                    results.append((whitespace + "Or Introduction: " + disjunction, succState, cost))
                # We deliberately hamper this rule because it is not very interesting.
                if len(sentence) == 1:
                    for symbol in self.symbols:
                        disjunction = sentence + " || " + symbol
                        if disjunction not in sentences:
                            addDisjunction(disjunction)
                        not_disjunction = sentence + " || ~" + symbol
                        if not_disjunction not in sentences:
                            addDisjunction(not_disjunction)

                # Or Elimination
                sentenceCopy = statement[0]
                disjunct = []   # List of statements connected by "||"
                or_index = sentenceCopy.find(" || ")
                if or_index > -1:
                    while or_index > -1:
                        atom = sentenceCopy[:(or_index)]
                        # If the parentheses are balanced for the atom, we take it to properly be part of a disjunction
                        if parensBalanced(atom):
                            disjunct.append(atom)
                        sentenceCopy = sentenceCopy[(or_index + 4):]
                        or_index = sentenceCopy.find(" || ")
                    # Loop and a half
                    disjunct.append(sentenceCopy)
                    disjuncts.add(tuple(disjunct))

            # Negation Introduction
            sentence = statement[0]
            isImplication, antecedent, consequent = processImplication(sentence)
            if isImplication:
                if consequent[0] == "~":
                    if antecedent not in phi_to_not_psi.keys():
                        phi_to_not_psi[antecedent] = list()
                    phi_to_not_psi[antecedent].append(consequent[1:])
                else:
                    if antecedent not in phi_to_psi.keys():
                        phi_to_psi[antecedent] = list()
                    phi_to_psi[antecedent].append(consequent)

            # Negation Elimination
            if sentence[:2] == "~~":
                newSentence = stripOuterParens(sentence[2:])
                if newSentence not in sentences:
                    succStatements = list(state[0])
                    succStatements.append((newSentence, "NE", state[1]))
                    succState = (tuple(succStatements), state[1])
                    results.append((whitespace + "Negation Elimination: " + newSentence, succState, 1))

            # Implication Elimination
            # Reuses the implication processing from the NI step.
            if isImplication:
                # Loops through all statements and sees if antecedent appears enabling us to derive consequent
                for statement2 in statements:
                    if statement2 == statement:
                        continue
                    sentence2 = statement2[0]
                    if sentence2 == antecedent and consequent not in sentences:
                        succStatements = list(state[0])
                        succStatements.append((consequent, "IE", state[1]))
                        succState = (tuple(succStatements), state[1])
                        results.append((whitespace + "Implication Elimination: " + consequent, succState, 1))

            # Biconditional Elimination
            def addBicondElimStatement(lhs, rhs, statements):
                newImplication = lhs + " -> " + rhs
                if newImplication not in sentences:
                    succStatements = list(state[0])
                    succStatements.append((newImplication, "BE", state[1]))
                    succState = (tuple(succStatements), state[1])
                    results.append((whitespace + "Biconditional Elimination: " + newImplication, succState, 1))

            if "<->" in self.connectiveSet:
                sentence = statement[0]
                bicond_index = sentence.find(" <-> ")
                while bicond_index > 0:
                    first = sentence[:(bicond_index)]
                    second = sentence[(bicond_index + 5):]
                    addBicondElimStatement(first, second, statements)
                    addBicondElimStatement(second, first, statements)
                    bicond_index = sentence[(bicond_index + 5):].find(" <-> ")

        if "&&" in self.connectiveSet:
            # Finishes adding all possible statements from And Introduction
            for atom1 in atoms:
                for atom2 in atoms:
                    conjunction = atom1.strip() + " && " + atom2.strip()
                    if conjunction not in sentences:
                        # We punish this rule of inference as well for being, quite frankly, not very interesting
                        cost = 10 if atom1 == atom2 else 3
                        succStatements = list(state[0])
                        succStatements.append((conjunction, "AI", state[1]))
                        succState = (tuple(succStatements), state[1])
                        results.append((whitespace + "And Introduction: " + conjunction, succState, cost))

            # Finishes adding all possible statements from And Elimination
            for conjunct in conjuncts:
                if conjunct not in sentences:
                    succStatements = list(state[0])
                    succStatements.append((conjunct, "AE", state[1]))
                    succState = (tuple(succStatements), state[1])
                    results.append((whitespace + "And Elimination: " + conjunct, succState, 1))

        if "||" in self.connectiveSet:
            # Finishes adding all possible statement from Or Elimination
            def addOrElimStatement(psi):
                succStatements = list(state[0])
                succStatements.append((psi, "OE", state[1]))
                succState = (tuple(succStatements), state[1])
                results.append((whitespace + "Or Elimination: " + psi, succState, 1))

            # Iterates through atoms in each disjunct and derives all things implied by every disjuncted unit
            for disjunction in list(disjuncts):    # List of disjuncted atoms
                isEntailed = True
                # Populate a list with all examples of psi for some implication statement (phi -> psi)
                psi_list = []
                for psi_l in phi_to_psi.values():
                    for psi in psi_l:
                        psi_list.append(psi)
                for not_psi_l in phi_to_not_psi.values():
                    for not_psi in not_psi_l:
                        psi_list.append("~" + not_psi)
                # Iterate through every psi and, if (phi -> psi) exists for every phi in the disjunction,
                # then we can add an or elimination statement containing psi
                for psi in psi_list:
                    if psi[:1] == "~":
                        for phi in disjunction:
                           if phi not in phi_to_not_psi.keys() or psi.strip("~") not in phi_to_not_psi[phi]:
                                isEntailed = False
                    else:
                        for phi in disjunction:
                            if phi not in phi_to_psi.keys() or psi not in phi_to_psi[phi]:
                                isEntailed = False
                    if isEntailed and psi not in sentences:
                        addOrElimStatement(psi)

        # Processes the dicts built during the above for loop to cover Negation Introduction cases
        for phi in phi_to_psi.keys():
            for psi in phi_to_psi[phi]:
                if phi in phi_to_not_psi.keys() and psi in phi_to_not_psi[phi]:
                    negation = "~" + phi
                    if negation not in sentences:
                        succStatements = list(state[0])
                        succStatements.append((negation, "NI", state[1]))
                        succState = (tuple(succStatements), state[1])
                        results.append((whitespace + "Negation Introduction: " + negation, succState, 1))

        # Implication Introduction and Reiteration
        if proofDepth > 0:
            subproof = []
            # Gets a list of all statements in the most recent subproof
            for i in range(len(statements)):
                if statements[i][2] < proofDepth:
                    subproof = []
                    continue
                elif statements[i][2] > proofDepth:
                    continue
                subproof.append(statements[i])

            # Allows Implication Introduction from the assumption to any reached conclusion
            assumption = subproof[0]
            assert assumption[1] == "A"
            for statement in subproof[1:]:
                # If the antecedent contains an implication or biconditional, we need parens around it
                if "->" in assumption[0]:
                    antecedent = "(" + assumption[0] + ")"
                else:
                    antecedent = assumption[0]
                newImplication = antecedent + " -> " + statement[0]
                if newImplication not in sentences:
                    succStatements = list(state[0])
                    succStatements.append((newImplication, "II", state[1] - 1))
                    succState = (tuple(succStatements), state[1] - 1)
                    II_whitespace = whitespace[2:]
                    results.append((II_whitespace + "Implication Introduction: " + newImplication, succState, 1))

            # Reiteration of statements allowed if we're inside a subproof
            for sentence in sentences:
                if sentence not in subproof or self.goal == sentence:
                    succStatements = list(state[0])
                    succStatements.append((sentence, "R", state[1]))
                    succState = (tuple(succStatements), state[1])
                    results.append((whitespace + "Reiteration: " + sentence, succState, 1))

        # Biconditional Introduction
        # If 'phi -> psi' and 'psi -> phi' for any phi and psi, can derive 'phi <-> psi'
        if "<->" in self.connectiveSet:
            phi_to_psi.update(phi_to_not_psi)   # Merges the 2 implication dicts
            for phi in phi_to_psi.keys():
                psi = phi_to_psi[phi]
                if psi in phi_to_psi.keys() and phi in phi_to_psi[psi]:
                    newBicond = phi + " <-> " + psi
                    if newBicond not in sentences:
                        succStatements = list(state[0])
                        succStatements.append((newBicond, "BI", state[1]))
                        succState = (tuple(succStatements), state[1])
                        results.append((whitespace + "Biconditional Introduction: " + newBicond, succState, 1))

        return results

# Uses a search problem and UCS to find a proof of a goal given premises
def solveFitchProof(premises, goal):
    # The first section formats the input into a usable format and extracts symbols
    symbolSet = set()
    # The statement set is used to keep track of full, parenthesized statements
    statementSet = set()
    connectiveSet = set()

    formattedPremises = []
    if premises != None:
        premiseSymbols = premises.split()
    else:
        premiseSymbols = []
    goalSymbols = goal.split()

    currPremise = 0     # The number of premises added to the list so far
    currUnit = ""       # The formatted premise so far

    inParens = False    # Keeps track of whether inside parentheses
    parensDepth = 0     # Depth of parentheses
    currParenUnit = ""  # The parenthesized unit made so far

    for symbol in premiseSymbols:
        if symbol == "*":
            if currPremise == 0:
                currPremise += 1
                continue
            formattedPremises.append(currUnit)
            currPremise += 1
            currUnit = ""

        elif symbol == "(":
            parensDepth += 1
            inParens = True
            currUnit += "("
        elif symbol == ")":
            parensDepth -= 1
            if parensDepth == 0: inParens = False
            currUnit += ")"
            currParenUnit = ""

        elif symbol == "AND" or symbol == "and" or symbol == "&&" or symbol == "&":
            currUnit += " && "
            connectiveSet.add("&&")
            if inParens: currParenUnit += " && "
        elif symbol == "OR" or symbol == "or" or symbol == "||" or symbol == "|":
            currUnit += " || "
            connectiveSet.add("||")
            if inParens: currParenUnit += " || "
        elif symbol == "NOT" or symbol == "not" or symbol == "~":
            currUnit += "~"
            if inParens: currParenUnit += "~"
        elif symbol == "=>" or symbol == "->":
            currUnit += " -> "
            if inParens: currParenUnit += " -> "
        elif symbol == "<=>" or symbol == "<->":
            currUnit += " <-> "
            connectiveSet.add("<->")
            if inParens: currParenUnit += " <-> "

        else:
            currUnit += symbol
            if inParens: currParenUnit += symbol
            symbolSet.add(symbol)

    # One and a half loops (less than a half, actually)
    if premises != None:
        formattedPremises.append(currUnit)

    currUnit = ""
    for symbol in goalSymbols:
        if symbol == "(":
            parensDepth += 1
            inParens = True
            currUnit += "("
        elif symbol == ")":
            parensDepth -= 1
            if parensDepth == 0: inParens = False
            currUnit += ")"
            currParenUnit = ""

        elif symbol == "AND" or symbol == "and" or symbol == "&&" or symbol == "&":
            currUnit += " && "
            connectiveSet.add("&&")
            if inParens: currParenUnit += " && "
        elif symbol == "OR" or symbol == "or" or symbol == "||" or symbol == "|":
            currUnit += " || "
            connectiveSet.add("||")
            if inParens: currParenUnit += " || "
        elif symbol == "NOT" or symbol == "not" or symbol == "~":
            currUnit += "~"
            if inParens: currParenUnit += "~"
        elif symbol == "=>" or symbol == "->":
            currUnit += " -> "
            if inParens: currParenUnit += " -> "
        elif symbol == "<=>" or symbol == "<->":
            currUnit += " <-> "
            connectiveSet.add("<->")
            if inParens: currParenUnit += " <-> "

        else:
            currUnit += symbol
            if inParens: currParenUnit += symbol
            symbolSet.add(symbol)

    formattedGoal = currUnit

    # Adds the goal to the statement set, since we might want to assume its negation.
    statementSet.add(formattedGoal)

    # Breaks the formatted goal into its parenthesized units and adds each of them to statementSet.
    def genParenUnits(formattedGoal):
        units = []
        stack = []
        for i, c in enumerate(formattedGoal):
            if c == "(":
                stack.append(i)
            elif c == ")" and stack:
                start = stack.pop()
                units.append(formattedGoal[start + 1 : i])
        return units

    units = genParenUnits(formattedGoal)
    for unit in units:
        if unit == "": continue
        statementSet.add(unit)

    # Prints the set of "meaningful statements" from the goal (for testing)
    # print statementSet

    # Prints the processed versions of the premises and goal (for testing)
    '''
    for premise in formattedPremises:
        print "Premise: ", premise
    print "Goal: ", formattedGoal
    '''

    # Solve the search problem with UCS
    ucs = util.UniformCostSearch(verbose = 0)
    ucs.solve(FitchProblem(formattedPremises, formattedGoal, symbolSet, statementSet, connectiveSet))
    proof = ucs.actions

    # Prints the premises, which do not appear in the solved proof's actions.
    for premise in formattedPremises:
        print "Premise: ", premise

    # Prints the proof, step by step.
    for step in proof:
        print step

    return proof


text:
using System;
using System.IO;
using System.Linq;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;

namespace HttpClient
{
	public class Application
	{
		// URL where we fetch the wisdom from
		public const string WisdomUrl = "http://twitter.com/statuses/user_timeline/823083.rss";

		static void Main (string[] args)
		{
			UIApplication.Main (args);
		}

		public static void Busy ()
		{
			UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
		}

		public static void Done ()
		{
			UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
		}

	}

	// The name AppDelegate is referenced in the MainWindow.xib file.
	public partial class AppDelegate : UIApplicationDelegate
	{
		// This method is invoked when the application has loaded its UI and its ready to run
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			window.AddSubview (navigationController.View);

			button1.TouchDown += Button1TouchDown;
			TableViewSelector.Configure (this.stack, new string [] {
				"http  - WebRequest",
				"https - WebRequest",
				"http  - NSUrlConnection"
			});

			window.MakeKeyAndVisible ();

			return true;
		}

		void Button1TouchDown (object sender, EventArgs e)
		{
			// Do not queue more than one request
			if (UIApplication.SharedApplication.NetworkActivityIndicatorVisible)
				return;

			switch (stack.SelectedRow ()){
			case 0:
				new DotNet (this).HttpSample ();
				break;

			case 1:
				new DotNet (this).HttpSecureSample ();
				break;

			case 2:
				new Cocoa (this).HttpSample ();
				break;
			}
		}

		public void RenderRssStream (Stream stream)
		{
			var doc = XDocument.Load (new XmlTextReader (stream));
			var items = doc.XPathSelectElements ("./rss/channel/item/title");
			XElement a = null;

			//
			// Since this is invoked on a separated thread, make sure that
			// we call UIKit only from the main thread.
			//
			InvokeOnMainThread (delegate {
				var table = new UITableViewController ();
				navigationController.PushViewController (table, true);

				// Put the data on a string [] so we can use our existing
				// UITableView renderer for strings.
				string [] entries = new string [items.Count ()];
				int i = 0;
				foreach (var e in items)
					entries [i++] = e.Value;

				TableViewSelector.Configure (table.View as UITableView, entries);
			});
		}

		public void RenderStream (Stream stream)
		{
			var reader = new System.IO.StreamReader (stream);

			InvokeOnMainThread (delegate {
				var view = new UIViewController ();
				var label = new UILabel (new RectangleF (20, 20, 300, 80)){
					Text = "The HTML returned by Google:"
				};
				var tv = new UITextView (new RectangleF (20, 100, 300, 400)){
					Text = reader.ReadToEnd ()
				};
				view.Add (label);
				view.Add (tv);

				navigationController.PushViewController (view, true);
			});
		}

		// This method is required in iPhoneOS 3.0
		public override void OnActivated (UIApplication application)
		{

		}
	}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = isTag;

var babelPluginFlowReactPropTypes_proptype_Target = require('../types').babelPluginFlowReactPropTypes_proptype_Target || require('react').PropTypes.any;

function isTag(target) /* : %checks */{
  return typeof target === 'string';
}
module.exports = exports['default'];


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Acacia tysonii Luehm.

### Remarks
null


text:
<?php
/**
 * Created by Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>.
 * Author: Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>
 * Project: jungle
 * IDE: PhpStorm
 * Date: 23.10.2016
 * Time: 20:06
 */
namespace Jungle\User\Verification {

	/**
	 * Interface InstructorInterface
	 * @package Jungle\User\Verification
	 */
	interface InstructorInterface{

		/**
		 * @param $verificationKey
		 * @param $instruction
		 * @return $this
		 */
		public function setHint($verificationKey, HintInterface $instruction);

		/**
		 * @param $verificationKey
		 * @return HintInterface
		 */
		public function getHint($verificationKey);

		/**
		 * @return HintInterface[]
		 */
		public function getHints();

	}

}


text:
<<<<<<< HEAD
<<<<<<< HEAD

# The cycle GC collector can be executed when any GC-tracked object is
# allocated, e.g. during a call to PyList_New(), PyDict_New(), ...
# Moreover, it can invoke arbitrary Python code via a weakref callback.
# This means that there are many places in the source where an arbitrary
# mutation could unexpectedly occur.

# The example below shows list_slice() not expecting the call to
# PyList_New to mutate the input list.  (Of course there are many
# more examples like this one.)

import weakref

class A(object):
    pass

def callback(x):
    del lst[:]

keepalive = []

for i in range(100):
    lst = [str(i)]
    a = A()
    a.cycle = a
    keepalive.append(weakref.ref(a, callback))
    del a
    while lst:
        keepalive.append(lst[:])
=======

# The cycle GC collector can be executed when any GC-tracked object is
# allocated, e.g. during a call to PyList_New(), PyDict_New(), ...
# Moreover, it can invoke arbitrary Python code via a weakref callback.
# This means that there are many places in the source where an arbitrary
# mutation could unexpectedly occur.

# The example below shows list_slice() not expecting the call to
# PyList_New to mutate the input list.  (Of course there are many
# more examples like this one.)

import weakref

class A(object):
    pass

def callback(x):
    del lst[:]

keepalive = []

for i in range(100):
    lst = [str(i)]
    a = A()
    a.cycle = a
    keepalive.append(weakref.ref(a, callback))
    del a
    while lst:
        keepalive.append(lst[:])
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======

# The cycle GC collector can be executed when any GC-tracked object is
# allocated, e.g. during a call to PyList_New(), PyDict_New(), ...
# Moreover, it can invoke arbitrary Python code via a weakref callback.
# This means that there are many places in the source where an arbitrary
# mutation could unexpectedly occur.

# The example below shows list_slice() not expecting the call to
# PyList_New to mutate the input list.  (Of course there are many
# more examples like this one.)

import weakref

class A(object):
    pass

def callback(x):
    del lst[:]

keepalive = []

for i in range(100):
    lst = [str(i)]
    a = A()
    a.cycle = a
    keepalive.append(weakref.ref(a, callback))
    del a
    while lst:
        keepalive.append(lst[:])
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
require('./dawan');

console.log(process.argv);


text:
"""The Zun Service API."""

import sys

from zun.common import profiler
from zun.common import service as zun_service
import zun.conf

CONF = zun.conf.CONF

def main():
    # Parse config file and command line options, then start logging
    zun_service.prepare_service(sys.argv)

    # Enable object backporting via the conductor
    # TODO(yuanying): Uncomment after rpc services are implemented
    # base.zunObject.indirection_api = base.zunObjectIndirectionAPI()

    # Setup OSprofiler for WSGI service
    profiler.setup('zun-api', CONF.api.host_ip)

    # Build and start the WSGI app
    launcher = zun_service.process_launcher()
    server = zun_service.WSGIService(
        'zun_api',
        CONF.api.enable_ssl_api
    )
    launcher.launch_service(server, workers=server.workers)
    launcher.wait()

if __name__ == '__main__':
    sys.exit(main())


text:
define({
  "_widgetLabel": "Analýza",
  "executeAnalysisTip": "Kliknutím na nástroj analýzy jej spustíte.",
  "noToolTip": "Nebyl nakonfigurován žádný nástroj analýzy.",
  "jobSubmitted": "Odesláno.",
  "jobCancelled": "Zrušeno.",
  "jobFailed": "Selhalo.",
  "jobSuccess": "Úspěšně dokončeno.",
  "executing": "Probíhá zpracování",
  "cancelJob": "Zrušit úlohu analýzy",
  "paramName": "Název parametru",
  "learnMore": "Další informace",
  "outputtip": "Poznámka: Výstupy prvků a tabulek se přidají do mapy v podobě operačních vrstev.",
  "outputSaveInPortal": "Data byla uložena do portálu.",
  "privilegeError": "V rámci role, přiřazené Vašemu uživatelskému účtu, není možné provádět analýzy. Požádejte administrátora Vaší organizace, aby Vám přidělil potřebná práva."
});


text:
@class JDBDatabase;

@interface CollectionsViewController : UITableViewController

@property (strong) JDBDatabase *database;

@end


text:
package io.github.ibuildthecloud.dstack.api.pubsub.subscribe;

import java.io.IOException;

public interface MessageWriter {

    void write(String message, Object writeLock) throws IOException;

}


text:
using PcapDotNet.Packets.IpV4;

namespace PcapDotNet.Packets.Igmp
{
    /// <summary>
    /// RFC 988.
    /// </summary>
    public sealed class IgmpConfirmGroupRequestVersion0Layer : IgmpVersion0Layer
    {
        /// <summary>
        /// The type of the IGMP message of concern to the host-router interaction.
        /// </summary>
        public override IgmpMessageType MessageTypeValue
        {
            get { return IgmpMessageType.ConfirmGroupRequestVersion0; }
        }

        /// <summary>
        /// Zero.
        /// </summary>
        public override uint IdentifierValue
        {
            get { return 0; }
        }

        /// <summary>
        /// Contains a host group address.
        /// </summary>
        public IpV4Address GroupAddress { get; set; }

        /// <summary>
        /// Contains the access key assigned to the host group identified in the Group Address field (zero for public groups).
        /// </summary>
        public ulong AccessKey { get; set; }

        /// <summary>
        /// Contains the access key assigned to the host group identified in the Group Address field (zero for public groups).
        /// </summary>
        public override ulong AccessKeyValue
        {
            get { return AccessKey; }
        }

        internal override byte CodeValue
        {
            get { return 0; }
        }

        internal override IpV4Address GroupAddressValue
        {
            get { return GroupAddress; }
        }
    }
}


text:
def create_csv_with_same_address_schools(schools, csv)
	schools.each do |school|
		address = school.Primary_Address
		matched_item = schools.find { | item | item.Primary_Address == address && item.ATS_System_Code != school.ATS_System_Code }
		school.Same_Address_As_Another_School = true;
		if matched_item != nil
			csv << school
		end
	end
end


text:
import {
  BaseCustomElement,
  reflectPropertiesToAttributes,
  mdlUpgrade,
} from '../utils';

class MaterialCheckbox extends BaseCustomElement {

  createdCallback() {
    this.classList.add('mdl-checkbox', 'mdl-js-checkbox');
    this._input = <input type="checkbox" class="mdl-checkbox__input"/>;
    this._label = {this.label};
    this._onclick = this._onclick.bind(this);
    <this>
      {this._input}
      {this._label}
    </this>
  }

  connectedCallback() {
    this.addEventListener('click', this._onclick);
  }

  disconnectedCallback() {
    this.removeEventListener('click', this._onclick);
  }

  _onclick() {
    if (this.disabled) return;
    this.checked = !this.checked;
  }

  attributeChangedCallback(attrName, oldVal, newVal) {
    this.classList.toggle('mdl-js-ripple-effect', this.ripple);
    this._input.disabled = this.disabled;
    this._label.textContent = this.label;
    if (attrName === 'checked') {
      this._input.checked = this.checked;
      this._input.dispatchEvent(new Event('change',{ bubbles: true }));
    }
  }

}

export default reflectPropertiesToAttributes(
  mdlUpgrade(MaterialCheckbox),
  [
    { propName: 'ripple', propType: Boolean },
    { propName: 'disabled', propType: Boolean },
    { propName: 'checked', propType: Boolean },
    { propName: 'label', propType: String },
  ]
);