text:
package com.rufushonour.crypto.vigenere;

import com.rufushonour.crypto.caesar.CaesarDecrypt;

import java.util.ArrayList;
import java.util.List;
/**
 * A class for decrypting vigenere ciphers
 * @author Rufus Honour
 * @author roh2@kent.ac.uk
 */
public class VigenereDecrypt {
    // An array to hold the alphabet so we can wrap around when we need to easier - also can add other characters here if we need them
    protected static char[] ALPHABET_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    /**
     * A method for getting the key of a vigenere cipher if the key length is known
     * It uses chi-squared statistics which compares it to the english letter frequencies
     * @param cipherText the ciphertext you want to decrypt
     * @param keyLength the length of the key
     * @return the keyword used for enciphering the text
     */
    public static String WithKeyLength(String cipherText, int keyLength) {
        String keyword = "";
        // for each of the letters in the key length we want to find a ceaser cipher for each one.
        for(int i = 0; i < keyLength; i++) {
            String newCipher = "";
            for(int j = 0; j < cipherText.length(); j++) {
                // creating the ceaser cipher
                if(!(((keyLength+i) * j) + 1 > cipherText.length())) {
                    if(j == 0) {
                        newCipher += cipherText.substring(i, i + 1);
                    } else {
                        newCipher += cipherText.substring((keyLength * j) + i, ((keyLength * j) + i) + 1);
                    }
                }
            }
            // Uses the ceaser decrypter class to get 26 possible combinations
            List<String> caesers = CaesarDecrypt.decrypt(newCipher);

            // We now compare these 26 caeser ciphers to the letter freqencies in english
            List<Double> chiSquared = new ArrayList<Double>();
            for(String cipher : caesers) {
                chiSquared.add(VCMath.getChiSquared(cipher));
            }

            int chiIndex = -1;
            double chiLowest = -1;
            // We want to find the lowest chi squared value which indicates its the closest to english
            for(int j = 0; j < chiSquared.size(); j++) {
                double chi = chiSquared.get(j);
                if(chiLowest == -1) {
                    chiLowest = chi;
                    chiIndex = j;
                }
                if(chi < chiLowest) {
                    chiLowest = chi;
                    chiIndex = j;
                }
            }

            char[] cipherTextChars = cipherText.toCharArray();
            char cipherchar = cipherTextChars[i];
            int cipherTextIndex = -1;
            // We want to get this from our alphabet array for easier adding and subtracting
            for(int k = 0; k < ALPHABET_ARRAY.length; k++) {
                if(ALPHABET_ARRAY[k] == cipherchar) {
                    cipherTextIndex = k;
                }
            }
            // Once we have found the chi squared index we want to minus the chiIndex (which corresponds to a letter) from the ciphertext value to get our plainTextIndex
            // All these indexs are numbers instead of letters but they correspond to letters from the ALPHABET_ARRAY static constant.
            int plainTextIndex = cipherTextIndex + chiIndex;
            // Subtract the ciphertText by the index of the plainText which will give us our key value
            for(int k = 0; k < plainTextIndex; k++) {
                if(cipherTextIndex == 0) {
                    cipherTextIndex = 25;
                } else {
                    cipherTextIndex -= 1;
                }
            }

            // Get the key char from the alphabet array and add it to our end value.
            keyword += ALPHABET_ARRAY[cipherTextIndex];
        }
        return keyword;
    }

    /**
     * Decrypt some vigenere cipher text encrypted with an key
     * @param cipherText the cipher text you want to decrypt
     * @param key the key you want to decrypt with
     * @return the decrypted text
     */
    public static String decryptWithKey(String cipherText, String key) {
        // The key is not always as long as the cipherText so we need to keep an eye on where we are.
        int keyIndex = 0;
        String decryptedText = "";

        char[] cipherTextChars = cipherText.toCharArray();
        char[] keyChars = key.toCharArray();

        // We need to loop through the cipherText
        for(int i = 0; i < cipherText.length(); i++) {
            // Variables for holding array indices of each type (key and cipertext)
            int alphabetKeyIndex = -1;
            int alphabetCipherIndex = -1;
            for(int j = 0; j < ALPHABET_ARRAY.length; j++) {
                // If the key char is in the array then we want to hold the index at which the statement equaled true
                if(ALPHABET_ARRAY[j] == keyChars[keyIndex]) {
                    alphabetKeyIndex = j;
                }

                // same as above but with the cipherText char instead
                if(ALPHABET_ARRAY[j] == cipherTextChars[i]) {
                    alphabetCipherIndex = j;
                }
            }
            // We subtract the cipherIndex by the index of the key, which will give us our decrypted letter
            // This is only done one at a time in case we hit 0 as we will want to wrap back around to 'Z' and carry on
            for(int j = 0; j < alphabetKeyIndex; j++) {
                if(alphabetCipherIndex == 0) {
                    alphabetCipherIndex = 25;
                } else {
                    alphabetCipherIndex -= 1;
                }
            }
            // The 'real' character is added to the end string
            decryptedText += ALPHABET_ARRAY[alphabetCipherIndex];

            // Start from the beginning index of the key
            if (keyIndex == key.length() - 1) {
                keyIndex = 0;
            } else {
                keyIndex++;
            }
        }
        return decryptedText;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace LASI.App.Dialogs
{
    /// <summary>
    /// Interaction logic for FindWindow.xaml
    /// </summary>
    public partial class FindWindow : Window
    {
        /// <summary>
        /// Initializes a new instance of the FindWindow class.
        /// </summary>
        public FindWindow() {
            InitializeComponent();
        }
        /// <summary>
        /// Executes a lexical search over applicable elements when invoked.
        /// </summary>
        /// <param name="sender">The source of the click event.</param>
        /// <param name="e">The arguments passed invocation.</param>
        private void findButton_Click(object sender, RoutedEventArgs e) {
            PerformFind(searchForTextBox.Text);
        }
        /// <summary>
        /// Executes a lexical search over an applicable set of elements in the current UI context using the provided text as the search seed.
        /// </summary>
        /// <param name="searchText">The text which seeds the search.</param>
        private void PerformFind(string searchText)
        {
            var toHighLight = GetElementsToSearch().Where(element => element.Content.ToString().IndexOf(searchText, StringComparison.OrdinalIgnoreCase) > -1);
        }

        /// <summary>
        /// Returns the collection of ContentControl UIElements over whose contents to search.
        /// </summary>
        /// <returns>The collection of ContentControl UIElements over whose contents to search.</returns>
        private IEnumerable<ContentControl> GetElementsToSearch() {
            throw new NotImplementedException();
        }
        private void Window_KeyDown(object sender, KeyEventArgs e) {
            if (e.Key == Key.Escape) {
                this.DialogResult = false;
                this.Close();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
echo Starting server in $SLEEP_BEFORE_APP_SERVER_STARTS_SECONDS seconds...

sleep $SLEEP_BEFORE_APP_SERVER_STARTS_SECONDS

echo Starting server...

nc -v -lk -p $SERVER_PORT -e /assets/process_request.sh


text:
@interface PodsDummy_Pods_jNSAttributedRange : NSObject
@end
@implementation PodsDummy_Pods_jNSAttributedRange
@end


text:
- [Background](Background)
- API mode vs. Data mode
- Why my data does not show up?
- Why the pagination does not show anything?
- How to specify column width?
- Can Vuetable do the data grouping?


text:
package org.intelligentsia.dowsers.command;

import java.util.UUID;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;

/**
 * Command declares an interface for executing an operation.

 *
 * Commands are created on the client application and then send to the Domain
 * layer.

 * Their purpose is to capture "Why did this change happen?".

 * All these commands will be send to the Command Bus which will delegate each
 * command to the command handler or command handlers.

 * This also effectively means that there is only one entry point into the
 * domain and that is via the Bus.

 * The responsibility of these command handlers is to execute the appropriate
 * behavior on the domain.
 *
 *
 * The Command concept encapsulates method calls in objects allowing us to issue
 * requests without knowing the requested operation or the requesting object.
 *
 * By default, "execute" method call command invoker.
 *
 *
 * Example of Command implementation:
 *
 *

 * public class FakeHelloCommand extends Command {
 *
 * 	private final String name;
 *
 * 	public FakeHelloCommand(final CommandInvoker commandInvoker, final String name) throws NullPointerException {
 * 		super(commandInvoker);
 * 		this.name = name;
 * 	}
 *
 * 	@Override
 * 	public void validate() throws NullPointerException, IllegalArgumentException {
 * 		Preconditions.checkNotNull(name, "name cannot be null");
 * 		Preconditions.checkArgument(!"".equals(name), "name must not be empty");
 * 	}
 *
 * 	public String getName() {
 * 		return name;
 * 	}
 * }
 *

 *
 *
 * @author Jerome Guibert
 */
public abstract class Command {

	/**
	 * Command identifier.
	 */
	private final String id;
	/**
	 * CommandInvoker instance.
	 */
	private final CommandInvoker commandInvoker;

	/**
	 * Build a new instance of Command.

	 * Command identity is based on UUID generation.
	 *
	 * @param commandInvoker
	 *            command Invoker instance.
	 *
	 * @throws NullPointerException
	 *             if commandInvoker is null
	 */
	public Command(final CommandInvoker commandInvoker) throws NullPointerException {
		this(UUID.randomUUID().toString(), commandInvoker);
	}

	/**
	 * Build a new instance of Command with specified identifier.
	 *
	 * @param id
	 *            identifier
	 * @param commandInvoker
	 *            command Invoker instance.
	 * @param execute
	 *            if true execute this command against command bus
	 * @throws NullPointerException
	 *             if id or commandInvoker is null
	 */
	protected Command(final String id, final CommandInvoker commandInvoker) throws NullPointerException {
		super();
		this.id = Preconditions.checkNotNull(id);
		this.commandInvoker = Preconditions.checkNotNull(commandInvoker);
	}

	/**
	 * Execute method.
	 */
	public final void execute() {
		validate();
		commandInvoker.invoke(this);
	}

	/**
	 * Check some validation before invoke handler. Validation should occurs in
	 * this methods before invoking herself with command invoker.
	 */
	protected void validate() throws RuntimeException {
		// do nothing
	}

	/**
	 * @return id of command
	 */
	public final String getId() {
		return id;
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return id.toString();
	}

	/**
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public final int hashCode() {
		return Objects.hashCode(id);
	}

	/**
	 * Command are compared on their id.
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public final boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		final Command other = (Command) obj;
		return Objects.equal(other.getId(), getId());
	}

}


text:
//
//  OCRDetailViewProtocol.h
//  KOResume
//
//  Created by Kevin O'Mara on 8/7/14.
//  Copyright (c) 2014 O'Mara Consulting Associates. All rights reserved.
//

#ifndef KOResume_OCRDetailViewProtocol_h
#define KOResume_OCRDetailViewProtocol_h

/**
 OCRDetailViewProtocol is a protocol that detail view controllers must adopt. It defines methods that
 the base class can invoke on subclasses.
 */
@protocol OCRDetailViewProtocol <NSObject>

/**
 The managed object the user selected.

 Subclasses should either cast or create a type appropriate reference to this object.
 */
@property (nonatomic, strong) NSManagedObject               *selectedManagedObject;

/**
 The fetchedResultsController used to retrieve the selectedPackage.
 */
@property (nonatomic, strong) NSFetchedResultsController    *fetchedResultsController;

/**
 A property used by the master view to cache the back button.
 */
@property (nonatomic, strong) UIBarButtonItem               *backButtonCached;

/**
 A property used by the master view to cache the popover controller.
 */
@property (nonatomic, strong) UIPopoverController           *popoverControllerCached;

/**
 A reference to the master view's popoverController.
 */
@property (nonatomic, strong) UIPopoverController           *masterPopoverController;

/**
 A property used by the master view to set the back button title.
 */

@property (nonatomic, strong) NSString                      *backButtonTitle;

@required

/**
 The method is called on the subclass when the selectedManagedObject changes.

 The subclass should update it's view to reflect the new data and perform other operations
 appropriate for its context.
 */
- (void)configureView;

/**
 Reloads the fetched Results

 @param aNote           The NSNotification object, or nil.
 */

- (void)reloadFetchedResults: (NSNotification*)aNote;

@end

#endif


text:
cask :v1 => 'synology-assistant' do
  version '5.2-5566'
  sha256 '8960586857f7fd1fb2cb683f9031b05344440b4c9f8dd5d8a735831d3b541e42'

  url "https://global.download.synology.com/download/Tools/Assistant/#{version}/Mac/Synology-Assistant-#{version}.dmg"
  name 'Synology Assistant'
  homepage 'https://www.synology.com/'
  license :gratis

  app 'Synology Assistant.app'

  zap :delete => '~/Library/Preferences/com.synology.DSAssistant.plist'
end


text:
package de.inetsoftware.jwebassembly.binary;

import java.io.IOException;

/**
 * An entry in the function section of the WebAssembly.
 *
 * @author Volker Berlin
 */
class ExportEntry extends SectionEntry {

    private String       name;

    private ExternalKind kind;

    private int          id;

    /**
     * Create an entry for the export section. This section contains a mapping from the external index to the type
     * signature index.
     *
     * @param name
     *            the exported name
     * @param kind
     *            the type of exported object
     * @param id
     *            the id inside the list of the related type
     */
    ExportEntry( String name, ExternalKind kind, int id ) {
        this.name = name;
        this.kind = kind;
        this.id = id;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeSectionEntry( WasmOutputStream stream ) throws IOException {
        stream.writeString( name );
        stream.writeVaruint32( kind.ordinal() );
        stream.writeVaruint32( id );
    }
}


text:
layout: api
id: bind
title: .bind
---

[← Back To API Reference](/docs/api-reference.html)

<markdown>
##.bind

```js
.bind(any|Promise<any> thisArg) -> BoundPromise
```

Same as calling [Promise.bind(thisArg, thisPromise)](.).
</markdown>

Please enable JavaScript to view the comments powered by Disqus.


text:
<?php

namespace ocause\model\session;

/**
 * Description of SessionCookie
 *
 * @author Joe
 */
class SessionCookie extends \oc\data\Model implements \oc\data\session\ISession {
	//put your code here
}


text:
<?php

// SonataAdminBundle:Core:create_button.html.twig
return array (
);


text:
from django.contrib import admin

from core.models import Project
from core.models import Experiment
from core.models import Material
from core.models import SampleType
from core.models import Sample
from core.models import Plate
from core.models import Well

class WellInline(admin.TabularInline):
    model = Well
    extra = 0

class PlateAdmin(admin.ModelAdmin):
    inlines = [
        WellInline
    ]

class ExperimentInline(admin.TabularInline):
    model = Experiment
    extra = 0

class ProjectAdmin(admin.ModelAdmin):
    inlines = [
        ExperimentInline
    ]

admin.site.register(Project,ProjectAdmin)
admin.site.register(Experiment)
admin.site.register(Material)
admin.site.register(SampleType)
admin.site.register(Sample)
admin.site.register(Plate,PlateAdmin)
admin.site.register(Well)


text:
'use strict';

var mongoose = require('mongoose');

var pollSchema = mongoose.Schema({

    title: String,
    hasVoted: [],
    choices: [],
    totalVotes: Number,
    url: String,
    choice0: Number,
    choice1: Number,
    choice2: Number,
    choice3: Number,
    choice4: Number,
    choice5: Number,
    choice6: Number,
    choice7: Number,
    choice8: Number,
    choice9: Number,
    createdBy: String

}, {
    timestamps: true
});

// create the model for users and export to app
module.exports = mongoose.model('Poll', pollSchema);


text:
require 'spec_helper'

describe 'config' do

  before do
    SnowyOwl.configure do |config|
      config.props_path = '/path/to/props'
      config.determine_context :context_key, &proc
      config.determinations_path = ''
      config.plots_path = ''
      config.play_books_path = ''
      config.is_persisting = false
      config.is_recovering = false
      config.persist_path = ''
      config.persist_callback &proc
      config.recover_callback  &proc
      config.spec_file = 'spec.rb'
    end
  end

  it 'should allow configure setting' do
    expect(SnowyOwl.props_path).to eq '/path/to/props'
    expect(SnowyOwl.determine_context :context_key).to eq(proc)
    expect(SnowyOwl.determinations_path).to eq ''
    expect(SnowyOwl.plots_path).to eq ''
    expect(SnowyOwl.play_books_path).to eq ''
    expect(SnowyOwl.is_persisting).to eq false
    expect(SnowyOwl.is_recovering).to eq false
    expect(SnowyOwl.persist_path).to eq ''
    expect(SnowyOwl.recover_callback).to eq(proc)
    expect(SnowyOwl.persist_callback).to eq(proc)
    expect(SnowyOwl.spec_file).to eq('spec.rb')
  end

  it 'should allow direct setting' do
    SnowyOwl.props_path = '/new_path/to/props'
    SnowyOwl.determine_context :context_key, &replacement_proc
    SnowyOwl.determinations_path = ''
    SnowyOwl.plots_path = ''
    SnowyOwl.play_books_path = ''
    SnowyOwl.is_persisting = false
    SnowyOwl.is_recovering = false
    SnowyOwl.persist_path = ''
    SnowyOwl.persist_callback &replacement_proc
    SnowyOwl.recover_callback  &replacement_proc
    SnowyOwl.spec_file = 'new_spec.rb'
    expect(SnowyOwl.props_path).to eq '/new_path/to/props'
    expect(SnowyOwl.determine_context :context_key).to eq(replacement_proc)
    expect(SnowyOwl.determinations_path).to eq ''
    expect(SnowyOwl.plots_path).to eq ''
    expect(SnowyOwl.play_books_path).to eq ''
    expect(SnowyOwl.is_persisting).to eq false
    expect(SnowyOwl.is_recovering).to eq false
    expect(SnowyOwl.persist_path).to eq ''
    expect(SnowyOwl.recover_callback).to eq(replacement_proc)
    expect(SnowyOwl.persist_callback).to eq(replacement_proc)
    expect(SnowyOwl.spec_file).to eq('new_spec.rb')
  end

  let(:proc) { Proc.new {} }
  let(:replacement_proc) { Proc.new {} }
end


text:
<?xml version="1.0" encoding="utf-8"?>

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US"/>
  <App xmlns="" ProductID="{cc298aea-1f63-48f2-89cf-b2593d10a428}" Title="ImplicitStyle.WinPhone" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal"  Author="ImplicitStyle.WinPhone author" Description="Sample description" Publisher="ImplicitStyle.WinPhone" PublisherID="{57a31321-e445-4182-9988-577552e9ca14}">
    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING"/>
      <Capability Name="ID_CAP_MEDIALIB_AUDIO"/>
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK"/>
      <Capability Name="ID_CAP_SENSORS"/>
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
    </Capabilities>
    <Tasks>
      <DefaultTask  Name ="_default" NavigationPage="MainPage.xaml"/>
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="PhoneApp1Token" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
          <Title>ImplicitStyle.WinPhone</Title>
          <BackContent></BackContent>
          <BackBackgroundImageURI></BackBackgroundImageURI>
          <BackTitle></BackTitle>
          <DeviceLockImageURI></DeviceLockImageURI>
          <HasLarge></HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA"/>
      <ScreenResolution Name="ID_RESOLUTION_WXGA"/>
      <ScreenResolution Name="ID_RESOLUTION_HD720P"/>
    </ScreenResolutions>
  </App>
</Deployment>


text:
package com.wesabe.api.util.money.tests;

import static com.wesabe.api.tests.util.CurrencyHelper.*;
import static com.wesabe.api.tests.util.DateHelper.*;
import static com.wesabe.api.tests.util.NumberHelper.*;
import static org.junit.Assert.*;

import java.util.Currency;

import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;

import com.wesabe.api.util.money.DollarPivotCurrencyExchangeRateMap;

@RunWith(Enclosed.class)
@SuppressWarnings("deprecation")
public class DollarPivotCurrencyExchangeRateMapTest {
	public static class Adding_Exchange_Rates_To_USD {
		@Test
		public void itAddsTheTargetCurrencyToSupportedCurrencies() throws Exception {
			DollarPivotCurrencyExchangeRateMap exchangeRates = new DollarPivotCurrencyExchangeRateMap();
			exchangeRates.addExchangeRate(USD, EUR, jun14th, decimal("1.76"));

			assertTrue(exchangeRates.getCurrencies().contains(EUR));
		}
	}

	public static class Adding_Exchange_Rates_To_Other_Currencies {
		@Test
		public void itThrowsAnException() throws Exception {
			DollarPivotCurrencyExchangeRateMap exchangeRates = new DollarPivotCurrencyExchangeRateMap();

			boolean exceptionThrown = false;
			try {
				exchangeRates.addExchangeRate(EUR, NOK, jun14th, decimal("1.76"));
			} catch (IllegalArgumentException e) {
				exceptionThrown = true;
			}

			assertTrue("should have thrown an exception, but didn't", exceptionThrown);
		}
	}

	public static class Calculating_Exchange_Rates {
		@Test
		public void itUsesUSDAsAPivotValue() throws Exception {
			DollarPivotCurrencyExchangeRateMap exchangeRates = new DollarPivotCurrencyExchangeRateMap();
			exchangeRates.addExchangeRate(USD, EUR, jun14th, decimal("0.7656"));
			exchangeRates.addExchangeRate(USD, NOK, jun14th, decimal("6.7258"));

			assertEquals(decimal("8.785004"), exchangeRates.getExchangeRate(EUR, NOK, jun14th));
			assertEquals(decimal("0.1138303"), exchangeRates.getExchangeRate(NOK, EUR, jun14th));
		}

		@Test
		public void itDoesStraightConversionsIfPossible() throws Exception {
			DollarPivotCurrencyExchangeRateMap exchangeRates = new DollarPivotCurrencyExchangeRateMap();
			exchangeRates.addExchangeRate(USD, GBP, jun14th, decimal("0.6846"));

			assertEquals(decimal("1.460707"), exchangeRates.getExchangeRate(GBP, USD, jun14th));
			assertEquals(decimal("0.6846000"), exchangeRates.getExchangeRate(USD, GBP, jun14th));
		}

		@Test
		public void itHandlesVeryDevaluedCurrencies() throws Exception {
			final Currency KRW = Currency.getInstance("KRW");
			DollarPivotCurrencyExchangeRateMap exchangeRates = new DollarPivotCurrencyExchangeRateMap();
			exchangeRates.addExchangeRate(USD, KRW, date(2008, 12, 31), decimal("1262.00"));

			assertEquals(decimal("0.0007923930"), exchangeRates.getExchangeRate(KRW, USD, date(2009, 4, 30)));
			assertEquals(decimal("1262.000"), exchangeRates.getExchangeRate(USD, KRW, date(2009, 4, 30)));
		}
	}
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Embedding a Bokeh Server With {{ framework }}</title>

    This Bokeh app below served by a Bokeh server that has been embedded
    in another web app framework. For more information see the section

        Embedding Bokeh Server as a Library
    in the User's Guide.

  {{ script|safe }}


text:
using System.Web.Http;

namespace Api.Web.Controllers
{
    public class BaseController : ApiController
    {

    }
}


text:
package cn.danielw.fop;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Daniel
 */
public class ObjectPoolPartition<T> {

    private static final Logger logger = Logger.getLogger(ObjectPoolPartition.class.getName());

    private final ObjectPool<T> pool;
    private final PoolConfig config;
    private final int partition;
    private final BlockingQueue<Poolable<T>> objectQueue;
    private final ObjectFactory<T> objectFactory;
    private int totalCount;

    public ObjectPoolPartition(ObjectPool<T> pool, int partition, PoolConfig config,
                               ObjectFactory<T> objectFactory, BlockingQueue<Poolable<T>> queue) {
        this.pool = pool;
        this.config = config;
        this.objectFactory = objectFactory;
        this.partition = partition;
        this.objectQueue = queue;
        for (int i = 0; i < config.getMinSize(); i++) {
            objectQueue.add(new Poolable<>(objectFactory.create(), pool, partition));
        }
        totalCount = config.getMinSize();
    }

    public BlockingQueue<Poolable<T>> getObjectQueue() {
        return objectQueue;
    }

    /**
     * @param delta the number to increase
     * @return the actual number of increased objects
     */
    @SuppressWarnings({"java:S112", "java:S2142"})
    public synchronized int increaseObjects(int delta) {
        if (delta + totalCount > config.getMaxSize()) {
            delta = config.getMaxSize() - totalCount;
        }
        try {
            for (int i = 0; i < delta; i++) {
                objectQueue.put(new Poolable<>(objectFactory.create(), pool, partition));
            }
            totalCount += delta;
            if (logger.isLoggable(Level.FINE))
                logger.fine("increase objects: count=" + totalCount + ", queue size=" + objectQueue.size());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return delta;
    }

    public synchronized boolean decreaseObject(Poolable<T> obj) {
        objectFactory.destroy(obj.getObject());
        totalCount--;
        return true;
    }

    public synchronized int getTotalCount() {
        return totalCount;
    }

    // set the scavenge interval carefully
    public synchronized void scavenge() throws InterruptedException {
        int delta = this.totalCount - config.getMinSize();
        if (delta <= 0) return;
        int removed = 0;
        long now = System.currentTimeMillis();
        Poolable<T> obj;
        while (delta-- > 0 && (obj = objectQueue.poll()) != null) {
            // performance trade off: delta always decrease even if the queue is empty,
            // so it could take several intervals to shrink the pool to the configured min value.
            if (logger.isLoggable(Level.FINE))
                logger.fine("obj=" + obj + ", now-last=" + (now - obj.getLastAccessTs()) + ", max idle=" +
                    config.getMaxIdleMilliseconds());
            if (now - obj.getLastAccessTs() > config.getMaxIdleMilliseconds() &&
                    ThreadLocalRandom.current().nextDouble(1) < config.getScavengeRatio()) {
                decreaseObject(obj); // shrink the pool size if the object reaches max idle time
                removed++;
            } else {
                objectQueue.put(obj); //put it back
            }
        }
        if (removed > 0 && logger.isLoggable(Level.FINE)) logger.fine(removed + " objects were scavenged.");
    }

    public synchronized int shutdown() {
        int removed = 0;
        long startTs = System.currentTimeMillis();
        while (this.totalCount > 0 && System.currentTimeMillis() - startTs < config.getShutdownWaitMilliseconds()) {
            Poolable<T> obj = objectQueue.poll();
            if (obj != null) {
                decreaseObject(obj);
                removed++;
            }
        }
        return removed;
    }
}


text:
=====
Units
=====

mBuild automatically performs unit conversions in its reader and writer functions.
When working with an :py:class:`mbuild.Compound`, mBuild uses the following units:

+----------+----------+
| Quantity |   Units  |
+==========+==========+
| distance |    nm    |
+----------+----------+
|   angle  | radians* |
+----------+----------+

\* :py:class:`mbuild.Lattice` and :py:class:`mbuild.Box` use degrees.

See also `foyer unit documentation <https://foyer.mosdef.org/en/stable/units.html>`_ and `ele documentation <https://ele-ment.readthedocs.io/en/latest/>`_.


text:
/* eslint-disable import/no-extraneous-dependencies, func-names, no-unused-expressions */
/* global describe, it, before, resetDOM */
import { expect } from 'chai';
import React from 'react';
import { shallow, mount } from 'enzyme';
import { MemoryRouterService } from 'frint-router';

import Link from './Link';

function createContextWithRouter(router) {
  return {
    app: {
      get(key) {
        if (key === 'router') {
          return router;
        }

        return null;
      }
    }
  };
}

describe('frint-route-react › Link', () => {
  before(function () {
    resetDOM();
  });

  it('renders anchor with href, className and children when no type prop is passed', function () {
    const linkContent = About;

    const wrapper = shallow(
      <Link className="anchor" to="/about">{linkContent}</Link>,
      { context: createContextWithRouter() }
    );

    expect(wrapper.name()).to.equal('a');
    expect(wrapper.hasClass('anchor')).to.be.true;

    expect(wrapper.children().length).to.equal(1);
    expect(wrapper.children().get(0)).to.eql(linkContent);
  });

  it('renders button with type, className and children when type prop is passed', function () {
    const linkContent = About;

    const wrapper = shallow(
      <Link className="fancy-button" to="/about" type="button">{linkContent}</Link>,
      { context: { app: {} } }
    );

    expect(wrapper.name()).to.equal('button');
    expect(wrapper.prop('type')).to.equal('button');
    expect(wrapper.hasClass('fancy-button')).to.be.true;

    expect(wrapper.children().length).to.equal(1);
    expect(wrapper.children().get(0)).to.eql(linkContent);
  });

  it('subscribes to router service for  matching route inexactly and changes activeClass accordingly ' +
    'when activeClassName is passed', function () {
    const router = new MemoryRouterService();

    const wrapper = mount(
      <Link
        activeClassName="anchor-active"
        className="anchor"
        to="/about"
      >
        About
      </Link>,
      { context: createContextWithRouter(router) }
    );

    router.push('/');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor')).to.be.true;
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;

    router.push('/about');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor')).to.be.true;
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;

    router.push('/about/whatever');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor')).to.be.true;
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;

    router.push('/');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor')).to.be.true;
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;
  });

  it('subscribes to router service for exactly matching route and changes activeClass accordingly ' +
    'when activeClassName and exact is passed', function () {
    const router = new MemoryRouterService();

    const wrapper = mount(
      <Link
        activeClassName="anchor-active"
        className="anchor"
        exact
        to="/about"
      >
        About
      </Link>,
      { context: createContextWithRouter(router) }
    );

    router.push('/');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;

    router.push('/about');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;

    router.push('/about/whatever');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;

    router.push('/');
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;
  });

  it('subscribes to router service for matching route and changes activeClass accordingly ' +
    'even when activeClassName is passed and changed later on', function () {
    const router = new MemoryRouterService();

    const wrapper = mount(
      <Link
        className="anchor"
        to="/about"
      >
        About
      </Link>,
      { context: createContextWithRouter(router) }
    );

    router.push('/about');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;

    wrapper.setProps({ activeClassName: 'anchor-active' });
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;

    wrapper.setProps({ activeClassName: 'anchor-super-active' });
    expect(wrapper.find(Link).children().hasClass('anchor-super-active')).to.be.true;
  });

  it('subscribes to router service for matching route and changes activeClass accordingly ' +
    'when "to" prop is changed', function () {
    const router = new MemoryRouterService();

    const wrapper = mount(
      <Link
        activeClassName="anchor-active"
        className="anchor"
        to="/about"
      >
        About
      </Link>,
      { context: createContextWithRouter(router) }
    );

    router.push('/about');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;

    wrapper.setProps({ to: '/contact' });
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;

    router.push('/contact');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;
  });

  it('subscribes to router service for matching route and changes activeClass accordingly ' +
    'when exact prop is changed', function () {
    const router = new MemoryRouterService();

    const wrapper = mount(
      <Link
        activeClassName="anchor-active"
        className="anchor"
        to="/about"
      >
        About
      </Link>,
      { context: createContextWithRouter(router) }
    );

    router.push('/about/whatever');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;

    wrapper.setProps({ exact: true });
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.false;

    router.push('/about');
    wrapper.update();
    expect(wrapper.find(Link).children().hasClass('anchor-active')).to.be.true;
  });

  it('unsubscribes from router getMatch$ when unmounted and when resubscribes', function () {
    let subscribeCount = 0;
    let unsubscribeCount = 0;

    const subscription = {
      unsubscribe() {
        unsubscribeCount += 1;
      }
    };

    const router = {
      getMatch$() {
        return {
          subscribe() {
            subscribeCount += 1;
            return subscription;
          }
        };
      }
    };

    const wrapper = mount(
      <Link
        activeClassName="anchor-active"
        className="anchor"
        to="/about"
      >
        About
      </Link>,
      { context: createContextWithRouter(router) }
    );

    expect(subscribeCount).to.equal(1);
    expect(unsubscribeCount).to.equal(0);

    // forcing to resubscribe by providing new url
    wrapper.setProps({ to: '/company' });
    expect(subscribeCount).to.equal(2);
    expect(unsubscribeCount).to.equal(1);

    wrapper.unmount();
    expect(subscribeCount).to.equal(2);
    expect(unsubscribeCount).to.equal(2);
  });

  describe('prevents default and doesn\'t stopPropagation when clicked ', function () {
    const pushedUrls = [];
    const actualRouter = new MemoryRouterService();

    const router = {
      push(url) {
        actualRouter.push(url);
        pushedUrls.push(url);
      },

      getHistory() {
        return actualRouter.getHistory();
      },

      getMatch(...args) {
        return actualRouter.getMatch.call(actualRouter, ...args);
      }
    };

    const wrapper = shallow(
      <Link className="anchor" to="/about">About</Link>,
      { context: createContextWithRouter(router) }
    );

    it('and pushes new url to router when it doesn\'t match current url', function () {
      let preventDefaultCalled = 0;
      let stopPropagationCalled = 0;
      wrapper.simulate('click', {
        preventDefault() { preventDefaultCalled += 1; },
        stopPropagation() { stopPropagationCalled += 1; }
      });

      expect(pushedUrls).to.deep.equal(['/about']);
      expect(preventDefaultCalled).to.equal(1);
      expect(stopPropagationCalled).to.equal(0);
    });

    it('and doesn\'t push new url to router when it matches current url', function () {
      let preventDefaultCalled = 0;
      let stopPropagationCalled = 0;
      wrapper.simulate('click', {
        preventDefault() { preventDefaultCalled += 1; },
        stopPropagation() { stopPropagationCalled += 1; }
      });

      // nothing new was added to the pushedUrls and that's the point
      expect(pushedUrls).to.deep.equal(['/about']);
      expect(preventDefaultCalled).to.equal(1);
      expect(stopPropagationCalled).to.equal(0);
    });
  });
});


text:
import unittest, random, sys, time, os
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_browse as h2b, h2o_import as h2i
import h2o_exec as h2e

def write_syn_dataset(csvPathname, rowCount, colCount, SEED):
    r1 = random.Random(SEED)
    dsf = open(csvPathname, "w+")

    for i in range(rowCount):
        rowData = []
        for j in range(colCount):
            r = "a"
            rowData.append(r)

        rowDataCsv = ",".join(map(str,rowData))
        dsf.write(rowDataCsv + "\n")

    dsf.close()

class Basic(unittest.TestCase):
    def tearDown(self):
        h2o.check_sandbox_for_errors()

    @classmethod
    def setUpClass(cls):
        global SEED, localhost
        SEED = h2o.setup_random_seed()
        localhost = h2o.decide_if_localhost()
        if (localhost):
            h2o.build_cloud(1,java_heap_GB=1)
        else:
            h2o_hosts.build_cloud_with_hosts()

    @classmethod
    def tearDownClass(cls):
        h2o.tear_down_cloud()

    def test_many_cols_with_syn(self):
        SYNDATASETS_DIR = h2o.make_syn_dir()
        tryList = [
            (100, 11000, 'cA', 5),
            (100, 10000, 'cB', 5),
            (100, 9000, 'cC', 5),
            (100, 8000, 'cD', 5),
            (100, 7000, 'cE', 5),
            (100, 6000, 'cF', 5),
            (100, 5000, 'cG', 5),
            ]

        ### h2b.browseTheCloud()
        lenNodes = len(h2o.nodes)

        cnum = 0
        for (rowCount, colCount, hex_key, timeoutSecs) in tryList:
            cnum += 1
            csvFilename = 'syn_' + str(SEED) + "_" + str(rowCount) + 'x' + str(colCount) + '.csv'
            csvPathname = SYNDATASETS_DIR + '/' + csvFilename

            print "Creating random", csvPathname
            write_syn_dataset(csvPathname, rowCount, colCount, SEED)

            parseResult = h2i.import_parse(path=csvPathname, schema='put', hex_key=hex_key, timeoutSecs=10)
            print csvFilename, 'parse time:', parseResult['response']['time']
            print "Parse result['destination_key']:", parseResult['destination_key']

            # We should be able to see the parse result?
            inspect = h2o_cmd.runInspect(None, parseResult['destination_key'])
            print "\n" + csvFilename

            if not h2o.browse_disable:
                h2b.browseJsonHistoryAsUrlLastMatch("Inspect")
                time.sleep(5)

            # try new offset/view
            inspect = h2o_cmd.runInspect(None, parseResult['destination_key'], offset=100, view=100)
            inspect = h2o_cmd.runInspect(None, parseResult['destination_key'], offset=99, view=89)
            inspect = h2o_cmd.runInspect(None, parseResult['destination_key'], offset=-1, view=53)

if __name__ == '__main__':
    h2o.unit_main()


text:
//------------------------------------------------------------------------------
// <copyright file="StateMachineStateQueryElement.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.ServiceModel.Activities.Tracking.Configuration
{
    using System.Activities.Tracking;
    using System.Configuration;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime;

    /// <summary>
    /// Configure StateMachineStateQuery element in DotNetConfig.xsd.
    /// </summary>
    [Fx.Tag.XamlVisible(false)]
    public class StateMachineStateQueryElement : TrackingQueryElement
    {
        // NOTE: this string is implicitly dependancy on StateMachineTrackingRecord.StateMachineStateRecordName
        // The value should not be updated without updating the referenced location too.
        private static readonly string StateMachineStateRecordName = "System.Activities.Statements.StateMachine";
        private ConfigurationPropertyCollection properties;

        /// <summary>
        /// Gets or sets the Activity name filter attribute in StateMachineTrackingQuery element.
        /// </summary>
        [ConfigurationProperty(TrackingConfigurationStrings.ActivityName, IsKey = true,
            DefaultValue = TrackingConfigurationStrings.StarWildcard)]
        [StringValidator(MinLength = 1)]
        [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule,
            MessageId = "System.ServiceModel.Activities.Tracking.Configuration.UserTrackingQueryElement.ActivityName",
            Justification = "StringValidator verifies minimum size")]
        public string ActivityName
        {
            get
            {
                return (string)base[TrackingConfigurationStrings.ActivityName];
            }

            set
            {
                base[TrackingConfigurationStrings.ActivityName] = value;
            }
        }

        /// <summary>
        /// Gets the attributes in StateMachineTrackingQuery element.
        /// </summary>
        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                if (this.properties == null)
                {
                    ConfigurationPropertyCollection properties = base.Properties;
                    properties.Add(new ConfigurationProperty(
                        TrackingConfigurationStrings.ActivityName,
                        typeof(string),
                        "*",
                        null,
                        new StringValidator(1, int.MaxValue, null),
                        System.Configuration.ConfigurationPropertyOptions.IsKey));
                    this.properties = properties;
                }

                return this.properties;
            }
        }

        /// <summary>
        /// Creates a StateMachine-specific CustomTrackingQuery, if the user specifies StateMachineTrackingQuery element in app.config.
        /// </summary>
        /// <returns>
        /// A CustomTrackingQuery instance that tracks StateMachine specific TrackingRecord.
        /// </returns>
        protected override TrackingQuery NewTrackingQuery()
        {
            // NOTE: to avoid a strict dependency over System.Activities.Statements.dll
            // we rely on the fact that StateMachineTrackingQuery is
            // derived from CustomTrackingQuery and is only a
            // CustomTrackingQuery instance with a specific name.
            // Therefore, this method would essentially create a StateMachineTrackingQuery instance.
            return new CustomTrackingQuery
            {
                Name = StateMachineStateRecordName,
                ActivityName = this.ActivityName
            };
        }
    }
}


text:
<!DOCTYPE html>
<html>
    <head>
        <title>{{title}}</title>
        <link rel='stylesheet' href='/style.css' type='text/css' media='screen' />
    </head>
    <body>
        <div id='content'>
            {{{yield}}}
        </div>
        <script type='text/javascript' src='/jquery-1.4.2.min.js' ></script>
        <script type='text/javascript' src='/black-book.js' ></script>
    </body>
</html>


text:
#ifndef JAVAHL_DIFF_OPTIONS_H
#define JAVAHL_DIFF_OPTIONS_H

#include <apr_tables.h>
#include "svn_types.h"
#include "svn_diff.h"
#include "Pool.h"
#include "JNIUtil.h"

class DiffOptions
{
 public:
  DiffOptions(jobject joptions);

  apr_array_header_t *optionsArray(SVN::Pool &resultPool) const;
  svn_diff_file_options_t *fileOptions(SVN::Pool &resultPool) const;

  svn_boolean_t useGitDiffFormat() const
  {
    return (flags & USE_GIT_DIFF_FORMAT ? TRUE : FALSE);
  }

 private:
  static const jint IGNORE_ALL_SPACE    = 0x01;
  static const jint IGNORE_SPACE_CHANGE = 0x02;
  static const jint IGNORE_EOL_STYLE    = 0x04;
  static const jint SHOW_C_FUNCTION     = 0x08;
  static const jint USE_GIT_DIFF_FORMAT = 0x10;

  const jint flags;
};

#endif /* JAVAHL_DIFF_OPTIONS_H */


text:
package org.apache.accumulo.monitor.rest.tservers;

import org.apache.accumulo.core.master.thrift.TableInfo;
import org.apache.accumulo.core.master.thrift.TabletServerStatus;

/**
 *
 * To use for XML Resource
 *
 * @since 2.0.0
 *
 */
public class TabletServer {

  // Variable names become JSON keys
  public TabletServerInformation server = new TabletServerInformation();

  public TabletServer() {}

  public TabletServer(TabletServerInformation server) {
    this.server = server;
  }

  public TabletServer(TabletServerStatus status) {
    server = new TabletServerInformation(status);
  }

  public void updateTabletServerInfo(TabletServerStatus status, TableInfo summary) {
    server.updateTabletServerInfo(status, summary);
  }
}


text:
import {Component} from '@angular/core';
import {Hero} from '../models/hero';

@Component({
  moduleId:module.id,
  selector:'hero-form',
  templateUrl:'../template/hero-form.component.html'
})
export class HeroFormComponent{
  powers = ['Really Smart', 'Super Flexible',
  'Super Hot', 'Weather Changer'];
  model = new Hero(18,'Dr IQ', this.powers[0],'Chuck Overstreet');

  submitted = false;
  onSubmit(){
    this.submitted = true;
  }
  //TODO: Remove this when we're done
  get diagnostic(){
    return JSON.stringify(this.model);
  }
  newHero(){
    this.model=new Hero(42,'','');
  }

}


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Material Design Bootstrap</title>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">
    <!-- Bootstrap core CSS -->
    <link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">
    <!-- Material Design Bootstrap -->
    <link href="<?php echo base_url(); ?>css/mdb.min.css" rel="stylesheet">
    <!-- Your custom styles (optional) -->
    <link href="<?php echo base_url(); ?>css/style.css" rel="stylesheet">
<style>
   <!-- TABS CSS -->
a:hover {
    color: #000;
    text-decoration: underline;
}
a {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
       <!-- TABS CSS  -->

nav-tabs .nav-item.show .nav-link, .nav-tabs .nav-link.active {
    color: #464a4c;
    background-color: #ff3547;
    border-color: #fff #fff #fff;
}

</style>
</head>
<body>


text:
from django import db
from django.conf import settings
from django.core.management.base import NoArgsCommand
from django.core.exceptions import MultipleObjectsReturned
from data.models import FoodSecurityStateRaw
import csv

# National Priorities Project Data Repository
# import_food_security_state.py

# Imports food security from the Census' Current Population Food Security Supplement
# source info: Data Ferrett (current population survey-->food security-->GESTCEN (geography variables) & HRFS12MD (food security supplement variables)
# npp csv:
# destination model:  FoodSecurityStateRaw

# HOWTO:
# 1) Log into the data ferrett and create a table using the above variables
# 2) "Make a table"
# 3) Use states as columns and the HRFS12MD variable contents as the columns
# 4) Select HHSUPWGT as the weighting variable (adjusts for household non-responses)
# 5) Save table as a .csv
# 2) Convert saved .csv to same formatting as npp csv
# 3) change SOURCE_FILE variable to the the path of the source file you just created
# 4) Run as Django management command from your project path "python manage.py import_food_security

# Safe to re-run: YES

SOURCE_FILE = '%s/hunger/foodsecurity.csv' % (settings.LOCAL_DATA_ROOT)
SOURCE_FILE_OLD = '%s/hunger/foodsecurity-pre2005.csv' % (settings.LOCAL_DATA_ROOT) #this is here for a one-time load of older data

class Command(NoArgsCommand):

    def handle_noargs(self, **options):

        def clean_num(value):
            if value.strip()=='':
                value=None
            else:
                value = value.replace(",","")
                value = int(value)
            return value

        insert_count = 0
        update_count = 0
        data_reader = csv.reader(open(SOURCE_FILE))

        print 'loading food security'
        for i, row in enumerate(data_reader):
            if i == 0:
                header_row = row;
            else:
                if row[0].strip().lower().find('total') != -1:
                    state = 'US'
                else:
                    state = row[0].strip()
                if len(state):
                    year = row[7]
                    try:
                        record = FoodSecurityStateRaw.objects.get(year=year,state=state)
                        update_count = update_count + 1
                    except MultipleObjectsReturned:
                        print 'error: multiple records exists for %s %s' % (year, state)
                    except:
                        insert_count = insert_count + 1
                        record = FoodSecurityStateRaw()
                        record.year = year
                        record.state = state

                    record.household_total = clean_num(row[1])
                    record.no_response = clean_num(row[2])
                    record.food_secure_high = clean_num(row[3])
                    record.food_secure_marginal = clean_num(row[4])
                    record.food_secure_low = clean_num(row[5])
                    record.food_secure_very_low = clean_num(row[6])

                    #print '%s %s %s' % (record.year, record.state, record.household_total)
                    record.save()
                    db.reset_queries()

        print 'done loading food security. %s records updated and %s records inserted' % (update_count, insert_count)

        #one time load for pre-2005 data, which is formatted a little differently and uses HRFS12M1 instead of HRFS12MD
        try:
            data_reader = csv.reader(open(SOURCE_FILE_OLD))
        except:
            return

        insert_count = 0
        update_count = 0
        print 'loading pre-2005 food security data'

        for i, row in enumerate(data_reader):
            if i == 0:
                header_row = row;
            else:
                if row[0].strip().lower().find('total') != -1:
                    state = 'US'
                else:
                    state = row[0].strip()
                if len(state):
                    year = row[7]
                    try:
                        record = FoodSecurityStateRaw.objects.get(year=year,state=state)
                        update_count = update_count + 1
                    except MultipleObjectsReturned:
                        print 'error: multiple records exists for %s %s' % (year, state)
                    except:
                        record = FoodSecurityStateRaw()
                        record.year = year
                        record.state = state
                        insert_count = insert_count + 1

                    record.household_total = clean_num(row[1])
                    record.no_response = clean_num(row[2])
                    record.food_secure = clean_num(row[4])
                    record.food_secure_low = clean_num(row[5])
                    record.food_secure_very_low = clean_num(row[6])

                    record.save()
                    db.reset_queries()

        print 'done loading pre-2005 food security. %s records updated and %s records inserted' % (update_count, insert_count)


text:
package com.yahoo.yqlplus.engine.internal.bytecode;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yahoo.yqlplus.api.types.YQLStructType;
import com.yahoo.yqlplus.api.types.YQLType;
import com.yahoo.yqlplus.engine.internal.plan.types.BytecodeExpression;
import com.yahoo.yqlplus.engine.internal.plan.types.ProgramValueTypeAdapter;
import com.yahoo.yqlplus.engine.internal.plan.types.TypeWidget;
import com.yahoo.yqlplus.engine.internal.plan.types.base.TypeAdaptingWidget;
import com.yahoo.yqlplus.language.parser.ProgramCompileException;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;

import javax.inject.Inject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

public class ASMClassSource {
    private static final AtomicLong ELEMENT_FACTORY = new AtomicLong(0);
    private Map<String, ClassLoader> loaderMap = Maps.newHashMap();
    private Set<ClassLoader> loaders = Sets.newIdentityHashSet();

    private final ConstantTable constantTable;
    private final ClassLoader loader = getClass().getClassLoader();
    private final ClassLoader compoundClassLoader;
    private final GeneratedClassLoader generatedClassLoader;
    private final String uniqueElement;
    private ASMProgramTypeAdapter types;

    private Set<String> usedNames = Sets.newHashSet();
    final List<UnitGenerator> units = Lists.newArrayList();
    boolean built = false;

    @Inject
    public ASMClassSource(Set<TypeAdaptingWidget> adapters, TypeAdaptingWidget defaultTypeAdapter) {
        this.uniqueElement = "gen" + ELEMENT_FACTORY.incrementAndGet();
        this.constantTable = new ConstantTable(this);
        this.types = new ASMProgramTypeAdapter(this, adapters, defaultTypeAdapter);
        this.compoundClassLoader = new CompoundClassLoader();
        this.generatedClassLoader = new GeneratedClassLoader(compoundClassLoader);
    }

    public ASMClassSource(ClassLoader parentClassloader) {
        this.uniqueElement = "gen" + ELEMENT_FACTORY.incrementAndGet();
        this.constantTable = new ConstantTable(this);
        this.compoundClassLoader = new CompoundClassLoader(parentClassloader);
        this.generatedClassLoader = new GeneratedClassLoader(compoundClassLoader);
    }

    public ASMClassSource createChildSource() {
        ASMClassSource childSource = new ASMClassSource(generatedClassLoader);
        childSource.types = types.createChild(childSource);
        return childSource;
    }

    public ASMClassSource createChildSource(ClassLoader classLoader) {
        ASMClassSource childSource = new ASMClassSource(classLoader);
        childSource.types = types.createChild(childSource);
        return childSource;
    }

    public String getUniqueElement() {
        return uniqueElement;
    }

    public String generateUniqueElement() {
        return "unit" + ELEMENT_FACTORY.incrementAndGet();
    }

    public void trace(OutputStream out) {
        List<UnitGenerator> reversed = Lists.newArrayList(units);
        Collections.reverse(reversed);
        for (UnitGenerator unit : reversed) {
            unit.trace(out);
        }
    }

    public void dump(OutputStream out) {
        generatedClassLoader.dump(new PrintStream(out));
    }

    public Type getType(Class<?> clazz) {
        addClass(clazz);
        return Type.getType(clazz);
    }

    public ProgramValueTypeAdapter getValueTypeAdapter() {
        return types;
    }

    public void addUnit(UnitGenerator unitGenerator) {
        Preconditions.checkState(!built, "ASMClassSource cannot be added to once built");
        if (usedNames.contains(unitGenerator.internalName)) {
            throw new ProgramCompileException("Duplicate class definition '%s'", unitGenerator.internalName);
        }
        usedNames.add(unitGenerator.internalName);
        units.add(unitGenerator);
    }

    public TypeWidget resultTypeFor(TypeWidget valueType) {
        return types.resultTypeFor(valueType);
    }

    public void analyze(OutputStream err) {
        generatedClassLoader.analyze(err);
    }

    public YQLType createYQLType(TypeWidget type) {
        return types.createYQLType(type);
    }

    private static class UnitPrep {
        final UnitGenerator unit;
        final List<String> names = Lists.newArrayList();

        UnitPrep(UnitGenerator unit) {
            this.unit = unit;
        }
    }

    public void build() throws IOException, ClassNotFoundException {
        Preconditions.checkState(!built, "ASMClassSource may only be built once");
        DynamicBootstrapUnit bootstrapper = new DynamicBootstrapUnit(this);
        bootstrapper.init();
        built = true;

        List<UnitPrep> unitPreps = Lists.newArrayList();
        List<UnitGenerator> reversed = Lists.newArrayList(units);
        Collections.reverse(reversed);
        for (UnitGenerator unit : reversed) {
            UnitPrep unitPrep = new UnitPrep(unit);
            unitPreps.add(unitPrep);
            ByteClassGenerator classes = new ByteClassGenerator();
            try {
                unit.generate(classes);
            } catch (NullPointerException |  ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {
                // this is almost inevitably an error from visitMaxes
                // so let's dump some data
                unit.trace(System.err);
                throw e;
            }
            for (Map.Entry<String, byte[]> e : classes) {
                generatedClassLoader.put(e.getKey(), e.getValue());
                unitPrep.names.add(e.getKey());
            }
        }
        Collections.reverse(unitPreps);
        for (UnitPrep unit : unitPreps) {
            for (String name : unit.names) {
                try {
                    generatedClassLoader.loadClass(name);
                } catch (ClassNotFoundException | ClassFormatError | VerifyError e) {
                    byte[] data = generatedClassLoader.getBytes(name);
                    ClassReader reader = new ClassReader(data);
                    TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(System.err));
                    reader.accept(tcv, 0);
                    ClassVisitor cc = new CheckClassAdapter(new ClassWriter(0), true);
                    new ClassReader(data).accept(cc, 0);
                    throw e;
                }
            }
        }

        for (UnitPrep unit : unitPreps) {
            for (String name : unit.names) {
                try {
                    Class<?> clazz = generatedClassLoader.getClass(name.replace('/', '.'));
                    unit.unit.prepare(clazz);
                } catch (ClassFormatError | VerifyError e) {
                    byte[] data = generatedClassLoader.getBytes(name);
                    ClassReader reader = new ClassReader(data);
                    TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(System.err));
                    reader.accept(tcv, 0);
                    ClassVisitor cc = new CheckClassAdapter(new ClassWriter(0), true);
                    new ClassReader(data).accept(cc, 0);
                    throw e;
                }
            }
        }
    }

    public Class<?> getGeneratedClass(UnitGenerator unitGenerator) throws ClassNotFoundException {
        return generatedClassLoader.loadClass(unitGenerator.className);
    }

    void addClass(Class<?> clazz) {
        if (clazz.getClassLoader() != null) {
            loaders.add(clazz.getClassLoader());
            loaderMap.put(clazz.getName(), clazz.getClassLoader());
        }
    }

    public BytecodeExpression constant(Object value) {
        return types.constant(value);
    }

    public BytecodeExpression constant(TypeWidget type, Object value) {
        return constantTable.constant(type, value);
    }

    public TypeWidget adapt(YQLType type) {
        return types.defaultRepresentation(type);
    }

    public TypeWidget adaptInternal(Class<?> clazz) {
        addClass(clazz);
        return types.adaptInternal(clazz);
    }

    public TypeWidget resolveStruct(YQLStructType valueType) {
        return types.defaultRepresentation(valueType);
    }

    public TypeWidget adaptInternal(java.lang.reflect.Type type) {
        return types.adaptInternal(type);
    }

    private class CompoundClassLoader extends ClassLoader {
        private CompoundClassLoader() {
        }

        private CompoundClassLoader(ClassLoader parent) {
            super(parent);
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            return loadClass(name, true);
        }

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            // favor our classloader
            // TODO: how bad is it that we can't avoid resolving the class?
            ClassLoader target = loaderMap.get(name);
            if (target != this && target != null) {
                return target.loadClass(name);
            }
            try {
                return loader.loadClass(name);
            } catch (ClassNotFoundException e) {
                // continue
            }
            // search all the classloaders
            for (ClassLoader loader : loaders) {
                try {
                    return loader.loadClass(name);
                } catch (ClassNotFoundException e) {
                    // continue
                }
            }
            return super.loadClass(name, resolve);
        }
    }
}


text:
@font-face {
  font-family: "Condiment";
  src: url('/css/fonts/Condiment/Condiment-Regular.woff') format('woff'), url('/css/fonts/Condiment/Condiment-Regular.ttf') format('truetype');
}

@font-face {
  font-family: "The Girl Next Door";
  src: url('/css/fonts/The_Girl_Next_Door/TheGirlNextDoor.woff') format('woff'), url('/css/fonts/The_Girl_Next_Door/TheGirlNextDoor.ttf') format('truetype');
}

@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/alan\/DevProjects\/CostSplitter\/www\/css\/_test\.scss}line{font-family:\000031}}
.test {
  color: green;
  border-radius: 6px;
}

@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/alan\/DevProjects\/CostSplitter\/www\/css\/_app\.scss}line{font-family:\000031}}
html, body {
  font-family: 'The Girl Next Door';
}

@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/alan\/DevProjects\/CostSplitter\/www\/css\/_app\.scss}line{font-family:\000035}}
.ionic-logo {
  display: block;
  margin: 15px auto;
  width: 96px;
  height: 96px;
}

@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/alan\/DevProjects\/CostSplitter\/www\/css\/_app\.scss}line{font-family:\0000312}}
.nav-bar.bar.bar-header .title {
  font-family: 'Condiment';
  font-size: 2em;
  line-height: 47px;
}

@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/alan\/DevProjects\/CostSplitter\/www\/css\/_app\.scss}line{font-family:\0000318}}
.button.add-event {
  top: 2px;
  right: 1px;
}

@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/alan\/DevProjects\/CostSplitter\/www\/css\/_app\.scss}line{font-family:\0000323}}
.currency {
  font-family: sans-serif;
}


text:
namespace ui {
class Accelerator;
class AcceleratorHistory;
}

namespace wm {
class AcceleratorDelegate;

// AcceleratorFilter filters key events for AcceleratorControler handling global
// keyboard accelerators.
class WM_EXPORT AcceleratorFilter : public ui::EventHandler {
 public:
  // AcceleratorFilter doesn't own |accelerator_history|, it's owned by
  // AcceleratorController.
  AcceleratorFilter(std::unique_ptr<AcceleratorDelegate> delegate,
                    ui::AcceleratorHistory* accelerator_history);
  ~AcceleratorFilter() override;

  // Overridden from ui::EventHandler:
  void OnKeyEvent(ui::KeyEvent* event) override;

 private:
  std::unique_ptr<AcceleratorDelegate> delegate_;
  ui::AcceleratorHistory* accelerator_history_;

  DISALLOW_COPY_AND_ASSIGN(AcceleratorFilter);
};

}  // namespace wm

#endif  // UI_WM_CORE_ACCELERATOR_FILTER_H_


text:
import Ember from 'ember';

export default Ember.Route.extend({
	model: function () {

		this.store.push({
			data: {
				type: 'test',
				id: 1,
				attributes: {}
			}
		});

		return this.store.recordForId('test', 1);
	}
});


text:
This repository contains the code used to produce the Large Scale Facial Model (LSFM) presented in:

> [**Large scale 3D Morphable Models**
J. Booth, A. Roussos, A. Ponniah, D. Dunaway, S. Zafeiriou.
*International Journal of Computer Vision (IJCV), April 2017*](https://link.springer.com/article/10.1007/s11263-017-1009-7)

> [**A 3D Morphable Model learnt from 10,000 faces**
J. Booth, A. Roussos, S. Zafeiriou, A. Ponniah, D. Dunaway.
*Proceedings of IEEE Int'l Conf. on Computer Vision and Pattern Recognition (CVPR), June 2016*](http://ibug.doc.ic.ac.uk/media/uploads/documents/0002.pdf)

It also provides [documentation about the models themselves](./MODELS.md).

## Installing and using the LSFM 3D Morphable Model construction pipeline

The code used to produce the LSFM models is **contained within this repository** and is completely open source under a **BSD license**. You are free to follow the [code's documentation](./CODE.md), which explains how to install this tool and run it yourself on a set of facial meshes to automatically build a 3D Morphable Model.

## Acquiring the LSFM Models

The **LSFM models** were produced by using this software pipeline on the (proprietary) MeIn3D dataset. For full terms and conditions, and to request access to the models, please visit the [LSFM website](http://ibug.doc.ic.ac.uk/resources/lsfm/). For technical details on the models we provide, see [MODELS.md](./MODELS.md).


text:
{-# LANGUAGE TemplateHaskell #-}

{-| Pure functions for manipulating the configuration state.

-}

{-

Copyright (C) 2014 Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module Ganeti.WConfd.ConfigState
  ( ConfigState
  , csConfigData
  , csConfigDataL
  , mkConfigState
  , bumpSerial
  , needsFullDist
  ) where

import Prelude ()
import Ganeti.Prelude

import Data.Function (on)
import System.Time (ClockTime(..))

import Ganeti.Config
import Ganeti.Lens
import Ganeti.Objects
import Ganeti.Objects.Lens

-- | In future this data type will include the current configuration
-- ('ConfigData') and the last 'FStat' of its file.
data ConfigState = ConfigState
  { csConfigData :: ConfigData
  }
  deriving (Eq, Show)

$(makeCustomLenses ''ConfigState)

-- | Creates a new configuration state.
-- This method will expand as more fields are added to 'ConfigState'.
mkConfigState :: ConfigData -> ConfigState
mkConfigState = ConfigState

bumpSerial :: (SerialNoObjectL a, TimeStampObjectL a) => ClockTime -> a -> a
bumpSerial now = set mTimeL now . over serialL succ

-- | Given two versions of the configuration, determine if its distribution
-- needs to be fully commited before returning the corresponding call to
-- WConfD.
needsFullDist :: ConfigState -> ConfigState -> Bool
needsFullDist = on (/=) (watched . csConfigData)
  where
    watched = (,,,,,,)
              <$> clusterCandidateCerts . configCluster
              <*> clusterMasterNode . configCluster
              <*> getMasterNodes
              <*> getMasterCandidates
              -- kvmd is running depending on the following:
              <*> clusterEnabledUserShutdown . configCluster
              <*> clusterEnabledHypervisors . configCluster
              <*> fmap nodeVmCapable . configNodes


text:
@interface Rev_col : CommonRView
@property (weak, nonatomic) IBOutlet UILabel *lb_text;

@end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.testing;

import com.facebook.presto.Session;
import com.facebook.presto.Session.SessionBuilder;
import com.facebook.presto.connector.system.StaticSystemTablesProvider;
import com.facebook.presto.connector.system.SystemTablesMetadata;
import com.facebook.presto.execution.QueryIdGenerator;
import com.facebook.presto.metadata.Catalog;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.spi.ConnectorId;
import com.facebook.presto.spi.connector.Connector;
import com.facebook.presto.spi.connector.ConnectorMetadata;
import com.facebook.presto.spi.connector.ConnectorSplitManager;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.security.Identity;
import com.facebook.presto.spi.transaction.IsolationLevel;
import com.facebook.presto.spi.type.TimeZoneKey;
import com.google.common.collect.ImmutableSet;

import java.util.Optional;

import static com.facebook.presto.spi.ConnectorId.createInformationSchemaConnectorId;
import static com.facebook.presto.spi.ConnectorId.createSystemTablesConnectorId;
import static java.util.Locale.ENGLISH;

public final class TestingSession
{
    public static final String TESTING_CATALOG = "testing_catalog";
    private static final QueryIdGenerator queryIdGenerator = new QueryIdGenerator();

    /*
     * Pacific/Apia
     *  - has DST (e.g. January 2017)
     *  - had DST change at midnight (on Sunday, 26 September 2010, 00:00:00 clocks were turned forward 1 hour)
     *  - had offset change since 1970 (offset in January 1970: -11:00, offset in January 2017: +14:00, offset in June 2017: +13:00)
     *  - a whole day was skipped during policy change (on Friday, 30 December 2011, 00:00:00 clocks were turned forward 24 hours)
     */
    public static final TimeZoneKey DEFAULT_TIME_ZONE_KEY = TimeZoneKey.getTimeZoneKey("Pacific/Apia");

    private TestingSession() {}

    public static SessionBuilder testSessionBuilder()
    {
        return testSessionBuilder(new SessionPropertyManager());
    }

    public static SessionBuilder testSessionBuilder(SessionPropertyManager sessionPropertyManager)
    {
        return Session.builder(sessionPropertyManager)
                .setQueryId(queryIdGenerator.createNextQueryId())
                .setIdentity(new Identity("user", Optional.empty()))
                .setSource("test")
                .setCatalog("catalog")
                .setSchema("schema")
                .setTimeZoneKey(DEFAULT_TIME_ZONE_KEY)
                .setLocale(ENGLISH)
                .setRemoteUserAddress("address")
                .setUserAgent("agent");
    }

    public static Catalog createBogusTestingCatalog(String catalogName)
    {
        ConnectorId connectorId = new ConnectorId(catalogName);
        return new Catalog(
                catalogName,
                connectorId,
                createTestSessionConnector(),
                createInformationSchemaConnectorId(connectorId),
                createTestSessionConnector(),
                createSystemTablesConnectorId(connectorId),
                createTestSessionConnector());
    }

    private static Connector createTestSessionConnector()
    {
        return new Connector()
        {
            @Override
            public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly)
            {
                return new ConnectorTransactionHandle() {};
            }

            @Override
            public ConnectorMetadata getMetadata(ConnectorTransactionHandle transaction)
            {
                return new SystemTablesMetadata(new ConnectorId("test_session_connector"), new StaticSystemTablesProvider(ImmutableSet.of()));
            }

            @Override
            public ConnectorSplitManager getSplitManager()
            {
                throw new UnsupportedOperationException();
            }
        };
    }
}


text:
package cz.metacentrum.perun.core.api.exceptions.rt;

/**
 *
 * @see cz.metacentrum.perun.core.api.exceptions.EntityNotAssignedException
 * @author Slavek Licehammer
 *
 */
public class EntityNotAssignedRuntimeException extends PerunRuntimeException {
	static final long serialVersionUID = 0;

	public EntityNotAssignedRuntimeException() {
		super();
	}

	public EntityNotAssignedRuntimeException(Throwable cause) {
		super(cause);
	}

	public EntityNotAssignedRuntimeException(String err) {
		super(err);
	}

	public EntityNotAssignedRuntimeException(String err, Throwable cause) {
		super(err, cause);
	}
}


text:
/**
 * Created by wangdi on 10/10/17.
 */
import * as types from '../actions/matrixActionsTypes';

const initialState = {
    matrix: [],
    generalColumnValues: [],
    generalRowValues: []
};

export default function counter(state = initialState, action){
    switch (action.type){
        case types.UPDATE_MATRIX:
            return Object.assign({}, state, {
                ...state,
                matrix: action.matrix
            });

        case types.RESET_MATRIX:
            return Object.assign({}, state, {
                ...state,
                matrix: action.matrix,
                generalRowValues: action.generalRowValues,
                generalColumnValues: action.generalColumnValues
            });

        case types.UPDATE_ROW_VALUE:
            return Object.assign({}, state, {
                ...state,
                generalRowValues: action.generalRowValues
            });

        case types.UPDATE_COLUMN_VALUE:
            return Object.assign({}, state, {
                ...state,
                generalColumnValues: action.generalColumnValues
            });

        default:
            return state;
    }
}


text:
* npm install
* npm run build
* npm run start

This uses the local version of rollbar in this repository.


text:
package com.splendidcode.angular.sample.login.Shiro;

import com.splendidcode.angular.sample.login.AuthInfo;
import com.splendidcode.angular.sample.login.AuthInfoFactory;
import com.splendidcode.angular.sample.login.hashing.Pbkdf2Options;
import com.splendidcode.angular.sample.login.hashing.Pbkdf2Utils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.junit.Before;
import org.junit.Test;

import static com.splendidcode.angular.sample.util.builders.Builders.newPbkdf2Options;
import static com.splendidcode.angular.sample.util.builders.Builders.newPbkdf2Utils;
import static org.fest.assertions.api.Assertions.assertThat;

public class Pbkdf2CredentialMatcherTest {

   private Pbkdf2CredentialMatcher matcher;
   private Pbkdf2Utils hasher;
   private Pbkdf2Options options;

   @Before
   public void setup() {
      options = newPbkdf2Options().build();
      hasher = newPbkdf2Utils().withOptions(options).build();
      matcher = new Pbkdf2CredentialMatcher(hasher);
   }

   @Test
   public void credentials_with_same_password_as_auth_info_match() {
      UsernamePasswordToken token = new UsernamePasswordToken("username", "password");
      AuthInfoFactory authInfoFactory = new AuthInfoFactory(hasher, options);
      AuthInfo authInfo = authInfoFactory.createAuthInfo("username", "password");
      SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("username", authInfo, "realm");
      boolean matches = matcher.doCredentialsMatch(token, authenticationInfo);
      assertThat(matches).isTrue();
   }

   @Test
   public void if_provided_credentials_are_null_it_should_not_match() {
      UsernamePasswordToken token = new UsernamePasswordToken("username", "password");
      SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("username", null, "realm");
      boolean matches = matcher.doCredentialsMatch(token, authenticationInfo);
      assertThat(matches).isFalse();
   }

   @Test
   public void credentials_with_different_password_as_auth_info_match() {
      UsernamePasswordToken token = new UsernamePasswordToken("username", "wrongPassword");
      AuthInfoFactory authInfoFactory = new AuthInfoFactory(hasher, options);
      AuthInfo authInfo = authInfoFactory.createAuthInfo("username", "password");
      SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("username", authInfo, "realm");
      boolean matches = matcher.doCredentialsMatch(token, authenticationInfo);
      assertThat(matches).isFalse();
   }
}


text:
import { StandardArticle } from "@artsy/reaction/dist/Components/Publishing/Fixtures/Articles"
import { AutocompleteList } from "client/components/autocomplete2/list"
import { mount } from "enzyme"
import { cloneDeep } from "lodash"
import React from "react"
import { Provider } from "react-redux"
import configureStore from "redux-mock-store"
import { FeaturingMentioned } from "../featuring_mentioned"
import { AdminFeaturing } from "../index"
require("typeahead.js")

describe("AdminFeaturing", () => {
  let props
  const getWrapper = (passedProps = props) => {
    const mockStore = configureStore([])
    const { article, featured, mentioned } = passedProps

    const store = mockStore({
      app: {
        channel: { type: "editorial" },
      },
      edit: {
        article,
        featured,
        mentioned,
      },
    })

    return mount(
      <Provider store={store}>
        <AdminFeaturing {...passedProps} />
      </Provider>
    )
  }

  beforeEach(() => {
    const article = cloneDeep(StandardArticle)

    props = {
      article,
      featured: {
        artist: [
          {
            _id: "123",
            name: "Pablo Picasso",
          },
        ],
        artwork: [],
      },
      mentioned: { artist: [], artwork: [] },
      metaphysicsURL: "https://metaphysics-staging.artsy.net",
      model: "artist",
      onChangeArticleAction: jest.fn(),
    }
  })

  it("Renders autocomplete fields", () => {
    const component = getWrapper()
    expect(component.find(AutocompleteList).length).toBe(6)
  })

  it("Renders feature/mentioned fields", () => {
    const component = getWrapper()
    expect(component.find(FeaturingMentioned).length).toBe(2)
  })
})


text:
# School Website Login Information.
$schoolWebsite = "https://integration.myschoolapp.com"
$apiUser = "my_username"
$apiPassword = "my_password"
$listID = "49748" # See note above about where to find the listID

# Get a login token to use for authentication
$response = Invoke-RestMethod "$schoolWebsite/api/authentication/login?username=$apiUser&password=$apiPassword&format=json"

if($response.Token) { # Did we get a token in our response?
    $token = $response.Token

	# Use the authentication token to retrieve a list.  You will need to
	# replace the list ID with one from your account.
    $response = Invoke-RestMethod "$schoolWebsite/api/list/$listID/?t=$token&format=json"

	# Convert the response to a CSV file that can be read by Excel
    $response | Export-CSV -NoTypeInformation -Encoding ascii -Path "C:/tmp/list.csv"

	# Open the list in Excel or whatever app handles CSV files
    Invoke-Item "C:\tmp\list.csv"

} else {
    echo "Login failed."
}


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"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>OPTRAJ: Référence de la classe src.util.profilehooks.HotShotFuncCoverage</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

OPTRAJ

Page principale

Paquetages

Classes

Fichiers

          <input type="text" id="MSearchField" value="Recherche" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Liste des classes

Index des classes

Hiérarchie des classes

Membres de classe

 Tout Classes Espaces de nommage Fichiers Fonctions Variables

src

util

profilehooks

HotShotFuncCoverage

Fonctions membres publiques |
Attributs publics |
Liste de tous les membres

Référence de la classe src.util.profilehooks.HotShotFuncCoverage

Coverage analysis for a function (uses _hotshot).
 Plus de détails...

Graphe de collaboration de src.util.profilehooks.HotShotFuncCoverage:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Fonctions membres publiques

def 	__init__

 	Creates a profiler for a function.  Plus de détails...

def 	__call__

 	Profile a singe call to the function.  Plus de détails...

def 	atexit

 	Stop profiling and print profile information to sys.stderr.  Plus de détails...

Attributs publics

 	fn

 	logfilename

 	profiler

 	ncalls

Description détaillée

Coverage analysis for a function (uses _hotshot).

HotShot coverage is reportedly faster than trace.py, but it appears to have problems with exceptions; also line counts in coverage reports are generally lower from line counts produced by TraceFuncCoverage. Is this my bug, or is it a problem with _hotshot?

Documentation des constructeurs et destructeur

          def src.util.profilehooks.HotShotFuncCoverage.__init__
          (

          self,

          fn

          )

Creates a profiler for a function.

Every profiler has its own log file (the name of which is derived from the function name).

HotShotFuncCoverage registers an atexit handler that prints profiling information to sys.stderr when the program terminates.

The log file is not removed and remains there to clutter the current working directory.

Documentation des fonctions membres

          def src.util.profilehooks.HotShotFuncCoverage.__call__
          (

          self,

          args,

          kw

          )

Profile a singe call to the function.

          def src.util.profilehooks.HotShotFuncCoverage.atexit
          (

          self)

Stop profiling and print profile information to sys.stderr.

This function is registered as an atexit hook.

Documentation des données membres

          src.util.profilehooks.HotShotFuncCoverage.fn

          src.util.profilehooks.HotShotFuncCoverage.logfilename

          src.util.profilehooks.HotShotFuncCoverage.ncalls

          src.util.profilehooks.HotShotFuncCoverage.profiler

La documentation de cette classe a été générée à partir du fichier suivant :

/home/sacapuces/optraj.istic.univ-rennes1.fr/vagrant/optraj.istic.univ-rennes1.fr/src/util/profilehooks.py

<address class="footer">
Généré le Jeudi Avril 24 2014 13:03:21 pour OPTRAJ par

 1.8.4
</address>


text:
require 'contracts'
require 'tasklist/task'

module Tasklist
  class Tasklist
    include Contracts

    attr_reader :tasks, :attrs

    def initialize
      @tasks = []
      @attrs = {}

      nil
    end

    Contract (Task) => nil
    def add(task)
      @tasks.push(task)
      nil
    end

    Contract Or[Tasklist,nil] => Tasklist
    def merge(tasklist)
      if tasklist then
        tasklist.tasks.each do |task|
          add(task)
        end
      end

      self
    end

    Contract Proc => Tasklist
    def select
      tasklist = Tasklist.new

      tasks.each do |task|
        tasklist.add(task) if yield task, self
      end

      tasklist
    end

    Contract String, Or[Object,nil] => Or[Object,nil]
    def attr(key, value=nil)
      if value then
        @attrs[key] = value
      end

      if @attrs.keys.include?(key) then
        return @attrs[key]
      else
        return nil
      end
    end

    Contract String => String
    def to_s
      str = Parser::TASK_START_PHRASE + "\n\n"
      tasks.each do |task|
        str += task.to_s + "\n"
      end

      str
    end
  end
end


text:
package AI::MXNet::AutoGrad;
use strict;
use warnings;
use AI::MXNet::Base;
use AI::MXNet::Function::Parameters;
use Scalar::Util qw(blessed);
use Carp qw(confess);

sub import
{
    my ($class, $short_name) = @_;
    if($short_name)
    {
        $short_name =~ s/[^\w:]//g;
        if(length $short_name)
        {
            my $short_name_package =<<"EOP";
            package $short_name;
            use parent 'AI::MXNet::AutoGrad';
            1;
EOP
            eval $short_name_package;
        }
    }
}

=head1 NAME

    AI::MXNet::AutoGrad - Autograd for NDArray.
=cut

=head2 set_is_training

    Set status to training/not training. When training, graph will be constructed
    for gradient computation. Operators will also run with ctx.is_train=True. For example,
    Dropout will drop inputs randomly when is_train=True while simply passing through
    if is_train=False.

    Parameters
    ----------
    is_train: bool

    Returns
    -------
    previous state before this set.
=cut

method set_is_training(Bool $is_train)
{
    return scalar(check_call(AI::MXNetCAPI::AutogradSetIsTraining($is_train)));
}

=head2 set_is_recording

    Set status to recording/not recording. When recording, graph will be constructed
    for gradient computation.

    Parameters
    ----------
    is_recoding: bool

    Returns
    -------
    previous state before this set.
=cut

method set_is_recording(Bool $is_recording)
{
    return scalar(check_call(AI::MXNetCAPI::AutogradSetIsRecording($is_recording)));
}

=head2 is_recording

    Get status on recording/not recording.

    Returns
    -------
    Current state of recording.
=cut

method is_recording()
{
    return scalar(check_call(AI::MXNetCAPI::AutogradIsRecording()));
}

=head2 is_training

    Get status on training/predicting.

    Returns
    -------
    Current state of training/predicting.
=cut

method is_training()
{
    return scalar(check_call(AI::MXNetCAPI::AutogradIsTraining()));
}

=head2 mark_variables

    Mark AI::MXNet::NDArrays as variables to compute gradient for autograd.

    Parameters
    ----------
    ArrayRef[AI::MXNet::NDArray] $variables
    ArrayRef[AI::MXNet::NDArray] $gradients
    GradReq|ArrayRef[GradReq]   :$grad_reqs='write'
=cut

method mark_variables(
    ArrayRef[AI::MXNet::NDArray]  $variables,
    ArrayRef[AI::MXNet::NDArray]  $gradients,
    GradReq|ArrayRef[GradReq]    :$grad_reqs='write'
)
{
    my @variable_handles = map { $_->handle } @{ $variables };
    my @gradient_handles = map { $_->handle } @{ $gradients };
    my @grad_reqs;
    if(not ref $grad_reqs)
    {
        @grad_reqs = (GRAD_REQ_MAP->{ $grad_reqs }) x scalar(@variable_handles);
    }
    else
    {
        @grad_reqs = map { GRAD_REQ_MAP->{ $_ } } @{ $grad_reqs };
    }
    check_call(
        AI::MXNetCAPI::AutogradMarkVariables(
            scalar(@variable_handles),
            \@variable_handles,
            \@grad_reqs,
            \@gradient_handles
        )
    );
}

=head2 backward

    Compute the gradients of heads w.r.t previously marked variables.

    Parameters
    ----------
    $heads: ArrayRef[AI::MXNet::NDArray]
        Output NDArray(s)
    :$head_grads=: Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]]
        Gradients with respect to heads.
    :$retain_graph=0: bool, optional
        Whether to retain graph.
    :$train_mode=1: bool, optional
        Whether to do backward for training or predicting.
=cut
method backward(
    AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] $heads,
    Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]] :$head_grads=,
    Bool :$retain_graph=0,
    Bool :$train_mode=1
)
{
    my ($head_handles, $hgrad_handles) = _parse_head($heads, $head_grads);
    check_call(
        AI::MXNetCAPI::AutogradBackwardEx(
            scalar(@{ $head_handles }),
            $head_handles,
            $hgrad_handles,
            0,
            [],
            $retain_graph,
            0,
            $train_mode
        )
    );
}

=head2 compute_gradient

    Compute the gradients of outputs w.r.t variables.

    Parameters
    ----------
    outputs: array ref of NDArray

    Returns
    -------
    gradients: array ref of NDArray
=cut

method compute_gradient(ArrayRef[AI::MXNet::NDArray] $outputs)
{
    __PACKAGE__->backward($outputs);
}

=head2 grad_and_loss

    Return function that computes both gradient of arguments and loss value.

    Parameters
    ----------
    func: a perl sub
        The forward (loss) function.
    argnum: an int or a array ref of int
        The index of argument to calculate gradient for.

    Returns
    -------
    grad_and_loss_func: a perl sub
        A function that would compute both the gradient of arguments and loss value.
=cut

method grad_and_loss(CodeRef $func, Maybe[Int|ArrayRef[Int]] $argnum=)
{
    return sub {
        my @args = @_;
        my @variables = @_;
        if(defined $argnum)
        {
            my @argnum = ref $argnum ? @$argnum : ($argnum);
            @variables = map { $args[$_] } @argnum;
        }
        map {
            assert(
                (blessed($_) and $_->isa('AI::MXNet::NDArray')),
                "type of autograd input should NDArray")
        } @variables;
        my @grads = map { $_->zeros_like } @variables;
        __PACKAGE__->mark_variables(\@variables, \@grads);
        my $outputs;
        __PACKAGE__->record(sub { $outputs = $func->(@args) });
        __PACKAGE__->backward(ref $outputs eq 'ARRAY' ? $outputs : [$outputs]);
        return (\@grads, $outputs);
    };
}

=head2 grad

    Compute the gradients of heads w.r.t variables. Gradients will be
    returned as new NDArrays instead of stored into `variable.grad`.
    Supports recording gradient graph for computing higher order gradients.

    .. Note: Currently only a very limited set of operators support higher order
    gradients.

    Parameters
    ----------
    $heads: NDArray or array ref of NDArray
        Output NDArray(s)
    $variables: NDArray or list of NDArray
        Input variables to compute gradients for.
    :$head_grads=: NDArray or list of NDArray or undef
        Gradients with respect to heads.
    :$retain_graph=: bool
        Whether to keep computation graph to differentiate again, instead
        of clearing history and release memory. Defaults to the same value
        as create_graph.
    :$create_graph=0: bool
        Whether to record gradient graph for computing higher order
    $train_mode=1: bool, optional
        Whether to do backward for training or prediction.

    Returns
    -------
    NDArray or list of NDArray:
        Gradients with respect to variables.

    Examples
    --------
    >>> $x = mx->nd->ones([1]);
    >>> $x->attach_grad();
    >>> mx->autograd->record(sub {
            $z = mx->nd->elemwise_add(mx->nd->exp($x), $x);
        });
    >>> $dx = mx->autograd->grad($z, [$x], create_graph=>1)
    >>> $dx->backward();
    >>> print($dx->grad->aspdl)
    [3.71828175]
=cut

method grad(
    AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] $heads,
    AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] $variables,
    Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]] :$head_grads=,
    Bool :$retain_graph=,
    Bool :$create_graph=0,
    Bool :$train_mode=1
)
{
    my ($head_handles, $hgrad_handles) = _parse_head($heads, $head_grads);
    my @var_handles;
    if(blessed $variables)
    {
        @var_handles = ($variables->handle);
    }
    else
    {
        assert(scalar(@{ $variables }), "variables cannot be an empty array.");
        @var_handles = map { $_->handle } @{ $variables };
    }

    $retain_graph //= $create_graph;

    my ($grad_vars, $grad_stypes)
        =
    check_call(
        AI::MXNetCAPI::AutogradBackwardEx(
            scalar(@{ $head_handles }),
            $head_handles,
            $hgrad_handles,
            scalar(@var_handles),
            \@var_handles,
            $retain_graph,
            $create_graph,
            $train_mode
        )
    );

    my @ret;
    zip(sub {
        my ($handle, $stype) = @_;
        push @ret, AI::MXNet::NDArray->new(handle => $handle, stype => $stype);
    }, $grad_vars, $grad_stypes);
    if(blessed $variables)
    {
        return $ret[0];
    }
    return \@ret;
}

=head2 train_mode

    Executes $sub within an autograd training scope context.
    Parameters
    ----------
    CodeRef $sub: a perl sub
=cut

method train_mode(CodeRef $sub)
{
    my $prev = __PACKAGE__->set_is_training(1);
    eval { $sub->(); };
    __PACKAGE__->set_is_training(0) unless $prev;
    confess($@) if $@;
}

=head2 predict_mode

    Executes $sub within an autograd predicting scope context.
    Parameters
    ----------
    CodeRef $sub: a perl sub
=cut

method predict_mode(CodeRef $sub)
{
    my $prev = __PACKAGE__->set_is_training(0);
    eval { $sub->(); };
    __PACKAGE__->set_is_training(1) if $prev;
    confess($@) if $@;
}

=head2 record

    Executes $sub within an autograd recording scope context
    and captures code that needs gradients to be calculated.
    Parameters
    ----------
    CodeRef $sub: a perl sub
    Maybe[Bool] :$train_mode=1
=cut

method record(CodeRef $sub, Maybe[Bool] :$train_mode=1)
{
    my $prev_train;
    if(defined $train_mode)
    {
        $prev_train = __PACKAGE__->set_is_training($train_mode);
    }
    my $prev_recording = __PACKAGE__->set_is_recording(1);
    eval { $sub->(); };
    if(defined $train_mode)
    {
        $prev_train = __PACKAGE__->set_is_training($prev_train) if not $prev_train == $train_mode;
    }
    __PACKAGE__->set_is_recording(0) unless $prev_recording;
    confess($@) if $@;
}

=head2 pause

    Executes $sub within an autograd recording scope context
    and captures code that needs gradients to be calculated.
    Parameters
    ----------
    CodeRef $sub: a perl sub
    Maybe[Bool] :$train_mode=0
=cut

method pause(CodeRef $sub, Maybe[Bool] :$train_mode=0)
{
    my $prev_train;
    if(defined $train_mode)
    {
        $prev_train = __PACKAGE__->set_is_training($train_mode);
    }
    my $prev_recording = __PACKAGE__->set_is_recording(0);
    eval { $sub->(); };
    if(defined $train_mode)
    {
        $prev_train = __PACKAGE__->set_is_training($prev_train) if not $prev_train == $train_mode;
    }
    __PACKAGE__->set_is_recording(1) if $prev_recording;
    confess($@) if $@;
}

=head2 get_symbol

    Retrieve recorded computation history as `Symbol`.

    Parameters
    ----------
    x : NDArray
        Array representing the head of computation graph.
    Returns
    -------
    Symbol
        The retrieved Symbol.
=cut

method get_symbol(AI::MXNet::NDArray $x)
{
    my $handle = scalar(check_call(AI::MXNetCAPI::AutogradGetSymbol($x->handle)));
    return AI::MXNet::Symbol->new(handle => $handle);
}

# parse head gradient for backward and grad.
func _parse_head($heads, $head_grads)
{
    if(blessed $heads)
    {
        $heads = [$heads];
    }
    if(blessed $head_grads)
    {
        $head_grads = [$head_grads];
    }
    my @head_handles = map { $_->handle } @{ $heads };
    my @hgrad_handles;
    if(defined $head_grads)
    {
        assert(
            (@{ $heads } == @{ $head_grads }),
            "heads and head_grads must be lists of the same length"
        );
        @hgrad_handles = map { defined($_) ? $_->handle : undef } @{ $head_grads };
    }
    return (\@head_handles, \@hgrad_handles);
}

1;