text:
"""Module defining multi-layer perceptron backpropagation neural network class"""
import json
import progressbar

import mlp_functions
import io_functions
import data_processing

class MLPNetwork(object):
    """Class to build an MLP network using stochastic gradient descent backpropagation learning"""
    def __init__(self, unified_filename, results_filename):
        self.results_filename = results_filename

        self.__read_parameters(unified_filename)
        self.__read_structure(unified_filename)
        self.__read_data(unified_filename)
        self.__data_preprocessing()
        self.__initialise_network()
        self.__backpropagation_loop()
        self.average_testing_error = 0
        self.__testing_loop()

        if self.params['save_summary']:
            self.__save_summary(results_filename)

    def __read_parameters(self, parameters_filename):
        with open('parameters/%s.json'
                  % parameters_filename) as parameters_file:
            self.params = json.load(parameters_file)

    def __read_structure(self, structure_filename):
        self.variable_types = io_functions.read_patterns_structure('data/%s_structure.csv'
                                                                   % structure_filename)

    def __read_data(self, data_filename):
        # read in training/validation patterns
        self.patterns = io_functions.read_patterns('data/%s.csv' % data_filename, self.params)

        # read in test patterns
        if self.params['testing']:
            self.test_patterns = io_functions.read_patterns('data/%s_test.csv'
                                                            % data_filename, self.params)

        # useful variable
        self.last_output = (self.params['input_dimensions'] + self.params['output_dimensions'])

    def __data_preprocessing(self):
        """Method to pre-process the data"""

        # split the data into training and validation patterns first
        if (self.params['validating'] and
                self.params['training_validation_ratio'] == 1):
            self.training_patterns = self.patterns
            self.validation_patterns = self.patterns

        elif (self.params['validating'] and
              self.params['training_validation_ratio'] < 1):
            num_training_patterns = int(
                len(self.patterns) * self.params['training_validation_ratio'])
            self.training_patterns = self.patterns[:num_training_patterns]
            self.validation_patterns = self.patterns[num_training_patterns:]

        elif not self.params['validating']:
            self.training_patterns = self.patterns

        # standardise the data
        # training patterns
        training_standardiser = data_processing.Standardiser(
            self.training_patterns, self.variable_types)

        training_standardiser.standardise_by_type()
        self.training_patterns = training_standardiser.patterns_out

        # validation patterns
        if self.params['validating']:
            validation_standardiser = data_processing.Standardiser(
                self.validation_patterns,
                self.variable_types,
                variables_mean=training_standardiser.variables_mean,
                variables_std=training_standardiser.variables_std)

            validation_standardiser.standardise_by_type()
            self.validation_patterns = validation_standardiser.patterns_out

        # test patterns
        if self.params['testing']:
            test_standardiser = data_processing.Standardiser(
                self.test_patterns,
                self.variable_types,
                variables_mean=training_standardiser.variables_mean,
                variables_std=training_standardiser.variables_std)

            test_standardiser.standardise_by_type()
            self.test_patterns = test_standardiser.patterns_out

        self.training_standardiser = training_standardiser

        # if scaling the output, adjust target training error accordingly
        if self.params['output_dimensions'] == 1:
            if data_processing.is_scale_type(self.variable_types[-1]):
                # to add effect of scalar, multiply by scale value
                target_training_error = (
                    self.params['target_training_error'] * float(self.variable_types[-1]))
            elif self.variable_types[-1] == 'numeric':
                # to add effect of numeric standardisation, divide by standard deviation
                target_training_error = (
                    self.params['target_training_error'] /
                    self.training_standardiser.variables_std[-1])
            else:
                target_training_error = self.params['target_training_error']
        else:
            target_training_error = self.params['target_training_error']

        self.target_training_error = target_training_error

    def __initialise_network(self):
        # network initialisation
        # set number of neurons in each layer
        # layer '0' is the input layer and defines number of inputs
        neurons_l = []
        neurons_l.append(self.params['input_dimensions'])

        for hidden_node_index in range(len(self.params['hidden_nodes'])):
            neurons_l.append(self.params['hidden_nodes'][hidden_node_index])

        # this may not always be the case but is set here
        neurons_l.append(self.params['output_dimensions'])

        # initialise weights
        weights_l_i_j = mlp_functions.initialise_weights(self.params,
                                                         neurons_l)

        self.neurons_l = neurons_l
        self.weights_l_i_j = weights_l_i_j

    def __backpropagation_loop(self):
        # backpropagation loop
        # epoch count starts at one
        epoch = 1
        training_errors = []
        repeat = True
        target_training_error_reached = False

        if self.params['validating']:
            validation_errors = []
            validation_error_best = 1000.0
            training_error_best = 0.0
            epoch_best = 0

        # initialise progress bar for console
        progress_bar = progressbar.ProgressBar(
            maxval=self.params['max_epochs'],
            widgets=[progressbar.Bar(
                '=', '[', ']'), ' ', progressbar.Percentage()])
        progress_bar.start()
        while repeat:
            training_error = 0.0
            progress_bar.update(epoch)

            for pattern in self.training_patterns:
                # load pattern
                input_pattern = pattern[:self.params['input_dimensions']]
                # set bias 'output'
                outputs_l_j = mlp_functions.initialise_bias(self.params)
                # add input pattern to 'output' of layer 0
                outputs_l_j[0].extend(input_pattern)

                # forward pass
                outputs_l_j = mlp_functions.forward_pass(
                    self.params, self.neurons_l, self.weights_l_i_j,
                    outputs_l_j)

                # update training_error
                output_pattern = pattern[self.params['input_dimensions']:
                                         self.last_output]
                teacher_i = []
                # account for i = 0
                teacher_i.append(None)
                teacher_i.extend(output_pattern)

                training_error = mlp_functions.update_ms_error(
                    self.neurons_l, training_error, teacher_i, outputs_l_j)

                # calculate errors
                errors_l_i = mlp_functions.calculate_errors(
                    self.params, self.neurons_l, self.weights_l_i_j,
                    teacher_i, outputs_l_j)

                # update weights
                self.weights_l_i_j = mlp_functions.update_weights(
                    self.params, self.neurons_l, self.weights_l_i_j,
                    errors_l_i, outputs_l_j)

            # calculate rms training error
            training_error = mlp_functions.calculate_rms_error(
                self.params['output_function'],
                training_error,
                self.neurons_l[-1],
                len(self.training_patterns)
            )

            # write out epoch training_error
            training_errors.append(training_error)

            # Write out weights and errors if specified
            if self.params['save_network']:
                if epoch % self.params['save_network_resolution'] == 0:
                    # append results to file
                    headers = (['epoch'] +
                               ['weight_%s_%s_%s' % (l+1, i+1, j)
                                for l in range(len(self.weights_l_i_j[1:]))
                                for i in range(len(self.weights_l_i_j[l+1][1:]))
                                for j in range(len(self.weights_l_i_j[l+1][i+1]))] +
                               ['error_%s_%s' % (l+1, i+1)
                                for l in range(len(errors_l_i[1:]))
                                for i in range(len(errors_l_i[l+1][1:]))])

                    result = [epoch]
                    result.extend(
                        [j for l in range(len(self.weights_l_i_j[1:]))
                         for i in range(len(self.weights_l_i_j[l+1][1:]))
                         for j in self.weights_l_i_j[l+1][i+1]])
                    result.extend(
                        [i for l in range(len(errors_l_i[1:]))
                         for i in errors_l_i[l+1][1:]])

                    io_functions.write_result_row(
                        'results/%s_weights.csv' % self.results_filename, headers, result)

            if self.params['validating']:
                validation_error = 0.0

                for pattern in self.validation_patterns:
                    # load pattern
                    input_pattern = pattern[:self.params['input_dimensions']]
                    # set bias 'output'
                    outputs_l_j = mlp_functions.initialise_bias(self.params)
                    # add input pattern to 'output' of layer 0
                    outputs_l_j[0].extend(input_pattern)

                    # forward pass
                    outputs_l_j = mlp_functions.forward_pass(
                        self.params, self.neurons_l, self.weights_l_i_j,
                        outputs_l_j)

                    # update validation error
                    output_pattern = pattern[self.params['input_dimensions']:
                                             self.last_output]

                    teacher_i = []
                    # account for i = 0
                    teacher_i.append(None)
                    teacher_i.extend(output_pattern)
                    validation_error = mlp_functions.update_ms_error(
                        self.neurons_l, validation_error, teacher_i,
                        outputs_l_j)

                # calculate rms validation error
                validation_error = mlp_functions.calculate_rms_error(
                    self.params['output_function'],
                    validation_error,
                    self.neurons_l[-1],
                    len(self.validation_patterns)
                )

                # make sure validation error is dropping
                if validation_error < validation_error_best:
                    validation_error_best = validation_error
                    best_weights_l_i_j = list(self.weights_l_i_j)
                    epoch_best = epoch

                validation_errors.append(validation_error)

            # record when target training error was reached
            if not target_training_error_reached:
                epoch_target_training_error = epoch
                if training_error < self.target_training_error:
                    target_training_error_reached = True

            # network training halting conditions
            if self.params['stop_at_target_training_error']:
                if (training_error < self.target_training_error or
                        epoch == self.params['max_epochs']):
                    repeat = False
            else:
                if epoch == self.params['max_epochs']:
                    repeat = False

            # finally, increment the epoch
            epoch += 1

        # reverse effects of standardiser on error when we only have a single output
        # only modifies error with numeric standardised outputs and scaled outputs
        if self.params['output_dimensions'] == 1:
            if data_processing.is_scale_type(self.variable_types[-1]):
                training_destandardiser_error = data_processing.Destandardiser(
                    [[item] for item in training_errors],
                    [self.variable_types[-1]])
                training_destandardiser_error.destandardise_by_type()
                training_errors = [
                    item[0] for item in training_destandardiser_error.patterns_out]
                if self.params['validating']:
                    validation_destandardiser_error = data_processing.Destandardiser(
                        [[item] for item in validation_errors],
                        [self.variable_types[-1]])
                    validation_destandardiser_error.destandardise_by_type()
                    validation_errors = [
                        item[0] for item in validation_destandardiser_error.patterns_out]
            elif self.variable_types[-1] == 'numeric':
                training_destandardiser_error = data_processing.Destandardiser(
                    [[item] for item in training_errors],
                    [self.variable_types[-1]],
                    variables_mean=[0],
                    variables_std=[self.training_standardiser.variables_std[-1]])
                training_destandardiser_error.destandardise_by_type()
                training_errors = [
                    item[0] for item in training_destandardiser_error.patterns_out]
                if self.params['validating']:
                    validation_destandardiser_error = data_processing.Destandardiser(
                        [[item] for item in validation_errors],
                        [self.variable_types[-1]],
                        variables_mean=[0],
                        variables_std=[self.training_standardiser.variables_std[-1]])
                    validation_destandardiser_error.destandardise_by_type()
                    validation_errors = [
                        item[0] for item in validation_destandardiser_error.patterns_out]

        # data for summary results
        self.training_errors = training_errors
        self.epoch_end = epoch - 1 # subtract one as increment occurs before while loop ends
        self.epoch_target_training_error = epoch_target_training_error
        self.training_error_end = training_errors[-1]

        if self.params['validating']:
            self.best_weights_l_i_j = best_weights_l_i_j
            self.validation_errors = validation_errors
            self.validation_error_end = validation_errors[-1]
            self.training_error_best = training_errors[epoch_best - 1] # epoch indexed from 1
            self.validation_error_best = validation_errors[epoch_best - 1] # epoch indexed from 1
            self.epoch_best = epoch_best

        # write out detailed results if specified
        if self.params['save_detailed']:
            headers = (['epoch'] +
                       ['training_error'] +
                       ['validation_error']
                      )
            for epoch_index, training_error in enumerate(training_errors):
                result = []
                if self.params['validating']:
                    result.append(epoch_index + 1) # start epoch count at one
                    result.append(training_error)
                    result.append(validation_errors[epoch_index])
                else:
                    result.append(epoch_index + 1)
                    result.append(training_error)

                io_functions.write_result_row(
                    'results/%s_detailed.csv' % self.results_filename, headers, result)

    def __testing_loop(self):
        # testing loop
        if self.params['testing']:
            testing_errors = []
            all_outputs_l_j = []

            for pattern in self.test_patterns:
                testing_error = 0.0
                # load pattern
                input_pattern = pattern[:self.params['input_dimensions']]

                # set bias 'output'
                outputs_l_j = mlp_functions.initialise_bias(self.params)
                # add input pattern to 'output' of layer 0
                outputs_l_j[0].extend(input_pattern)

                # forward pass
                # use weight at lowest validation error
                if self.params['validating'] and self.params['best_weights']:
                    outputs_l_j = mlp_functions.forward_pass(
                        self.params, self.neurons_l, self.best_weights_l_i_j,
                        outputs_l_j)
                # use weight at lowest training error
                else:
                    outputs_l_j = mlp_functions.forward_pass(
                        self.params, self.neurons_l, self.weights_l_i_j,
                        outputs_l_j)

                # update test error
                output_pattern = pattern[self.params['input_dimensions']:
                                         self.last_output]

                teacher_i = []
                # account for i = 0
                teacher_i.append(None)
                teacher_i.extend(output_pattern)

                testing_error = mlp_functions.update_ms_error(
                    self.neurons_l, testing_error, teacher_i, outputs_l_j)

                # calculate rms testing error
                testing_error = mlp_functions.calculate_rms_error(
                    self.params['output_function'],
                    testing_error,
                    self.neurons_l[-1],
                    1
                )

                all_outputs_l_j.append(outputs_l_j)
                testing_errors.append(testing_error)

            # remove standardisation effects from data
            test_destandardiser_data = data_processing.Destandardiser(
                self.test_patterns,
                self.variable_types,
                variables_mean=self.training_standardiser.variables_mean,
                variables_std=self.training_standardiser.variables_std)

            test_destandardiser_data.destandardise_by_type()

            # remove standardisation effects from net outputs
            test_destandardiser_net = data_processing.Destandardiser(
                [item[-1][1:] for item in all_outputs_l_j],
                self.variable_types[self.params['input_dimensions']:self.last_output],
                variables_mean=self.training_standardiser.variables_mean[
                    self.params['input_dimensions']:self.last_output],
                variables_std=self.training_standardiser.variables_std[
                    self.params['input_dimensions']:self.last_output])

            test_destandardiser_net.destandardise_by_type()

            # reverse effects of standardiser on error when we only have a single output
            # only modifies error with numeric standardised outputs and scaled outputs
            if self.params['output_dimensions'] == 1:
                if data_processing.is_scale_type(self.variable_types[-1]):
                    test_destandardiser_error = data_processing.Destandardiser(
                        [[item] for item in testing_errors],
                        [self.variable_types[-1]])
                    test_destandardiser_error.destandardise_by_type()
                elif self.variable_types[-1] == 'numeric':
                    test_destandardiser_error = data_processing.Destandardiser(
                        [[item] for item in testing_errors],
                        [self.variable_types[-1]],
                        variables_mean=[0],
                        variables_std=[self.training_standardiser.variables_std[-1]])
                    test_destandardiser_error.destandardise_by_type()
                else:
                    test_destandardiser_error = None
            else:
                test_destandardiser_error = None

            # append testing results to file
            if self.params['save_testing']:
                headers = (['input_%s' % i for i in range(len(input_pattern))] +
                           ['output_%s' % i for i in range(len(output_pattern))] +
                           ['test_output_%s' % i for i in range(len(outputs_l_j[-1][1:]))] +
                           ['testing_error']
                          )
                for pattern_number in range(len(test_destandardiser_data.patterns_out)):
                    if test_destandardiser_error is not None:
                        result = (test_destandardiser_data.patterns_out[pattern_number] +
                                  test_destandardiser_net.patterns_out[pattern_number] +
                                  test_destandardiser_error.patterns_out[pattern_number])
                    else:
                        result = (test_destandardiser_data.patterns_out[pattern_number] +
                                  test_destandardiser_net.patterns_out[pattern_number] +
                                  [testing_errors[pattern_number]])

                    io_functions.write_result_row(
                        'results/%s_testing.csv' % self.results_filename, headers, result)

            # calculate average testing error
            if test_destandardiser_error is not None:
                self.average_testing_error = (
                    sum([item[0] for item in test_destandardiser_error.patterns_out]) /
                    float(len(testing_errors)))
                self.testing_errors = [item[0] for item in test_destandardiser_error.patterns_out]
            else:
                self.average_testing_error = sum(testing_errors)/float(len(testing_errors))
                self.testing_errors = testing_errors

    def __save_summary(self, results_filename):
        # save some data
        headers = ['weight_init_mean', 'weight_init_range',
                   'random_numbers_seed', 'hidden_layers_function',
                   'output_function', 'training_rate',
                   'hidden_nodes', 'epoch_end', 'training_error_end',
                   'epoch_target_training_error', 'average_testing_error',
                   'validation_error_end', 'epoch_best',
                   'training_error_best', 'validation_error_best'
                  ]
        result = []
        result.append(self.params['weight_init_mean'])
        result.append(self.params['weight_init_range'])
        result.append(self.params['random_numbers_seed'])
        result.append(self.params['hidden_layers_function'])
        result.append(self.params['output_function'])
        result.append(self.params['training_rate'])
        result.append(self.params['hidden_nodes'])
        result.extend([self.epoch_end, self.training_error_end,
                       self.epoch_target_training_error, self.average_testing_error])

        if self.params['validating']:
            result.extend([self.validation_error_end, self.epoch_best,
                           self.training_error_best, self.validation_error_best])

        io_functions.write_result_row(
            'results/%s.csv' % results_filename, headers, result)


text:
layout: single
title: "Asilo politico."
redirect_from: /node/79
categories:
tags: []
comments:
---
Ayer sufrí una experiencia traumática.

Sin saber como, me vi rodeado por dos afganos y un curdo que me convirtieron en víctima de una de actividades que, por lo que yo sé (en contraposición a lo que dice la tele), es da las más representativas del mudo árabe: la hospitalidad.

Ayer, pasé una de las noches más agradables en esta nueva etapa irlandesa saboreando una deliciosa cena afgana en compañía de miembros (o debería decir personajes) de 5 países distintos: Afganistán, España, Irán, Irlanda y Holanda.

A pesar de la exquisita comida, el buen vino y la mejor conversación, en cualquier reunión que en algo se parezca a la de ayer, siempre quedará un sabor amargo. El sabor del Asilo Político (más bien el Asilo Polipatético) que, tristemente, se podría considerar una de las actividades más representativas del mundo occidental.

No solo blindamos nuestras fronteras a los inmigrantes, si no que las puertas que dejamos abiertas (para no mearnos en los derechos humanos desde el trampolín) se convierten en un laberinto burocrático en la que los solicitantes de asilo muren de sed. Sed de trabajo, sed de reconocimiento, sed de libertad. Mueren de sed en un mar de opulencia.

redpajama_set_name: RedPajamaGithub


text:
const React = require('react');
const renderer = require('react-test-renderer');

const prettyFormat = require('../');
const ReactTestComponent = require('../plugins/ReactTestComponent');
const ReactElement = require('../plugins/ReactElement');

function assertPrintedJSX(actual, expected, opts) {
  expect(
    prettyFormat(
      actual,
      Object.assign(
        {
          plugins: [ReactElement],
        },
        opts,
      ),
    ),
  ).toEqual(expected);
  expect(
    prettyFormat(
      renderer.create(actual).toJSON(),
      Object.assign(
        {
          plugins: [ReactTestComponent, ReactElement],
        },
        opts,
      ),
    ),
  ).toEqual(expected);
}

test('supports a single element with no props or children', () => {
  assertPrintedJSX(React.createElement('Mouse'), '<Mouse />');
});

test('supports a single element with no props', () => {
  assertPrintedJSX(
    React.createElement('Mouse', null, 'Hello World'),
    '<Mouse>\n  Hello World\n</Mouse>',
  );
});

test('supports a single element with number children', () => {
  assertPrintedJSX(
    React.createElement('Mouse', null, 4),
    '<Mouse>\n  4\n</Mouse>',
  );
});

test('supports a single element with mixed children', () => {
  assertPrintedJSX(
    React.createElement('Mouse', null, [[1, null], 2, undefined, [false, [3]]]),
    '<Mouse>\n  1\n  2\n  3\n</Mouse>',
  );
});

test('supports props with strings', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {style: 'color:red'}),
    '<Mouse\n  style="color:red"\n/>',
  );
});

test('supports props with numbers', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {size: 5}),
    '<Mouse\n  size={5}\n/>',
  );
});

test('supports a single element with a function prop', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {onclick: function onclick() {}}),
    '<Mouse\n  onclick={[Function onclick]}\n/>',
  );
});

test('supports a single element with a object prop', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {customProp: {one: '1', two: 2}}),
    '<Mouse\n  customProp={\n    Object {\n      "one": "1",\n      "two": 2,\n    }\n  }\n/>',
  );
});

test('supports an element with and object prop and children', () => {
  assertPrintedJSX(
    React.createElement(
      'Mouse',
      {customProp: {one: '1', two: 2}},
      React.createElement('Mouse'),
    ),
    '<Mouse\n  customProp={\n    Object {\n      "one": "1",\n      "two": 2,\n    }\n  }\n>\n  <Mouse />\n</Mouse>',
  );
});

test('supports an element with complex props and mixed children', () => {
  assertPrintedJSX(
    React.createElement(
      'Mouse',
      {customProp: {one: '1', two: 2}, onclick: function onclick() {}},
      'HELLO',
      React.createElement('Mouse'),
      'CIAO',
    ),
    '<Mouse\n  customProp={\n    Object {\n      "one": "1",\n      "two": 2,\n    }\n  }\n  onclick={[Function onclick]}\n>\n  HELLO\n  <Mouse />\n  CIAO\n</Mouse>',
  );
});

test('escapes children properly', () => {
  assertPrintedJSX(
    React.createElement(
      'Mouse',
      null,
      '"-"',
      React.createElement('Mouse'),
      '\\ \\\\',
    ),
    '<Mouse>\n  "-"\n  <Mouse />\n  \\ \\\\\n</Mouse>',
  );
});

test('supports everything all together', () => {
  assertPrintedJSX(
    React.createElement(
      'Mouse',
      {customProp: {one: '1', two: 2}, onclick: function onclick() {}},
      'HELLO',
      React.createElement(
        'Mouse',
        {customProp: {one: '1', two: 2}, onclick: function onclick() {}},
        'HELLO',
        React.createElement('Mouse'),
        'CIAO',
      ),
      'CIAO',
    ),
    '<Mouse\n  customProp={\n    Object {\n      "one": "1",\n      "two": 2,\n    }\n  }\n  onclick={[Function onclick]}\n>\n  HELLO\n  <Mouse\n    customProp={\n      Object {\n        "one": "1",\n        "two": 2,\n      }\n    }\n    onclick={[Function onclick]}\n  >\n    HELLO\n    <Mouse />\n    CIAO\n  </Mouse>\n  CIAO\n</Mouse>',
  );
});

test('sorts props in nested components', () => {
  /* eslint-disable sort-keys */
  assertPrintedJSX(
    React.createElement(
      'Mouse',
      {
        zeus: 'kentaromiura watched me fix this',
        abc: {
          one: '1',
          two: 2,
        },
      },
      React.createElement(
        'Mouse',
        {
          xyz: 123,
          acbd: {
            one: '1',
            two: 2,
          },
        },
        'NESTED',
      ),
    ),
    '<Mouse\n  abc={\n    Object {\n      "one": "1",\n      "two": 2,\n    }\n  }\n  zeus="kentaromiura watched me fix this"\n>\n  <Mouse\n    acbd={\n      Object {\n        "one": "1",\n        "two": 2,\n      }\n    }\n    xyz={123}\n  >\n    NESTED\n  </Mouse>\n</Mouse>',
  );
  /* eslint-enable sort-keys */
});

test('supports a single element with React elements as props', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement('div'),
    }),
    '<Mouse\n  prop={<div />}\n/>',
  );
});

test('supports a single element with React elements with props', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement('div', {foo: 'bar'}),
    }),
    '<Mouse\n  prop={\n    <div\n      foo="bar"\n    />\n  }\n/>',
  );
});

test('supports a single element with custom React elements with props', () => {
  function Cat() {
    return React.createElement('div');
  }
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement(Cat, {foo: 'bar'}),
    }),
    '<Mouse\n  prop={\n    <Cat\n      foo="bar"\n    />\n  }\n/>',
  );
});

test('supports a single element with custom React elements with props (using displayName)', () => {
  function Cat() {
    return React.createElement('div');
  }
  Cat.displayName = 'CatDisplayName';
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement(Cat, {foo: 'bar'}),
    }),
    '<Mouse\n  prop={\n    <CatDisplayName\n      foo="bar"\n    />\n  }\n/>',
  );
});

test('supports a single element with custom React elements with props (using anonymous function)', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement(
        () => {
          React.createElement('div');
        },
        {foo: 'bar'},
      ),
    }),
    '<Mouse\n  prop={\n    <Unknown\n      foo="bar"\n    />\n  }\n/>',
  );
});

test('supports a single element with custom React elements with a child', () => {
  function Cat(props) {
    return React.createElement('div', props);
  }
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement(Cat, {}, React.createElement('div')),
    }),
    '<Mouse\n  prop={\n    <Cat>\n      <div />\n    </Cat>\n  }\n/>',
  );
});

test('supports Unknown element', () => {
  // Suppress React.createElement(undefined) console error
  const consoleError = console.error;
  console.error = jest.fn();
  expect(
    prettyFormat(React.createElement(undefined), {
      plugins: [ReactElement],
    }),
  ).toEqual('<Unknown />');
  console.error = consoleError;
});

test('supports a single element with React elements with a child', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement('div', null, 'mouse'),
    }),
    '<Mouse\n  prop={\n    <div>\n      mouse\n    </div>\n  }\n/>',
  );
});

test('supports a single element with React elements with children', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement(
        'div',
        null,
        'mouse',
        React.createElement('span', null, 'rat'),
      ),
    }),
    '<Mouse\n  prop={\n    <div>\n      mouse\n      <span>\n        rat\n      </span>\n    </div>\n  }\n/>',
  );
});

test('supports a single element with React elements with array children', () => {
  assertPrintedJSX(
    React.createElement('Mouse', {
      prop: React.createElement('div', null, 'mouse', [
        React.createElement('span', {key: 1}, 'rat'),
        React.createElement('span', {key: 2}, 'cat'),
      ]),
    }),
    '<Mouse\n  prop={\n    <div>\n      mouse\n      <span>\n        rat\n      </span>\n      <span>\n        cat\n      </span>\n    </div>\n  }\n/>',
  );
});

test('uses the supplied line seperator for min mode', () => {
  assertPrintedJSX(
    React.createElement(
      'Mouse',
      {customProp: {one: '1', two: 2}, onclick: function onclick() {}},
      'HELLO',
      React.createElement(
        'Mouse',
        {customProp: {one: '1', two: 2}, onclick: function onclick() {}},
        'HELLO',
        React.createElement('Mouse'),
        'CIAO',
      ),
      'CIAO',
    ),
    '<Mouse customProp={{"one": "1", "two": 2}} onclick={[Function onclick]}>HELLO<Mouse customProp={{"one": "1", "two": 2}} onclick={[Function onclick]}>HELLO<Mouse />CIAO</Mouse>CIAO</Mouse>',
    {min: true},
  );
});

test('ReactElement plugin highlights syntax', () => {
  const jsx = React.createElement('Mouse', {
    prop: React.createElement(
      'div',
      null,
      'mouse',
      React.createElement('span', null, 'rat'),
    ),
  });
  expect(
    prettyFormat(jsx, {
      highlight: true,
      plugins: [ReactElement],
    }),
  ).toMatchSnapshot();
});

test('ReactTestComponent plugin highlights syntax', () => {
  const jsx = React.createElement('Mouse', {
    prop: React.createElement(
      'div',
      null,
      'mouse',
      React.createElement('span', null, 'rat'),
    ),
  });
  expect(
    prettyFormat(renderer.create(jsx).toJSON(), {
      highlight: true,
      plugins: [ReactTestComponent, ReactElement],
    }),
  ).toMatchSnapshot();
});

test('throws if theme option is null', () => {
  const jsx = React.createElement(
    'Mouse',
    {style: 'color:red'},
    'Hello, Mouse!',
  );
  expect(() => {
    prettyFormat(jsx, {
      highlight: true,
      plugins: [ReactElement],
      theme: null,
    });
  }).toThrow('pretty-format: Option "theme" must not be null.');
});

test('throws if theme option is not of type "object"', () => {
  expect(() => {
    const jsx = React.createElement(
      'Mouse',
      {style: 'color:red'},
      'Hello, Mouse!',
    );
    prettyFormat(jsx, {
      highlight: true,
      plugins: [ReactElement],
      theme: 'beautiful',
    });
  }).toThrow(
    'pretty-format: Option "theme" must be of type "object" but instead received "string".',
  );
});

test('throws if theme option has value that is undefined in ansi-styles', () => {
  expect(() => {
    const jsx = React.createElement(
      'Mouse',
      {style: 'color:red'},
      'Hello, Mouse!',
    );
    prettyFormat(jsx, {
      highlight: true,
      plugins: [ReactElement],
      theme: {
        content: 'unknown',
        prop: 'yellow',
        tag: 'cyan',
        value: 'green',
      },
    });
  }).toThrow(
    'pretty-format: Option "theme" has a key "content" whose value "unknown" is undefined in ansi-styles.',
  );
});

test('ReactElement plugin highlights syntax with color from theme option', () => {
  const jsx = React.createElement(
    'Mouse',
    {style: 'color:red'},
    'Hello, Mouse!',
  );
  expect(
    prettyFormat(jsx, {
      highlight: true,
      plugins: [ReactElement],
      theme: {
        value: 'red',
      },
    }),
  ).toMatchSnapshot();
});

test('ReactTestComponent plugin highlights syntax with color from theme option', () => {
  const jsx = React.createElement(
    'Mouse',
    {style: 'color:red'},
    'Hello, Mouse!',
  );
  expect(
    prettyFormat(renderer.create(jsx).toJSON(), {
      highlight: true,
      plugins: [ReactTestComponent, ReactElement],
      theme: {
        value: 'red',
      },
    }),
  ).toMatchSnapshot();
});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.lcodecore.tkrefreshlayout.widget.CircleImageView
        android:id="@+id/avatar"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="16dp"
        android:src="@drawable/avatar1" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_margin="16dp"
        android:layout_toRightOf="@+id/avatar"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_song"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:text="What Do You Mean?"
            android:textColor="#656565"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_singer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:text="Justin Bieber"
            android:textColor="#B1B1B1"
            android:textSize="12sp" />
    </LinearLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="16dp"
        android:src="@drawable/play" />
</RelativeLayout>


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 quickforms.sme.pregapp;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import quickforms.sme.*;
import quickforms.dao.Database;
import quickforms.dao.LookupPair;

/**
 * @author Ben Eze
 */
public class Pregapp_EmailNotification_RuleEngine implements RuleEngine {
    private final int minimumWeek = 0;
    private final int maximumWeek = 40;
    private String senderAlias="";
    private String senderEmail = "";
    private String senderPassword = "";
    private Boolean testMode = false;
    private final String adminUserEmails = "eze.ben@gmail.com";

    /***
     * Processes and sends notifications for all those that match the pregnancy anniversary
     *
     * @param context
     * @param ds
     * @param factID
     * @param oldContextStr
     * @throws Exception
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void process(Map<String, String[]> context, DataSource ds, String factID, List<List<LookupPair>> oldContextStr) throws Exception {
        //Get context details
        try {

            this.testMode = Boolean.parseBoolean(context.get("chkMode")[0]);

            System.out.println(String.format("Test mode:%s", context.get("chkMode")[0].toString()));
            System.out.println(String.format("Test mode:%s", this.testMode.toString()));

        } catch (Exception e) {
            System.out.println(String.format("Exception reading form parameters: %s", e.getMessage()));
        }

        //Pull the pregapp email settings. If this fails, go ahead and use the default
        Pregapp_EmailNotification_Settings settings = UseFulMethods.getPregappEmailSettings();

        //get all Users
        Database db = new Database(ds);
        String app = context.get("app")[0];
        String lkup_UsersJSon = db.getResultSet(app, "lkup_Users", null, null, null, null);
        List<Map> allUsersLkUp = UseFulMethods.createRSContext(lkup_UsersJSon);
        System.out.println(String.format("Results found: %d", allUsersLkUp.size()));
        int emailsSent = 0;
        String subscriberEmailConfirmation = "";

        for (Map<String, String[]> row : allUsersLkUp) //for each user
        {
        	try{
        		//sent email and add to db
                String userKey = row.get("usersKey")[0];
                String userEmail = row.get("Email")[0];

                int currWeek = getNotificationCurrentWeek(UseFulMethods.getDateFromString(row.get("DueDate")[0]));    //calculate user week

                System.out.println(String.format("Details for user:%s, key:%s, current week:%d Due Date:%s ", userEmail, userKey, currWeek, row.get("DueDate")[0]));

                if (currWeek >= minimumWeek && currWeek <= maximumWeek) {
                    String messageLog = String.format("Email sent for user:%s, key:%s, current week:%d ", userEmail, userKey, currWeek);

                    sendNotificationEmail(settings, row, app, currWeek);
                    System.out.println(messageLog);

                    emailsSent += 1;
                    if (subscriberEmailConfirmation == "")
                        subscriberEmailConfirmation = messageLog;
                    else
                        subscriberEmailConfirmation += "
" + messageLog;
                }

        	}catch(Exception e){
        		System.out.println(String.format("Exception sending email for %s: %s", row.get("Email")[0], e.getMessage()));
        	}
        }

        //Send confirmation daily to show that the messages were actually sent
        this.sendAdminConfirmationEmail(settings, emailsSent, subscriberEmailConfirmation);
    }

    /**
     * Sends the notification email congratulating the pregnant mom on another weekly anniversary
     *
     * @param row
     * @param app
     * @param currWeek
     * @return
     * @throws IOException
     * @throws Exception
     */
    public String[] sendNotificationEmail(Pregapp_EmailNotification_Settings settings, Map<String, String[]> row, String app, int currWeek) throws IOException, Exception {

    	this.senderEmail = settings.getDefaultSenderEmail();
    	this.senderAlias = settings.getDefaultSenderAlias();
    	this.senderPassword = settings.getDefaultSenderPassword();

        String subject = settings.getSubjectTemplate().replace("@@Subscriber", "Subscriber").replace("@@WeekNumber", Integer.toString(currWeek));
        String message = settings.getBodyTemplate().replace("@@WeekNumber", Integer.toString(currWeek)).replace("@@Subscriber", "Subscriber");
        String recipientEmail = row.get("Email")[0];

        //If we are testing, send the email to ourselves
        if (this.testMode) {
            recipientEmail = settings.getAdminEmails();
            message = "This is a test notification.....";
        }

        UseFulMethods.sendEmail(this.senderEmail, this.senderAlias, this.senderPassword, recipientEmail, subject, message);
        String[] params = new String[2];
        params[0] = senderEmail;
        params[1] = message;

        return params;
    }

    /**
     * sends confirmation email to administrators
     *
     * @param app
     * @param numberOfEmails
     */
    private void sendAdminConfirmationEmail(Pregapp_EmailNotification_Settings settings, int numberOfEmails, String messageLog) {

        try {

        	this.senderEmail = settings.getDefaultSenderEmail();
        	this.senderAlias = settings.getDefaultSenderAlias();
        	this.senderPassword = settings.getDefaultSenderPassword();

            String message = String.format("%d subscriber emails have been sent!

 %s", numberOfEmails, messageLog);
            UseFulMethods.sendEmail(this.senderEmail, this.senderAlias, this.senderPassword, this.adminUserEmails, "Daily notification summary", message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, String[]> setNewContext(Map<String, String[]> context, String UsersKey, String message, Integer currWeek, String factID, String senderEmail) throws Exception {
        Map<String, String[]> newContext = new HashMap<String, String[]>(context);
        newContext.put("senderEmail", new String[]{senderEmail});
        newContext.put("weeksK", new String[]{String.valueOf(currWeek)});
        newContext.put("usersK", new String[]{UsersKey});
        newContext.put("message", new String[]{message});
        newContext.put("emailType", new String[]{"1"});
        newContext.put("requestNumber", new String[]{factID});
        newContext.put("sendEmail", new String[]{"false"});
        return newContext;
    }

    public Map<String, String[]> setOldContext(Map<String, String[]> context, String factID, String senderEmail) throws Exception {
        Map<String, String[]> newContext = new HashMap<String, String[]>(context);
        newContext.put("senderEmail", new String[]{senderEmail});
        newContext.put("updateid", new String[]{factID});
        newContext.put("message", new String[]{"Initiation for Weekly Email Request"});
        newContext.remove("createdDate");
        newContext.put("sendEmail", new String[]{"false"});

        return newContext;
    }

    /**
     * gets the current week if the due date anniversary is the week day as today
     *
     * @param dueDateStr Due date for the pregnancy
     * @return number between minimumWeek - 40
     * @throws Exception
     */
    private int getNotificationCurrentWeek(Date dueDate) throws Exception {

        Integer minimumValue = minimumWeek - 1;

        if (dueDate == null)
            return minimumValue;

        //Get the date format
        DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());

        //Get the current date
        String curDateStr = formatter.format(System.currentTimeMillis());
        Date curDate = formatter.parse(curDateStr);

        //If the current date is not the weekly anniversary,
        //then we are done
        Calendar calDueDate = Calendar.getInstance();
        Calendar calCurrentDate = Calendar.getInstance();

        calDueDate.setTime(dueDate);
        calCurrentDate.setTime(curDate);

        //System.out.println("Due date day of the week: " + calDueDate.get(Calendar.DAY_OF_WEEK));
        //System.out.println("Current day of the week: " + calCurrentDate.get(Calendar.DAY_OF_WEEK));

        if (calDueDate.get(Calendar.DAY_OF_WEEK)
                != calCurrentDate.get(Calendar.DAY_OF_WEEK))
            return minimumValue;

        //Today is the weekly anniversary, we go ahead and process
        //the number of weeks
        int dueDays = (int) (long) (TimeUnit.DAYS.convert((dueDate.getTime() - curDate.getTime())
                , TimeUnit.MILLISECONDS));

        double weeks = ((double) dueDays / 7.0);

        if (weeks < this.minimumWeek) //Way beyond due date
            return minimumValue;
        else if (weeks >= 0)
            return (int) (40.0 - weeks); //Before due date
        else
            return (int) weeks; //After delivery up to the minimum allowed
    }

    public static void main(String[] args) {

    	try{
    		UseFulMethods.sendEmail("autoReplyPregApp@gmail.com", "Test Alias", "autoReplyPregApp1", "eze.ben@gmail.com", "Daily notification summary", "Test message");
    		UseFulMethods.sendEmail("autoReplyPregApp@gmail.com", "Test Alias", "autoReplyPregApp1", "eze.ben@gmail.com", "Daily notification summary", "Test message");
    	}catch(Exception e){
    		e.printStackTrace();
    	}

    	System.out.println("Testing");
        Pregapp_EmailNotification_RuleEngine pregappRuleEngine = new Pregapp_EmailNotification_RuleEngine();

        try {
            String currentWeek = "08/10/2015";
            System.out.println(pregappRuleEngine.getNotificationCurrentWeek(UseFulMethods.getDateFromString(currentWeek)));

            currentWeek = "31/05/2016";
            System.out.println(pregappRuleEngine.getNotificationCurrentWeek(UseFulMethods.getDateFromString(currentWeek)));

            currentWeek = "21/06/2016";
            System.out.println(pregappRuleEngine.getNotificationCurrentWeek(UseFulMethods.getDateFromString(currentWeek)));

            currentWeek = "11/03/2016";
            System.out.println(pregappRuleEngine.getNotificationCurrentWeek(UseFulMethods.getDateFromString(currentWeek)));

            currentWeek = "20/10/2016";
            System.out.println(pregappRuleEngine.getNotificationCurrentWeek(UseFulMethods.getDateFromString(currentWeek)));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Testing - sending emails");
        Pregapp_EmailNotification_Settings settings = UseFulMethods.getPregappEmailSettings();

        Map<String, String[]> row = new HashMap<String, String[]>();
        String[] email = new String[] {"eze.ben@gmail.com"};
        row.put("Email", email);

        try {
			pregappRuleEngine.sendNotificationEmail(settings, row, "", 31);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}


text:
namespace omaha {

namespace {

// Formats a single unescaped argument. Placeholder %N is replaced with
// parameters[N - 1]. Returns false if a placeholder %N is encountered where N >
// parameters.size().
// A series of % characters followed by a digit may be escaped by doubling the %
// characters. See examples in the class comments for AppCommandFormatter.
bool InterpolateArgument(const std::vector<CString>& parameters,
                         const CString& raw_argument,
                         CString* formatted_argument) {
  size_t percent_count = 0;
  int input_length = raw_argument.GetLength();
  *formatted_argument = _T("");

  for (int i = 0; i < input_length; ++i) {
    TCHAR current = raw_argument[i];
    if (current >= _T('1') && current <= _T('9')) {
      // Before a digit, dump out escaped percent-signs.
      while (percent_count > 1) {
        formatted_argument->AppendChar(_T('%'));
        percent_count -= 2;
      }

      if (percent_count) {
        // There was an odd number of percent-signs. Evaluate the last one as a
        // placeholder.
        ASSERT1(percent_count == 1);

        size_t parameter_index = current - _T('1');
        if (parameter_index >= parameters.size()) {
          *formatted_argument = _T("");
          return false;
        }

        formatted_argument->Append(parameters[parameter_index]);
        // dump out parameters[current - _T('1')]
        percent_count = 0;
      } else {
        // There was an even number of percent-signs. Output the digit itself.
        formatted_argument->AppendChar(current);
      }
    } else if (current != _T('%') || i + 1 == input_length) {
      // At the end of the string, or before a regular character, dump out
      // queued percent-signs.
      while (percent_count > 0) {
        formatted_argument->AppendChar(_T('%'));
        --percent_count;
      }
      // If this is a percent-sign, it's also the last character. Otherwise, it
      // is just a regular (non-digit, non-percent-sign) character.
      formatted_argument->AppendChar(current);
    } else if (current == _T('%')) {
      // This is a percent-sign, possibly followed by a digit, not the last
      // character. Queue it up and we will output it later.
      percent_count++;
    }
  }

  return true;
}

// Escape a string so that it will be interpreted as a single command-line
// argument according to the rules at
// http://msdn.microsoft.com/library/windows/desktop/17w5ykft(v=vs.85).aspx .
CString QuoteForCommandLine(const CString& input) {
  CString output;

  if (input.IsEmpty()) {
    return _T("\"\"");
  }

  bool contains_whitespace = input.FindOneOf(_T(" \t")) != -1;
  if (contains_whitespace) {
    output.AppendChar(_T('"'));
  }

  size_t slash_count = 0;
  int input_length = input.GetLength();

  for (int i = 0; i < input_length; ++i) {
    if (input[i] == _T('"')) {
      // Before a quote, dump out (doubled) slashes
      while (slash_count > 0) {
        output.Append(_T("\\\\"));
        --slash_count;
      }
      output.Append(_T("\\\""));
    } else if (input[i] != _T('\\') || i + 1 == input_length) {
      // At the end of the string, or before a regular character, dump out
      // queued slashes.
      while (slash_count > 0) {
        output.AppendChar(_T('\\'));
        --slash_count;
      }
      // If this is a slash, it's also the last character. Otherwise, it is just
      // a regular (non-quote, non-slash) character.
      output.AppendChar(input[i]);
    } else if (input[i] == _T('\\')) {
      // This is a slash, possibly followed by a quote, not the last character.
      // Queue it up and we will output it later.
      slash_count++;
    }
  }

  if (contains_whitespace) {
    output.AppendChar(_T('"'));
  }

  return output;
}

}  // namespace

AppCommandFormatter::AppCommandFormatter(const CString& command_format) {
  int num_args = 0;
  CString temp(command_format);
  scoped_hlocal argv_handle(::CommandLineToArgvW(temp.GetBuffer(),
                                                 &num_args));
  if (!valid(argv_handle) || num_args < 1) {
    // Empty process name will cause Format to always fail.
    return;
  } else {
    WCHAR** original_argv = reinterpret_cast<WCHAR**>(get(argv_handle));
    process_name_ = original_argv[0];
    for (int i = 1; i < num_args; ++i) {
      command_line_argument_formats_.push_back(original_argv[i]);
    }
  }
}

HRESULT AppCommandFormatter::Format(const std::vector<CString>& parameters,
                                    CString* process_name,
                                    CString* command_line_arguments) const {
  ASSERT1(process_name);
  ASSERT1(command_line_arguments);
  if (!process_name || !command_line_arguments) {
    return E_INVALIDARG;
  }

  if (process_name_.IsEmpty()) {
    return E_FAIL;
  }

  CORE_LOG(L3, (_T("[AppCommandFormatter::Format][%s][%s]"),
                *process_name, *command_line_arguments));

  CString temp_arguments(_T(""));

  for (size_t i = 0; i < command_line_argument_formats_.size(); ++i) {
    int format_length = command_line_argument_formats_[i].GetLength();

    CString formatted_argument;
    if (!InterpolateArgument(parameters,
                             command_line_argument_formats_[i],
                             &formatted_argument)) {
      CORE_LOG(LE, (_T("[InterpolateArgument failed]")));
      return E_INVALIDARG;
    }
    temp_arguments.Append(QuoteForCommandLine(formatted_argument));

    if (i + 1 < command_line_argument_formats_.size()) {
      temp_arguments.AppendChar(_T(' '));
    }
  }

  *process_name = process_name_;

  *command_line_arguments = temp_arguments;

  return S_OK;
}

}  // namespace omaha


text:
import sys

#####################################
# Calculates the determinant of a 3x3 matrix
def det3(mat):
  return ((mat[0][0]*mat[1][1]*mat[2][2]) + (mat[0][1]*mat[1][2]*mat[2][0]) + (mat[0][2]*mat[1][0]*mat[2][1]) - (mat[0][2]*mat[1][1]*mat[2][0]) - (mat[0][1]*mat[1][0]*mat[2][2]) - (mat[0][0]*mat[1][2]*mat[2][1]))

#####################################
# a function that takes the cell parameters, in angstrom, and a list of fractional coordinates
# and returns the structure in Cartesian coordinates
#
# Assumes the cellParam matrix is of the form:
# | ax  ay  az |
# | bx  by  bz |
# | cx  cy  cz |
#
def frac2cart(cellParam, fracCoords):
  cartCoords = []
  for i in fracCoords:
    xPos = i[1]*cellParam[0][0] + i[2]*cellParam[1][0] + i[3]*cellParam[2][0]
    yPos = i[1]*cellParam[0][1] + i[2]*cellParam[1][1] + i[3]*cellParam[2][1]
    zPos = i[1]*cellParam[0][2] + i[2]*cellParam[1][2] + i[3]*cellParam[2][2]
    cartCoords.append([i[0], xPos, yPos, zPos])
  return cartCoords

#####################################
# a function that takes the cell parameters, in angstrom, and a list of Cartesian coordinates
# and returns the structure in fractional coordinates
#
# Uses Cramer's Rule to solve for the fractional coordinates
#
# Assumes the cellParam matrix is of the form:
# | ax  ay  az |
# | bx  by  bz |
# | cx  cy  cz |
#
# Need to use the transpose of this matrix in calculation, so call transpose function first
#
# Assumes cartCoords are of the form:
# | X  x0  y0  z0 |
# | X  x1  y1  z1 |
# | X  x2  y2  z2 |
# | ............. |
# where X is the element symbol
def cart2frac(cellParam, cartCoords):
  latCnt = [x[:] for x in [[None]*3]*3]
  for a in range(3):
    for b in range(3):
	  latCnt[a][b] = cellParam[b][a]

  fracCoords = []
  detLatCnt = det3(latCnt)
  for i in cartCoords:
    aPos = (det3([[i[1], latCnt[0][1], latCnt[0][2]], [i[2], latCnt[1][1], latCnt[1][2]], [i[3], latCnt[2][1], latCnt[2][2]]])) / detLatCnt
    bPos = (det3([[latCnt[0][0], i[1], latCnt[0][2]], [latCnt[1][0], i[2], latCnt[1][2]], [latCnt[2][0], i[3], latCnt[2][2]]])) / detLatCnt
    cPos = (det3([[latCnt[0][0], latCnt[0][1], i[1]], [latCnt[1][0], latCnt[1][1], i[2]], [latCnt[2][0], latCnt[2][1], i[3]]])) / detLatCnt
    fracCoords.append([i[0], aPos, bPos, cPos])
  return fracCoords

#####################################
reader = open(sys.argv[1], 'r')
sourceFile = reader.readlines()
reader.close()

# Determine which direction the transformation needs to happen
# filename[0] will hold the base filename
# filename[1] will hold the file extension
#   cart means the input is in Cartesian coordinates
#   frac means the input is in fractional coordinates
filename = sys.argv[1].split('.')

# Find the starting positions for the three pertinent sections of file
counter = 0
atomNumPos = 0
coordPos = 0
latVectPos = 0
for line in sourceFile:
  if "Number of atoms" in line:
    atomNumPos = counter
  elif "coordinates" in line:
    coordPos = counter + 1
  elif "Lattice vectors" in line:
    latVectPos = counter + 1
  counter += 1

numAtoms = int(sourceFile[atomNumPos].split(":")[-1].strip())

coords = []
for i in sourceFile[coordPos:coordPos+numAtoms]:
  temp = i.split()
  temp[1] = float(temp[1])
  temp[2] = float(temp[2])
  temp[3] = float(temp[3])
  coords.append(temp)

latVectsRaw = sourceFile[latVectPos:latVectPos+3]
latVects = []
temp1 = latVectsRaw[0].split()
latVects.append([float(temp1[1]), float(temp1[2]), float(temp1[3])])
temp2 = latVectsRaw[1].split()
latVects.append([float(temp2[1]), float(temp2[2]), float(temp2[3])])
temp3 = latVectsRaw[2].split()
latVects.append([float(temp3[1]), float(temp3[2]), float(temp3[3])])

# Convert the input coordinates into the other type
if (filename[-1] == "cart"):
  print "Converting to fractional coordinates..."
  newCoords = cart2frac(latVects, coords)
elif (filename[-1] == "frac"):
  print "Converting to Cartesian coordinates..."
  newCoords = frac2cart(latVects, coords)

# Create the output strings and write them to the file
outputData = []
outputData.append(sourceFile[atomNumPos])
outputData.append('\n')
outputData.append(sourceFile[latVectPos-1])
outputData.append(sourceFile[latVectPos])
outputData.append(sourceFile[latVectPos+1])
outputData.append(sourceFile[latVectPos+2])
outputData.append('\n')
if (filename[-1] == "cart"):
  outputData.append("Fractional coordinates:\n")
elif (filename[-1] == "frac"):
  outputData.append("Cartesian coordinates:\n")
for k in newCoords:
  temp = "{0[0]:<2}   {0[1]:> 10.6f}   {0[2]:> 10.6f}   {0[3]:> 10.6f}\n".format(k)
  outputData.append(temp)
outputData.append('\n')

if (filename[-1] == "cart"):
  outFilename = filename[0] + ".frac"
elif (filename[-1] == "frac"):
  outFilename = filename[0] + ".cart"

writer = open(outFilename, 'w')
writer.write(''.join(outputData))
writer.close()


text:
package org.fedoraproject.xmvn.deployer;

/**
 * @author Mikolaj Izdebski
 */
public interface DeploymentResult
{
    Exception getException();
}


text:
'use strict';

var twoDigits = require('./twoDigits');
var getFormatInfo = require('./getFormatInfo');

module.exports = function (name, value, formatOrInfo) {

	var formatInfo = formatOrInfo;

	if (!formatInfo || !formatInfo.hour || typeof formatInfo == 'string') {
		formatInfo = getFormatInfo(formatInfo);
	}

	if (!formatInfo) {
		return;
	}

	var info = formatInfo[name];

	if (value && name === 'meridian' && info.specified) {
		return info.uppercase ? value.toUpperCase() : value.toLowerCase();
	}

	return info.specified ? info.len == 2 ? twoDigits(value) : value : '';
};


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

  <AU_DISABLED>DESABILITADO</AU_DISABLED>

  <AU_Type>Tipo: </AU_Type>
  <AU_TargetAoE>Área de efecto</AU_TargetAoE>
  <AU_TargetSelf>Dirige así mismo</AU_TargetSelf>
  <AU_TargetThing>Dirige a Otros</AU_TargetThing>
  <AU_TargetLocation>Locación a donde se dirige</AU_TargetLocation>
  <AU_Cooldown>Enfriamiento: </AU_Cooldown>
  <AU_Extra>Extra</AU_Extra>
  <AU_MentalStateChance>Chance del Estado Mental</AU_MentalStateChance>
  <AU_EffectChance>Chance de efecto</AU_EffectChance>
  <AU_PawnAbilityRecharging>{0} Necesita tiempo para recargar</AU_PawnAbilityRecharging>

  <AU_AoEProperties>Propiedades del Área de Efecto</AU_AoEProperties>
  <AU_TargetClass>Objetivo: </AU_TargetClass>
  <AU_AoECharacters>Personajes</AU_AoECharacters>
  <AU_AoEFriendlyFire>Fuego Amigo: </AU_AoEFriendlyFire>
  <AU_AoEMaxTargets>Objetivos Máximos: </AU_AoEMaxTargets>
  <AU_AoEStartsFromCaster>Comienza desde el emisor: </AU_AoEStartsFromCaster>

</LanguageData>


text:
import sinon from 'sinon'
import noop from '@segmentstream/utils/noop'
import reset from './../reset.js'
import GoogleAnalytics from './../../src/integrations/GoogleAnalytics.js'
import OWOXBIStreaming from './../../src/integrations/OWOXBIStreaming.js'
import ddManager from './../../src/ddManager.js'

describe('Integrations: OWOXBIStreaming', () => {
  describe('OWOXBIStreaming', () => {
    let ga
    let owox
    const options = {
      trackingId: 'UA-51485228-7',
      domain: 'auto'
    }

    beforeEach(() => {
      window.digitalData = {
        events: []
      }
      ga = new GoogleAnalytics(window.digitalData, options)
      owox = new OWOXBIStreaming(window.digitalData)

      // reset in case GA was loaded
      // from previous tests asyncronously
      ga.reset()
      owox.reset()

      // OWOX should depend on Google Analtics, so this order is for reason
      // to test that everything works well even if OWOX BI is added before GA
      // TODO: change order and make sure everything works
      ddManager.addIntegration('Google Analytics', ga)
      ddManager.addIntegration('OWOX BI Streaming', owox)
    })

    afterEach(() => {
      ga.reset()
      owox.reset()
      ddManager.reset()
      reset()
    })

    describe('before loading', () => {
      beforeEach(() => {
        sinon.stub(ga, 'load')
        sinon.stub(owox, 'load')
      })

      afterEach(() => {
        ga.load.restore()
        owox.load.restore()
      })

      describe('#initialize', () => {
        it('should require Google Analytics OWOXBIStreaming plugin', () => {
          window.ga = noop
          sinon.stub(window, 'ga')
          ddManager.initialize()
          ddManager.on('ready', () => {
            window.ga.calledWith('ddl.require', 'OWOXBIStreaming')
            window.ga.calledWith('provide', 'OWOXBIStreaming')
            window.ga.restore()
          })
        })

        it('should require Google Analytics OWOXBIStreaming plugin', () => {
          owox.setOption('sessionStreaming', true)
          owox.setOption('sessionIdDimension', 'sessionId')
          window.ga = noop
          sinon.stub(window, 'ga')
          ddManager.initialize()
          ddManager.on('ready', () => {
            window.ga.calledWith('ddl.require', 'OWOXBIStreaming', {
              sessionIdDimension: 'sessionId'
            })
            window.ga.restore()
          })
        })
      })
    })
  })
})


text:
module Azure::RecoveryServicesBackup::Mgmt::V2016_12_01
  module Models
    #
    # Long term policy schedule.
    #
    class LongTermSchedulePolicy < SchedulePolicy

      include MsRestAzure

      def initialize
        @schedulePolicyType = "LongTermSchedulePolicy"
      end

      attr_accessor :schedulePolicyType

      #
      # Mapper for LongTermSchedulePolicy class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'LongTermSchedulePolicy',
          type: {
            name: 'Composite',
            class_name: 'LongTermSchedulePolicy',
            model_properties: {
              schedulePolicyType: {
                client_side_validation: true,
                required: true,
                serialized_name: 'schedulePolicyType',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
using Marvel_Catalog_App.Data.Models;
using MarvelCatalog_App.Data.Repositories;
using MarvelCatalog_App.Data.UnitOfWork;
using MarvelCatalog_App.Services;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarvelCatalog_App.Tests.Services.ComicsServiceTests
{
    [TestFixture]
    public class Constructor_Should
    {
        [Test]
        public void Throw_ArgumentNullException_When_UnitOfWork_IsNull()
        {
            var mockedRepo = new Mock<IEfRepository<ComicsDataModel>>();

            // Arrang & Act & Assert
            Assert.That(() => new ComicsService(null, mockedRepo.Object),
                        Throws.ArgumentNullException.With.Message.Contains("unitOfwork"));
        }

        [Test]
        public void Throw_ArgumentNullException_When_IEfRepository_IsNull()
        {
            // Arrange
            var mockedUnitOfWork = new Mock<IUnitOfWork>();

            // Act & Assert
            Assert.That(() => new ComicsService(mockedUnitOfWork.Object, null),
                                Throws.ArgumentNullException.With.Message.Contains("comicsRepository"));
        }
    }
}


text:
API endpoints
=============

Basic
-----

- /rest-auth/login/ (POST)

    - username (string)
    - password (string)

- /rest-auth/logout/ (POST)

- /rest-auth/password/reset/ (POST)

    - email

- /rest-auth/password/reset/confirm/ (POST)

    - uid
    - token
    - new_password1
    - new_password2

    .. note:: uid and token are sent in email after calling /rest-auth/password/reset/

- /rest-auth/password/change/ (POST)

    - new_password1
    - new_password2
    - old_password

    .. note:: ``OLD_PASSWORD_FIELD_ENABLED = True`` to use old_password.

- /rest-auth/user/ (GET)

- /rest-auth/user/ (PUT/PATCH)

    - username
    - first_name
    - last_name
    - email

Registration
------------

- /rest-auth/registration/ (POST)

    - username
    - password1
    - password2
    - email

    .. note:: This endpoint is based on ``allauth.account.views.SignupView`` and uses the same form as in this view. To override fields you have to create custom Signup Form and define it in django settings:

        .. code-block:: python

            ACCOUNT_FORMS = {
                'signup': 'path.to.custom.SignupForm'
            }

        See allauth documentation for more details.

- /rest-auth/registration/verify-email/ (POST)

    - key

Social Media Authentication
---------------------------

Basing on example from installation section :doc:`Installation </installation>`

- /rest-auth/facebook/ (POST)

    - access_token
    - code


text:
#region Disclaimer/License Info

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

// sBlog.Net

// sBlog.Net is a minimalistic blog engine software.

// Homepage: http://sblogproject.net
// Github: http://github.com/karthik25/sBlog.Net

// This project is licensed under the BSD license.
// See the License.txt file for more information.

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

#endregion
namespace sBlog.Net.Domain.Interfaces
{
    public interface IHasher
    {
        string HashString(string srcString);
    }
}


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

public class ItemSubPart : MonoBehaviour {
    private MeshRenderer meshRenderer;
    private Material originalMaterial;

    public int partIndex = 0;

    internal void UpdateImprovement(RemoteFortressReader.ItemImprovement improvement)
    {

        if (meshRenderer == null)
            meshRenderer = GetComponentInChildren<MeshRenderer>();

        if (originalMaterial == null)
            originalMaterial = meshRenderer.sharedMaterial;

        Color partColor = ContentLoader.GetColor(improvement.material);
        float textureIndex = ContentLoader.GetPatternIndex(improvement.material);
        float shapeIndex = ContentLoader.GetShapeIndex(improvement.material);

        meshRenderer.sharedMaterial = ContentLoader.getFinalMaterial(originalMaterial, partColor.a);

        MaterialPropertyBlock prop = new MaterialPropertyBlock();
        prop.SetColor("_MatColor", partColor);
        prop.SetFloat("_MatIndex", textureIndex);
        prop.SetFloat("_ShapeIndex", shapeIndex);
        meshRenderer.SetPropertyBlock(prop);
    }
}


text:
package io.noties.markwon.image.file;

import android.content.Context;
import android.content.res.AssetManager;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import io.noties.markwon.image.ImageItem;
import io.noties.markwon.image.SchemeHandler;

/**
 * @since 3.0.0
 */
public class FileSchemeHandler extends SchemeHandler {

    public static final String SCHEME = "file";

    /**
     * @see io.noties.markwon.image.destination.ImageDestinationProcessorAssets
     */
    @NonNull
    public static FileSchemeHandler createWithAssets(@NonNull AssetManager assetManager) {
        return new FileSchemeHandler(assetManager);
    }

    /**
     * @see #createWithAssets(AssetManager)
     * @see io.noties.markwon.image.destination.ImageDestinationProcessorAssets
     * @since 4.0.0
     */
    @NonNull
    public static FileSchemeHandler createWithAssets(@NonNull Context context) {
        return new FileSchemeHandler(context.getAssets());
    }

    @NonNull
    public static FileSchemeHandler create() {
        return new FileSchemeHandler(null);
    }

    private static final String FILE_ANDROID_ASSETS = "android_asset";

    @Nullable
    private final AssetManager assetManager;

    @SuppressWarnings("WeakerAccess")
    FileSchemeHandler(@Nullable AssetManager assetManager) {
        this.assetManager = assetManager;
    }

    @NonNull
    @Override
    public ImageItem handle(@NonNull String raw, @NonNull Uri uri) {

        final List<String> segments = uri.getPathSegments();
        if (segments == null
                || segments.size() == 0) {
            // pointing to file & having no path segments is no use
            throw new IllegalStateException("Invalid file path: " + raw);
        }

        final InputStream inputStream;

        final boolean assets = FILE_ANDROID_ASSETS.equals(segments.get(0));
        final String fileName = uri.getLastPathSegment();

        if (assets) {

            // no handling of assets here if we have no assetsManager
            if (assetManager != null) {

                final StringBuilder path = new StringBuilder();
                for (int i = 1, size = segments.size(); i < size; i++) {
                    if (i != 1) {
                        path.append('/');
                    }
                    path.append(segments.get(i));
                }
                // load assets

                try {
                    inputStream = assetManager.open(path.toString());
                } catch (IOException e) {
                    throw new IllegalStateException("Exception obtaining asset file: " +
                            "" + raw + ", path: " + path.toString(), e);
                }
            } else {
                throw new IllegalStateException("Supplied file path points to assets, " +
                        "but FileSchemeHandler was not supplied with AssetsManager. " +
                        "Use `#createWithAssets` factory method to create FileSchemeHandler " +
                        "that can handle android assets");
            }

        } else {

            final String path = uri.getPath();
            if (TextUtils.isEmpty(path)) {
                throw new IllegalStateException("Invalid file path: " + raw + ", " + path);
            }

            try {
                inputStream = new BufferedInputStream(new FileInputStream(new File(path)));
            } catch (FileNotFoundException e) {
                throw new IllegalStateException("Exception reading file: " + raw, e);
            }
        }

        final String contentType = MimeTypeMap
                .getSingleton()
                .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(fileName));

        return ImageItem.withDecodingNeeded(contentType, inputStream);
    }

    @NonNull
    @Override
    public Collection<String> supportedSchemes() {
        return Collections.singleton(SCHEME);
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.UseConditionalExpression
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.UseConditionalExpression
    <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
    Friend Class VisualBasicUseConditionalExpressionForReturnCodeRefactoringProvider
        Inherits AbstractUseConditionalExpressionForReturnCodeFixProvider(Of
            StatementSyntax, MultiLineIfBlockSyntax, ExpressionSyntax, TernaryConditionalExpressionSyntax)

        Protected Overrides Function IsRef(returnOperation As IReturnOperation) As Boolean
            ' VB does not have ref returns.
            Return False
        End Function

        Protected Overrides Function GetMultiLineFormattingRule() As AbstractFormattingRule
            Return MultiLineConditionalExpressionFormattingRule.Instance
        End Function

        Protected Overrides Function WrapWithBlockIfAppropriate(ifStatement As MultiLineIfBlockSyntax, statement As StatementSyntax) As StatementSyntax
            Return statement
        End Function
    End Class
End Namespace


text:
package org.springframework.richclient.image;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;

/**
 * A resource decorator that represents an underlying graphical AWT image, such
 * as a GIF, JPEG, or PNG.
 *
 * @author Keith Donald
 */
public class AwtImageResource extends AbstractResource implements ImageObserver {
    private Resource wrappedResource;

    private boolean imageLoaded;

    private boolean imageError;

    public static final String RESOURCE_PREFIX = "image:";

    /**
     * Constructs a AwtImageResource for the following io.core.Resource. This
     * assumes the wrapped resource actually points to a underlying image.
     *
     * @param resource
     *            The wrapped resource.
     * @throws IllegalArgumentException,
     *             if the resource is invalid.
     */
    public AwtImageResource(Resource resource) {
        Assert.notNull(resource);
        if (resource instanceof AwtImageResource) {
            throw new IllegalArgumentException("Wrapping another AwtImageResource instance is illegal.");
        }
        this.wrappedResource = resource;
    }

    public String getDescription() {
        return wrappedResource.getDescription();
    }

    public Resource createRelative(String relativePath) throws IOException {
        return wrappedResource.createRelative(relativePath);
    }

    public boolean exists() {
        return wrappedResource.exists();
    }

    public boolean isOpen() {
        return wrappedResource.isOpen();
    }

    public URL getURL() throws IOException {
        return wrappedResource.getURL();
    }

    public File getFile() throws IOException {
        return wrappedResource.getFile();
    }

    public String getFilename() throws IllegalStateException {
        return wrappedResource.getFilename();
    }

    public InputStream getInputStream() throws IOException {
        return wrappedResource.getInputStream();
    }

    /**
     * Loads the image from the underlying core.io.Resource.
     *
     * This method does not cache. Calling it successively will result in a new
     * image being loaded each time.
     *
     * @throws java.io.IOException
     *             If an error occurred while reading from the resource input
     *             stream.
     */
    public Image getImage() throws IOException {
        return loadImage(getInputStream());
    }

    /**
     * Load an image from the underlying resource's input stream. Constructs a
     * new Image object from the data read from the input stream
     * on each call.
     *

     * This method loads the image fully into memory. This improves UI
     * responsiveness when the image is needed by the GUI event-dispatching
     * thread.
     *
     * @param stream
     *            The input stream.
     * @return The resulting Image object.
     * @throws java.io.IOException
     *             If an error occurred while reading from the stream.
     */
    private synchronized Image loadImage(InputStream stream) throws IOException {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        byte data[] = FileCopyUtils.copyToByteArray(stream);

        Image image = toolkit.createImage(data);
        imageLoaded = false;
        imageError = false;
        // fully loads the image into memory
        toolkit.prepareImage(image, -1, -1, this);
        while (!imageLoaded && !imageError) {
            try {
                wait();
            }
            catch (InterruptedException ex) {
            }
        }
        if (imageError) {
            throw new IOException("Error preparing image from resource.");
        }
        return image;
    }

    public synchronized boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) {
        if ((infoflags & (ALLBITS | FRAMEBITS)) != 0) {
            imageLoaded = true;
            notifyAll();
        }
        else {
            if ((infoflags & ERROR) != 0) {
                imageError = true;
                notifyAll();
            }
        }
        return true;
    }

    public boolean equals(Object o) {
        if (!(o instanceof AwtImageResource)) {
            return false;
        }
        AwtImageResource r = (AwtImageResource)o;
        return wrappedResource.equals(r.wrappedResource);
    }

    public int hashCode() {
        return wrappedResource.hashCode();
    }
}


text:
Open Doors

Get The Key

Everyone

Should Have A High Level Knowledge Of

Web Development

Principles

Cupcake ipsum dolor. Sit amet lollipop candy gummi bears sugar plum gingerbread marshmallow. Chocolate bar chocolate tiramisu wafer cake tootsie roll. Liquorice sesame snaps sugar plum gingerbread brownie candy canes caramels. Powder marshmallow unerdwear.com tiramisu jelly-o sweet roll marzipan biscuit. Jujubes donut jelly beans wafer. Chupa chups cheesecake marzipan apple pie toffee powder sugar plum caramels croissant. Cotton candy soufflé pastry sugar plum pie croissant danish. Sugar plum gummies jelly beans cotton candy candy sweet. Tart pudding croissant. Gummi bears liquorice chocolate bar cake. Muffin applicake pie caramels chupa chups croissant sweet halvah. Halvah liquorice chocolate bar. Cupcake halvah cookie jujubes.

Think

Try

Read

Connect

Anywhere

Cupcake ipsum dolor. Sit amet lollipop candy gummi bears sugar plum gingerbread marshmallow. Chocolate bar chocolate tiramisu wafer cake tootsie roll. Liquorice sesame snaps sugar plum gingerbread brownie candy canes caramels. Powder marshmallow unerdwear.com tiramisu jelly-o sweet roll marzipan biscuit. Jujubes donut jelly beans wafer. Chupa chups cheesecake marzipan apple pie toffee powder sugar plum caramels croissant. Cotton candy soufflé pastry sugar plum pie croissant danish. Sugar plum gummies jelly beans cotton candy candy sweet. Tart pudding croissant. Gummi bears liquorice chocolate bar cake. Muffin applicake pie caramels chupa chups croissant sweet halvah. Halvah liquorice chocolate bar. Cupcake halvah cookie jujubes.

Everything You Touch

Touches Code.

You can't escape it.

Embrace It

          Even if you never write a line of code in your life, these principles can apply to everything that you do.

Or... You could just become a developer.

Cupcake ipsum dolor. Sit amet lollipop candy gummi bears sugar plum gingerbread marshmallow. Chocolate bar chocolate tiramisu wafer cake tootsie roll. Liquorice sesame snaps sugar plum gingerbread brownie candy canes caramels. Powder marshmallow unerdwear.com tiramisu jelly-o sweet roll marzipan biscuit. Jujubes donut jelly beans wafer. Chupa chups cheesecake marzipan apple pie toffee powder sugar plum caramels croissant. Cotton candy soufflé pastry sugar plum pie croissant danish. Sugar plum gummies jelly beans cotton candy candy sweet. Tart pudding croissant. Gummi bears liquorice chocolate bar cake. Muffin applicake pie caramels chupa chups croissant sweet halvah. Halvah liquorice chocolate bar. Cupcake halvah cookie jujubes.

Cupcake ipsum dolor. Sit amet lollipop candy gummi bears sugar plum gingerbread marshmallow. Chocolate bar chocolate tiramisu wafer cake tootsie roll. Liquorice sesame snaps sugar plum gingerbread brownie candy canes caramels. Powder marshmallow unerdwear.com tiramisu jelly-o sweet roll marzipan biscuit. Jujubes donut jelly beans wafer. Chupa chups cheesecake marzipan apple pie toffee powder sugar plum caramels croissant. Cotton candy soufflé pastry sugar plum pie croissant danish. Sugar plum gummies jelly beans cotton candy candy sweet. Tart pudding croissant. Gummi bears liquorice chocolate bar cake. Muffin applicake pie caramels chupa chups croissant sweet halvah. Halvah liquorice chocolate bar. Cupcake halvah cookie jujubes.

Think

Try

Read

Connect

Top


text:
package com.badlogic.gdx.ai.steer.behaviors;

import com.badlogic.gdx.ai.steer.Limiter;
import com.badlogic.gdx.ai.steer.Steerable;
import com.badlogic.gdx.ai.steer.SteeringAcceleration;
import com.badlogic.gdx.ai.steer.SteeringBehavior;
import com.badlogic.gdx.ai.steer.utils.RayConfiguration;
import com.badlogic.gdx.ai.steer.utils.rays.CentralRayWithWhiskersConfiguration;
import com.badlogic.gdx.ai.steer.utils.rays.ParallelSideRayConfiguration;
import com.badlogic.gdx.ai.steer.utils.rays.SingleRayConfiguration;
import com.badlogic.gdx.ai.utils.Collision;
import com.badlogic.gdx.ai.utils.Ray;
import com.badlogic.gdx.ai.utils.RaycastCollisionDetector;
import com.badlogic.gdx.math.Vector;

/** With the {@code RaycastObstacleAvoidance} the moving agent (the owner) casts one or more rays out in the direction of its
 * motion. If these rays collide with an obstacle, then a target is created that will avoid the collision, and the owner does a
 * basic seek on this target. Typically, the rays extend a short distance ahead of the character (usually a distance corresponding
 * to a few seconds of movement).
 *

 * This behavior is especially suitable for large-scale obstacles like walls.
 *

 * You should use the {@link RayConfiguration} more suitable for your game environment. Some basic ray configurations are provided
 * by the framework: {@link SingleRayConfiguration}, {@link ParallelSideRayConfiguration} and
 * {@link CentralRayWithWhiskersConfiguration}. There are no hard and fast rules as to which configuration is better. Each has its
 * own particular idiosyncrasies. A single ray with short whiskers is often the best initial configuration to try but can make it
 * impossible for the character to move down tight passages. The single ray configuration is useful in concave environments but
 * grazes convex obstacles. The parallel configuration works well in areas where corners are highly obtuse but is very susceptible
 * to the corner trap.
 *

 *
 *
The corner trap
 All the basic configurations for multi-ray obstacle avoidance can suffer from a crippling problem
 * with acute angled corners (any convex corner, in fact, but it is more prevalent with acute angles). Consider a character with
 * two parallel rays that is going towards a corner. As soon as its left ray is colliding with the wall near the corner, the
 * steering behavior will turn it to the left to avoid the collision. Immediately, the right ray will then be colliding the other
 * side of the corner, and the steering behavior will turn the character to the right. The character will repeatedly collide both
 * sides of the corner in rapid succession. It will appear to home into the corner directly, until it slams into the wall. It will
 * be unable to free itself from the trap.
 *

 * The fan structure, with a wide enough fan angle, alleviates this problem. Often, there is a trade-off, however, between
 * avoiding the corner trap with a large fan angle and keeping the angle small to allow the character to access small passages. At
 * worst, with a fan angle near PI radians, the character will not be able to respond quickly enough to collisions detected on its
 * side rays and will still graze against walls. There are two approaches that work well and represent the most practical
 * solutions to the problem:
 *

 *
Adaptive fan angles: If the character is moving successfully without a collision, then the fan angle is narrowed. If
 * a collision is detected, then the fan angle is widened. If the character detects many collisions on successive frames, then the
 * fan angle will continue to widen, reducing the chance that the character is trapped in a corner.

 *
Winner ray: If a corner trap is detected, then one of the rays is considered to have won, and the collisions
 * detected by other rays are ignored for a while.

 *

 * It seems that the most practical solution is to use adaptive fan angles, with one long ray cast and two shorter whiskers.
 *
 * @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface
 *
 * @author davebaol */
public class RaycastObstacleAvoidance<T extends Vector<T>> extends SteeringBehavior<T> {

	/** The inputRay configuration */
	protected RayConfiguration<T> rayConfiguration;

	/** The collision detector */
	protected RaycastCollisionDetector<T> raycastCollisionDetector;

	/** The minimum distance to a wall, i.e. how far to avoid collision. */
	protected float distanceFromBoundary;

	private Collision<T> outputCollision;
	private Collision<T> minOutputCollision;

	/** Creates a {@code RaycastObstacleAvoidance} behavior.
	 * @param owner the owner of this behavior */
	public RaycastObstacleAvoidance (Steerable<T> owner) {
		this(owner, null);
	}

	/** Creates a {@code RaycastObstacleAvoidance} behavior.
	 * @param owner the owner of this behavior
	 * @param rayConfiguration the ray configuration */
	public RaycastObstacleAvoidance (Steerable<T> owner, RayConfiguration<T> rayConfiguration) {
		this(owner, rayConfiguration, null);
	}

	/** Creates a {@code RaycastObstacleAvoidance} behavior.
	 * @param owner the owner of this behavior
	 * @param rayConfiguration the ray configuration
	 * @param raycastCollisionDetector the collision detector */
	public RaycastObstacleAvoidance (Steerable<T> owner, RayConfiguration<T> rayConfiguration,
		RaycastCollisionDetector<T> raycastCollisionDetector) {
		this(owner, rayConfiguration, raycastCollisionDetector, 0);
	}

	/** Creates a {@code RaycastObstacleAvoidance} behavior.
	 * @param owner the owner of this behavior
	 * @param rayConfiguration the ray configuration
	 * @param raycastCollisionDetector the collision detector
	 * @param distanceFromBoundary the minimum distance to a wall (i.e., how far to avoid collision). */
	public RaycastObstacleAvoidance (Steerable<T> owner, RayConfiguration<T> rayConfiguration,
		RaycastCollisionDetector<T> raycastCollisionDetector, float distanceFromBoundary) {
		super(owner);
		this.rayConfiguration = rayConfiguration;
		this.raycastCollisionDetector = raycastCollisionDetector;
		this.distanceFromBoundary = distanceFromBoundary;

		this.outputCollision = new Collision<T>(newVector(owner), newVector(owner));
		this.minOutputCollision = new Collision<T>(newVector(owner), newVector(owner));
	}

	@Override
	protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
		T ownerPosition = owner.getPosition();
		float minDistanceSquare = Float.POSITIVE_INFINITY;

		// Get the updated rays
		Ray<T>[] inputRays = rayConfiguration.updateRays();

		// Process rays
		for (int i = 0; i < inputRays.length; i++) {
			// Find the collision with current ray
			boolean collided = raycastCollisionDetector.findCollision(outputCollision, inputRays[i]);

			if (collided) {
				float distanceSquare = ownerPosition.dst2(outputCollision.point);
				if (distanceSquare < minDistanceSquare) {
					minDistanceSquare = distanceSquare;
					// Swap collisions
					Collision<T> tmpCollision = outputCollision;
					outputCollision = minOutputCollision;
					minOutputCollision = tmpCollision;
				}
			}
		}

		// Return zero steering if no collision has occurred
		if (minDistanceSquare == Float.POSITIVE_INFINITY) return steering.setZero();

		// Calculate and seek the target position
		steering.linear.set(minOutputCollision.point)
			.mulAdd(minOutputCollision.normal, owner.getBoundingRadius() + distanceFromBoundary).sub(owner.getPosition()).nor()
			.scl(getActualLimiter().getMaxLinearAcceleration());

		// No angular acceleration
		steering.angular = 0;

		// Output steering acceleration
		return steering;
	}

	/** Returns the ray configuration of this behavior. */
	public RayConfiguration<T> getRayConfiguration () {
		return rayConfiguration;
	}

	/** Sets the ray configuration of this behavior.
	 * @param rayConfiguration the ray configuration to set
	 * @return this behavior for chaining. */
	public RaycastObstacleAvoidance<T> setRayConfiguration (RayConfiguration<T> rayConfiguration) {
		this.rayConfiguration = rayConfiguration;
		return this;
	}

	/** Returns the raycast collision detector of this behavior. */
	public RaycastCollisionDetector<T> getRaycastCollisionDetector () {
		return raycastCollisionDetector;
	}

	/** Sets the raycast collision detector of this behavior.
	 * @param raycastCollisionDetector the raycast collision detector to set
	 * @return this behavior for chaining. */
	public RaycastObstacleAvoidance<T> setRaycastCollisionDetector (RaycastCollisionDetector<T> raycastCollisionDetector) {
		this.raycastCollisionDetector = raycastCollisionDetector;
		return this;
	}

	/** Returns the distance from boundary, i.e. the minimum distance to an obstacle. */
	public float getDistanceFromBoundary () {
		return distanceFromBoundary;
	}

	/** Sets the distance from boundary, i.e. the minimum distance to an obstacle.
	 * @param distanceFromBoundary the distanceFromBoundary to set
	 * @return this behavior for chaining. */
	public RaycastObstacleAvoidance<T> setDistanceFromBoundary (float distanceFromBoundary) {
		this.distanceFromBoundary = distanceFromBoundary;
		return this;
	}

	//
	// Setters overridden in order to fix the correct return type for chaining
	//

	@Override
	public RaycastObstacleAvoidance<T> setOwner (Steerable<T> owner) {
		this.owner = owner;
		return this;
	}

	@Override
	public RaycastObstacleAvoidance<T> setEnabled (boolean enabled) {
		this.enabled = enabled;
		return this;
	}

	/** Sets the limiter of this steering behavior. The given limiter must at least take care of the maximum linear acceleration.
	 * @return this behavior for chaining. */
	@Override
	public RaycastObstacleAvoidance<T> setLimiter (Limiter limiter) {
		this.limiter = limiter;
		return this;
	}

}


text:
using Org.Apache.Reef.Common.Task;
using Org.Apache.Reef.Utilities;
using System;

namespace Org.Apache.Reef.Common.Exceptions
{
    public class EvaluatorException : System.Exception, IIdentifiable
    {
        private readonly string _evaluatorId;

        public EvaluatorException(string evaluatorId)
        {
            _evaluatorId = evaluatorId;
            RunningTask = null;
        }

        public EvaluatorException(string evaluatorId, string message, System.Exception cause)
            : base(message, cause)
        {
            _evaluatorId = evaluatorId;
            RunningTask = null;
        }

        public EvaluatorException(string evaluatorId, string message)
            : this(evaluatorId, message, (IRunningTask)null)
        {
        }

        public EvaluatorException(string evaluatorId, string message, IRunningTask runningTask)
            : base(message)
        {
            _evaluatorId = evaluatorId;
            RunningTask = runningTask;
        }

        public EvaluatorException(string evaluatorId, System.Exception cause)
            : this(evaluatorId, cause, null)
        {
        }

        public EvaluatorException(string evaluatorId, Exception cause, IRunningTask runningTask)
            : base(string.Empty, cause)
        {
            _evaluatorId = evaluatorId;
            RunningTask = runningTask;
        }

        public IRunningTask RunningTask { get; set; }

        public string Id
        {
            get { return _evaluatorId; }
            set { }
        }
    }
}


text:
package nl.knaw.huygens.timbuctoo.search.description.propertyparser;

import nl.knaw.huygens.timbuctoo.search.description.PropertyParser;
import org.apache.commons.lang3.StringUtils;

class StringPropertyParser implements PropertyParser {
  @Override
  public String parse(String value) {
    return value;
  }

  @Override
  public Comparable<?> parseForSort(String value) {
    String parsedValue = parse(value);
    return parsedValue == null ? null : StringUtils.stripToEmpty(parsedValue);
  }

}


text:
/*
 * Do not modify this file. This file is generated from the sns-2010-03-31.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.SimpleNotificationService.Model
{
    /// <summary>
    /// Container for the parameters to the RemovePermission operation.
    /// Removes a statement from a topic's access control policy.
    /// </summary>
    public partial class RemovePermissionRequest : AmazonSimpleNotificationServiceRequest
    {
        private string _label;
        private string _topicArn;

        /// <summary>
        /// Empty constructor used to set  properties independently even when a simple constructor is available
        /// </summary>
        public RemovePermissionRequest() { }

        /// <summary>
        /// Instantiates RemovePermissionRequest with the parameterized properties
        /// </summary>
        /// <param name="topicArn">The ARN of the topic whose access control policy you wish to modify.</param>
        /// <param name="label">The unique label of the statement you want to remove.</param>
        public RemovePermissionRequest(string topicArn, string label)
        {
            _topicArn = topicArn;
            _label = label;
        }

        /// <summary>
        /// Gets and sets the property Label.
        /// <para>
        /// The unique label of the statement you want to remove.
        /// </para>
        /// </summary>
        public string Label
        {
            get { return this._label; }
            set { this._label = value; }
        }

        // Check to see if Label property is set
        internal bool IsSetLabel()
        {
            return this._label != null;
        }

        /// <summary>
        /// Gets and sets the property TopicArn.
        /// <para>
        /// The ARN of the topic whose access control policy you wish to modify.
        /// </para>
        /// </summary>
        public string TopicArn
        {
            get { return this._topicArn; }
            set { this._topicArn = value; }
        }

        // Check to see if TopicArn property is set
        internal bool IsSetTopicArn()
        {
            return this._topicArn != null;
        }

    }
}