text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer-when-downgrade">

<title>Pneumàtica - La vista cansada</title>
<meta name="description" content="">

<link rel="icon" type="image/x-icon" href="https://carlesbellver.github.io/favicon.ico">
<link rel="apple-touch-icon-precomposed" href="https://carlesbellver.github.io/favicon.png">

<link rel="stylesheet" href="https://carlesbellver.github.io/css/light.css?rnd=1602439750" />

<link rel="stylesheet" href="https://carlesbellver.github.io/css/style.css?rnd=1602439750" />

<meta property="og:title" content="Pneumàtica" />
<meta property="og:description" content="Alberto Manguel cita un proverbi islandès citat per William H. Auden: "A cadascú li plau l'olor dels seus pets". Amb això fan referència als nombrosos diaris o dietaris de la literatura universal: la passió pel jo, l'obsessió de parlar de mi, de mi, de mi." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://carlesbellver.github.io/2006/08/22/pneumtica.html" />
<meta property="article:published_time" content="2006-08-22T22:00:00+00:00" />
<meta property="article:modified_time" content="2006-08-22T22:00:00+00:00" />

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Pneumàtica"/>
<meta name="twitter:description" content="Alberto Manguel cita un proverbi islandès citat per William H. Auden: "A cadascú li plau l'olor dels seus pets". Amb això fan referència als nombrosos diaris o dietaris de la literatura universal: la passió pel jo, l'obsessió de parlar de mi, de mi, de mi."/>

    Anar al contingut principal

    La vista cansada

        Informació

        Etiquetes

Pneumàtica

Alberto Manguel cita un proverbi islandès citat per William H. Auden: "A cadascú li plau l'olor dels seus pets". Amb això fan referència als nombrosos diaris o dietaris de la literatura universal: la passió pel jo, l'obsessió de parlar de mi, de mi, de mi. L'egotisme.

Si jo m'invento un diari d'una altra persona com estic fent en el meu proper llibre —Això no és tot, pretesament escrit per un tal Charles Beauvoir entre l'any 2001 i el 2002—, m'estic tirant uns pets seus imaginaris, o són els meus pets de debò i faig com si se'ls hagués tirat un altre jo fictici? Crec que la resposta correcta és la segona.

(Deu ser l'agost, aquesta calor de merda.)

2006-08-22

Carles Bellver Torlà

    <button class="theme-switcher">
        Tema fosc
    </button>

redpajama_set_name: RedPajamaGithub


text:
@echo off

REM Sets up the VistALink connector in Glassfish.

SETLOCAL ENABLEEXTENSIONS

REM Load configuration settings.
call config.bat

echo Building the VistALink connector...
pushd ..\vljRar
REM Must use "call" because gradlew is a batch file.
call gradlew rar
copy build\distributions\vistalink-1.6.rar ..\install\resources\
popd

echo Copying the VistALink configuration file...
copy resources\gov.va.med.vistalink.connectorConfig.xml "%GF_DOMAIN_DIR%\lib\classes\"
IF ERRORLEVEL 1 goto Abort

echo Deploying VistALink connector...
REM Must use "call" because asadmin is a batch file.
call %ASADMIN% deploy resources\vistalink-1.6.rar
IF ERRORLEVEL 1 goto Abort

echo Creating VistALink Connection Pool in Glassfish...
call %ASADMIN% create-connector-connection-pool --raname vistalink-1.6 --connectiondefinition javax.resource.cci.ConnectionFactory --property connectorJndiName=vlj/Asrc500 --description "VistALink connector to Asrc500 VistA" vljAsrc500Pool
IF ERRORLEVEL 1 goto Abort
call %ASADMIN% ping-connection-pool vljAsrc500Pool
IF ERRORLEVEL 1 goto Abort
call %ASADMIN% create-connector-resource --poolname vljAsrc500Pool vlj/Asrc500
IF ERRORLEVEL 1 goto Abort

goto End

:Abort
echo Aborting script due to error.

:End


text:
module.exports = function (length, threshold) {
    var tightPack = 0,
        loosePack = 0,
        tightPackSize = 0,
        loosePackSize = 0;

    tightPackMultiplier = Math.floor(length / threshold);
    tightPackSize = threshold;

    loosePack = length % threshold;

    if (loosePack === 0 && length % 2 === 0) {
        // Swap them to favor loose packing if the length is even
        loosePackSize = threshold - 1;
        loosePack = tightPackMultiplier * tightPackSize;

        // Reset tight pack
        tightPackMultipier = 0;
        tightPackSize      = 0;
    } else if (loosePack % 2 !== 0) {
        // If odd
        tightPackMultiplier--;
        loosePackSize = loosePack + 1;
        loosePack = Math.pow(loosePackSize, 2);
    } else {
        // Nice even remainder
        loosePackSize = loosePack;
    }

    tightPack = tightPackMultiplier * tightPackSize;

    var structure = [];

    var i = 0;
    for (i = 0; i < loosePack; i++) {
        structure.push(loosePackSize);
    }

    for (i = 0; i < tightPack; i++) {
        structure.push(tightPackSize);
    }

    return structure;
};


text:
namespace BashSoft.Exceptions
{
    using System;

    public class InvalidNumberParseException : Exception
    {
        public const string UnableToParseNumber = "The sequence you've written is not a valid number.";

        public InvalidNumberParseException()
            : base(UnableToParseNumber)
        {
        }

        public InvalidNumberParseException(string message)
            : base(message)
        {
        }
    }
}


text:
using System;
using System.Collections.Generic;

namespace MathParserNet
{
    [Serializable]
    public class FunctionArgumentList : List<string>
    {

    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>cam-occ: src/g2m/g2m.hh File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Classes

Files

File List

File Members

Classes

src/g2m/g2m.hh File Reference

#include <vector>

#include <limits.h>

#include <QString>

#include <QProcess>

#include <QObject>

#include <BRepTools.hxx>

#include "canonLine.hh"

#include "machineStatus.hh"

#include "nanotimer.hh"

#include "uio.hh"

Include dependency graph for g2m.hh:

<map name="src_2g2m_2g2m_8hh" id="src_2g2m_2g2m_8hh">
<area shape="rect" id="node15" href="canon_line_8hh.html" title="canonLine.hh" alt="" coords="611,86,709,117"/><area shape="rect" id="node55" href="machine_status_8hh.html" title="machineStatus.hh" alt="" coords="933,166,1059,197"/><area shape="rect" id="node67" href="nanotimer_8hh.html" title="nanotimer.hh" alt="" coords="1327,86,1423,117"/><area shape="rect" id="node72" href="uio_8hh.html" title="uio.hh" alt="" coords="1545,246,1601,277"/><area shape="rect" id="node25" href="canon_8hh.html" title="canon.hh" alt="" coords="548,246,623,277"/><area shape="rect" id="node43" href="tool_8hh.html" title="tool.hh" alt="" coords="207,326,268,357"/></map>

This graph shows which files directly or indirectly include this file:

<map name="src_2g2m_2g2m_8hhdep" id="src_2g2m_2g2m_8hhdep">
<area shape="rect" id="node3" href="g2m_8cc.html" title="src/g2m/g2m.cc" alt="" coords="5,86,120,117"/><area shape="rect" id="node5" href="g2m__threaded_8hh.html" title="src/g2m/g2m_threaded.hh" alt="" coords="144,86,317,117"/><area shape="rect" id="node7" href="g2m__threaded_8cc.html" title="src/g2m/g2m_threaded.cc" alt="" coords="205,166,379,197"/></map>

Go to the source code of this file.

Classes

class  	g2m

 	This class does the high level stuff for creating a model from gcode. It runs the interpreter, and creates a canonLine object for each canonical command generated by the interpreter. It also does error checking and stores the cannonLines. It calls methods on each canonLine object to display it. Eventually it will enable the user to see which gcode line creates which bit of the path, and vice versa.  More...

<address class="footer">Generated by

 1.7.1 </address>


text:
package net.aionstudios.n2d.audio;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioManager {

	public static Clip loadSound(String soundFile) {
	    File f = new File(soundFile);
	    AudioInputStream audioIn = null;
	    Clip clip = null;
	    try {
	    	audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());
	    	clip = AudioSystem.getClip();
			clip.open(audioIn);
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedAudioFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return clip;
	}

	public static void playSound(Clip clip) {
		clip.start();
	}

	public static void stopSound(Clip clip) {
		clip.stop();
	}

}


text:
<?php
use Codeception\Util\Fixtures;

/**
 * Contains tests related to the /experiments/* endpoint.
 * @run Normal: codecept run api ExperimentCest
 * @run Single: codecept run api ExperimentCest:<functionName>$ (note: runs only the test with <functionName>)
 * @run Partial: codecept run api ExperimentCest:<functionName> (note: runs any tests that begin with <functionName>)
 * @run With steps: codecept run api ExperimentCest --steps (can be combined with Single or Partial)
 * @run With debug: codecept run api ExperimentCest --debug (can be combined with Single or Partial)
 *
 * BUG: @test createExperiment: Create a experiment.
 * BUG: @test createExperimentWithoutAuthentication: [NEG] Create a experiment without authentication.
 * @test createExperimentWithWrongAuthentication: [NEG] Create a experiment with wrong authentication.
 * @test getExperiment: Get a experiment.
 * @test getExperimentWithWrongAuthentication: [NEG] Get a experiment with wrong authentication.
 * @test getExperimentsPreview: Gets a list of basic info for experiments that are or have been funding.
 * @test getTagsForExperiments: Get tags that are available for experiments.
 * BUG: @test setTagsForExperiment: Set tags for an experiment.
 */

class ExperimentCest
{
    private function getExperimentId($I)
    {
        try {
            $experimentId = Fixtures::get('experimentId');
        } catch (Exception $e) {
            $experimentId = $this->setExperimentId($I);
        }
        return $experimentId;
    }

    private function setExperimentId($I)
    {
        $I->createExperimentResponse(true);
        $experimentId = $I->decodeResponse($I, 'experiment_id');
        Fixtures::add('experimentId', $experimentId);

        return $experimentId;
    }

    public function _before(ApiTester $I)
    {
    }

    public function _after(ApiTester $I)
    {
    }

    public function createExperiment(ApiTester $I)
    {
        $I->wantTo('succeed at creating a new experiment');

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);

        $I->createExperimentResponse();

        $I->checkResponse($I, 'create_experiment');
        $experimentId = $I->decodeResponse($I, 'experiment_id');
        $I->comment('The ID of the created experiment is: '.$experimentId);

        // Add this experiment to fixtures
        Fixtures::add('experimentId', $experimentId);
    }

    public function createExperimentWithoutAuthentication(ApiTester $I)
    {
        $I->wantTo('fail at creating a new experiment without authentication');

        $I->setRole('creator');
        $I->setStatus('failure');
        $I->setAuthorization(false);

        $I->createExperimentResponse();

        $I->checkResponse($I, 'message');
        $message = $I->decodeResponse($I, 'message');
        $I->comment('Message: '.$message);
    }

    public function createExperimentWithWrongAuthentication(ApiTester $I)
    {
        $I->wantTo('fail at creating a new experiment with wrong authentication');

        $I->setRole('creator');
        $I->setStatus('failure');
        $I->setAuthorization(true, '12345');

        $I->createExperimentResponse();

        $I->checkResponse($I, 'message');
        $message = $I->decodeResponse($I, 'message');
        $I->comment('Message: '.$message);
    }

    public function getExperiment(ApiTester $I)
    {
        $I->wantTo('succeed at getting a experiment');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);

        $I->getExperimentResponse($experimentId);

        $I->checkResponse($I, 'get_experiment');
        $experimentId = $I->decodeResponse($I, 'experiment_id');
        $I->comment('The ID of the retreived experiment is: '.$experimentId);
    }

    public function getExperimentWithWrongAuthentication(ApiTester $I)
    {
        $I->wantTo('fail at getting a experiment with wrong authentication');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('failure');
        $I->setAuthorization(true, '12345');

        $I->getExperimentResponse($experimentId);

        $I->checkResponse($I, 'message');
        $message = $I->decodeResponse($I, 'message');
        $I->comment('Message: '.$message);
    }

    public function getExperimentsPreview(ApiTester $I)
    {
        $I->wantTo('succeed at experiments preview');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('visitor');
        $I->setStatus('success');
        $I->setAuthorization(false);

        $I->getExperimentsPreviewResponse();

        $I->checkResponse($I, 'get_experiments_preview');
        $experimentId = $I->decodeResponse($I, 'preview_experiment_id');
        $I->comment('The ID of the first retrieved experiment is: '.$experimentId);
    }

	public function getExperimentsPreviewWithQuery(ApiTester $I)
	{
		$query = '?place=index&tag=1';

		$I->wantTo('succeed at experiments preview with a query parameter');
		$experimentId = $this->getExperimentId($I);

		$I->setRole('visitor');
		$I->setStatus('success');
		$I->setAuthorization(false);

		$I->getExperimentsPreviewResponse(false, $query);

		$I->checkResponse($I, 'get_experiments_preview');
		$experimentPreviews = $I->decodeResponse($I, 'experiment_previews');
		$I->comment('The number of matching experiments is: '.count($experimentPreviews));
	}

    public function getAvailableTagsForExperiments(ApiTester $I)
    {
        $I->wantTo('succeed at getting available tags for experiments');

        $I->setRole('visitor');
        $I->setStatus('success');
        $I->setAuthorization(false);

        $I->getAvailableTagsForExperimentsResponse();

        $I->checkResponse($I, 'get_tags_for_experiments');
        $tagId = $I->decodeResponse($I, 'tag_id');
        $I->comment('The ID of the first retrieved tag is: '.$tagId);
    }

    public function setTagsForExperiment(ApiTester $I)
    {
        $tagsToSet = [1, 2, 5];

        $I->wantTo('succeed at setting tags for experiment');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);

        $I->setTagsForExperimentResponse($experimentId, ['tags' => $tagsToSet]);

        $I->checkResponse($I, 'message');
        $message = $I->decodeResponse($I, 'message');
        $I->comment('Message: '.$message);

        // test the set tags
        $I->getExperimentResponse($experimentId);
        $tags = $I->decodeResponse($I, 'experiment_tags');

        // convert array to match POST body
        $tempTags = [];
        for ($i = 0; $i <= count($tags)-1; $i++) {
            array_push($tempTags, $tags[$i]['id']);
        };
        $I->assertSame($tagsToSet, $tempTags);
    }

    public function setLinksForExperiment(ApiTester $I)
    {
        $linksToSet[0]['url'] = "http://www.mbl.is";
        $linksToSet[0]['title'] = "The Morning Newspaper";

        $linksToSet[1]['url'] = "https://www.karolinafund.com";
        $linksToSet[1]['title'] = "Karolina Fund";

        $I->wantTo('succeed at setting links for experiment');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);

        $I->setLinksForExperimentResponse($experimentId, ['links' => $linksToSet]);

        $I->checkResponse($I, 'message');
        $message = $I->decodeResponse($I, 'message');
        $I->comment('Message: '.$message);

        // test the set links
        $I->getExperimentResponse($experimentId);
        $links = $I->decodeResponse($I, 'experiment_links');

        $I->assertSame($linksToSet[1]['url'], $links[1]['url']);
        $I->assertSame('www.karolinafund.com', $links[1]['site']);
    }

    public function setGeographicLocation(ApiTester $I)
    {
        $I->wantTo('succeed at changing geographic location for experiment');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);

        $I->setSettingForExperimentResponse($experimentId, ['geographic_location' => 'Helsinki']);

        $I->getExperimentResponse($experimentId);
        $geographicLocation = $I->decodeResponse($I, 'experiment_geographic_location');

        $I->assertSame('Helsinki', $geographicLocation);
    }

    public function moveToNextStage(ApiTester $I)
    {
        $I->wantTo('succeed at moving the experiment to the next stage');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);

        $endpoint = '/experiments/'.$experimentId.'/stagemoves/';

        $I->setHeaders($I);
        $I->getExperimentResponse($experimentId);

        $experimentResponse = $I->decodeResponse($I);
        $orgStage = $experimentResponse['experiment']['stage'];

        $I->sendPOST($endpoint, array());

        $I->getExperimentResponse($experimentId);

        $experimentResponse = $I->decodeResponse($I);

        $I->assertSame($orgStage + 1, $experimentResponse['experiment']['stage']);
    }

    public function setLanguage(ApiTester $I)
    {
        $I->wantTo('succeed at setting custom language for experiment');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);
        $I->setHeaders($I);

        $fields['title'] = array('value' => 'My title ...', 'format' => 'plaintext');
        $I->sendPATCH('/experiments/'.$experimentId.'/language/en/', array('language' => $fields));

        $I->getExperimentResponse($experimentId);
        $response = $I->decodeResponse($I);

        $langVal = $response['experiment']['language']['title']['value'];
        $I->assertSame('My title ...', $langVal);
    }
    public function setCustomLanguage(ApiTester $I)
    {
        $I->wantTo('succeed at setting custom language for experiment');
        $experimentId = $this->getExperimentId($I);

        $I->setRole('creator');
        $I->setStatus('success');
        $I->setAuthorization(true);
        $I->setHeaders($I);

        $fields['my_custom_field'] = array('value' => 'Some value!', 'format' => 'plaintext');
        $I->sendPATCH('/experiments/'.$experimentId.'/custom_language/en/', array('custom_language' => $fields));

        $I->getExperimentResponse($experimentId);
        $response = $I->decodeResponse($I);

        $customLangVal = $response['experiment']['custom_language']['my_custom_field']['value'];
        $I->assertSame('Some value!', $customLangVal);
    }

	public function getTeamEmailsAsAdmin (ApiTester $I)
	{
		$I->wantTo('succeed at getting team emails from experiment index as admin');

		$I->setRole('admin');
		$I->setStatus('success');
		$I->setAuthorization(true);

		$I->getExperimentsPreviewResponse();

		$I->checkResponse($I, 'get_experiments_preview');

		$experimentEmails = $I->decodeResponse($I, 'team_emails');
		$I->assertNotSame(NULL, $experimentEmails);
		$I->comment('The first email in the team is: '.$experimentEmails[0]);
	}

	public function getTeamEmailsAsVisitor (ApiTester $I)
	{
		$I->wantTo('succeed at getting NULL team emails from experiment index as visitor');

		$I->setRole('visitor');
		$I->setStatus('success');
		$I->setAuthorization(false);

		$I->getExperimentsPreviewResponse();

		$I->checkResponse($I, 'get_experiments_preview');

		$experimentEmails = $I->decodeResponse($I, 'team_emails');
		$I->assertSame(NULL, $experimentEmails);
	}

    public function publishUnpublishExperimentAsCreator (ApiTester $I)
	{
		$I->wantTo('succeed at publishing and unpublishing an experiment as creator');

        $experimentId = $this->getExperimentId($I);

		$I->setRole('creator');
		$I->setStatus('success');
		$I->setAuthorization(true);

		$I->publishExperimentResponse($experimentId);

		$I->checkResponse($I, 'message');

		// see if show_in is OK
        $I->getExperimentResponse($experimentId, true);

        $experimentShowIn = $I->decodeResponse($I, 'experiment_show_in');
        $experimentShowInIndex = NULL;
        if(array_key_exists('index', $experimentShowIn)){
            $experimentShowInIndex = $experimentShowIn['index'];
        }
		$I->assertTrue($experimentShowInIndex);

        $I->unpublishExperimentResponse($experimentId);

        $I->checkResponse($I, 'message');

		// see if show_in is OK
        $I->getExperimentResponse($experimentId, true);

        $experimentShowIn = $I->decodeResponse($I, 'experiment_show_in');

        $experimentShowInIndex = NULL;
        if(array_key_exists('index', $experimentShowIn)){
            $experimentShowInIndex = $experimentShowIn['index'];
        }
		$I->assertFalse($experimentShowInIndex);
	}

    public function publishUnpublishExperimentAsAdmin (ApiTester $I)
	{
		$I->wantTo('succeed at publishing and unpublishing an experiment as admin');

        $experimentId = $this->getExperimentId($I);

		$I->setRole('admin');
		$I->setStatus('success');
		$I->setAuthorization(true);

		$I->publishExperimentResponse($experimentId);

        $I->checkResponse($I, 'message');

		// see if show_in is OK
        $I->getExperimentResponse($experimentId, true);

        $experimentShowIn = $I->decodeResponse($I, 'experiment_show_in');

        $experimentShowInIndex = NULL;
        if(array_key_exists('index', $experimentShowIn)){
            $experimentShowInIndex = $experimentShowIn['index'];
        }
		$I->assertTrue($experimentShowInIndex);

        $I->unpublishExperimentResponse($experimentId);

        $I->checkResponse($I, 'message');

		// see if show_in is OK
        $I->getExperimentResponse($experimentId, true);

        $experimentShowIn = $I->decodeResponse($I, 'experiment_show_in');

        $experimentShowInIndex = NULL;
        if(array_key_exists('index', $experimentShowIn)){
            $experimentShowInIndex = $experimentShowIn['index'];
        }
		$I->assertFalse($experimentShowInIndex);
	}

    public function publishUnpublishExperimentAsVisitor (ApiTester $I)
	{
		$I->wantTo('fail at publishing and unpublishing an experiment as visitor');

        $experimentId = $this->getExperimentId($I);

		$I->setRole('visitor');
		$I->setStatus('failure');
		$I->setAuthorization(true);

		$I->publishExperimentResponse($experimentId);

		$I->checkResponse($I, 'message');

        // set published
		$I->publishExperimentResponse($experimentId, true);

        $I->unpublishExperimentResponse($experimentId);

	    $I->checkResponse($I, 'message');
	}
}


text:
@interface CCPShowPhotoVC : UIViewController

@property (nonatomic,strong) NSMutableArray *imageArray;
@property (nonatomic,strong) PHFetchResult *fetchResult;
@property (nonatomic,assign) BOOL isIOS8;
@end


text:
id: 5900f4771000cf542c50ff89
challengeType: 5
title: 'Problem 266: Pseudo Square Root'
forumTopicId: 301915
---

## Description

The divisors of 12 are: 1,2,3,4,6 and 12.
The largest divisor of 12 that does not exceed the square root of 12 is 3.
We shall call the largest divisor of an integer n that does not exceed the square root of n the pseudo square root (PSR) of n.
It can be seen that PSR(3102)=47.

Let p be the product of the primes below 190.
Find PSR(p) mod 1016.

## Instructions

## Tests

```yml
tests:
  - text: <code>euler266()</code> should return 1096883702440585.
    testString: assert.strictEqual(euler266(), 1096883702440585);

```

## Challenge Seed

```js
function euler266() {
  // Good luck!
  return true;
}

euler266();
```

## Solution

```js
// solution required
```


text:
namespace app { namespace Fuse { namespace Animations { struct MixerBase; } } }
namespace app { namespace Uno { namespace UX { struct Property__string; } } }

namespace app {
namespace Fuse {
namespace Animations {

struct MasterProperty__string;

struct MasterProperty__string__uType : ::app::Fuse::Animations::MasterBase__string__uType
{
    ::app::Fuse::Animations::MasterPropertyGet __interface_1;
};

MasterProperty__string__uType* MasterProperty__string__typeof();

void MasterProperty__string___ObjInit_1(MasterProperty__string* __this, ::app::Uno::UX::Property__string* property, ::app::Fuse::Animations::MixerBase* mixerBase);
::uString* MasterProperty__string__get_RestValue(MasterProperty__string* __this);
::uObject* MasterProperty__string__GetPropertyObject(MasterProperty__string* __this);
void MasterProperty__string__OnInactive(MasterProperty__string* __this);

struct MasterProperty__string : ::app::Fuse::Animations::MasterBase__string
{
    ::uStrong< ::app::Uno::UX::Property__string*> Property;

    void _ObjInit_1(::app::Uno::UX::Property__string* property, ::app::Fuse::Animations::MixerBase* mixerBase) { MasterProperty__string___ObjInit_1(this, property, mixerBase); }
    ::uObject* GetPropertyObject() { return MasterProperty__string__GetPropertyObject(this); }
};

}}}

#endif


text:
// <copyright file="ILockTimeRounding.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>

using System;

namespace FubarDev.WebDavServer.Locking
{
    /// <summary>
    /// Interface for classes that want to implement custom rounding
    /// </summary>
    public interface ILockTimeRounding
    {
        /// <summary>
        /// The rounding implementation
        /// </summary>
        /// <param name="dt">The date and time to round</param>
        /// <returns>The new <see cref="DateTime"/></returns>
        DateTime Round(DateTime dt);

        /// <summary>
        /// The rounding implementation
        /// </summary>
        /// <param name="ts">The time span to round</param>
        /// <returns>The new timestamp</returns>
        TimeSpan Round(TimeSpan ts);
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_snowfall"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.jetradarmobile.snowfall.sample.SnowfallActivity">

  <com.jetradarmobile.snowfall.SnowfallView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:snowflakeAlphaMax="255"
    app:snowflakeAlphaMin="150"
    app:snowflakeAngleMax="5"
    app:snowflakeImage="@drawable/snowflake"
    app:snowflakeSizeMax="32dp"
    app:snowflakeSizeMin="8dp"
    app:snowflakeSpeedMax="12"
    app:snowflakeSpeedMin="4"
    app:snowflakesAlreadyFalling="false"
    app:snowflakesFadingEnabled="true"
    app:snowflakesNum="250" />

</FrameLayout>


text:
package org.apache.geode.internal.lang;

/**
 * The ThrowableUtils class is an abstract utility class for working with {@code Throwable}s.
 * <p/>
 *
 * @see java.lang.Throwable
 */
public abstract class ThrowableUtils {

  /**
   * Get the root cause of a {@link Throwable}. Returns the specified {@code throwable} if its
   * {@code getCause} returns null.
   *
   * @param throwable the {@code Throwable} to get the root cause of.
   * @return the root cause of the specified {@code throwable}.
   *
   * @throws NullPointerException if {@code throwable} is null
   */
  public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() == null) {
      return throwable;
    }

    Throwable cause;
    while ((cause = throwable.getCause()) != null) {
      throwable = cause;
    }
    return throwable;
  }

  /**
   * Returns true if the {@link Throwable} or any of its causes as returned by {@code getCause()}
   * are an instance of the specified subclass of {@code Throwable}.
   *
   * @param throwable the {@code Throwable} to check the causes of.
   * @param causeClass the subclass of {@code Throwable} to check for.
   * @return true if any cause of {@code throwable} is an instance of {@code causeClass}.
   *
   * @throws NullPointerException if {@code throwable} is null
   */
  public static boolean hasCauseType(Throwable throwable, Class<? extends Throwable> causeClass) {
    if (causeClass.isInstance(throwable)) {
      return true;
    }

    Throwable cause;
    while ((cause = throwable.getCause()) != null) {
      throwable = cause;
      if (causeClass.isInstance(throwable)) {
        return true;
      }
    }

    return false;
  }

  /**
   * Returns true if the {@link Throwable} or any of its causes contain the specified
   * {@code message}.
   *
   * @param throwable the {@code Throwable} to check the causes of.
   * @param message the {@code Throwable} message to check for.
   * @return true if any cause of {@code throwable} contains the specified {@code message}.
   *
   * @throws NullPointerException if {@code throwable} is null
   */
  public static boolean hasCauseMessage(Throwable throwable, String message) {
    if (throwable.getMessage().contains(message)) {
      return true;
    }

    Throwable cause;
    while ((cause = throwable.getCause()) != null) {
      throwable = cause;
      if (throwable.getMessage().contains(message)) {
        return true;
      }
    }

    return false;
  }

  /**
   * Set the root cause of an exception, if possible, to be newRootCause
   */
  public static void setRootCause(Throwable exception, Throwable newRootCause) {
    Throwable nt = exception;
    while (nt.getCause() != null) {
      nt = nt.getCause();
    }

    // Don't try to set something as it's own cause
    if (nt == newRootCause) {
      return;
    }

    nt.initCause(newRootCause);
  }

}


text:
> Creates an alias for a word when used.
> As the first word of a command.

- Create a generic alias:

`alias {{word}}="{{command}}"`

- Remove an aliased command:

`unalias {{word}}`

- Full list of aliased words:

`alias -p`

- Turn rm an interative command:

`alias {{rm}}="{{rm -i}}"`

- Override la as ls -a:

`alias {{la}}="{{ls -a}}"`


text:
var _ = require('underscore');
var assert = require('assert');
var cowboy = require('../../index');
var fs = require('fs');
var shell = require('shelljs');
var testsUtil = require('../util');
var util = require('util');

var _installModulesDir = util.format('%s/._cowboy_test_install', __dirname);
var _testModulesDir = util.format('%s/test_modules', __dirname);

describe('Modules', function() {

    beforeEach(function(callback) {
        // Ensure we're running with an empty install modules directory
        _clearModules(true);
        testsUtil.reloadContext({'modules': {'dir': _testModulesDir}}, callback);
    });

    after(function(callback) {
        // Reset the context to default configuration after all tests here are complete
        _clearModules(true);
        testsUtil.reloadContext(callback);
    });

    describe('init', function() {
        it('automatically creates the node_modules directory inside the cowboy modules directory', function(callback) {
            testsUtil.reloadContext({'modules': {'dir': _installModulesDir}}, function(err) {
                assert.ok(!err);
                assert.ok(fs.existsSync(util.format('%s/node_modules', _installModulesDir)));
                _clearModules(true);
                return callback();
            });
        });
    });

    describe('install', function() {

        beforeEach(function(callback) {
            // All install tests default to the install modules directory
            return testsUtil.reloadContext({'modules': {'dir': _installModulesDir}}, callback);
        });

        it('installs to the correct modules directory', function(callback) {
            this.timeout(5000);

            // Install the local _cowboy_test1 module
            cowboy.modules.install(util.format('%s/test_modules/node_modules/_cowboy_test1', __dirname), function(err, module) {
                assert.ok(!err);
                assert.ok(fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s/package.json', _installModulesDir, module.timestamp)));
                _validateModuleTest1(module, _installModulesDir, module.timestamp);
                return callback();
            });
        });

        it('installs a new version of the same module when installed twice', function(callback) {
            this.timeout(10000);

            // Install the local _cowboy_test1 module
            cowboy.modules.install(util.format('%s/test_modules/node_modules/_cowboy_test1', __dirname), function(err, firstModule) {
                assert.ok(!err);
                assert.ok(fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s/package.json', _installModulesDir, firstModule.timestamp)));
                _validateModuleTest1(firstModule, _installModulesDir, firstModule.timestamp);

                // Wait a little bit to ensure we get a new millisecond
                cowboy.modules.install(util.format('%s/test_modules/node_modules/_cowboy_test1', __dirname), function(err, secondModule) {
                    assert.ok(!err);

                    // Ensure only the second module exists
                    assert.ok(!fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s/package.json', _installModulesDir, firstModule.timestamp)));
                    assert.ok(fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s/package.json', _installModulesDir, secondModule.timestamp)));
                    _validateModuleTest1(secondModule, _installModulesDir, secondModule.timestamp);
                    return callback();
                });
            });
        });

        it('emits an "install" event after successful installation', function(callback) {
            this.timeout(5000);

            // Install the local _cowboy_test1 module and ensure it emits the event
            var installUri = util.format('%s/test_modules/node_modules/_cowboy_test1', __dirname);
            cowboy.modules.install(installUri);
            cowboy.modules.onModuleInstall('test', function(uri, module, done) {
                cowboy.modules.offModuleInstall('test');
                assert.strictEqual(uri, installUri);
                assert.ok(fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s/package.json', _installModulesDir, module.timestamp)));
                _validateModuleTest1(module, _installModulesDir, module.timestamp);
                done();
                return callback();
            });
        });

        it('installing an invalid module results in an error', function(callback) {
            this.timeout(5000);

            // Install the local _cowboy_invalid_cowboy module
            cowboy.modules.install(util.format('%s/test_modules/node_modules/_cowboy_invalid_cowboy', __dirname), function(err, module) {
                assert.ok(err);
                assert.strictEqual(err.module, '_cowboy_invalid_cowboy');
                return callback();
            });
        });

        it('gives an error when trying to install the core cowboy module', function(callback) {
            this.timeout(5000);

            // Ensure it does not trigger an install event
            function _fail() { assert.fail(); }
            cowboy.modules.onModuleInstall('test', _fail);

            // Try and install the imposter cowboy module
            cowboy.modules.install(util.format('%s/test_modules/node_modules/cowboy', __dirname), function(err, module) {
                assert.ok(err);

                cowboy.modules.offModuleInstall('test');
                return callback();
            });
        });
    });

    describe('uninstall', function() {
        beforeEach(function(callback) {
            // All install tests default to the install modules directory
            return testsUtil.reloadContext({'modules': {'dir': _installModulesDir}}, callback);
        });

        it('removes the module directory when uninstalled', function(callback) {
            this.timeout(5000);

            // Install the local _cowboy_test1 module
            cowboy.modules.install(util.format('%s/test_modules/node_modules/_cowboy_test1', __dirname), function(err, module) {
                assert.ok(!err);
                assert.ok(fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s/package.json', _installModulesDir, module.timestamp)));
                _validateModuleTest1(module, _installModulesDir, module.timestamp);

                // Now uninstall it and ensure it has disappeared from the FS
                cowboy.modules.uninstall('_cowboy_test1', function(err) {
                    assert.ok(!err);
                    assert.ok(!fs.existsSync(util.format('%s/node_modules/_cowboy_test1+%s', _installModulesDir, module.timestamp)));

                    // Ensure the module is not listed
                    cowboy.modules.get('_cowboy_test1', function(err) {
                        assert.ok(err);
                        return callback();
                    });
                });
            });
        });
    });

    describe('ls', function() {
        it('lists an empty modules array from an empty modules directory', function(callback) {
            testsUtil.reloadContext({'modules': {'dir': _installModulesDir}}, function(err) {
                cowboy.modules.ls(function(err, modules) {
                    assert.ok(!err);
                    assert.strictEqual(modules.length, 1);
                    assert.strictEqual(modules[0].npm.name, 'cowboy');
                    return callback();
                });
            });
        });

        it('lists healthy modules while filtering out unhealthy modules', function(callback) {
            cowboy.modules.ls(function(err, modules) {
                assert.ok(!err);
                assert.strictEqual(modules.length, 3);

                var hasTest1 = false;
                var hasTest2 = false;

                _.each(modules, function(module) {
                    assert.ok(module.npm);
                    assert.ok(module.cowboy);
                    if (module.npm.name === '_cowboy_test1') {
                        hasTest1 = true;
                        _validateModuleTest1(module, _testModulesDir);
                    } else if (module.npm.name === '_cowboy_test2') {
                        hasTest2 = true;
                        _validateModuleTest2(module, _testModulesDir);
                    }
                });

                assert.ok(hasTest1, 'Expected to get test1 module');
                assert.ok(hasTest2, 'Expected to get test2 module');

                return callback();
            });
        });

        it('ignores the core cowboy module in its module loading directory if it accidentally exists', function(callback) {
            this.timeout(5000);

            testsUtil.reloadContext({'modules': {'dir': _installModulesDir}}, function(err) {
                assert.ok(!err);

                // Install our imposter cowboy module and ensure the installed version of the module still comes from our runtime cowboy module
                cowboy.modules.install(util.format('%s/test_modules/node_modules/cowboy', __dirname), function(err, module) {
                    assert.ok(err);

                    cowboy.modules.ls(function(err, modules) {
                        assert.ok(!err);

                        // Ensure we have a cowboy module and it is the legitimate version, not the imposter installed version
                        var cowboyModule = _.find(modules, function(module) { return (module.npm.name === 'cowboy'); });
                        assert.ok(cowboyModule);
                        assert.strictEqual(require(util.format('%s/../../package', __dirname)).version, cowboyModule.npm.version);
                        return callback();
                    });
                });
            });
        });
    });

    describe('get', function() {
        it('gets a valid module', function(callback) {
            cowboy.modules.get('_cowboy_test1', function(err, module) {
                assert.ok(!err);
                _validateModuleTest1(module, _testModulesDir);
                return callback();
            });
        });

        it('returns an error for an invalid and non-existing module', function(callback) {
            cowboy.modules.get('_cowboy_invalid_cowboy', function(err) {
                assert.ok(err);
                assert.strictEqual(err.module, '_cowboy_invalid_cowboy');
                cowboy.modules.get('_cowboy_invalid_package', function(err) {
                    assert.ok(err);
                    assert.strictEqual(err.module, '_cowboy_invalid_package');
                    cowboy.modules.get('non_existing_module', function(err) {
                        assert.ok(err);
                        assert.strictEqual(err.module, 'non_existing_module');
                        return callback();
                    });
                });
            });
        });
    });
});

var _validateModuleTest1 = function(module, moduleDir, timestamp) {
    assert.ok(module.npm);
    assert.ok(module.cowboy);

    var expectedRoot = util.format('%s/node_modules/_cowboy_test1', moduleDir);
    if (timestamp) {
        expectedRoot = util.format('%s/node_modules/_cowboy_test1+%s', moduleDir, timestamp);
    }

    assert.strictEqual(module.root, expectedRoot);
    assert.strictEqual(module.npm.name, '_cowboy_test1');
    assert.strictEqual(module.npm.version, '0.0.1');
    assert.ok(!module.cowboy.plugins);
};

var _validateModuleTest2 = function(module, moduleDir, timestamp) {
    assert.ok(module.npm);
    assert.ok(module.cowboy);

    var expectedRoot = util.format('%s/node_modules/_cowboy_test2', moduleDir);
    if (timestamp) {
        expectedRoot = util.format('%s/node_modules/_cowboy_test2+%s', moduleDir, timestamp);
    }

    assert.strictEqual(module.root, util.format('%s/node_modules/_cowboy_test2', moduleDir));
    assert.strictEqual(module.npm.name, '_cowboy_test2');
    assert.strictEqual(module.npm.version, '0.0.1');
    assert.ok(!module.cowboy.plugins);
};

var _clearModules = function(includeNodeModules) {
    if (includeNodeModules) {
        shell.rm('-rf', util.format('%s/node_modules', _installModulesDir));
    } else {
        shell.rm('-rf', util.format('%s/node_modules/*', _installModulesDir));
    }
};


text:
import leon.lang._

object LocalScope {
  sealed abstract class Color
  case class Red() extends Color
  case class Black() extends Color

  sealed abstract class Tree
  case class Empty() extends Tree
  case class Node(color: Color, left: Tree, value: Int, right: Tree) extends Tree

  sealed abstract class OptionInt
  case class Some(v : Int) extends OptionInt
  case class None() extends OptionInt

  def blackBalanced(t : Tree) : Boolean = t match {
    case Node(_, l, v, r) => {
      // hide r
    	val r: Int = 5
    	//val f: ((Int, Int) => Boolean) = (x: Int, y: Int) => false

	    Some(5) match {
	      case Some(newInt) => hole(0)
	    }

    	false
    }

    case Empty() => true
  }
}


text:
class ReviewAuditCertificatePolicy < ApplicationPolicy
  def create?
    fa = record.form_answer
    admin? || subject.lead?(fa) || subject.primary?(fa)
  end
end


text:
//
// Created by Aman LaChapelle on 5/25/17.
//
// pytorch_inference
// Copyright (c) 2017 Aman LaChapelle
// Full license at pytorch_inference/LICENSE.txt
//

#ifndef PYTORCH_INFERENCE_CONVOLUTION_HPP
#define PYTORCH_INFERENCE_CONVOLUTION_HPP

// Python
#include <Python.h>
#include <numpy/ndarraytypes.h>

// STL
#include <assert.h>
#include <string>
#include <vector>

// Project
#include "Layer.hpp"
#include "../functional/convolution.hpp"
#include "../py_object.hpp"
#include "../utils.hpp"

namespace pytorch {
  /**
   * @class Conv2d "include/layers.hpp"
   * @file "include/layers.hpp"
   * @brief Equivalent to Conv2d in pytorch.
   *
   * Implements the forward pass for pytorch's nn.Conv2d module. Note that clearly something needs to happen to
   * get the tensors from python to C++, but I've tried to take care of this through the import constructor.
   */
  class Conv2d : public Layer {
  private:
    tensor filters;
    tensor bias;
    conv_params_t params;
    pycpp::py_object utils;
    bool has_bias = false;

  public:
    /**
     * @brief Constructs a Conv2d object given parameters, filters, and bias tensors.
     *
     * @param params The convolution parameters like filter size, stride, and padding.
     * @param filters The trained filter tensors. For those comfortable with Py_Cpp.
     * @param bias The trained bias tensors. For those comfortable with Py_Cpp.
     */
    explicit Conv2d(const conv_params_t &params,
           const tensor &filters,
           const tensor &bias) : params(params), has_bias(true) {
      int Cout = filters.data().dims(3); int Cin = filters.data().dims(2);
      this->filters = tensor(af::unwrap(filters.data(), params.filter_x, params.filter_y, params.filter_x, params.filter_y, 0, 0));
      this->filters = af::reorder(this->filters.data(), 3, 0, 2, 1);
      this->filters = af::moddims(this->filters.data(), Cout, this->filters.data().dims(1)*Cin); // comment to use nested for functional
      internal::check_size(bias.data().dims(2), Cout, __func__);
      this->bias = bias;
    }

    /**
     * @brief Constructs a Conv2d object given the filenames and sizes of the requisite tensors. Also requires
     * convolution parameters like the other constructor.
     *
     * @param params The convolution parameters like filter size, stride, and padding.
     * @param filters_filename The file where the filters tensor is saved. Will be loaded with numpy.load(filename).
     * @param filt_dims The dimensions of the filter tensor in pytorch convention - (batch, channels, h, w)
     * @param bias_filename The file where the bias tensor is saved. Will be loaded with numpy.load(filename).
     * @param bias_dims The dimensions of the bias tensor in pytorch convention - (batch, channels, h, w)
     * @param python_home Where the utility scripts are - holds the loading script necessary to load up the tensors.
     */
    explicit Conv2d(const conv_params_t &params,
           const std::string &filters_filename = "",
           const std::vector<int> &filt_dims = {},
           const std::string &bias_filename = "",
           const std::vector<int> &bias_dims = {},
           const std::string &python_home = "../scripts") : params(params),
                                                            utils("utils", python_home) {

      if (!filters_filename.empty()){
        this->add_filters(filters_filename, filt_dims);
      }

      if (!bias_filename.empty()){
        this->has_bias = true;
        this->add_bias(bias_filename, bias_dims);
      }

    }

    /**
     * @brief Copy constructor, constructs a Conv2d object that is exactly a copy of the argument.
     *
     * @param other Another Conv2d object.
     */
    Conv2d(const Conv2d &other){
      filters = other.filters;
      bias = other.bias;
      params = other.params;
    }

    /**
     * @brief Destructor - for now trivial, may need to take on some functionality.
     * TODO: add filter/bias saving on destroy, corresponding constructor to remake layer
     */
    virtual ~Conv2d() = default;

    /**
     * @brief Read in filters from a file given here if it wasn't passed to the constructor. Overwrites
     * current contents of this->filters.
     *
     * @param filters_filename The file where the filters tensor is saved. Will be loaded with numpy.load(filename).
     * @param filt_dims The dimensions of the filter tensor in pytorch convention - (batch, channels, h, w)
     */
    inline void add_filters(const std::string &filters_filename,
                            const std::vector<int> &filt_dims){
      assert(filt_dims.size() > 0);
      _object *filts = utils("load_array", {pycpp::to_python(filters_filename)}, {});
      assert(filts);
      filters = internal::from_numpy(reinterpret_cast<PyArrayObject *>(filts), filt_dims.size(), filt_dims);
      int Cout = filters.data().dims(3); int Cin = filters.data().dims(2);
      filters = af::unwrap(filters.data(), params.filter_x, params.filter_y, params.filter_x, params.filter_y, 0, 0);
      filters = af::reorder(filters.data(), 3, 0, 2, 1);
      filters = af::moddims(filters.data(), Cout, filters.data().dims(1)*Cin); // comment to use nested for functional
    }

    /**
     * @brief Read in bias from a file given here if it wasn't passed to the constructor. Overwrites
     * current contents of this->bias.
     *
     * @param bias_filename The file where the bias tensor is saved. Will be loaded with numpy.load(filename).
     * @param bias_dims The dimensions of the bias tensor in pytorch convention - (batch, channels, h, w)
     */
    inline void add_bias(const std::string &bias_filename,
                         const std::vector<int> &bias_dims){
      assert(bias_dims.size() > 0);
      _object *bs = utils("load_array", {pycpp::to_python(bias_filename)}, {});
      assert(bs);
      bias = internal::from_numpy(reinterpret_cast<PyArrayObject *>(bs), bias_dims.size(), bias_dims);
      internal::check_size(bias.data().dims(2), filters.data().dims(0), __func__);
      this->has_bias = true;
    }

    /**
     * @brief Forward function, takes data and performs the Conv2d operation using the already-initialized
     * filters and bias tensors
     *
     * @param input Input data size (h_in, w_in, Cin, batch)
     * @return Convolved data size (h_out, w_out, Cout, batch)
     */
    inline std::vector<tensor> forward(const std::vector<tensor> &input){
      return {functional::conv2d(params, input[0], filters, bias, this->has_bias)};
    }

    /**
     * @brief Forward function, takes data and performs the Conv2d operation using the already-initialized
     * filters and bias tensors
     *
     * @param input Input data size (h_in, w_in, Cin, batch)
     * @return Convolved data size (h_out, w_out, Cout, batch)
     */
    inline std::vector<tensor> operator()(const std::vector<tensor> &input){
      return {functional::conv2d(params, input[0], filters, bias, this->has_bias)};
    }

  };
} // pytorch

#endif //PYTORCH_INFERENCE_CONVOLUTION_HPP


text:
                         Control De Clientes

                              <a href="<?=base_url()?>home">Dashboard

                              <a href="<?=base_url()?>clients/InactiveClients"> Clientes

                               Editar Cliente

              <?= form_open('clients/updateInactiveClient/'.$id); ?>
                <?php
                    if ($client){
                       ?>

                            NameClient:
                            <?= form_error('clientname') ?>
                            <input type="text" size="20" id="clientname" name="clientname" placeholder="Name Client" class="form-clientname form-control" value="<?= $client->nameClient?>" required/>

                            Status:
                            <?= form_error('status') ?>
                            <select name="status"  class="form-control" required>
                                <option value="Activo">Activo</option>
                                <option value="Inactivo">Inactivo</option>
                          </select>

                            Sector:
                            <?= form_error('sector') ?>
                            <input type="text" size="20" id="sector" name="typeSector" placeholder="Sector" class="form-sector form-control" value="<?= $client->typeSector?>" required/>

                         <button type="submit" class="btn btn-primary">Save</button>

                 </form>
                    <?php
                    }else{
                        redirect('clients/inactiveClients');
                    }
                ?>


text:
{% extends 'base.html' %}
{% load render_table from django_tables2 %}

{% block breadcrumb %}

Projects

{{ object.name }}

{% endblock breadcrumb %}

{% block content %}

Project {{ object.name }}

                Edit Project
                Delete Project

                    Description: {{ object.description }}

Deployments: {{ object.get_deployment_count }}

Invalidate tasks cache

                    {% for stage in stages %}

                            {{ stage.stage_configurations.count }}
                            {{ stage.name }}

                    {% empty %}

No stage configured yet

                    {% endfor %}

                        Add Stage

                        Project Configuration

                    {% render_table configurations %}

                        Add Configuration

                        Stages

                    {% render_table stage_table %}

                        Add Stage

                        Project Hooks

                    {% render_table hook_table %}

                        Add Hook

                        Recent Deployments

                    {% render_table deployment_table %}

{% endblock content %}


text:
"""
Example script with basic usage of the EMUS package for MBAR estimates
using the iterative EMUS solver.
(for simplicity we have moved all plotting commands to the bottom of the script).
Please note that the demo requires matplotlib, which is not a dependency in the emus package to keep things lightweight.
"""
import numpy as np
from emus import usutils as uu
from emus import emus, iter_avar
import matplotlib.pyplot as plt

# Define Simulation Parameters
T = 310                             # Temperature in Kelvin
k_B = 1.9872041E-3                  # Boltzmann factor in kcal/mol
kT = k_B * T
meta_file = 'cv_meta.txt'         # Path to Meta File
dim = 1                             # 1 Dimensional CV space.
period = 360                        # Dihedral Angles periodicity
nbins = 60                          # Number of Histogram Bins.

# Load data
psis, cv_trajs, neighbors = uu.data_from_meta(
    meta_file, dim, T=T, k_B=k_B, period=period)

# Calculate the partition function for each window
z_iter, F_iter = emus.calculate_zs(psis, neighbors=neighbors, n_iter=5)

plt.plot(np.arange(len(z_iter)), -np.log(z_iter), label='Window Free Energies')
plt.xlabel(r'Window Index')
plt.ylabel('Window FE Unitless')
plt.legend()
plt.show()

domain = ((-180.0, 180.))            # Range of dihedral angle values
# Calculate new PMF
iterpmf, edges = emus.calculate_pmf(
    cv_trajs, psis, domain, nbins=nbins, z=z_iter, kT=kT)

fdata = [((traj > 25) & (traj < 100)).flatten() for traj in cv_trajs]
prob_C7ax_iter = emus.calculate_obs(
    psis, z_iter, fdata, use_iter=True)  # Just calculate the probability

fe_C7ax = -np.log(prob_C7ax_iter)
fe_C7ax_err, fe_C7ax_contribs, fe_C7ax_taus = iter_avar.calc_log_avg_ratio(psis, z_iter, fdata, neighbors=neighbors)

avg_pmf, edges = emus.calculate_avg_on_pmf(
    cv_trajs, psis, (-180, 180), z_iter, fdata, use_iter=True, nbins=nbins)

# ~~~ Data Output Section ~~~ #
# Plot the EMUS, Iterative EMUS pmfs.
pmf_centers = (edges[0][1:]+edges[0][:-1])/2.
plt.figure()
plt.plot(pmf_centers, iterpmf, label='Iter EMUS PMF')
plt.xlabel(r'$\psi$ dihedral angle')
plt.ylabel('Unitless FE')
plt.legend()
plt.title('Iterative EMUS potentials of Mean Force')
plt.show()

# Print the C7 ax basin probability
print("Iterative EMUS Free Energy of C7ax basin is %f +/- %f" % (fe_C7ax, fe_C7ax_err))

fig, (ax1, ax2) = plt.subplots(2)
ax1.semilogy(np.arange(len(z_iter)), fe_C7ax_contribs, c="C0")
ax2.semilogy(np.arange(len(z_iter)), fe_C7ax_taus, c="C1")
ax2.set_xlabel(r'Window Index')
ax1.set_ylabel('Contribs to Error')
ax2.set_ylabel('ACTimes')
plt.show()


text:
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

package org.uma.jmetal.util.experiment.component;

import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.experiment.ExperimentComponent;
import org.uma.jmetal.util.experiment.Experiment;
import org.uma.jmetal.util.experiment.util.MultithreadedExperimentExecutor;
import org.uma.jmetal.util.experiment.util.TaggedAlgorithm;

import java.io.File;

/**
 * This class executes the algorithms the have been configured with a instance of class
 * {@link Experiment}. For each combination algorithm + problem + runId an instance
 * of {@link TaggedAlgorithm} is created and inserted as a task of a {@link MultithreadedExperimentExecutor},
 * which runs all the algorithms.
 *
 * The result of the execution is a pair of files FUNrunId.tsv and VARrunID.tsv per experiment, which are
 * stored in the directory {@link Experiment #getExperimentBaseDirectory()}/algorithmName/problemName.
 *
 * @author Antonio J. Nebro <antonio@lcc.uma.es>
 */
public class ExecuteAlgorithms<S extends Solution<?>, Result> implements ExperimentComponent {
  private Experiment<S, Result> experiment;

  /** Constructor */
  public ExecuteAlgorithms(Experiment<S, Result> configuration) {
    this.experiment = configuration ;
  }

  @Override
  public void run() {
    JMetalLogger.logger.info("ExecuteAlgorithms: Preparing output directory");
    prepareOutputDirectory() ;

    MultithreadedExperimentExecutor<S, Result> parallelExecutor ;

    parallelExecutor = new MultithreadedExperimentExecutor<S, Result>(experiment.getNumberOfCores()) ;
    parallelExecutor.start(this);

    for (TaggedAlgorithm<Result> algorithm : experiment.getAlgorithmList()) {
      //for (int i = 0; i < experiment.getIndependentRuns(); i++) {
      //TaggedAlgorithm<Result> clonedAlgorithm = SerializationUtils.clone(algorithm) ;
      parallelExecutor.addTask(new Object[]{algorithm, algorithm.getRunId(), experiment});
      //}
    }
    parallelExecutor.parallelExecution();
    parallelExecutor.stop();  }

  private void prepareOutputDirectory() {
    if (experimentDirectoryDoesNotExist()) {
      createExperimentDirectory() ;
    }
  }

  private boolean experimentDirectoryDoesNotExist() {
    boolean result;
    File experimentDirectory;

    experimentDirectory = new File(experiment.getExperimentBaseDirectory());
    if (experimentDirectory.exists() && experimentDirectory.isDirectory()) {
      result = false;
    } else {
      result = true;
    }

    return result;
  }

  private void createExperimentDirectory() {
    File experimentDirectory;
    experimentDirectory = new File(experiment.getExperimentBaseDirectory());

    if (experimentDirectory.exists()) {
      experimentDirectory.delete() ;
    }

    boolean result ;
    result = new File(experiment.getExperimentBaseDirectory()).mkdirs() ;
    if (!result) {
      throw new JMetalException("Error creating experiment directory: " +
          experiment.getExperimentBaseDirectory()) ;
    }
  }
}


text:
/**
 @file SplayDemo.java
 @author Morgan McGuire, morgan@cs.brown.edu
 @created 2002-09-15
 @edited  2002-09-16
 */

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.*;

/**
 @file SplayDemo.java
 @author Morgan McGuire, morgan@cs.brown.edu
 @created 2002-09-15
 @edited  2002-09-16
 */

public class SplayDemo extends JApplet {

    /** The demo can maintain multiple trees to show balance
        differences. */
    BinaryTree tree[]      = new BinaryTree[2];

    /** Part of the UI */
    JComboBox mouseAction = null;

    public SplayDemo() {
        tree[0] = new BinaryTree(null);
        tree[1] = new SplayTree(null);
        build3Trees();

        JPanel vbox = new JPanel();
        vbox.setLayout(new BorderLayout());
        vbox.setBackground(java.awt.Color.white);

        JPanel trees = new JPanel();
        trees.setBackground(java.awt.Color.white);

        trees.add(new TreeDisplay(this, tree[0], "Binary Tree"));
        trees.add(new TreeDisplay(this, tree[1], "Splay Tree"));
        vbox.add(trees, BorderLayout.CENTER);

        JPanel controls = new JPanel();
        controls.add(new JLabel("Mouse click"));
        controls.setBackground(java.awt.Color.white);

        mouseAction =
            new JComboBox(
               new String[]{"accesses", "rotates", "deletes", "inserts"});
        controls.add(mouseAction);
        controls.add(new JLabel("a node.   Pre-built trees: "));

        {
            JButton button = new JButton("1");
            button.setToolTipText("Build a tree for executing a case 1 splay step.");
            button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {build1Trees(); repaint();}
                });
            controls.add(button);
        }

        {
            JButton button = new JButton("2");
            button.setToolTipText("Build a tree for executing a case 2 splay step.");
            button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {build2Trees(); repaint();}
                });
            controls.add(button);
        }

        {
            JButton button = new JButton("3");
            button.setToolTipText("Build a tree for executing a case 3 splay step.");
            button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {build3Trees(); repaint();}
                });
            controls.add(button);
        }

        {
            JButton button = new JButton("?");
            button.setToolTipText("Build a random tree.");
            button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {buildRandomTrees(); repaint();}
                });
            controls.add(button);
        }

        vbox.add(controls, BorderLayout.SOUTH);

        setContentPane(vbox);

        mouseAction.setSelectedIndex(0);
    }

    private void buildRandomTrees() {
        for (int t = 0; t < tree.length; ++t) {
            tree[t].setRoot(null);
        }

        for (int j = 0; j < 10; ++j) {
            int key = (int)(Math.random() * 20);
            for (int t = 0; t < tree.length; ++t) {
                tree[t].insert(key);
            }
        }
    }

    private void build1Trees() {
        // Build case 1 trees

        //                4
        //             2    5
        //           1   3
        for (int t = 0; t < tree.length; ++t) {
            tree[t].setRoot(
                            new Node(4,
                                     new Node(2, new Node(1), new Node(3)),
                                     new Node(5)));
        }
    }

    private void build2Trees() {
        // Build case 2 trees

        //                7
        //             5     8
        //           3   6
        //         1  4

        for (int t = 0; t < tree.length; ++t) {
            tree[t].setRoot(
               new Node(7,
                   new Node(5, new Node(3, new Node(1), new Node(4)), new Node(6)),
                   new Node(8)));
        }
    }

    private void build3Trees() {
        // Build case 3 trees

        //                3
        //             1     8
        //                 5   9
        //               4   7

        for (int t = 0; t < tree.length; ++t) {
            tree[t].setRoot(
               new Node(3,
                        new Node(1),
                        new Node(8, new Node(5, new Node(4), new Node(7)), new Node(9))));
        }
    }

    private void buildTrees() {
        //
        //                4
        //           2        8
        //         1   3    6
        //                5   7
        //
        for (int t = 0; t < tree.length; ++t) {
            tree[t].setRoot(
            new Node(4,
                     new Node(2, new Node(1), new Node(3)),
                     new Node(8, new Node(6, new Node(5), new Node(7)))));
        }
    }

    /**
       Invoked by the display when the user clicks the left
       mouse button on a node.  -1 means no node was selected.
       Repaints the whole applet.
     */
    public void leftMouse(int key, TreeDisplay display) {
        System.out.println("---------------------------------");

        String action = (String)mouseAction.getSelectedItem();

        if (action == "accesses") {
            for (int t = 0; t < tree.length; ++t) {
                tree[t].get(key);
            }
        } else if (action == "rotates") {
            // Rotate just that tree
            display.tree.rotate(key);
        } else if (action == "deletes") {
            // Delete from all trees
            for (int t = 0; t < tree.length; ++t) {
                tree[t].delete(key);
            }
        } else if (action == "inserts") {
            for (int i = 0; i < 100; ++i) {
                int k = (int)(Math.random() * 20);
                // Note that tree 0 is the binary tree, so the get
                // won't trigger a splay.
                if (tree[0].get(k) == null) {
                    for (int t = 0; t < tree.length; ++t) {
                        tree[t].insert(k);
                    }
                    break;
                }
            }
        }

        for (int t = 0; t < tree.length; ++t) {
            tree[t].debugCheckIntegrity();
        }

        repaint();
    }

    public static void main(String arg[]) {
        JFrame frame = new JFrame("Splay Tree Demo");
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });

        SplayDemo demo = new SplayDemo();
        frame.setContentPane(demo);
        frame.pack();
        frame.setVisible(true);
    }
}


text:
#include <grpc/support/port_platform.h>

#ifdef GPR_WINSOCK_SOCKET

#include <grpc/support/log.h>
#include <grpc/support/thd.h>

#include "src/core/iomgr/timer_internal.h"
#include "src/core/iomgr/iomgr_internal.h"
#include "src/core/iomgr/iocp_windows.h"
#include "src/core/iomgr/pollset.h"
#include "src/core/iomgr/pollset_windows.h"

gpr_mu grpc_polling_mu;
static grpc_pollset_worker *g_active_poller;
static grpc_pollset_worker g_global_root_worker;

void grpc_pollset_global_init() {
  gpr_mu_init(&grpc_polling_mu);
  g_active_poller = NULL;
  g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
      g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev =
          &g_global_root_worker;
}

void grpc_pollset_global_shutdown() { gpr_mu_destroy(&grpc_polling_mu); }

static void remove_worker(grpc_pollset_worker *worker,
                          grpc_pollset_worker_link_type type) {
  worker->links[type].prev->links[type].next = worker->links[type].next;
  worker->links[type].next->links[type].prev = worker->links[type].prev;
  worker->links[type].next = worker->links[type].prev = worker;
}

static int has_workers(grpc_pollset_worker *root,
                       grpc_pollset_worker_link_type type) {
  return root->links[type].next != root;
}

static grpc_pollset_worker *pop_front_worker(
    grpc_pollset_worker *root, grpc_pollset_worker_link_type type) {
  if (has_workers(root, type)) {
    grpc_pollset_worker *w = root->links[type].next;
    remove_worker(w, type);
    return w;
  } else {
    return NULL;
  }
}

static void push_front_worker(grpc_pollset_worker *root,
                              grpc_pollset_worker_link_type type,
                              grpc_pollset_worker *worker) {
  worker->links[type].prev = root;
  worker->links[type].next = worker->links[type].prev->links[type].next;
  worker->links[type].prev->links[type].next =
      worker->links[type].next->links[type].prev = worker;
}

/* There isn't really any such thing as a pollset under Windows, due to the
   nature of the IO completion ports. We're still going to provide a minimal
   set of features for the sake of the rest of grpc. But grpc_pollset_work
   won't actually do any polling, and return as quickly as possible. */

void grpc_pollset_init(grpc_pollset *pollset) {
  memset(pollset, 0, sizeof(*pollset));
  pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
      pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
          &pollset->root_worker;
}

void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
                           grpc_closure *closure) {
  pollset->shutting_down = 1;
  grpc_pollset_kick(pollset, GRPC_POLLSET_KICK_BROADCAST);
  if (!pollset->is_iocp_worker) {
    grpc_exec_ctx_enqueue(exec_ctx, closure, true, NULL);
  } else {
    pollset->on_shutdown = closure;
  }
}

void grpc_pollset_destroy(grpc_pollset *pollset) {}

void grpc_pollset_reset(grpc_pollset *pollset) {
  GPR_ASSERT(pollset->shutting_down);
  GPR_ASSERT(
      !has_workers(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET));
  pollset->shutting_down = 0;
  pollset->is_iocp_worker = 0;
  pollset->kicked_without_pollers = 0;
  pollset->on_shutdown = NULL;
}

void grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
                       grpc_pollset_worker *worker, gpr_timespec now,
                       gpr_timespec deadline) {
  int added_worker = 0;
  worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
      worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
          worker->links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
              worker->links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev = NULL;
  worker->kicked = 0;
  worker->pollset = pollset;
  gpr_cv_init(&worker->cv);
  if (grpc_timer_check(exec_ctx, now, &deadline)) {
    goto done;
  }
  if (!pollset->kicked_without_pollers && !pollset->shutting_down) {
    if (g_active_poller == NULL) {
      grpc_pollset_worker *next_worker;
      /* become poller */
      pollset->is_iocp_worker = 1;
      g_active_poller = worker;
      gpr_mu_unlock(&grpc_polling_mu);
      grpc_iocp_work(exec_ctx, deadline);
      grpc_exec_ctx_flush(exec_ctx);
      gpr_mu_lock(&grpc_polling_mu);
      pollset->is_iocp_worker = 0;
      g_active_poller = NULL;
      /* try to get a worker from this pollsets worker list */
      next_worker = pop_front_worker(&pollset->root_worker,
                                     GRPC_POLLSET_WORKER_LINK_POLLSET);
      if (next_worker == NULL) {
        /* try to get a worker from the global list */
        next_worker = pop_front_worker(&g_global_root_worker,
                                       GRPC_POLLSET_WORKER_LINK_GLOBAL);
      }
      if (next_worker != NULL) {
        next_worker->kicked = 1;
        gpr_cv_signal(&next_worker->cv);
      }

      if (pollset->shutting_down && pollset->on_shutdown != NULL) {
        grpc_exec_ctx_enqueue(exec_ctx, pollset->on_shutdown, true, NULL);
        pollset->on_shutdown = NULL;
      }
      goto done;
    }
    push_front_worker(&g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL,
                      worker);
    push_front_worker(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET,
                      worker);
    added_worker = 1;
    while (!worker->kicked) {
      if (gpr_cv_wait(&worker->cv, &grpc_polling_mu, deadline)) {
        break;
      }
    }
  } else {
    pollset->kicked_without_pollers = 0;
  }
done:
  if (!grpc_closure_list_empty(exec_ctx->closure_list)) {
    gpr_mu_unlock(&grpc_polling_mu);
    grpc_exec_ctx_flush(exec_ctx);
    gpr_mu_lock(&grpc_polling_mu);
  }
  if (added_worker) {
    remove_worker(worker, GRPC_POLLSET_WORKER_LINK_GLOBAL);
    remove_worker(worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
  }
  gpr_cv_destroy(&worker->cv);
}

void grpc_pollset_kick(grpc_pollset *p, grpc_pollset_worker *specific_worker) {
  if (specific_worker != NULL) {
    if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
      for (specific_worker =
               p->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next;
           specific_worker != &p->root_worker;
           specific_worker =
               specific_worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next) {
        specific_worker->kicked = 1;
        gpr_cv_signal(&specific_worker->cv);
      }
      p->kicked_without_pollers = 1;
      if (p->is_iocp_worker) {
        grpc_iocp_kick();
      }
    } else {
      if (p->is_iocp_worker && g_active_poller == specific_worker) {
        grpc_iocp_kick();
      } else {
        specific_worker->kicked = 1;
        gpr_cv_signal(&specific_worker->cv);
      }
    }
  } else {
    specific_worker =
        pop_front_worker(&p->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
    if (specific_worker != NULL) {
      grpc_pollset_kick(p, specific_worker);
    } else if (p->is_iocp_worker) {
      grpc_iocp_kick();
    } else {
      p->kicked_without_pollers = 1;
    }
  }
}

void grpc_kick_poller(void) { grpc_iocp_kick(); }

#endif /* GPR_WINSOCK_SOCKET */


text:
from __future__ import print_function
# Author: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
# Copyright (c) 2014 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from time import sleep
from upm import pyupm_adxl345 as adxl345

def main():
    # Create an I2C accelerometer object
    adxl = adxl345.Adxl345(0)

    # Loop indefinitely
    while True:
        adxl.update() # Update the data
        raw = adxl.getRawValues() # Read raw sensor data
        force = adxl.getAcceleration() # Read acceleration force (g)
        print("Raw: %6d %6d %6d" % (raw[0], raw[1], raw[2]))
        print("ForceX: %5.2f g" % (force[0]))
        print("ForceY: %5.2f g" % (force[1]))
        print("ForceZ: %5.2f g\n" % (force[2]))

        # Sleep for 1 s
        sleep(1)

if __name__ == '__main__':
    main()


text:
function t=isoctave()
%ISOCTAVE  True if the operating environment is octave.
%   Usage: t=isoctave();
%
%   Returns 1 if the operating environment is octave, otherwise
%   0 (Matlab)

% @file    isoctave.m
% @brief   Returns true if using octave
% @author  Sarah Keating
%
%
% ISOCTAVE.M
%
% COPYRIGHT : (c) NUHAG, Dept.Math., University of Vienna, AUSTRIA
%             http://nuhag.eu/
%             Permission is granted to modify and re-distribute this
%             code in any manner as long as this notice is preserved.
%             All standard disclaimers apply.
%

if exist('OCTAVE_VERSION')
  % Only Octave has this variable.
  t='1';
else
  t='0';
end;


text:
class VipHandler
	# Parses Voting Information Project format version 1.4

	require 'rubygems'
	require 'libxml'

	include LibXML::XML::SaxParser::Callbacks

	Debug = ENV['VIP_DEBUG'].to_i || 0   #debug level

	# defines which top-level elements to parse
	TopElements = ["source","state",
	               "locality","precinct", "election",
	               "precinct_split", "election_administration",
	               "election_official", "ballot_drop_location",
	               "contest","candidate","campaign_issue",
	               "candidate_statement","custom_ballot",
	               "custom_note","referendum",
	               "polling_location","street_segment",
	               "street_address", "ballot","ballot_response",
	               "tabulation_area"]

	# don't try to map the following ID elements to objects
	IdExceptions = ["vip_id", "file_internal_id"]

	# store the file_internal_id and other arguments referencing
	# an object that hasn't been stored yet
	def save_unresolved(obj,attrib,val)
		# Add it to a table storing unresolved objects
		badone = UnresolvedId.new do |u|
			u.source       = @source
			u.object_class = obj.class.name
			u.parameter    = attrib
			u.val          = val
		end

		# save it to a stack.  We'll store it when the object gets an ID
		@unresolved_ids.push(badone)

		puts 'Added '+attrib+' to resolution list.  Fail.' if Debug > 3
	end

	# search through all classes to find the referenced file_internal_id.
	# stores an unresolvedId object and returns false on failure, returns
	# object if found successfully
	def store_arbitrary_object_reference(obj,object_id, store_unresolved)
		(TopElements-["source"]).each do |top|
			puts "trying "+top+" class" if Debug > 4
			lookup_class = top.camelize.constantize
			referenced_obj = lookup_class.find(:first,
			                                   :conditions => ["source_id = ? AND file_internal_id = ?",
			                                                   @source.id, object_id])
			puts "got it" if Debug > 4 and !referenced_obj.nil?
			if !referenced_obj.nil?
				puts "Found: "+lookup_class.name+"\t"+referenced_obj.id.to_s if Debug > 4
				obj.object_type = lookup_class.name
				obj.object_id   = referenced_obj.id
				return true
			end
		end

		# we haven't found the referenced ID in the stack yet.
		# Add it to a table storing unresolved objects
		if store_unresolved
			save_unresolved(obj,"object_id",object_id)
		end

		# save file_internal_id in place of object id, unless it's HABTM
		obj.[]=(innerattrib,val) if obj.has_attribute?(innerattrib)

		return false
	end

	# return an object based on the file_internal_id. looks at obj and attrib to
	# determine what type of object to return.  if external_vip_id and external_datetime
	# are set, that referenced source will be searched
	def get_object_by_file_internal_id(obj, attrib, file_internal_id, external_vip_id = nil, external_datetime = nil)

		#grab attribute type from innerattrib (drop _id)
		attribute_type = attrib[0,attrib.size-3]
		puts attribute_type if Debug > 3

		#get the class corresponding to the parameter
		attr_reflection =   obj.class.reflect_on_association(attribute_type.to_sym)
		attr_reflection ||= obj.class.reflect_on_association(attribute_type.pluralize.to_sym)

		attribute_class = attr_reflection.klass
		obj_source = @source

		#TODO: test external links functionality
		# look up the external source if it's referenced
		if (external_vip_id and external_datetime) then
			puts "External" if Debug > 3
			obj_source = Source.find(:first, :conditions =>
						 ["date = ? AND vip_id = ?",
		                                  external_datetime,
		                                  external_vip_id])
		end

		#find the referenced object.  only grab the id...we just save a ref to the object
		obj_source.nil? ? nil : attribute_class.find(:first,
		                                             :conditions => ["source_id = ? AND file_internal_id = ?",
		                                                             obj_source.id, file_internal_id ],
		                                             :select => "id")
	end

	# Takes attrib as the element from xml with val as it's value.
	# Assumes that element name is the class attribute name, except in
	# the case of id's.
	# * Maps element's ID to file_internal_id
	# * Overwrites IDs referenced by elements to database internal IDs
	def add_xml_attribute(obj, attrib, val, store_unresolved = true, external_vip_id = nil, external_datetime = nil)
		#don't store unnecessary white space
		val.strip!

		if (attrib.eql?("id"))
			puts attrib if Debug > 4
			innerattrib = "file_internal_id"
		else
			innerattrib = attrib
		end

		# if it's an object_id, it's probably a custom_note
		# don't try to resolve it until the end of the document
		if innerattrib.eql?("object_id") then

			puts "object_id" if Debug > 4

			if store_arbitrary_object_reference(obj,val,store_unresolved)
				return true
			end

		# store object if it exists
		#TODO: size-3 or size-4?
		elsif obj.respond_to?(innerattrib) or
		   obj.respond_to?(innerattrib[0,innerattrib.size-3].pluralize) then

			if (innerattrib[-3,3] == '_id' && !IdExceptions.include?(innerattrib))

				#this is an ID in the file we need to map
				#to the database's internal ID
				referenced_obj = get_object_by_file_internal_id(obj, attrib, val,
				                                                external_vip_id, external_datetime)
				puts referenced_obj.inspect if Debug > 9

				if !referenced_obj.nil? then
					# store object id
					if obj.has_attribute?(innerattrib) #!HABTM?
						#not HABTM
						puts "Adding singular object " + innerattrib if Debug > 4
						obj.[]=(innerattrib,referenced_obj.id)
					else
						#HABTM
						puts "Adding plural object " + innerattrib if Debug > 4
						#TODO: size-3 or size-4?
		   				plural_attrib = innerattrib[0,innerattrib.size-3].pluralize

						eval('obj.'+plural_attrib).push referenced_obj
					end

					puts 'Set '+innerattrib+' to valid object.  Success.' if Debug > 3
					return true

				else #referenced object is nil
					# we haven't found the referenced ID in the stack yet.
					if store_unresolved
						save_unresolved(obj,attrib,val)
					end

					# save file_internal_id in place of object id, unless it's HABTM
					obj.[]=(innerattrib,val) if obj.has_attribute?(innerattrib)

					return false

				end #if referenced_obj.nil?

			else #just a normal attribute, not an object reference

				obj.[]=(innerattrib,val)

				puts 'Set '+innerattrib+' to '+val.to_s if Debug > 5

				return true

			end #id check
		else #attribute doesn't apply here
			puts "Ignored "+attrib+" in " +obj.class.name if Debug > 0
		end #attribute existence check

	end #add_xml_attribute

	# sets several variables used in the rest of the application.  also
	# links source to contributor if defined
	def initialize(contributor = nil)
		#stack of xml elements and attributes
		@stack       = [];

		#whether or not to save next set of characters
		@store_chars = false;

		#source object used throughout
		@source      = nil

		#array to store id's not resolved from file_internal_id to database id's
		@unresolved_ids = []

		@contrib = contributor
	end

	# this parser callback function decides where to send a new element.  If the parser
	# is not already in a top-level element, it will process if the element is in
	# TopElements. If we are in a top-level element, it directs the parser to start
	# storing characters.  Additionally, if attributes are specified within tags, it
	# directs them to add_xml_attribute
	def on_start_element_ns(element, attributes, prefix, uri, namespaces)
		element.downcase!
		puts "Start "+element.downcase if Debug > 2

		# NOTE: This parsing relies on the simple two-level structure
		# of VIP data.
		if (@stack.size == 0 && TopElements.include?(element)) then
		   if element == 'source'
		      obj = Source.new
		      @source = obj
		   else
		      raise if @source.nil?
		      obj = element.camelcase.constantize.new
		      obj.source = @source
		   end

		   #store attributes inside start tag
		   attributes.each {|k,v|
			   puts k if Debug > 4
			   add_xml_attribute(obj,k,v)
		   }
		   @stack.push(obj)

		elsif (@stack.size == 1) then # && Innerelements.include?(element)) then
			   @stack.push(String.new(element))
			   @stack.push(String.new())
			   @store_chars = true
		else
			puts "Ignoring element: "+element if Debug > 0
		end

	end

	# store characters as they come inside an element. This may be called
	# more than once within an element.
	def on_characters(chars)
		if (@store_chars) then
			#TODO: why can't we just edit @stack.last ?
			buffer = @stack.pop
			buffer += chars
			@stack.push(buffer)
		end
	end

	# once all elements have been parsed, looks through unresolved_ids for objects that
	# had not been stored yet. Also timestamps end of source import and appends state to
	# street_address field
	def on_end_document()

		if ['PostgreSQL','MySQL'].include?(@source.connection.adapter_name) then
			resolve_ids_sql
			#resolve_ids_activerecord
		else
			resolve_ids_activerecord
		end

		puts UnresolvedId.count(:conditions => {:source_id => @source.id}).to_s + " unresolved IDs" if Debug > 3

		# add state_id to streets.  this eases later lookup
		# We use a shortcut when we can, rails convention if we're not sure
		if ['PostgreSQL','MySQL'].include?(@source.connection.adapter_name) then
			add_state_to_addresses_sql
		else
			add_state_to_addresses_activerecord
		end

		@source.import_completed_at = Time.now
		@source.contrib = @contrib unless @contrib.nil?
		@source.activate!
		@source.save

	end

	# updates new street_addresses with state_id to speed lookups.  uses SQL for speed
	def add_state_to_addresses_sql
		['ss.start_street_address_id','ss.end_street_address_id'].each do |addr_id_col|
			@source.connection.execute("UPDATE street_addresses sa
       	                                     SET    sa.state_id = (
			                       SELECT l.state_id
					 	 FROM street_segments ss,
       	                                              precincts p,
       	                                              localities l
			                        WHERE sa.id = #{addr_id_col}
			                          AND ss.precinct_id = p.id
			                          AND p.locality_id = l.id LIMIT 1)
			                     WHERE sa.state_id IS NULL
		                               AND sa.source_id = #{@source.id}")
		end
	end

	# updates new street_addresses with state_id to speed lookups.  uses ActiveRecord for compatibility
	def add_state_to_addresses_activerecord
		addresses = StreetAddress.find(:all, :select => "id",
		                               :conditions => ["source_id = ? AND state_id IS NULL", @source.id])
		addresses.each do |address|
			addr = StreetAddress.find(address.id)
			addr.state = addr.street_segments.first.precinct.locality.state
			addr.save
		end
	end

	# go through unresolved IDs and try to match to real objects.  if classlist is set,
	# only attempt to resolve those classes. uses ActiveRecord for compatibility
	def resolve_ids_activerecord(classlist = nil)
		#TODO: switch to UnresolvedId.each with rails 2.3

		#TODO: a rails bug is preventing the line from being written like this:
#		conditions = {:source => @source}

		conditions = {"source_id" => @source.id}
		if classlist
			conditions[:object_class] = classlist
		end

		unresolved_ids = UnresolvedId.find(:all, :select => "id",
		                                   :conditions => conditions)
		puts unresolved_ids.size.to_s + " unresolved to loop" if Debug > 4
		unresolved_ids.each do |unresolved|
			#load the rest of the record/object
			u = UnresolvedId.find(unresolved.id)

			obj = u.object_class.constantize.find_by_id(u.object_id)
			if (add_xml_attribute(obj,u.parameter,u.val.to_s,false)) then
				puts "Resolved" if Debug > 3
				obj.save
				u.destroy
			elsif Debug > 3
				puts "Not Resolved: "+obj.class.name+"\t"+u.object_id.to_s+"\t"+u.parameter.to_s+"\t"+u.val.to_s
			end
		end
	end

	# go through unresolved IDs and try to match to real objects.  uses SQL for speed
	def resolve_ids_sql
		(TopElements-["custom_note", "tabulation_area"]).each do |element|
			paramlist = UnresolvedId.count(:parameter, :group => "parameter",
			                               :conditions => ["source_id = ? AND object_class = ?",
			                                              @source.id, element.camelcase])
			paramlist.each do |param,cnt|
				#all params are ids, chop the last 3
				param_name = param[0 .. param.size - 4]

				#get the type of association
				element_klass = element.camelcase.constantize
				assoc   = element_klass.reflect_on_association(param_name.to_sym)
				assoc ||= element_klass.reflect_on_association(param_name.pluralize.to_sym)
				raise "no reflection between "+element_klass.name+" and "+param_name+" or "+param_name.pluralize unless assoc

				param_class = assoc.class_name
				case assoc.macro
					when :has_and_belongs_to_many
						insert_table = [element_klass.name.tableize, param_class.tableize].sort.join("_")
						resolve_ids_habtm_sql(@source, element_klass, param, param_class, insert_table)
					when :belongs_to
						resolve_ids_belongs_to_sql(@source, element_klass, param, param_class)
					when :has_many
						if assoc.options.keys.include?(:through)
							insert_table = assoc.options[:through].to_s.tableize
							resolve_ids_habtm_sql(@source, element_klass, param, param_class, insert_table)
						else
							raise "unexpected association macro type :has_many "+element_klass.name+" and "+param_name
						end
					when :has_one
						raise "unexpected association macro type :has_one between "+element_klass.name+" and "+param_name
				end #case

			end #each param
		end #each TopElement
		resolve_ids_activerecord(["CustomNote","TabulationArea"])
	end #method

	# resolves HABTM ids. uses SQL for speed
	def resolve_ids_habtm_sql(source, klass, param, param_class, insert_table)

		temptable = resolve_ids_temptable_sql(source, klass, param, param_class)

		source.connection.execute "
			INSERT INTO #{insert_table} (#{klass.name.underscore + "_id"}, #{param})
				SELECT object_id, param_id FROM #{temptable};"

		resolve_ids_cleanup_sql(source, temptable)

		return true
	end

	# resolves belongs_to ids. uses SQL for speed
	def resolve_ids_belongs_to_sql(source, klass, param, param_class)

		temptable = resolve_ids_temptable_sql(source, klass, param, param_class)

		update_statement = "
		UPDATE #{klass.name.tableize} SET #{param} = (
		 SELECT param_id FROM #{temptable} WHERE object_id=#{klass.name.tableize}.id)"
		update_statement += " WHERE source_id = #{source.id}" if klass.name != "Source"

		source.connection.execute update_statement

		resolve_ids_cleanup_sql(source, temptable)

		return true
	end

	# get rid of the resolved ids and table
	def resolve_ids_cleanup_sql(source, temptable)
		source.connection.execute "
		DELETE FROM unresolved_ids
		      WHERE EXISTS (SELECT 1 FROM #{temptable}
		                     WHERE unresolved_id = unresolved_ids.id)
		            AND source_id = #{source.id};"

		source.connection.execute "DROP TABLE #{temptable}"
	end

	#join unresolved ids with the temporary table
	def resolve_ids_temptable_sql(source, klass, param, param_class)

		temptable = "resolution" + rand(30000).to_s
		object_class = klass.name
		object_table = object_class.tableize
		parameter_table = param_class.tableize

		source.connection.execute "
		CREATE TEMPORARY TABLE #{temptable}
		SELECT unresolved_ids.id as unresolved_id, object_table.id AS object_id, parameter_table.id AS param_id
		  FROM #{object_table} AS object_table,
		       #{parameter_table} AS parameter_table,
		       unresolved_ids
		 WHERE unresolved_ids.object_id = object_table.id
		   AND unresolved_ids.object_class = '#{object_class}'
		   AND unresolved_ids.val = parameter_table.file_internal_id
		   AND unresolved_ids.parameter = '#{param}'
		   AND parameter_table.source_id = #{source.id}
		   AND unresolved_ids.source_id = #{source.id};"

		source.connection.execute "
		CREATE INDEX idx_#{temptable}_unresolved_id on #{temptable} (unresolved_id)"

		source.connection.execute "
		CREATE INDEX idx_#{temptable}_object_id on #{temptable} (object_id)"

		return temptable
	end

	# if an attribute of a top-level element, sends attribute and characters to
	# add_xml_attribute.  If the end of a top-level element, saves the object
	def on_end_element_ns(element, prefix, uri)

		if (@store_chars) then
			chars   = @stack.pop
			element = @stack.pop
			obj     = @stack.last
			add_xml_attribute(obj,element,chars)
			@store_chars = false;
		else
			puts "End "+element+" \n " + @stack.size.to_s if Debug>2
			if @stack.size == 1 then
				obj = @stack.pop
				if (obj.save(false)) then
#					puts "Saving #{element} with #{@unresolved_ids.size} unresolved ids"
					UnresolvedId.transaction do
						@unresolved_ids.each do |u|
							u.object_id = obj.id
							u.save(false)
						end
		   				@unresolved_ids = []
					end #transaction
					puts "file_internal_id: " + obj.file_internal_id.to_s if Debug > 3
					puts "saved" if Debug > 4
				else
					puts element + ' not saved.  Id: '+obj.file_internal_id.to_s if Debug > 3
				end #if obj.save
			end #stack.size == 1
		end #store_chars
	end

	def method_missing(method_name, *attributes, &block) #:nodoc:
	end
end