text:
import logging

from django.forms import ValidationError
from django.utils.translation import force_unicode, ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables

from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.utils import validators

from openstack_dashboard import api

LOG = logging.getLogger(__name__)

class BaseUserForm(forms.SelfHandlingForm):
    def __init__(self, request, *args, **kwargs):
        super(BaseUserForm, self).__init__(request, *args, **kwargs)
        # Populate tenant choices
        tenant_choices = [('', _("Select a project"))]

        for tenant in api.keystone.tenant_list(request, admin=True):
            if tenant.enabled:
                tenant_choices.append((tenant.id, tenant.name))
        self.fields['tenant_id'].choices = tenant_choices

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(forms.Form, self).clean()
        if 'password' in data:
            if data['password'] != data.get('confirm_password', None):
                raise ValidationError(_('Passwords do not match.'))
        return data

ADD_PROJECT_URL = "horizon:admin:projects:create"

class CreateUserForm(BaseUserForm):
    name = forms.CharField(label=_("User Name"))
    email = forms.EmailField(label=_("Email"))
    password = forms.RegexField(
            label=_("Password"),
            widget=forms.PasswordInput(render_value=False),
            regex=validators.password_validator(),
            error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
            label=_("Confirm Password"),
            required=False,
            widget=forms.PasswordInput(render_value=False))
    tenant_id = forms.DynamicChoiceField(label=_("Primary Project"),
                                         add_item_link=ADD_PROJECT_URL)
    role_id = forms.ChoiceField(label=_("Role"))

    def __init__(self, *args, **kwargs):
        roles = kwargs.pop('roles')
        super(CreateUserForm, self).__init__(*args, **kwargs)
        role_choices = [(role.id, role.name) for role in roles]
        self.fields['role_id'].choices = role_choices

    # We have to protect the entire "data" dict because it contains the
    # password and confirm_password strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        try:
            LOG.info('Creating user with name "%s"' % data['name'])
            new_user = api.keystone.user_create(request,
                                                data['name'],
                                                data['email'],
                                                data['password'],
                                                data['tenant_id'],
                                                True)
            messages.success(request,
                             _('User "%s" was successfully created.')
                             % data['name'])
            if data['role_id']:
                try:
                    api.keystone.add_tenant_user_role(request,
                                             data['tenant_id'],
                                             new_user.id,
                                             data['role_id'])
                except:
                    exceptions.handle(request,
                                      _('Unable to add user'
                                        'to primary project.'))
            return new_user
        except:
            exceptions.handle(request, _('Unable to create user.'))

class UpdateUserForm(BaseUserForm):
    id = forms.CharField(label=_("ID"), widget=forms.HiddenInput)
    name = forms.CharField(label=_("User Name"))
    email = forms.EmailField(label=_("Email"))
    password = forms.RegexField(label=_("Password"),
            widget=forms.PasswordInput(render_value=False),
            regex=validators.password_validator(),
            required=False,
            error_messages={'invalid':
                    validators.password_validator_msg()})
    confirm_password = forms.CharField(
            label=_("Confirm Password"),
            widget=forms.PasswordInput(render_value=False),
            required=False)
    tenant_id = forms.ChoiceField(label=_("Primary Project"))

    def __init__(self, request, *args, **kwargs):
        super(UpdateUserForm, self).__init__(request, *args, **kwargs)

        if api.keystone.keystone_can_edit_user() is False:
            for field in ('name', 'email', 'password', 'confirm_password'):
                self.fields.pop(field)

    # We have to protect the entire "data" dict because it contains the
    # password and confirm_password strings.
    @sensitive_variables('data', 'password')
    def handle(self, request, data):
        failed, succeeded = [], []
        user_is_editable = api.keystone.keystone_can_edit_user()
        user = data.pop('id')
        tenant = data.pop('tenant_id')

        if user_is_editable:
            password = data.pop('password')
            data.pop('confirm_password', None)

        if user_is_editable:
            # Update user details
            msg_bits = (_('name'), _('email'))
            try:
                api.keystone.user_update(request, user, **data)
                succeeded.extend(msg_bits)
            except:
                failed.extend(msg_bits)
                exceptions.handle(request, ignore=True)

        # Update default tenant
        msg_bits = (_('primary project'),)
        try:
            api.keystone.user_update_tenant(request, user, tenant)
            succeeded.extend(msg_bits)
        except:
            failed.append(msg_bits)
            exceptions.handle(request, ignore=True)

        # Check for existing roles
        # Show a warning if no role exists for the tenant
        user_roles = api.keystone.roles_for_user(request, user, tenant)
        if not user_roles:
            messages.warning(request,
                             _('The user %s has no role defined for' +
                             ' that project.')
                             % data.get('name', None))

        if user_is_editable:
            # If present, update password
            # FIXME(gabriel): password change should be its own form and view
            if password:
                msg_bits = (_('password'),)
                try:
                    api.keystone.user_update_password(request, user, password)
                    succeeded.extend(msg_bits)
                except:
                    failed.extend(msg_bits)
                    exceptions.handle(request, ignore=True)

        if succeeded:
            messages.success(request, _('User has been updated successfully.'))
        if failed:
            failed = map(force_unicode, failed)
            messages.error(request,
                           _('Unable to update %(attributes)s for the user.')
                             % {"attributes": ", ".join(failed)})
        return True


text:
package framing

import (
	"errors"
	"fmt"
	"io"
	"reflect"
	"testing"
)

func TestNewDecoder(t *testing.T) {
	var (
		byteCopy = UnmarshalFunc(func(b []byte, m interface{}) error {
			if m == nil {
				return errors.New("unmarshal target may not be nil")
			}
			v, ok := m.(*[]byte)
			if !ok {
				return fmt.Errorf("expected *[]byte instead of %T", m)
			}
			if v == nil {
				return errors.New("target *[]byte may not be nil")
			}
			*v = append((*v)[:0], b...)
			return nil
		})
		fakeError        = errors.New("fake unmarshal error")
		errorUnmarshaler = UnmarshalFunc(func(_ []byte, _ interface{}) error {
			return fakeError
		})
		singletonReader = func(b []byte) ReaderFunc {
			eof := false
			return func() ([]byte, error) {
				if eof {
					panic("reader should only be called once")
				}
				eof = true
				return b, io.EOF
			}
		}
		errorReader = func(err error) ReaderFunc {
			return func() ([]byte, error) { return nil, err }
		}
	)
	for ti, tc := range []struct {
		r        Reader
		uf       UnmarshalFunc
		wants    []byte
		wantsErr error
	}{
		{errorReader(ErrorBadSize), byteCopy, nil, ErrorBadSize},
		{singletonReader(([]byte)("james")), byteCopy, ([]byte)("james"), io.EOF},
		{singletonReader(([]byte)("james")), errorUnmarshaler, nil, fakeError},
	} {
		var (
			buf []byte
			d   = NewDecoder(tc.r, tc.uf)
			err = d.Decode(&buf)
		)
		if err != tc.wantsErr {
			t.Errorf("test case %d failed: expected error %q instead of %q", ti, tc.wantsErr, err)
		}
		if !reflect.DeepEqual(buf, tc.wants) {
			t.Errorf("test case %d failed: expected %#v instead of %#v", ti, tc.wants, buf)
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package characters;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
 *
 * @author mars
 */
public class DateDisplay {
    public static void main(String[] args){
    Date today = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat();
    SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE MMMM dd, yyyy");
        //default short format display
        System.out.println(String.format("Today is %s", sdf.format(today)));

        //programmer-designated long format display
        System.out.println(String.format("Today is %s", sdf2.format(today)));
    }
}


text:
package it.soft.domain;

import java.io.Serializable;
import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

/**
 * The persistent class for the stampe_solleciti database table.
 *
 */
@Entity
@Table(name = "stampe_solleciti")
public class StampeSolleciti implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idstampe_solleciti")
    private BigDecimal idstampeSolleciti;

    @Column(name = "data_inserimento")
    private String dataInserimento;

    @Column(name = "data_scadenza")
    private String dataScadenza;

    @Lob()
    private byte[] file;

    @Column(name = "giorni_validita_alert")
    private Integer giorniValiditaAlert;

    @Column(name = "id_abuso")
    private BigDecimal idAbuso;

    @Column(name = "id_pratica")
    private BigDecimal idPratica;

    @Column(name = "nome_file_stampa")
    private String nomeFileStampa;

    @Column(name = "pratica_evasa")
    private Boolean praticaEvasa;

    @Column(name = "progressivo_abuso")
    private Integer progressivoAbuso;

    public StampeSolleciti() {
    }

    public BigDecimal getIdstampeSolleciti() {
	return this.idstampeSolleciti;
    }

    public void setIdstampeSolleciti(BigDecimal idstampeSolleciti) {
	this.idstampeSolleciti = idstampeSolleciti;
    }

    public String getDataInserimento() {
	return this.dataInserimento;
    }

    public void setDataInserimento(String dataInserimento) {
	this.dataInserimento = dataInserimento;
    }

    public String getDataScadenza() {
	return this.dataScadenza;
    }

    public void setDataScadenza(String dataScadenza) {
	this.dataScadenza = dataScadenza;
    }

    public byte[] getFile() {
	return this.file;
    }

    public void setFile(byte[] file) {
	this.file = file;
    }

    public int getGiorniValiditaAlert() {
	return this.giorniValiditaAlert;
    }

    public void setGiorniValiditaAlert(int giorniValiditaAlert) {
	this.giorniValiditaAlert = giorniValiditaAlert;
    }

    public BigDecimal getIdAbuso() {
	return this.idAbuso;
    }

    public void setIdAbuso(BigDecimal idAbuso) {
	this.idAbuso = idAbuso;
    }

    public BigDecimal getIdPratica() {
	return this.idPratica;
    }

    public void setIdPratica(BigDecimal idPratica) {
	this.idPratica = idPratica;
    }

    public String getNomeFileStampa() {
	return this.nomeFileStampa;
    }

    public void setNomeFileStampa(String nomeFileStampa) {
	this.nomeFileStampa = nomeFileStampa;
    }

    public Boolean getPraticaEvasa() {
	return this.praticaEvasa;
    }

    public void setPraticaEvasa(Boolean praticaEvasa) {
	this.praticaEvasa = praticaEvasa;
    }

    public int getProgressivoAbuso() {
	return this.progressivoAbuso;
    }

    public void setProgressivoAbuso(int progressivoAbuso) {
	this.progressivoAbuso = progressivoAbuso;
    }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Recursos para la Facultad de Ciencias Médicas de la Universidad de San Carlos de Guatemala, anatomia, Fisiologia, bioquimica, salud publica, Semiologia médica, ayuda para estudiantes, Sección de Semiología Médica">
  <meta name="author" content="Jorge A.M.L. AML Productions y Solarin Industries.">
  <link rel="icon" href="pictures/icon.png">
  <meta property="og:image" content="../pictures/icon.png" />
	<title>Dermatología Médica</title>

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

    <link href="https://fonts.googleapis.com/css?family=Patrick+Hand+SC" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Neucha" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="css/theme-aml/paper_style.css">
    <link rel="stylesheet" media="(max-width: 736px)" href="css/theme-aml/responsive/max-paper-736px.css">
    <link rel="stylesheet" media="(min-width: 860px)" href="css/theme-aml/responsive/min-paper-768px.css">

    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" rel="stylesheet">
    <link href="css/bootstrap/ie10-viewport-bug-workaround.css" rel="stylesheet">


text:
package de.fintasys.the_15_puzzle_game;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;

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

import butterknife.ButterKnife;
import de.fintasys.the_15_puzzle_game.adapter.MediaGalleryAdapter;
import de.fintasys.the_15_puzzle_game.dialogs.ErrorDialog;
import de.fintasys.the_15_puzzle_game.interfaces.IImageModel;
import de.fintasys.the_15_puzzle_game.interfaces.IMediaGalleryView;
import de.fintasys.the_15_puzzle_game.model.InstagramModel;
import de.fintasys.the_15_puzzle_game.presenter.MediaGalleryActivityPresenter;

public class MediaGalleryActivity extends AppCompatActivity implements IMediaGalleryView {

    private final String TAG = getClass().getSimpleName();

    private MediaGalleryActivityPresenter mediaGalleryAcitvityPresenter;
    private MediaGalleryAdapter adapter;
    private List<String> media;
    private final int GRID_SIZE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_gallery);
        ButterKnife.bind(this);

        if(getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        IImageModel instagramModel = new InstagramModel(this);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        mediaGalleryAcitvityPresenter = new MediaGalleryActivityPresenter(this, instagramModel);

        media = new ArrayList<>();

        // Set the adapter
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
        recyclerView.setLayoutManager(new GridLayoutManager(this, GRID_SIZE));
        adapter = new MediaGalleryAdapter(this, media, mediaClickListener, (int)(metrics.widthPixels / (float)GRID_SIZE));
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mediaGalleryAcitvityPresenter.init();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showError(String message) {
        new ErrorDialog(this, message).show();
    }

    @Override
    public void updateMedia(List<String> newMedia) {
        media.clear();
        media.addAll(newMedia);
        adapter.notifyDataSetChanged();
    }

    private View.OnClickListener mediaClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int)v.getTag();
            Intent i = new Intent();
            i.putExtra("url", media.get(position));
            setResult(RESULT_OK, i);
            finish();
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}


text:
package org.klomp.snark;

import java.net.URI;
import java.util.List;

import net.i2p.I2PAppContext;
import net.i2p.update.*;

/**
 *
Handles the request to update the router by firing up a magnet.
 * {@link net.i2p.util.EepGet} calls to download the latest signed update file
 * and displaying the status to anyone who asks.
 *

 *
After the download completes the signed update file is verified with
 * {@link net.i2p.crypto.TrustedUpdate}, and if it's authentic the payload
 * of the signed update file is unpacked and the router is restarted to complete
 * the update process.
 *

 *
 * This does not do any checking, that is handled by the NewsFetcher.
 *
 * @since 0.9.4
 */
class UpdateHandler implements Updater {
    private final I2PAppContext _context;
    private final UpdateManager _umgr;
    private final SnarkManager _smgr;

    public UpdateHandler(I2PAppContext ctx, UpdateManager umgr, SnarkManager smgr) {
        _context = ctx;
        _umgr = umgr;
        _smgr = smgr;
    }

    /**
     *  Start a download and return a handle to the download task.
     *  Should not block.
     *
     *  @param id plugin name or ignored
     *  @param maxTime how long you have
     *  @return active task or null if unable to download
     */
    public UpdateTask update(UpdateType type, UpdateMethod method, List<URI> updateSources,
                             String id, String newVersion, long maxTime) {
        if ((type != UpdateType.ROUTER_SIGNED && type != UpdateType.ROUTER_SIGNED_SU3) ||
            method != UpdateMethod.TORRENT || updateSources.isEmpty())
            return null;
        UpdateRunner update = new UpdateRunner(_context, _umgr, _smgr, type, updateSources, newVersion);
        _umgr.notifyProgress(update, "" + _smgr.util().getString("Updating") + "");
        return update;
    }
}


text:
import 'babel-polyfill';

import 'ts-helpers';

const testContext = (<{ context?: Function }>require)
  .context('./', true, /^(.(?!tests\.entry))*\.tsx?$/);

testContext('./index.tsx');
// testContext('./routers/profile/profile.page.tsx')

testContext.keys().forEach(
  key => {
    if (/\.test\.tsx?$/.test(key)) {
      testContext(key);
    }
  });


text:
@interface VIManagedObjectDefaultMapper : VIManagedObjectMapper
@end

@interface VIManagedObjectMapper()
@property (nonatomic) NSArray *mapsArray;
- (void)updateForeignComparisonKey;
- (id)checkNull:(id)inputObject;
- (id)checkDate:(id)inputObject withDateFormatter:(NSDateFormatter *)dateFormatter;
- (id)checkString:(id)outputObject withDateFormatter:(NSDateFormatter *)dateFormatter;
- (id)checkClass:(id)inputObject managedObject:(NSManagedObject *)object key:(NSString *)key;
- (Class)expectedClassForObject:(NSManagedObject *)object andKey:(id)key;
@end

@implementation VIManagedObjectMapper

+ (instancetype)mapperWithUniqueKey:(NSString *)comparisonKey andMaps:(NSArray *)mapsArray;
{
    VIManagedObjectMapper *mapper = [[self alloc] init];
    [mapper setMapsArray:mapsArray];
    [mapper setUniqueComparisonKey:comparisonKey];
    return mapper;
}

+ (instancetype)defaultMapper
{
    return [[VIManagedObjectDefaultMapper alloc] init];
}

- (id)init
{
    self = [super init];
    if (self) {
        _overwriteObjectsWithServerChanges = YES;
    }
    return self;
}

- (void)setUniqueComparisonKey:(NSString *)uniqueComparisonKey
{
    _uniqueComparisonKey = uniqueComparisonKey;
    _foreignUniqueComparisonKey = nil;
    if (uniqueComparisonKey) {
        [self updateForeignComparisonKey];
    }
}

- (void)setMapsArray:(NSArray *)mapsArray
{
    _mapsArray = mapsArray;
    _foreignUniqueComparisonKey = nil;
    if (mapsArray) {
        [self updateForeignComparisonKey];
    }
}

- (void)updateForeignComparisonKey
{
    [self.mapsArray enumerateObjectsUsingBlock:^(VIManagedObjectMap *aMap, NSUInteger idx, BOOL *stop) {
        if ([aMap.coreDataKey isEqualToString:self.uniqueComparisonKey]) {
            _foreignUniqueComparisonKey = aMap.inputKeyPath;
        }
    }];
}

#pragma mark - Description
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p>\nMaps:%@\nUniqueKey:%@",
            NSStringFromClass([self class]),
            self,
            self.mapsArray,
            self.uniqueComparisonKey];
}

#pragma mark - Import Safety Checks

- (id)checkNull:(id)inputObject
{
    if ([[NSNull null] isEqual:inputObject]) {
        return nil;
    }
    return inputObject;
}

- (id)checkNumber:(id)inputObject withNumberFormatter:(NSNumberFormatter *)numberFormatter
{
    if (![inputObject isKindOfClass:[NSString class]]) {
        return inputObject;
    }

    //Bug: using DEFAULT mapper, if the input string COULD be made a number it WILL be made a number.
    //Be wary of the default mapper
    id number = [numberFormatter numberFromString:inputObject];
    return number ? number : inputObject;
}

- (id)checkDate:(id)inputObject withDateFormatter:(NSDateFormatter *)dateFormatter
{
    if (![inputObject isKindOfClass:[NSString class]]) {
        return inputObject;
    }
    id date = [dateFormatter dateFromString:inputObject];
    return date ? date : inputObject;
}

- (id)checkString:(id)outputObject withNumberFormatter:(NSNumberFormatter *)numberFormatter
{
    if (![outputObject isKindOfClass:[NSNumber class]]) {
        return outputObject;
    }
    id numberString = [numberFormatter stringFromNumber:outputObject];
    return numberString ? numberString : outputObject;
}

- (id)checkString:(id)outputObject withDateFormatter:(NSDateFormatter *)dateFormatter
{
    if (![outputObject isKindOfClass:[NSDate class]]) {
        return outputObject;
    }
    id dateString = [dateFormatter stringFromDate:outputObject];
    return dateString ? dateString : outputObject;
}

- (id)checkClass:(id)inputObject managedObject:(NSManagedObject *)object key:(NSString *)key
{
    Class expectedClass = [self expectedClassForObject:object andKey:key];
    if (![inputObject isKindOfClass:expectedClass]) {
        CDLog(@"Wrong kind of class for %@\nProperty: %@ \nExpected: %@\nReceived: %@",
              object,
              key,
              NSStringFromClass(expectedClass),
              NSStringFromClass([inputObject class]));
        return nil;
    }
    return inputObject;
}

- (Class)expectedClassForObject:(NSManagedObject *)object andKey:(id)key
{
    NSDictionary *attributes = [[object entity] attributesByName];
    NSAttributeDescription *attributeDescription = [attributes valueForKey:key];
    return NSClassFromString([attributeDescription attributeValueClassName]);
}

@end

#pragma mark - Dictionary Input and Output
@implementation VIManagedObjectMapper (dictionaryInputOutput)
- (void)setInformationFromDictionary:(NSDictionary *)inputDict forManagedObject:(NSManagedObject *)object
{
    [self.mapsArray enumerateObjectsUsingBlock:^(VIManagedObjectMap *aMap, NSUInteger idx, BOOL *stop) {
        id inputObject = [inputDict valueForKeyPath:aMap.inputKeyPath];
        inputObject = [self checkDate:inputObject withDateFormatter:aMap.dateFormatter];
        inputObject = [self checkNumber:inputObject withNumberFormatter:aMap.numberFormatter];
        inputObject = [self checkClass:inputObject managedObject:object key:aMap.coreDataKey];
        inputObject = [self checkNull:inputObject];
        [object safeSetValue:inputObject forKey:aMap.coreDataKey];
    }];
}

- (NSDictionary *)dictionaryRepresentationOfManagedObject:(NSManagedObject *)object
{
    NSMutableDictionary *outputDict = [NSMutableDictionary new];
    [self.mapsArray enumerateObjectsUsingBlock:^(VIManagedObjectMap *aMap, NSUInteger idx, BOOL *stop) {
        id outputObject = [object valueForKey:aMap.coreDataKey];
        outputObject = [self checkString:outputObject withDateFormatter:aMap.dateFormatter];
        outputObject = [self checkString:outputObject withNumberFormatter:aMap.numberFormatter];
        if (outputObject) {
            outputDict[aMap.inputKeyPath] = outputObject;
        }
    }];

    return [outputDict copy];
}

NSString *const period = @".";
- (NSDictionary *)hierarchicalDictionaryRepresentationOfManagedObject:(NSManagedObject *)object
{
    NSMutableDictionary *outputDict = [NSMutableDictionary new];
    [self.mapsArray enumerateObjectsUsingBlock:^(VIManagedObjectMap *aMap, NSUInteger idx, BOOL *stop) {
        id outputObject = [object valueForKey:aMap.coreDataKey];
        outputObject = [self checkString:outputObject withDateFormatter:aMap.dateFormatter];
        outputObject = [self checkString:outputObject withNumberFormatter:aMap.numberFormatter];

        NSArray *components = [aMap.inputKeyPath componentsSeparatedByString:period];
        [self createNestedDictionary:outputDict fromKeyPathComponents:components];
        if (outputObject) {
            [outputDict setValue:outputObject forKeyPath:aMap.inputKeyPath];
        }
    }];

    return [outputDict copy];
}

- (void)createNestedDictionary:(NSMutableDictionary *)outputDict fromKeyPathComponents:(NSArray *)components
{
    __block NSMutableDictionary *nestedDict = outputDict;
    NSUInteger lastObjectIndex = [components count] - 1;
    [components enumerateObjectsUsingBlock:^(NSString *keyPathComponent, NSUInteger idx, BOOL *stop) {
        if(![nestedDict valueForKey:keyPathComponent] && idx < lastObjectIndex) {
            nestedDict[keyPathComponent] = [NSMutableDictionary dictionary];
        }
        nestedDict = [nestedDict valueForKey:keyPathComponent];
    }];
}

@end

#pragma mark - Dictionary Input and Output with the Default Mapper
@implementation VIManagedObjectDefaultMapper
- (void)setInformationFromDictionary:(NSDictionary *)inputDict forManagedObject:(NSManagedObject *)object
{
    //this default mapper assumes that local keys and entities match foreign keys and entities
    [inputDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        id inputObject = obj;
        inputObject = [self checkDate:inputObject withDateFormatter:[VIManagedObjectMap defaultDateFormatter]];
        inputObject = [self checkNumber:inputObject withNumberFormatter:[VIManagedObjectMap defaultNumberFormatter]];
        inputObject = [self checkClass:inputObject managedObject:object key:key];
        inputObject = [self checkNull:inputObject];
        [object safeSetValue:inputObject forKey:key];
    }];
}

- (NSDictionary *)dictionaryRepresentationOfManagedObject:(NSManagedObject *)object
{
    NSDictionary *attributes = [[object entity] attributesByName];
    NSMutableDictionary *outputDict = [NSMutableDictionary new];
    [attributes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        id outputObject = [object valueForKey:key];
        outputObject = [self checkString:outputObject withDateFormatter:[VIManagedObjectMap defaultDateFormatter]];
        if (outputObject) {
            outputDict[key] = outputObject;
        }
    }];

    return [outputDict copy];
}

- (NSDictionary *)hierarchicalDictionaryRepresentationOfManagedObject:(NSManagedObject *)object
{
    //the default mapper does not have key paths
    return [self dictionaryRepresentationOfManagedObject:object];
}

@end


text:
===========
Usage Model
===========

Units
#####

Simply put, the functionality provided by |Specware| consists in the
capability to construct specs, morphisms, diagrams, code, proofs, and
other entities. All these entities are collectively called
*units*.

Some of the operations made available by |Specware| to construct units
are fairly sophisticated. Examples are colimits, extraction of proof
obligations, discharging of proof obligations by means of external
theorem provers, and code generation.

The |Metaslang| language is the vehicle to construct units. The
language has syntax to express all the unit-constructing operations
that |Specware| provides. The user defines units in |Metaslang|,
writing the definitions in ``.sw`` files. (This file extension comes
from the first letters of the two syllables in "|Specware|".)

.. todo:: Are there plans for other ways? If not, drop this paragraph.

Currently, the only way to construct units in |Specware| is by writing
text in |Metaslang|. The ``.sw`` files that define units are edited
outside of |Specware|, using XEmacs, Notepad, Vim, or any other text
editor of choice. These files are processed by |Specware| by giving
suitable commands to the |SShell|. Future versions of |Specware| will
include the ability to construct units by other means. For instance,
instead of listing the nodes and edges of a diagram in text, it will
be possible to draw the diagram on the screen.

Interaction
###########

The interaction between the user and |Specware| takes place through
the |SShell|.

When ``.sw`` files are processed by |Specware|, progress and error
messages are displayed in the window containing the |SShell|. In
addition, the results of processing are saved into an internal cache
that |Specware| maintains. Lastly, processing of certain kinds of
units result in new files being created. For example, when Lisp code
is generated from a spec, the code is deposited into a ``.lisp`` file.

From the |SShell| it is possible to evaluate |Metaslang| expressions
in the context of a given spec, either directly or through generated
Lisp code.

|Specware| also features auxiliary commands to display information
about units, inspect and clear the internal cache, and inspect and
change the ``SWPATH`` environment variable, which determines how unit
identifiers are resolved to ``.sw`` files.


text:
define([
    'amber_vm/smalltalk',
    './helpers',
    'jquery',
    'amber_core/Kernel-Objects',
    'amber_core/Kernel-Classes',
    'amber_core/Kernel-Methods',
    'amber_core/Kernel-Collections',
    'amber_core/Kernel-Infrastructure',
    'amber_core/Kernel-Exceptions',
    'amber_core/Kernel-Transcript',
    'amber_core/Kernel-Announcements',
    'amber_core/Canvas'
], function (smalltalk) { return smalltalk; });


text:
<?xml version="1.0"?>
<openreport xmlns="http://www.iff.org/openreport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="openreport.xsd">
    <globals>
        <templates>

            <template display-name="page-template" version="1"
                      name="page_template">
                <![CDATA[
			<#assign jsFile=((reportConfig['page']['js']['nodeContent'])!'')?trim?split(',') />
			<#assign cssFile=((reportConfig['page']['css']['nodeContent'])!'')?trim?split(',') />
			<!DOCTYPE html>

			    <meta charset='UTF-8' />
			    <meta http-equiv='X-UA-Compatible' content='IE=edge' />
				<meta http-equiv="content-type" content="text/html; charset=utf-8" />
				<meta name="author" content="Unknown" />
				<title>${reportConfig['display-name']}</title>
				<#list (cssFile![]) as item>
				<link href="${ctx}/${item}" rel="stylesheet" type="text/css" />
				</#list>

${reportConfig['display-name']}

			    	<form class='or-cdts-form' onsubmit='return false' id="${reportConfig['name']}">

						    		${conditionContent!''}
						    		${actionContent!''}

			    		${dataContent!''}
			    		${paginationContent!''}
			    	</form>

			<#list (jsFile![]) as item>

			</#list>

			]]>
            </template>
            <template display-name="condition-template" version="1" name="condition_template">
                <![CDATA[

				<#list reportConfig['conditions']?keys as key>
					<#assign item=reportConfig['conditions'][key] />
					<#if item['html']?has_content>
						${item['html']}
					<#else>
						<#assign htmlWidget><input type="${item['name']}" name="${item['name']}" /></#assign>

${item['display-name']}

${htmlWidget}

					</#if>
				</#list>

			]]>
            </template>
            <template display-name="action-template" version="1" name="action_template">
                <![CDATA[

				<#list reportConfig['actions']?keys as key>
					<#assign item=reportConfig['actions'][key] />

						<button class="or_submitable" type="submit"
							<#list item?keys as key>
								<#if ',name,display-name,action,'?contains(','+key+',') ><#else>
									${key}="${item[key]}"
								</#if>
							</#list>
						>
							${item['display-name']}
						</button>

				</#list>

			]]>
            </template>
            <template display-name="data-template" version="1" name="data_template">
                <![CDATA[

						<#list (queryResult['columnNames']![]) as columnName>

${columnName}

						</#list>

					<#list (queryResult['result']![]) as record>

							<#list record?keys as columnName>

${record[columnName]?string}

							</#list>

					</#list>

			]]>
            </template>
            <template display-name="pagination-template" version="1" name="pagination_template">
                <![CDATA[
			<#assign pageSize=queryResult['pageSize'] totalCount=queryResult['totalCount'] currentPage=queryResult['currentPage']+1  totalPage=(totalCount/pageSize)?round />
			<#assign pageNumbers=helper('org.iff.infra.util.PaginationHelper').middleCurrentPage(pageSize, totalCount, currentPage) />

						当前记录${queryResult['result']?size}条,共 ${totalCount}条,共${totalPage}页

					<#if totalPage gt 1>
						<#if (currentPage<1)><#assign currentPage=1 /></#if><#if (currentPage>totalPage)><#assign currentPage=totalPage /></#if>
						<#list pageNumbers as pageNo>
							<#if pageNo_index==0>
								<<
							<#elseif !pageNo_has_next>
								>>
							<#else>
								${pageNo}
							</#if>
						</#list>
					</#if>

			]]>
            </template>
        </templates>
        <htmlwidgets>
            <htmlwidget name="html" beanName="TC_COM_HW_html"/>
            <htmlwidget name="blank" beanName="TC_COM_HW_blank"/>
            <htmlwidget name="hidden" beanName="TC_COM_HW_hidden"/>
            <htmlwidget name="script" beanName="TC_COM_HW_script"/>
            <htmlwidget name="text" beanName="TC_COM_HW_text"/>
            <htmlwidget name="cn2select" beanName="TC_COM_HW_cn2select"/>
            <htmlwidget name="select" beanName="TC_COM_HW_select"/>
            <htmlwidget name="mselect" beanName="TC_COM_HW_mselect"/>
        </htmlwidgets>
        <datasources>
            <datasource name="testDataSource"
                        user="iff"
                        password="iff"
                        url="jdbc:mysql://localhost:3306/foodmart?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false"
            />
        </datasources>
    </globals>
    <reports>
        <report display-name="test" datasource="dataSourceReport" name="test">
            <actions>
                <action display-name="Query" name="query" action="query" href="op=query"/>
            </actions>
            <conditions>
                <condition display-name="product_class_id" return-type="string" name="product_class_id"
                           default-value="test" type="html"></condition>
                <condition display-name="brand_name" return-type="string" name="brand_name"
                           default-value="test" type="html"></condition>
            </conditions>
            <query>
                <![CDATA[
					select product_class_id,brand_name,sku,srp,gross_weight,net_weight,recyclable_package,low_fat,units_per_case,cases_per_pallet
					from product
					where 1=1
					#[and product_class_id=:product_class_id]
					#[and brand_name=:brand_name]
				]]>
            </query>
            <crosstable>
                <columns>
                    <column name="recyclable_package"/>
                    <column name="low_fat"/>
                </columns>
                <rows>
                    <row name="product_class_id"/>
                    <row name="brand_name"/>
                </rows>

                    <value name="gross_weight" summary-method="sum" display-name="总计GROSS重量"/>
                    <value name="net_weight" summary-method="avg" display-name="平均NET重量"/>

            </crosstable>
            <page>
                <js>resource/js/jquery-1.11.1.js,resource/extension/openreport/openreport.js</js>
                <css>resource/extension/openreport/openreport.css</css>
                <javascript>
                    <![CDATA[
						$(function() {
							or_bind_submitable('.or_submitable');
						});
						$(function() {
							or_select_init();
							or_city_select_init();
						});
						$(function() {
							or_url_param_fill();
						});
					]]>
                </javascript>
            </page>
        </report>
        <report display-name="list" datasource="dataSourceReport" name="list" page-size="10">
            <actions>
                <action display-name="Query" name="query" action="query" href="op=query"/>
                <action display-name="Excel" name="excel" action="excel" href="op=excel" target="_blank"/>
            </actions>
            <conditions>
                <condition display-name="product_class_id" return-type="string" name="product_class_id"
                           default-value="test" type="html"></condition>
                <condition display-name="brand_name" return-type="string" name="brand_name"
                           default-value="test" type="html"></condition>
            </conditions>
            <query>
                <![CDATA[
					select product_class_id,brand_name,sku,srp,gross_weight,net_weight,recyclable_package,low_fat,units_per_case,cases_per_pallet
					from product
					where 1=1
					#[and product_class_id=:product_class_id]
					#[and brand_name=:brand_name]
				]]>
            </query>
            <page>
                <js>resource/js/jquery-1.11.1.js,resource/extension/openreport/openreport.js</js>
                <css>resource/extension/openreport/openreport.css</css>
                <javascript>
                    <![CDATA[
						$(function() {
							or_bind_submitable('.or_submitable');
						});
						$(function() {
							or_select_init();
							or_city_select_init();
						});
						$(function() {
							or_url_param_fill();
						});
					]]>
                </javascript>
            </page>
        </report>
    </reports>
</openreport>


text:
'use strict';

// MODULES //

var addon = require( './../src/addon.node' );

// MAIN //

/**
* Computes the L2-norm of a single-precision floating-point vector.
*
* @param {PositiveInteger} N - number of values over which to compute the L2-norm
* @param {Float32Array} x - input array
* @param {PositiveInteger} stride - stride length
* @returns {number} L2-norm of `x`
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
*
* var x = new Float32Array( [ 1.0, -2.0, 2.0 ] );
* var N = 3;
*
* var z = snrm2( N, x, 1 );
* // returns 3.0
*/
function snrm2( N, x, stride ) {
	return addon( N, x, stride );
}

// EXPORTS //

module.exports = snrm2;


text:
package com.antsoft.ant.beans.propertyeditor;

import javax.swing.*;
import java.beans.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.lang.reflect.*;

public class PropertyPanel extends JPanel{

  private Class customizer;
  private Component[] components;
  private JLabel[] labels;
  private String flag;
  //private BeanTester tester;

  public PropertyPanel(Class customizer){
    //this.tester = tester;
    this.customizer = customizer;
    flag = "c";
    setSize(300,360);
    setVisible(true);
    jInit();
  }

  public PropertyPanel(Component[] components,JLabel[] labels){
    //this.tester = tester;
    this.components = components;
    this.labels = labels;
    flag = "e";
    setSize(300,360);
    setVisible(true);
    jInit();
  }

  private void jInit(){
    removeAll();
    setLayout(new FlowLayout(FlowLayout.LEFT));

    if(flag.equals("e")){
      for(int i=0; i<components.length; i++){
        if((labels[i] != null)&&(components[i] != null)){
          labels[i].setPreferredSize(new Dimension(70,20));
          components[i].setSize(new Dimension(170,25));
          add(labels[i]);
          add(components[i]);
        }
      }
    }else if(flag.equals("c")){
      try{
        add((Component)customizer.newInstance());
      }catch(Exception ex){
        ex.printStackTrace();
      }
    }
  }
}


text:
<?php

class Ffuenf_Econda_Block_Adminhtml_System_Config_Fieldset_Teaser extends Ffuenf_Common_Block_Adminhtml_System_Config_Fieldset_Teaser
{
    protected $_moduleName = 'Ffuenf_Econda';
}


text:
layout: post
title: "See Invisibility"
date: 2015-07-30
source: PHB.274
tags: [bard, sorcerer, wizard, artificer, level2, divination]
---

**2nd-level divination**

**Casting Time**: 1 action

**Range**: Self

**Components**: V, S, M (a pinch of tale and a small sprinkling of powdered silver)

**Duration**: 1 hour

**Saving Throw**:

**Save For**:

**Damage**: []

For the duration, you see invisible creatures and objects as if they were visible, and you can see into the Ethereal Plane. Ethereal creatures and objects appear ghostly and translucent.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.Azure.Common.Authentication
{
    public enum AzureModule
    {
        AzureServiceManagement,
        AzureResourceManager,
        AzureProfile
    }
}


text:
<?php

namespace Fidry\LaravelYaml\DependencyInjection\Definition;

/**
 * This definition is a simple object encapsulating the required data to register an alias to the Application container.
 *
 * @author Théo FIDRY <theo.fidry@gmail.com>
 */
final class Alias
{
    /**
     * @var string
     */
    private $alias;

    /**
     * @var string
     */
    private $aliased;

    /**
     * @param string $alias  Alias name
     * @param string $aliased Name of the service for which the alias is for
     */
    public function __construct($alias, $aliased)
    {
        $this->alias = $alias;
        $this->aliased = $aliased;
    }

    /**
     * @return string
     */
    public function getAlias()
    {
        return $this->alias;
    }

    public function getAliased()
    {
        return $this->aliased;
    }
}


text:
#pragma once

#include <QtCore/qglobal.h>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QWidget>
	#include <QtGui/QLabel>
	#include <QtGui/QVBoxLayout>
#else
	#include <QtWidgets/QWidget>
	#include <QtWidgets/QLabel>
	#include <QtWidgets/QVBoxLayout>
#endif

#include <QtCore/QFile>
#include <QtCore/QString>
#include <QtCore/QEventLoop>

#include "trikGuiDialog.h"

namespace trikGui {

/// Widget showing parameters of wireless access point on the controller.
class WiFiAPWidget : public TrikGuiDialog
{
	Q_OBJECT

public:
	/// Constructor
	/// @param parent - parent of this widget in Qt object hierarchy.
	explicit WiFiAPWidget(QWidget *parent = 0);

	void renewFocus() override;

private:
	void getParameters();

	QVBoxLayout mMainLayout;
	QVBoxLayout mParametersLayout;
	QLabel mTitle;
	QLabel mNetworkLabel;
	QLabel mKeyLabel;
	QLabel mIpLabel;
};

}


text:
package ts.eclipse.ide.terminal.interpreter.internal.commands;

import java.util.List;

import ts.eclipse.ide.terminal.interpreter.ICommandInterpreter;
import ts.eclipse.ide.terminal.interpreter.ICommandInterpreterFactory;

/**
 * After a "del" command, this interpreter refresh the Project Explorer.
 *
 */
public class DelCommandInterpreterFactory implements ICommandInterpreterFactory {

	@Override
	public ICommandInterpreter create(List<String> parameters, String workingDir) {
		if (parameters.size() < 1) {
			return null;
		}
		String path = parameters.get(0);
		return new DelCommandInterpreter(path, workingDir);
	}

}


text:
@interface MOEViewController ()

@end

@implementation MOEViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)didFace:(id)sender
{
    [[FacebookMOE shareInstance] startLoginFacebookWithCompletion:^(NSString *responseString, id object, int errorCode, NSString *description, NSError *error) {

        NSLog(@"%@", responseString);

    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
using WPFDemo.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPFDemo.Command
{
    // Undo/Redo command for removing Lines.
    public class RemoveLinesCommand : IUndoRedoCommand
    {
        // Regions can be used to make code foldable (minus/plus sign to the left).
        #region Fields

        // The 'lines' field holds the current collection of lines,
        //  and the reference points to the same collection as the one the MainViewModel point to,
        //  therefore when this collection is changed in a object of this class,
        //  it also changes the collection that the MainViewModel uses.
        // For a description of an ObservableCollection see the MainViewModel class.
        private ObservableCollection<Line> lines;

        // The 'linesToRemove' field holds a collection of existing lines, that are removed from the 'lines' collection,
        //  and if undone, they are added to the collection.
        private List<Line> linesToRemove;

        #endregion

        #region Constructor

        // For changing the current state of the diagram
        //  (or at least the relevant parts).
        public RemoveLinesCommand(ObservableCollection<Line> _lines, List<Line> _linesToRemove)
        {
            lines = _lines;
            linesToRemove = _linesToRemove;
        }

        #endregion

        #region Methods

        // For doing and redoing the command.
        public void Execute()
        {
            // This is a lambda expression, that iterates the 'linesToRemove' collection,
            //  and for each one removes it from the 'lines' collection.
            // Java:
            //  foreach (Line line in linesToRemove)
            //  {
            //    lines.Remove(line);
            //  }
            linesToRemove.ForEach(x => lines.Remove(x));
        }

        // For undoing the command.
        public void UnExecute()
        {
            // This is a lambda expression, that iterates the 'linesToRemove' collection,
            //  and for each one adds it to the 'lines' collection.
            // Java:
            //  foreach (Line line in linesToRemove)
            //  {
            //    lines.Add(line);
            //  }
            linesToRemove.ForEach(x => lines.Add(x));
        }

        #endregion
    }
}


text:
import CryptoHelpers from '../../utils/CryptoHelpers';
import Network from '../../utils/Network';
import helpers from '../../utils/helpers';
import KeyPair from '../../utils/KeyPair';
import Address from '../../utils/Address';
import zxcvbn from 'zxcvbn';

class SignupCtrl {
    constructor(AppConstants, $state, Alert, WalletBuilder, $localStorage, $timeout) {
        'ngInject';

        //Local storage
        this._storage = $localStorage;
        // Alert service
        this._Alert = Alert;
        // WalletBuilder service
        this._WalletBuilder = WalletBuilder;
        // $state for redirect
        this._$state = $state;
        // App constants
        this._AppConstants = AppConstants;
        // $timeout to digest asynchronously
        this._$timeout = $timeout;

        // Signup properties
        this.network = this._AppConstants.defaultNetwork;
        // Available networks
        this.networks = Network.data;
        // Get wallets from local storage or create empty array
        this._storage.wallets = this._storage.wallets || [];
        // Needed to prevent user to click twice on send when already processing
        this.okPressed = false;

        // Force users to confirm they have account keys safe
        this.haveWalletFile = false;
        this.havePrivateKeySaved = false;

        // Wallet data to show
        this.rawWallet = "";
        this.walletPrivateKey = "";

        this.formData = {};

        // Wallet types
        this.walletTypes = [{
            "type": 1 // Simple
        }, {
            "type": 2 // Brain
        }, {
            "type": 3 // Private key
        }];

        // Default is "create a new wallet" (PRNG)
        this._selectedType = this.walletTypes[0];

        this.passwordStrengthInfo = {};
    }

    /**
     * changeWalletType() Change the selected wallet type
     *
     * @param type: Type number
     */
    changeWalletType(type) {
        // Set wallet type
        this._selectedType = this.walletTypes[type - 1];
    }

    /**
     * changeNetwork() Change wallet network
     *
     * @param network: Network id to use at wallet creation
     */
    changeNetwork(id) {
        if (id == Network.data.Mijin.id && this._AppConstants.mijinDisabled) {
            this._Alert.mijinDisabled();
            // Reset network to default
            this.network = this._AppConstants.defaultNetwork;
            return;
        } else if (id == Network.data.Mainnet.id && this._AppConstants.mainnetDisabled) {
            this._Alert.mainnetDisabled();
            // Reset network to default
            this.network = this._AppConstants.defaultNetwork;
            return;
        }
        // Set Network
        this.network = id;
    }

    /**
     * download() trigger download of the wallet
     *
     * @param wallet: Wallet object
     */
    download(wallet) {
        if (!wallet) {
            this._Alert.errorWalletDownload();
            return;
        }
        // Wallet object string to word array
        var wordArray = CryptoJS.enc.Utf8.parse(JSON.stringify(wallet));
        // Word array to base64
        var base64 = CryptoJS.enc.Base64.stringify(wordArray);
        // Set download element attributes
        $("#downloadWallet").attr('href', 'data:application/octet-stream,' + base64);
        $("#downloadWallet").attr('download', wallet.name + '.wlt');
        // Simulate click to trigger download
        document.getElementById("downloadWallet").click();
    }

    /**
     * createWallet() create a new PRNG wallet
     */
    createWallet() {
            // Check form
            if (!this.formData || !this.formData.walletName || !this.formData.password || !this.formData.confirmPassword) {
                this._Alert.missingFormData();
                return;
            }

            // Check if wallet already loaded
            if (helpers.haveWallet(this.formData.walletName, this._storage.wallets)) {
                this._Alert.walletNameExists();
                return;
            }

            // Check if passwords match
            if (this.formData.password !== this.formData.confirmPassword) {
                this._Alert.passwordsNotMatching();
                return;
            }

            this.okPressed = true;

                // Create the wallet from form data
                return this._WalletBuilder.createWallet(this.formData.walletName, this.formData.password, this.network).then((wallet) => {
                    this._$timeout(() => {
                        if (wallet) {
                            // On success concat new wallet to local storage wallets
                            this._storage.wallets = this._storage.wallets.concat(wallet);
                            this._Alert.createWalletSuccess();
                            // Trigger download
                            this.download(wallet);
                            // Set wallet data for view
                            this.rawWallet = this.encodeWallet(wallet);
                            // We need private key so we create a common object with the wallet password
                            let common = { "password": this.formData.password, "privateKey": "" };
                            // Decrypt account private key
                            if(!CryptoHelpers.passwordToPrivatekeyClear(common, wallet.accounts[0], wallet.accounts[0].algo, true)) {
                                this.walletPrivateKey = "Cannot get the private key..";
                            } else if (!CryptoHelpers.checkAddress(common.privateKey, wallet.accounts[0].network, wallet.accounts[0].address)) {
                                this._Alert.invalidPassword();
                                this.walletPrivateKey = "Wallet address does not correspond to decrypted private key..";
                                // Enable send button
                                this.okPressed = false;
                                return;
                            } else {
                                // Set the decrypted private key
                                this.walletPrivateKey = common.privateKey;
                            }
                            // Unlock button
                            this.okPressed = false;
                            // Reset form data
                            this.formData = "";
                            // Open modal and force user to backup data
                            $('#safetyModal').modal({
                              backdrop: 'static',
                              keyboard: false
                            });
                        }
                    }, 10);
                },
                (err) => {
                    this._Alert.createWalletFailed(err);
                    this.okPressed = false;
                });
    }

    /**
     * createBrainWallet() create a new brain wallet
     */
    createBrainWallet() {
            // Check form
            if (!this.formData || !this.formData.walletName || !this.formData.password || !this.formData.confirmPassword) {
                this._Alert.missingFormData();
                return;
            }

            // Check if wallet already loaded
            if (helpers.haveWallet(this.formData.walletName, this._storage.wallets)) {
                this._Alert.walletNameExists();
                return;
            }

            // Check if passwords match
            if (this.formData.password !== this.formData.confirmPassword) {
                this._Alert.passwordsNotMatching();
                return;
            }

            if (this.network === Network.data.Mainnet.id && this.formData.password.length < 40) {
                this._Alert.brainPasswordTooShort();
                return;
            }

            if (this.network === Network.data.Mainnet.id && zxcvbn(this.formData.password).score < 3) {
                this._Alert.passphraseIsWeak();
                return;
            }

            this.okPressed = true;

                // Create the wallet from form data
                return this._WalletBuilder.createBrainWallet(this.formData.walletName, this.formData.password, this.network).then((wallet) => {
                    this._$timeout(() => {
                        if (wallet) {
                            // On success concat new wallet to local storage wallets
                            this._storage.wallets = this._storage.wallets.concat(wallet);
                            this._Alert.createWalletSuccess();
                            // Trigger download
                            this.download(wallet)
                            // Set wallet data for view
                            this.rawWallet = this.encodeWallet(wallet);
                            this.walletPrivateKey = CryptoHelpers.derivePassSha(this.formData.password, 6000).priv;
                            // Unlock button
                            this.okPressed = false;
                            // Reset form data
                            this.formData = "";
                            // Open modal and force user to backup data
                            $('#safetyModal').modal({
                              backdrop: 'static',
                              keyboard: false
                            });
                        }
                    }, 10);
                },
                (err) => {
                    this._Alert.createWalletFailed(err);
                    this.okPressed = false;
                });
    }

    /**
     * createPrivateKeyWallet() create a new private key wallet
     */
    createPrivateKeyWallet() {
            // Check form
            if (!this.formData || !this.formData.walletName || !this.formData.password || !this.formData.confirmPassword || !this.formData.privateKey) {
                this._Alert.missingFormData();
                return;
            }

            // Check if wallet already loaded
            if (helpers.haveWallet(this.formData.walletName, this._storage.wallets)) {
                this._Alert.walletNameExists();
                return;
            }

            // Check if passwords match
            if (this.formData.password !== this.formData.confirmPassword) {
                this._Alert.passwordsNotMatching();
                return;
            }

            if (this.formData.privateKey.length === 64 || this.formData.privateKey.length === 66) {

                let kp = KeyPair.create(this.formData.privateKey);
                this.formData.address = Address.toAddress(kp.publicKey.toString(), this.network);

                this.okPressed = true;

                // Create the wallet from form data
                return this._WalletBuilder.createPrivateKeyWallet(this.formData.walletName, this.formData.password, this.formData.address, this.formData.privateKey, this.network).then((wallet) => {
                    this._$timeout(() => {
                        if (wallet) {
                            // On success concat new wallet to local storage wallets
                            this._storage.wallets = this._storage.wallets.concat(wallet);
                            this._Alert.createWalletSuccess();
                            // Trigger download
                            this.download(wallet)
                            // Set wallet data for view
                            this.rawWallet = this.encodeWallet(wallet);
                            this.walletPrivateKey = this.formData.privateKey;
                            // Unlock button
                            this.okPressed = false;
                            // Reset form data
                            this.formData = "";
                            // Open modal and force user to backup data
                            $('#safetyModal').modal({
                              backdrop: 'static',
                              keyboard: false
                            });
                        }
                    }, 10);
                },
                (err) => {
                    this._Alert.createWalletFailed(err);
                    this.okPressed = false;
                });
            } else {
                this._Alert.invalidPrivateKey();
            }
    }

    generateAddress() {
        if(undefined !== this.formData.privateKey && this.formData.privateKey.length) {
            if (this.formData.privateKey.length === 64 || this.formData.privateKey.length === 66) {
                let kp = KeyPair.create(this.formData.privateKey);
                this.formData.address = Address.toAddress(kp.publicKey.toString(), this.network);
            } else {
                this.formData.address = "";
                this._Alert.invalidPrivateKey();
            }
        }
    }

    /**
     * Redirect to login page
     */
    redirect() {
        this._$state.go("app.login");
    }

    /**
     * Encode a wallet object to base 64
     */
    encodeWallet(wallet) {
        // Wallet object string to word array
        var wordArray = CryptoJS.enc.Utf8.parse(JSON.stringify(wallet));
        // Word array to base64
        return CryptoJS.enc.Base64.stringify(wordArray);
    }

    /**
     * Update the passphrase strength information
     */
    updatePasswordStrengthInfo() {
        this.passwordStrengthInfo = zxcvbn(this.formData.password);
    }

}

export default SignupCtrl;


text:
package org.varnerlab.kwatee.cellfreemodel.model;

public class VLCGMetaboliteSymbol {

    // Class/instance attributes
    private String _strSymbol = "";
    private double _bdlCoeff = 0.0;
    private String _strLocation = "";

    /** Creates a new instance of StateSymbol */
    public VLCGMetaboliteSymbol() {
    }

    public void setLocation(String location) {
        _strLocation = location;
    }

    public String getLocation() {
        return(_strLocation);
    }

    public void setSymbol(String symbol) {
        this._strSymbol=symbol;
    }

    public void setCoefficient(double value) {
        this._bdlCoeff=value;
    }

    public String getSymbol() {
        return (this._strSymbol);
    }

    public double getCoefficient() {
        return(this._bdlCoeff);
    }
}


text:
module ArDocStore
  module Attributes
    module CallbackSupport
      def self.included(mod)
        mod.send :include,  ActiveSupport::Callbacks
        mod.send :extend, ClassMethods
        mod.define_callbacks :build
      end

      module ClassMethods
        def before_build(method)
          set_callback :build, :before, method
        end

        def after_build(method)
          set_callback :build, :after, method
        end
      end
    end
  end
end


text:
 Export to Excel
<button class="btn btn-default" v-on="click: upload"> Import from Excel</button>

Upload File Excel

        	{!!Form::open(['route' => $import, 'files' => 'true'])!!}

        		{!!Form::file('excel', ['class' => 'form-control btn btn-default', 'required'])!!}

        		{!!Form::submit('Upload', ['class' => 'btn btn-info'])!!}

        	{!!Form::close()!!}


text:
keitai-performance-testing
==========================

Performance test scripts for Project Keitai, the RESTful web service extensions for Sakai

## Pre-requisites

* A working Sakai instance. Project Keitai ships in Sakai 10 but backports are available.
* An installation of [Apache jMeter](http://jmeter.apache.org/download_jmeter.cgi).

## Getting started

1. Clone this repository :)
2. In Sakai, as an administrator, create a site that will be used for testing.
3. In Sakai, as an administrator, import the data/users.csv file to create 4000 sample users. There are 4000 users, you can cut down the number of users if you like.
4. In Sakai, go to the site you created, use Site Info > Add participants and copy the list of users in the data/users-for-sites.csv file, to add all of the users to the site. You can cut down this list of users as well.
5. In Sakai, go to the site you created, add the tools you want to test and as much sample data as required.
6. Configure keitai.properties for your environment.
7. Start JMeter via `./jmeter.sh -p /path/to/keitai.properties`
8. Add the relevant tests to JMeter.
9. Run, analyse data.

## Enhanced testing
The majority of the entity providers provide a 'my' service which gives a view for the user across all sites. For example the gradebook /direct/gradebook/my.json will give you the gradebook items for the current user in all sites.
The performance tests already make a request to the 'my' service so simply adding more sites with the same users will allow you to ramp up the amount of load and get more realistic results.


text:
<html>
<head>
    <title>
    @section('title')
        Palmabit package samples
    @show
    </title>
    {{HTML::style('css/style.css')}}
</head>
<body>
    @include('partials.header')
    @yield('content')
    @section('scripts')
        {{HTML::script("https://code.jquery.com/jquery-2.1.1.min.js")}}
    @show
</body>
</html>


text:
/*! \file

  UNION-FIND algorithm from Aho, Hopcroft & Ullman,
  The Design and Analysis of Computer Algorithms, Addison Wesley 1974

*/

#include "UnionFindUniverse.h"

#define UF_NIL -1

namespace OA {

//***********************************************************************************************
// internal class UnionFindElement
//***********************************************************************************************

class UnionFindElement {
public:
  UnionFindElement() { };

  int &Count() { return count; };
  int &Root() { return root; };
  int &Parent() { return parent; }
  int &Name() { return name; }
  void Init(int i);
private:
  int parent;
  int name;
  int count;
  int root;
};

void UnionFindElement::Init(int i)
{
  name = root = i;
  parent = UF_NIL;
  count = 1;
}

//***********************************************************************************************
// class UnionFindUniverse interface operations
//***********************************************************************************************

UnionFindUniverse::UnionFindUniverse(unsigned int highWaterMark)
{
  e = new UnionFindElement[highWaterMark];

  for (unsigned int i = 0; i < highWaterMark; i++) {
    e[i].Init(i);
  }
}

UnionFindUniverse::~UnionFindUniverse()
{
  if (e)
    delete [] e;
}

int UnionFindUniverse::Find(int v)
{
  if (Parent(v) == UF_NIL)
    return Name(v);

  Parent(v) = do_FIND(Parent(v));

  return Name(Parent(v));
}

void UnionFindUniverse::Union(int i, int j, int k)
{
  if ((i == j) && (j == k))
    return;

  int large, small;
  if (Count(Root(i)) > Count(Root(j))) {
    large = Root(i);
    small = Root(j);
  } else {
    large = Root(j);
    small = Root(i);
  }

  Parent(small) = large;
  Count(large) += Count(small);
  Name(large) = k;
  Root(k) = large;
}

//***********************************************************************************************
// class UnionFindUniverse private operations
//***********************************************************************************************

int UnionFindUniverse::do_FIND(int v)
{
  if (Parent(v) == UF_NIL)
    return v;

  Parent(v) = do_FIND(Parent(v));

  return Parent(v);
}

int &UnionFindUniverse::Count(int i)
{
  return e[i].Count();
}

int &UnionFindUniverse::Root(int i)
{
  return e[i].Root();
}
int &UnionFindUniverse::Parent(int i)
{
  return e[i].Parent();
}

int &UnionFindUniverse::Name(int i)
{
  return e[i].Name();
}

} // end of namespace OA


text:
using testing::Return;
using testing::_;

namespace policy {

namespace {

const char kMainSettingsPage[] = "chrome://settings-frame";

const char kCrosSettingsPrefix[] = "cros.";

// Contains the details of a single test case verifying that the controlled
// setting indicators for a pref affected by a policy work correctly. This is
// part of the data loaded from chrome/test/data/policy/policy_test_cases.json.
class IndicatorTestCase {
 public:
  IndicatorTestCase(const base::DictionaryValue& policy,
                    const std::string& value,
                    bool readonly)
      : policy_(policy.DeepCopy()), value_(value), readonly_(readonly) {}
  ~IndicatorTestCase() {}

  const base::DictionaryValue& policy() const { return *policy_; }

  const std::string& value() const { return value_; }

  bool readonly() const { return readonly_; }

 private:
  scoped_ptr<base::DictionaryValue> policy_;
  std::string value_;
  bool readonly_;

  DISALLOW_COPY_AND_ASSIGN(IndicatorTestCase);
};

// Contains the testing details for a single pref affected by a policy. This is
// part of the data loaded from chrome/test/data/policy/policy_test_cases.json.
class PrefMapping {
 public:
  PrefMapping(const std::string& pref,
              bool is_local_state,
              const std::string& indicator_test_setup_js,
              const std::string& indicator_selector)
      : pref_(pref),
        is_local_state_(is_local_state),
        indicator_test_setup_js_(indicator_test_setup_js),
        indicator_selector_(indicator_selector) {
  }
  ~PrefMapping() {}

  const std::string& pref() const { return pref_; }

  bool is_local_state() const { return is_local_state_; }

  const std::string& indicator_test_setup_js() const {
    return indicator_test_setup_js_;
  }

  const std::string& indicator_selector() const {
    return indicator_selector_;
  }

  const ScopedVector<IndicatorTestCase>& indicator_test_cases() const {
    return indicator_test_cases_;
  }
  void AddIndicatorTestCase(IndicatorTestCase* test_case) {
    indicator_test_cases_.push_back(test_case);
  }

 private:
  std::string pref_;
  bool is_local_state_;
  std::string indicator_test_setup_js_;
  std::string indicator_selector_;
  ScopedVector<IndicatorTestCase> indicator_test_cases_;

  DISALLOW_COPY_AND_ASSIGN(PrefMapping);
};

// Contains the testing details for a single policy. This is part of the data
// loaded from chrome/test/data/policy/policy_test_cases.json.
class PolicyTestCase {
 public:
  PolicyTestCase(const std::string& name,
                 bool is_official_only,
                 bool can_be_recommended,
                 const std::string& indicator_selector)
      : name_(name),
        is_official_only_(is_official_only),
        can_be_recommended_(can_be_recommended),
        indicator_selector_(indicator_selector) {}
  ~PolicyTestCase() {}

  const std::string& name() const { return name_; }

  bool is_official_only() const { return is_official_only_; }

  bool can_be_recommended() const { return can_be_recommended_; }

  bool IsOsSupported() const {
#if defined(OS_WIN)
    const std::string os("win");
#elif defined(OS_MACOSX)
    const std::string os("mac");
#elif defined(OS_CHROMEOS)
    const std::string os("chromeos");
#elif defined(OS_LINUX)
    const std::string os("linux");
#else
#error "Unknown platform"
#endif
    return std::find(supported_os_.begin(), supported_os_.end(), os) !=
        supported_os_.end();
  }
  void AddSupportedOs(const std::string& os) { supported_os_.push_back(os); }

  bool IsSupported() const {
#if !defined(OFFICIAL_BUILD)
    if (is_official_only())
      return false;
#endif
    return IsOsSupported();
  }

  const base::DictionaryValue& test_policy() const { return test_policy_; }
  void SetTestPolicy(const base::DictionaryValue& policy) {
    test_policy_.Clear();
    test_policy_.MergeDictionary(&policy);
  }

  const ScopedVector<PrefMapping>& pref_mappings() const {
    return pref_mappings_;
  }
  void AddPrefMapping(PrefMapping* pref_mapping) {
    pref_mappings_.push_back(pref_mapping);
  }

  const std::string& indicator_selector() const { return indicator_selector_; }

 private:
  std::string name_;
  bool is_official_only_;
  bool can_be_recommended_;
  std::vector<std::string> supported_os_;
  base::DictionaryValue test_policy_;
  ScopedVector<PrefMapping> pref_mappings_;
  std::string indicator_selector_;

  DISALLOW_COPY_AND_ASSIGN(PolicyTestCase);
};

// Parses all policy test cases and makes then available in a map.
class PolicyTestCases {
 public:
  typedef std::map<std::string, PolicyTestCase*> PolicyTestCaseMap;
  typedef PolicyTestCaseMap::const_iterator iterator;

  PolicyTestCases() {
    base::FilePath path = ui_test_utils::GetTestFilePath(
        base::FilePath(FILE_PATH_LITERAL("policy")),
        base::FilePath(FILE_PATH_LITERAL("policy_test_cases.json")));
    std::string json;
    if (!base::ReadFileToString(path, &json)) {
      ADD_FAILURE();
      return;
    }
    int error_code = -1;
    std::string error_string;
    base::DictionaryValue* dict = NULL;
    scoped_ptr<base::Value> value(base::JSONReader::ReadAndReturnError(
        json, base::JSON_PARSE_RFC, &error_code, &error_string));
    if (!value.get() || !value->GetAsDictionary(&dict)) {
      ADD_FAILURE() << "Error parsing policy_test_cases.json: " << error_string;
      return;
    }
    Schema chrome_schema = Schema::Wrap(GetChromeSchemaData());
    if (!chrome_schema.valid()) {
      ADD_FAILURE();
      return;
    }
    for (Schema::Iterator it = chrome_schema.GetPropertiesIterator();
         !it.IsAtEnd(); it.Advance()) {
      PolicyTestCase* policy_test_case = GetPolicyTestCase(dict, it.key());
      if (policy_test_case)
        policy_test_cases_[it.key()] = policy_test_case;
    }
  }

  ~PolicyTestCases() {
    STLDeleteValues(&policy_test_cases_);
  }

  const PolicyTestCase* Get(const std::string& name) const {
    const iterator it = policy_test_cases_.find(name);
    return it == end() ? NULL : it->second;
  }

  const PolicyTestCaseMap& map() const { return policy_test_cases_; }
  iterator begin() const { return policy_test_cases_.begin(); }
  iterator end() const { return policy_test_cases_.end(); }

 private:
  PolicyTestCase* GetPolicyTestCase(const base::DictionaryValue* tests,
                                    const std::string& name) {
    const base::DictionaryValue* policy_test_dict = NULL;
    if (!tests->GetDictionary(name, &policy_test_dict))
      return NULL;
    bool is_official_only = false;
    policy_test_dict->GetBoolean("official_only", &is_official_only);
    bool can_be_recommended = false;
    policy_test_dict->GetBoolean("can_be_recommended", &can_be_recommended);
    std::string indicator_selector;
    policy_test_dict->GetString("indicator_selector", &indicator_selector);
    PolicyTestCase* policy_test_case = new PolicyTestCase(name,
                                                          is_official_only,
                                                          can_be_recommended,
                                                          indicator_selector);
    const base::ListValue* os_list = NULL;
    if (policy_test_dict->GetList("os", &os_list)) {
      for (size_t i = 0; i < os_list->GetSize(); ++i) {
        std::string os;
        if (os_list->GetString(i, &os))
          policy_test_case->AddSupportedOs(os);
      }
    }
    const base::DictionaryValue* policy = NULL;
    if (policy_test_dict->GetDictionary("test_policy", &policy))
      policy_test_case->SetTestPolicy(*policy);
    const base::ListValue* pref_mappings = NULL;
    if (policy_test_dict->GetList("pref_mappings", &pref_mappings)) {
      for (size_t i = 0; i < pref_mappings->GetSize(); ++i) {
        const base::DictionaryValue* pref_mapping_dict = NULL;
        std::string pref;
        if (!pref_mappings->GetDictionary(i, &pref_mapping_dict) ||
            !pref_mapping_dict->GetString("pref", &pref)) {
          ADD_FAILURE() << "Malformed pref_mappings entry in "
                        << "policy_test_cases.json.";
          continue;
        }
        bool is_local_state = false;
        pref_mapping_dict->GetBoolean("local_state", &is_local_state);
        std::string indicator_test_setup_js;
        pref_mapping_dict->GetString("indicator_test_setup_js",
                                     &indicator_test_setup_js);
        std::string indicator_selector;
        pref_mapping_dict->GetString("indicator_selector", &indicator_selector);
        PrefMapping* pref_mapping = new PrefMapping(
            pref, is_local_state, indicator_test_setup_js, indicator_selector);
        const base::ListValue* indicator_tests = NULL;
        if (pref_mapping_dict->GetList("indicator_tests", &indicator_tests)) {
          for (size_t i = 0; i < indicator_tests->GetSize(); ++i) {
            const base::DictionaryValue* indicator_test_dict = NULL;
            const base::DictionaryValue* policy = NULL;
            if (!indicator_tests->GetDictionary(i, &indicator_test_dict) ||
                !indicator_test_dict->GetDictionary("policy", &policy)) {
              ADD_FAILURE() << "Malformed indicator_tests entry in "
                            << "policy_test_cases.json.";
              continue;
            }
            std::string value;
            indicator_test_dict->GetString("value", &value);
            bool readonly = false;
            indicator_test_dict->GetBoolean("readonly", &readonly);
            pref_mapping->AddIndicatorTestCase(
                new IndicatorTestCase(*policy, value, readonly));
          }
        }
        policy_test_case->AddPrefMapping(pref_mapping);
      }
    }
    return policy_test_case;
  }

  PolicyTestCaseMap policy_test_cases_;

  DISALLOW_COPY_AND_ASSIGN(PolicyTestCases);
};

// Returns a pseudo-random integer distributed in [0, range).
int GetRandomNumber(int range) {
  return rand() % range;
}

// Splits all known policies into subsets of the given |chunk_size|. The
// policies are shuffled so that there is no correlation between their initial
// alphabetic ordering and the assignment to chunks. This ensures that the
// expected number of policies with long-running test cases is equal for each
// subset. The shuffle algorithm uses a fixed seed, ensuring that no randomness
// is introduced into the testing process.
std::vector<std::vector<std::string> > SplitPoliciesIntoChunks(int chunk_size) {
  Schema chrome_schema = Schema::Wrap(GetChromeSchemaData());
  if (!chrome_schema.valid())
    ADD_FAILURE();

  std::vector<std::string> policies;
  for (Schema::Iterator it = chrome_schema.GetPropertiesIterator();
       !it.IsAtEnd(); it.Advance()) {
    policies.push_back(it.key());
  }

  // Use a fixed random seed to obtain a reproducible shuffle.
  srand(1);
  std::random_shuffle(policies.begin(), policies.end(), GetRandomNumber);

  std::vector<std::vector<std::string> > chunks;
  std::vector<std::string>::const_iterator it = policies.begin();
  const std::vector<std::string>::const_iterator end = policies.end();
  for ( ; end - it >= chunk_size; it += chunk_size)
    chunks.push_back(std::vector<std::string>(it, it + chunk_size));
  if (it != end)
    chunks.push_back(std::vector<std::string>(it, end));
  return chunks;
}

void VerifyControlledSettingIndicators(Browser* browser,
                                       const std::string& selector,
                                       const std::string& value,
                                       const std::string& controlled_by,
                                       bool readonly) {
  std::stringstream javascript;
  javascript << "var nodes = document.querySelectorAll("
             << "    'span.controlled-setting-indicator"
             <<          selector.c_str() << "');"
             << "var indicators = [];"
             << "for (var i = 0; i < nodes.length; i++) {"
             << "  var node = nodes[i];"
             << "  var indicator = {};"
             << "  indicator.value = node.value || '';"
             << "  indicator.controlledBy = node.controlledBy || '';"
             << "  indicator.readOnly = node.readOnly || false;"
             << "  indicator.visible ="
             << "      window.getComputedStyle(node).display != 'none';"
             << "  indicators.push(indicator)"
             << "}"
             << "domAutomationController.send(JSON.stringify(indicators));";
  content::WebContents* contents =
      browser->tab_strip_model()->GetActiveWebContents();
  std::string json;
  // Retrieve the state of all controlled setting indicators matching the
  // |selector| as JSON.
  ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents, javascript.str(),
                                                     &json));
  scoped_ptr<base::Value> value_ptr(base::JSONReader::Read(json));
  const base::ListValue* indicators = NULL;
  ASSERT_TRUE(value_ptr.get());
  ASSERT_TRUE(value_ptr->GetAsList(&indicators));
  // Verify that controlled setting indicators representing |value| are visible
  // and have the correct state while those not representing |value| are
  // invisible.
  if (!controlled_by.empty()) {
    EXPECT_GT(indicators->GetSize(), 0u)
        << "Expected to find at least one controlled setting indicator.";
  }
  bool have_visible_indicators = false;
  for (base::ListValue::const_iterator indicator = indicators->begin();
       indicator != indicators->end(); ++indicator) {
    const base::DictionaryValue* properties = NULL;
    ASSERT_TRUE((*indicator)->GetAsDictionary(&properties));
    std::string indicator_value;
    std::string indicator_controlled_by;
    bool indicator_readonly;
    bool indicator_visible;
    EXPECT_TRUE(properties->GetString("value", &indicator_value));
    EXPECT_TRUE(properties->GetString("controlledBy",
                                      &indicator_controlled_by));
    EXPECT_TRUE(properties->GetBoolean("readOnly", &indicator_readonly));
    EXPECT_TRUE(properties->GetBoolean("visible", &indicator_visible));
    if (!controlled_by.empty() && (indicator_value == value)) {
      EXPECT_EQ(controlled_by, indicator_controlled_by);
      EXPECT_EQ(readonly, indicator_readonly);
      EXPECT_TRUE(indicator_visible);
      have_visible_indicators = true;
    } else {
      EXPECT_FALSE(indicator_visible);
    }
  }
  if (!controlled_by.empty()) {
    EXPECT_TRUE(have_visible_indicators)
        << "Expected to find at least one visible controlled setting "
        << "indicator.";
  }
}

}  // namespace

TEST(PolicyPrefsTestCoverageTest, AllPoliciesHaveATestCase) {
  // Verifies that all known policies have a test case in the JSON file.
  // This test fails when a policy is added to
  // components/policy/resources/policy_templates.json but a test case is not
  // added to chrome/test/data/policy/policy_test_cases.json.
  Schema chrome_schema = Schema::Wrap(GetChromeSchemaData());
  ASSERT_TRUE(chrome_schema.valid());

  PolicyTestCases policy_test_cases;
  for (Schema::Iterator it = chrome_schema.GetPropertiesIterator();
       !it.IsAtEnd(); it.Advance()) {
    EXPECT_TRUE(ContainsKey(policy_test_cases.map(), it.key()))
        << "Missing policy test case for: " << it.key();
  }
}

// Base class for tests that change policy.
class PolicyPrefsTest : public InProcessBrowserTest {
 protected:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    EXPECT_CALL(provider_, IsInitializationComplete(_))
        .WillRepeatedly(Return(true));
    BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    ui_test_utils::WaitForTemplateURLServiceToLoad(
        TemplateURLServiceFactory::GetForProfile(browser()->profile()));
  }

  virtual void TearDownOnMainThread() OVERRIDE {
    ClearProviderPolicy();
  }

  void ClearProviderPolicy() {
    provider_.UpdateChromePolicy(PolicyMap());
    base::RunLoop().RunUntilIdle();
  }

  void SetProviderPolicy(const base::DictionaryValue& policies,
                         PolicyLevel level) {
    PolicyMap policy_map;
    for (base::DictionaryValue::Iterator it(policies);
         !it.IsAtEnd(); it.Advance()) {
      const PolicyDetails* policy_details = GetChromePolicyDetails(it.key());
      ASSERT_TRUE(policy_details);
      policy_map.Set(
          it.key(),
          level,
          POLICY_SCOPE_USER,
          it.value().DeepCopy(),
          policy_details->max_external_data_size ?
              new ExternalDataFetcher(base::WeakPtr<ExternalDataManager>(),
                                      it.key()) :
              NULL);
    }
    provider_.UpdateChromePolicy(policy_map);
    base::RunLoop().RunUntilIdle();
  }

  MockConfigurationPolicyProvider provider_;
};

// Verifies that policies make their corresponding preferences become managed,
// and that the user can't override that setting.
IN_PROC_BROWSER_TEST_F(PolicyPrefsTest, PolicyToPrefsMapping) {
  PrefService* local_state = g_browser_process->local_state();
  PrefService* user_prefs = browser()->profile()->GetPrefs();

  const PolicyTestCases test_cases;
  for (PolicyTestCases::iterator it = test_cases.begin();
       it != test_cases.end(); ++it) {
    const ScopedVector<PrefMapping>& pref_mappings =
        it->second->pref_mappings();
    if (!it->second->IsSupported() || pref_mappings.empty())
      continue;

    LOG(INFO) << "Testing policy: " << it->first;

    for (ScopedVector<PrefMapping>::const_iterator
             pref_mapping = pref_mappings.begin();
         pref_mapping != pref_mappings.end();
         ++pref_mapping) {
      // Skip Chrome OS preferences that use a different backend and cannot be
      // retrieved through the prefs mechanism.
      if (StartsWithASCII((*pref_mapping)->pref(), kCrosSettingsPrefix, true))
        continue;

      PrefService* prefs = (*pref_mapping)->is_local_state() ?
          local_state : user_prefs;
      // The preference must have been registered.
      const PrefService::Preference* pref =
          prefs->FindPreference((*pref_mapping)->pref().c_str());
      ASSERT_TRUE(pref);

      // Verify that setting the policy overrides the pref.
      ClearProviderPolicy();
      prefs->ClearPref((*pref_mapping)->pref().c_str());
      EXPECT_TRUE(pref->IsDefaultValue());
      EXPECT_TRUE(pref->IsUserModifiable());
      EXPECT_FALSE(pref->IsUserControlled());
      EXPECT_FALSE(pref->IsManaged());

      SetProviderPolicy(it->second->test_policy(), POLICY_LEVEL_MANDATORY);
      EXPECT_FALSE(pref->IsDefaultValue());
      EXPECT_FALSE(pref->IsUserModifiable());
      EXPECT_FALSE(pref->IsUserControlled());
      EXPECT_TRUE(pref->IsManaged());
    }
  }
}

class PolicyPrefIndicatorTest
    : public PolicyPrefsTest,
      public testing::WithParamInterface<std::vector<std::string> > {
};

// Verifies that controlled setting indicators correctly show whether a pref's
// value is recommended or enforced by a corresponding policy.
IN_PROC_BROWSER_TEST_P(PolicyPrefIndicatorTest, CheckPolicyIndicators) {
  const PolicyTestCases test_cases;
  PrefService* local_state = g_browser_process->local_state();
  PrefService* user_prefs = browser()->profile()->GetPrefs();

  ui_test_utils::NavigateToURL(browser(), GURL(kMainSettingsPage));

  for (std::vector<std::string>::const_iterator it = GetParam().begin();
       it != GetParam().end(); ++it) {
    const PolicyTestCase* policy_test_case = test_cases.Get(*it);
    ASSERT_TRUE(policy_test_case) << "PolicyTestCase not found for " << *it;
    if (!policy_test_case->IsSupported())
      continue;
    const ScopedVector<PrefMapping>& pref_mappings =
        policy_test_case->pref_mappings();
    if (policy_test_case->indicator_selector().empty()) {
      bool has_pref_indicator_tests = false;
      for (ScopedVector<PrefMapping>::const_iterator
               pref_mapping = pref_mappings.begin();
           pref_mapping != pref_mappings.end();
           ++pref_mapping) {
        if (!(*pref_mapping)->indicator_test_cases().empty()) {
          has_pref_indicator_tests = true;
          break;
        }
      }
      if (!has_pref_indicator_tests)
        continue;
    }

    LOG(INFO) << "Testing policy: " << *it;

    if (!policy_test_case->indicator_selector().empty()) {
      // Check that no controlled setting indicator is visible when no value is
      // set by policy.
      ClearProviderPolicy();
      VerifyControlledSettingIndicators(browser(),
                                        policy_test_case->indicator_selector(),
                                        std::string(),
                                        std::string(),
                                        false);
      // Check that the appropriate controlled setting indicator is shown when a
      // value is enforced by policy.
      SetProviderPolicy(policy_test_case->test_policy(),
                        POLICY_LEVEL_MANDATORY);
      VerifyControlledSettingIndicators(browser(),
                                        policy_test_case->indicator_selector(),
                                        std::string(),
                                        "policy",
                                        false);
    }

    for (ScopedVector<PrefMapping>::const_iterator
             pref_mapping = pref_mappings.begin();
         pref_mapping != pref_mappings.end();
         ++pref_mapping) {
      const ScopedVector<IndicatorTestCase>&
          indicator_test_cases = (*pref_mapping)->indicator_test_cases();
      if (indicator_test_cases.empty())
        continue;

      if (!(*pref_mapping)->indicator_test_setup_js().empty()) {
        ASSERT_TRUE(content::ExecuteScript(
            browser()->tab_strip_model()->GetActiveWebContents(),
            (*pref_mapping)->indicator_test_setup_js()));
      }

      std::string indicator_selector = (*pref_mapping)->indicator_selector();
      if (indicator_selector.empty())
        indicator_selector = "[pref=\"" + (*pref_mapping)->pref() + "\"]";
      for (ScopedVector<IndicatorTestCase>::const_iterator
               indicator_test_case = indicator_test_cases.begin();
           indicator_test_case != indicator_test_cases.end();
           ++indicator_test_case) {
        // Check that no controlled setting indicator is visible when no value
        // is set by policy.
        ClearProviderPolicy();
        VerifyControlledSettingIndicators(
            browser(), indicator_selector, std::string(), std::string(), false);
        // Check that the appropriate controlled setting indicator is shown when
        // a value is enforced by policy.
        SetProviderPolicy((*indicator_test_case)->policy(),
                          POLICY_LEVEL_MANDATORY);
        VerifyControlledSettingIndicators(browser(), indicator_selector,
                                          (*indicator_test_case)->value(),
                                          "policy",
                                          (*indicator_test_case)->readonly());

        if (!policy_test_case->can_be_recommended())
          continue;

        PrefService* prefs = (*pref_mapping)->is_local_state() ?
            local_state : user_prefs;
        // The preference must have been registered.
        const PrefService::Preference* pref =
            prefs->FindPreference((*pref_mapping)->pref().c_str());
        ASSERT_TRUE(pref);

        // Check that the appropriate controlled setting indicator is shown when
        // a value is recommended by policy and the user has not overridden the
        // recommendation.
        SetProviderPolicy((*indicator_test_case)->policy(),
                          POLICY_LEVEL_RECOMMENDED);
        VerifyControlledSettingIndicators(browser(), indicator_selector,
                                          (*indicator_test_case)->value(),
                                          "recommended",
                                          (*indicator_test_case)->readonly());
        // Check that the appropriate controlled setting indicator is shown when
        // a value is recommended by policy and the user has overridden the
        // recommendation.
        prefs->Set((*pref_mapping)->pref().c_str(), *pref->GetValue());
        VerifyControlledSettingIndicators(browser(), indicator_selector,
                                          (*indicator_test_case)->value(),
                                          "hasRecommendation",
                                          (*indicator_test_case)->readonly());
        prefs->ClearPref((*pref_mapping)->pref().c_str());
      }
    }
  }
}

INSTANTIATE_TEST_CASE_P(PolicyPrefIndicatorTestInstance,
                        PolicyPrefIndicatorTest,
                        testing::ValuesIn(SplitPoliciesIntoChunks(10)));

}  // namespace policy