text:
void compute_error( const Eigen::Matrix3d &R, const Eigen::Vector3d &t,
                   const Eigen::Matrix3d &Rsoln, const Eigen::Vector3d &tsoln,
                  double &rot_angle_err, double &trans_angle_err, double &trans_scale_err );

struct Ray {
    // Image location in camera coordinates
    Eigen::Vector3d x;
    // Camera center
    Eigen::Vector3d c;
};
typedef std::pair<Ray,Ray> RayPair;
typedef std::vector<RayPair> RayPairList;

struct Problem
{
    Eigen::Matrix3d R;
    Eigen::Vector3d t;
    RayPairList ray_pairs;
};

void generateProblem( double trans_mag, double angle, double noise, Problem &prob, int nrays = 18 );


text:
@implementation MGLoginTool

+ (void)setUid:(NSString *)uid
{
    [[NSUserDefaults standardUserDefaults] setObject:uid forKey:@"uid"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)getUid
{
    return [self getUid:NO];
}

+(NSString *)getUid:(BOOL)isShowViewController
{
    NSString *uid = [[NSUserDefaults standardUserDefaults] valueForKey:@"uid"];

    if (isShowViewController) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MGLoginRegisterViewController *loginVc = [[MGLoginRegisterViewController alloc] init];
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:loginVc animated:YES completion:nil];
        });
    }

    return uid;
}
@end

redpajama_set_name: RedPajamaGithub


text:
class HomeController < ApplicationController
  def show
    @registration = Registration.new(category_name: "non_member", country: "Switzerland")
    @grouped_events = Event.order(:start).group_by{|e| e.start.to_date}
    @speakers = Speaker.order(:last_name, :first_name)
    @countries = (Country.find_all_countries_by_subregion('Northern America')+Country.find_all_countries_by_region('Europe')).uniq.sort_by(&:name)
  end
end


text:
!> This endpoint has yet to be implemented. Please be patient as we add the endpoints from v2. The endpoint will return a 501 Not Implemented error.

This endpoint returns a list of tournaments people have used the [/tournaments](/endpoints/tournaments) endpoint to search for.

You may want to use [pagination](pagination) for this request.

## HTTP Request
`GET https://api.royaleapi.com/tournaments/known`

Name | Method | Description
--- | --- | ---
/tournaments/known | GET | List of known tournaments

## Query String Parameters

All query string parameters default to `0`, set the value to `1` for it to be active

Name     | Data Type | Required / Optional | Description
-------- | --- | --- | ---
1k       | number | optional | Filters out only 1k tournaments
open     | number | optional | Filters out only open tournaments
full     | number | optional | Filters out only full tournaments
inprep   | number | optional | Filters out only tournaments in preperation
joinable | number | optional | Filters out only joinable tournaments

[/tournaments/open](/endpoints/tournaments_open), [/tournaments/1k](/endpoints/tournaments_1k), [/tournaments/inprep](/endpoints/tournaments_inprep), [/tournaments/full](/endpoints/tournaments_full) and [/tournaments/joinable](/endpoints/tournaments_joinable) already implement some of these filters. However, you can still mix and match!

## Response
https://api.royaleapi.com/tournaments/known

The above command returns JSON structured like this. In the actual response, there will be a maximum of 100 tournaments:

Full JSON response

```json
[
    {
        "tag": "CUUVGVP",
        "open": true,
        "status": "inPreparation",
        "name": "hola",
        "currentPlayers": 50,
        "maxPlayers": 50,
        "prepTime": 7200,
        "duration": 3600,
        "createTime": 1518090895,
        "startTime": null,
        "endTime": null
    }
]
```


text:
from awips.dataaccess import DataAccessLayer as DAL
from awips.dataaccess import CombinedTimeQuery as CTQ

import unittest
import os

#
# Test the CombinedTimedQuery module
#
#     SOFTWARE HISTORY
#
#    Date            Ticket#       Engineer       Description
#    ------------    ----------    -----------    --------------------------
#    06/24/16        5591          bsteffen       Initial Creation.
#    11/08/16        5895          tgurney        Change grid model
#
#
#

class CombinedTimeQueryTestCase(unittest.TestCase):

    @classmethod
    def setUp(cls):
        host = os.environ.get('DAF_TEST_HOST')
        if host is None:
            host = 'edex-cloud.unidata.ucar.edu'
        DAL.changeEDEXHost(host)

    def testSuccessfulQuery(self):
        req = DAL.newDataRequest('grid')
        req.setLocationNames('RUC130')
        req.setParameters('T','GH')
        req.setLevels('300MB', '500MB','700MB')
        times = CTQ.getAvailableTimes(req);
        self.assertNotEqual(len(times), 0)

    def testNonIntersectingQuery(self):
        """
        Test that when a parameter is only available on one of the levels that no times are returned.
        """
        req = DAL.newDataRequest('grid')
        req.setLocationNames('RUC130')
        req.setParameters('T','GH', 'LgSP1hr')
        req.setLevels('300MB', '500MB','700MB','0.0SFC')
        times = CTQ.getAvailableTimes(req);
        self.assertEqual(len(times), 0)


text:
<?php

namespace Emayk\Ics\Repo\Productdetails;

class ProductdetailsArray implements  ProductdetailsInterface{

    protected $productdetails;
    /*function __construct() { }*/

    /**
     * @return mixed
     */
    public function all()
    {
        // TODO: Implement all() method.
    }

    /**
     * Simpan Productdetails
     *
     * @return mixed
     */
    public function store()
    {
        // TODO: Implement store() method.
    }

    /**
     * Menghapus Productdetails
     *
     * @param $id
     * @return mixed
     *
     */
    public function delete($id)
    {
        // TODO: Implement delete() method.
    }

    /**
     * Update Informasi Productdetails
     *
     * @param $id
     * @param array $productdetails
     * @return mixed
     */
    public function update($id)
    {
        // TODO: Implement update() method.
    }

    /**
     *
     * Mendapatkan Productdetails berdasarkan id yang diberikan
     *
     * @param $id
     * @return mixed
     */
    public function find($id)
    {
        // TODO: Implement find() method.
    }

    /**
    *
    * Menampilkan Page Untuk Buat Data
    *
    **/

    public function create()
    {
        // TODO: Implement create() method.
    }
        /**
     * Menampilkan Resource
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        // TODO: Implement show() method.
    }
    /**
     * Menampilkan Data Untuk di edit
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        // TODO: Implement edit() method.
    }

    /**
     * Remove from Storage
     *
     */
    public function destroy($id)
    {
        // TODO: Implement destroy() method.
    }

}


text:
package com.linecorp.armeria.server.metrics;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

import java.nio.charset.StandardCharsets;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.Mockito;

import com.linecorp.armeria.common.ServiceInvocationContext;
import com.linecorp.armeria.common.metrics.MetricConsumer;
import com.linecorp.armeria.server.AbstractServerTest;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.Service;
import com.linecorp.armeria.server.ServiceCodec;
import com.linecorp.armeria.server.ServiceCodec.DecodeResult;
import com.linecorp.armeria.server.ServiceCodec.DecodeResultType;
import com.linecorp.armeria.server.ServiceInvocationHandler;

import io.netty.buffer.ByteBufHolder;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.AttributeKey;
import io.netty.util.DefaultAttributeMap;

@RunWith(Enclosed.class)
public class MetricCollectingServiceCodecTest {
    @SuppressWarnings("unchecked")
    protected static void setupServer(
            ServerBuilder sb, ServiceInvocationHandler handler, final MetricConsumer consumer) throws Exception {
        ServiceCodec codec = Mockito.mock(ServiceCodec.class);
        DecodeResult decodeResult = Mockito.mock(DecodeResult.class);
        DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap();
        ServiceInvocationContext invocationContext = Mockito.mock(ServiceInvocationContext.class);

        when(decodeResult.type()).thenReturn(DecodeResultType.SUCCESS);
        when(decodeResult.invocationContext()).thenReturn(invocationContext);
        when(invocationContext.attr(any())).then(x -> defaultAttributeMap.attr(AttributeKey.valueOf("TEST")));
        when(invocationContext.method()).thenReturn("someMethod");

        when(codec.decodeRequest(any(), any(), any(), any(), any(), any(), any(), any(), any()))
                .thenReturn(decodeResult);

        when(codec.encodeResponse(any(), any())).thenReturn(Unpooled.EMPTY_BUFFER);
        when(codec.encodeFailureResponse(any(), any())).thenReturn(Unpooled.EMPTY_BUFFER);

        sb.serviceAt("/", Service.of(new MetricCollectingServiceCodec(codec, consumer), handler));
    }

    abstract static class ExecutionCheckingTest extends AbstractServerTest {
        private int executed;

        protected MetricConsumer defaultConsumer = (a, b, c, d, e, f, g, h) -> executed += 1;

        @Test
        public void test() throws Exception {
            try (CloseableHttpClient hc = HttpClients.createMinimal()) {
                final HttpPost req = new HttpPost(uri("/"));
                req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

                hc.execute(req);

                assertEquals(1, executed);
            }
        }
    }

    public static class NormalResponseTest extends ExecutionCheckingTest {
        @Override
        protected void configureServer(ServerBuilder sb) throws Exception {
            setupServer(sb, (ctx, blockingTaskExecutor, promise) -> promise.trySuccess("Hello World"),
                        defaultConsumer);
        }
    }

    public static class TypedResponseTest extends ExecutionCheckingTest {
        @Override
        protected void configureServer(ServerBuilder sb) throws Exception {
            ByteBufHolder response = Mockito.mock(ByteBufHolder.class);
            when(response.content()).thenReturn(Unpooled.EMPTY_BUFFER);
            setupServer(sb, (ctx, blockingTaskExecutor, promise) -> promise.trySuccess(response),
                        defaultConsumer);
        }
    }

    public static class HttpResponseTest extends ExecutionCheckingTest {
        @Override
        protected void configureServer(ServerBuilder sb) throws Exception {
            setupServer(
                    sb, (ctx, blockingTaskExecutor, promise) -> promise.trySuccess(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)),
                    defaultConsumer);
        }
    }

    public static class ExceptionResponseTest extends ExecutionCheckingTest {
        @Override
        protected void configureServer(ServerBuilder sb) throws Exception {
            setupServer(sb, (ctx, blockingTaskExecutor, promise) -> promise.tryFailure(new RuntimeException()),
                        defaultConsumer);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.syshuman.kadir.haircolor3.view.activities.TrainingActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <ImageButton
                android:id="@+id/btnClearData"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/action_help"
                android:layout_gravity="end"
                android:layout_margin="10dp"
                android:background="@drawable/delete32" />
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_training" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btnBLE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@drawable/bt_passive"
        app:backgroundTint="@android:color/darker_gray" />

</android.support.design.widget.CoordinatorLayout>


text:
'use strict';

describe('Reports E2E Tests:', function() {
	describe('Test Reports page', function() {
		/*it('Should not include new Reports', function() {
			browser.get('http://localhost:3000/#!/reports');
			expect(element.all(by.repeater('report in reports')).count()).toEqual(0);
		});*/
		it('Valid login', function() {
			browser.get('http://localhost:3000/login');
			var username = element(by.id('inputEmail'));
			username.sendKeys("agent@demo.com");

			var password = element(by.id('inputPassword'));
			password.sendKeys("demo");

			var button = element(by.buttonText('Sign In'));
			button.click();

			expect(browser.getCurrentUrl()).toMatch('localhost:3000/app/');
		});
		it('invalid login', function() {
			browser.get('http://localhost:3000/login');
			var username = element(by.id('inputEmail'));
			username.sendKeys("agt@demo.com");

			var password = element(by.id('inputPassword'));
			password.sendKeys("demo");

			var button = element(by.buttonText('Sign In'));
			button.click();

			expect(browser.getCurrentUrl()).toMatch('localhost:3000/login');
		});
	});
});


text:
#include <gtest/gtest.h>

#include "graphs/strongly_connected_components_tarjan.hpp"
#include "graphs/edge_types.hpp"
#include "graphs/graph.hpp"

namespace gt = testing;

namespace pk
{
namespace graphs
{
namespace testing
{

struct strongly_connected_components_tarjan_tester : public gt::Test
{
    static const int V = 10;
    static const int E = 20;

    typedef edge edge_type;
    typedef graph_factory<V, E, edge_type> graph_factory_type;
    typedef graph_factory_type::graph_type graph_type;

    graph_factory_type gf;

    // tested class:
    strongly_connected_components_tarjan<graph_type> scc;
};

/**
 * (0)--->(1)--------->(2)<--->(3)
 *  ^      | \___.      |       ^
 *  |      |     |      |       |
 *  |      v     v      v       v
 *  `-----(4)-->(5)<-->(6)<----(7)
 */
TEST_F(strongly_connected_components_tarjan_tester, tests_xyz)
{
    // given
    gf.add_directed_edge(edge_type(0/*from*/, 1/*to*/));
    gf.add_directed_edge(edge_type(1, 2));
    gf.add_directed_edge(edge_type(1, 4));
    gf.add_directed_edge(edge_type(1, 5));
    gf.add_directed_edge(edge_type(2, 3));
    gf.add_directed_edge(edge_type(2, 6));
    gf.add_directed_edge(edge_type(3, 2));
    gf.add_directed_edge(edge_type(3, 7));
    gf.add_directed_edge(edge_type(4, 0));
    gf.add_directed_edge(edge_type(4, 5));
    gf.add_directed_edge(edge_type(5, 6));
    gf.add_directed_edge(edge_type(6, 5));
    gf.add_directed_edge(edge_type(7, 3));
    gf.add_directed_edge(edge_type(7, 6));

    const graph_type& g = gf.create(8);

    // when
    int component_ids[V];
    const int num_of_components = scc.run(g, component_ids);

    // then
    ASSERT_EQ(3, num_of_components);

    const int first_component_id = component_ids[0];
    EXPECT_EQ(first_component_id, component_ids[0]);
    EXPECT_EQ(first_component_id, component_ids[1]);
    EXPECT_EQ(first_component_id, component_ids[4]);

    const int second_component_id = component_ids[2];
    EXPECT_EQ(second_component_id, component_ids[2]);
    EXPECT_EQ(second_component_id, component_ids[3]);
    EXPECT_EQ(second_component_id, component_ids[7]);

    const int third_component_id = component_ids[5];
    EXPECT_EQ(third_component_id, component_ids[5]);
    EXPECT_EQ(third_component_id, component_ids[6]);
}

} // namespace testing
} // namespace graphs
} // namespace pk


text:
<?php

/**
 * Cursor for template parser encapsulating text and position.
 *
 * This class takes care of traversing a text block and keeping track of
 * {@link ezcTemplateCursor::position position}, {@link ezcTemplateCursor::line line number}
 * and {@link ezcTemplateCursor::column column number}.
 *
 * Moving the cursor position is done with gotoBeginning(), gotoEnd(),
 * gotoLineBeginning(), gotoLineEnd(), advance() and gotoPosition().
 * Checking the position can be done with atBeginning(), atEnd(),
 * {@link ezcTemplateCursor::position position}, {@link ezcTemplateCursor::line line}
 * and {@link ezcTemplateCursor::column column}.
 * Matching for strings and regular expression is done with findPosition(),
 * current(), subString(), match(), pregMatch() and pregMatchComplete().
 *
 * In addition there are methods for working with cursor objects, they are
 * copy(), cursorAt() and length().
 *
 * This example shows how to advance through the text with different
 * matching methods and print the positions.
 * <code>
 * $text = "hello world!";
 * $c = new ezcTemplateCursor( $text );
 * $c->match( "hello", true );
 * echo "position: ", $c->position, "\n";
 * echo "line: ",     $c->line, "\n";
 * echo "column: ",   $c->column, "\n";
 * $c->pregMatch( "/^[ ]+world/", true );
 * echo "position: ", $c->position, "\n";
 * echo "line: ",     $c->line, "\n";
 * echo "column: ",   $c->column, "\n";
 * echo "current: '", $c->current(), "'\n";
 * </code>
 *
 * @package Template
 * @version 1.4.2
 * @access private
 */
class ezcTemplateCursor
{
    /**
     * The text to which the cursors operates on.
     * @var string
     */
    public $text;

    /**
     * The byte position in the text, starts at 0.
     * @var int
     */
    public $position;

    /**
     * The current line number, starts at 1.
     * @var int
     */
    public $line;

    /**
     * The current column number, starts at 0.
     * @var int
     */
    public $column;

    /**
     * Initialise with text block and position data.
     *
     * @param string $text     Text block which the cursor position relates to.
     * @param int $position The string position in the text, starts at 0.
     * @param int $line     The line position in the text, starts at 1.
     * @param int $column   The column position in the text, starts at 0.
     */
    public function __construct( $text, $position = 0, $line = 1, $column = 0 )
    {
        $this->text = $text;
        $this->position = $position;
        $this->line = $line;
        $this->column = $column;
    }

    /**
     * Copies all the properties of cursor $other to this cursor.
     *
     * @param ezcTemplateCursor $other The cursor object to copy from.
     * @return void
     */
    public function copy( ezcTemplateCursor $other )
    {
        $this->text = $other->text;
        $this->position = $other->position;
        $this->line = $other->line;
        $this->column = $other->column;
    }

    /**
     * Calculates the length between this cursor and the specified cursor.
     * Note: If the specified cursor is before this one it returns negative values.
     *
     * @param ezcTemplateCursor $other The cursor to use as end position for measuring length.
     * @return int
     */
    public function length( ezcTemplateCursor $other )
    {
        return $other->position - $this->position;
    }

    /**
     * Checks if the cursor is at the beggining of the text and returns true if
     * it is.
     *
     * @return bool
     */
    public function atBeginning()
    {
        return $this->position == 0;
    }

    /**
     * Checks if the cursor is at the end of the text and returns true if it is.
     *
     * @return bool
     * Note: The cursor is considered at the end if it is placed after the last
     *       character in the text ( ie. strlen( $text ) ), this is different
     *       from being at the last character ( strlen( $text ) - 1 ).
     */
    public function atEnd()
    {
        return $this->position == strlen( $this->text );
    }

    /**
     * Moves the cursor to the beginning of the text.
     *
     * @see atBeginning()
     * @return void
     */
    public function gotoBeginning()
    {
        $this->position = 0;
        $this->line = 1;
        $this->column = 0;
    }

    /**
     * Moves the cursor to the end of the text.
     *
     * @see atEnd()
     * @return void
     */
    public function gotoEnd()
    {
        $endPosition = strlen( $this->text );
        if ( $this->position == $endPosition )
            return;

        $lines = preg_split( "#\r\n|\r|\n#", substr( $this->text, $this->position ) );
        if ( count( $lines ) > 0 )
        {
            $endLine = $this->line + count( $lines ) - 1;
            $lastLine = $lines[count( $lines ) - 1];
            if ( count( $lines ) > 1 )
                $endColumn = strlen( $lastLine );
            else
                $endColumn = $this->column + strlen( $lastLine );
        }
        else
        {
            $endLine = $this->line;
            $endColumn = $this->column;
        }
        $this->position = $endPosition;
        $this->line = $endLine;
        $this->column = $endColumn;
    }

    /**
     * Moves the cursor to the beginning of the current line.
     *
     * @see gotoLineEnd()
     * @return void
     */
    public function gotoLineBeginning()
    {
        $this->position -= $this->column;
        $this->column = 0;
    }

    /**
     * Moves the cursor to the end of the current line.
     * The end of the line is considered right before the EOL marker.
     *
     * Note: If the current line is at the end of the buffer the position will
     *       be placed at the end of the buffer similar to gotoEnd().
     * @see gotoLineBeginning()
     * @return void
     */
    public function gotoLineEnd()
    {
        $endPosition = strlen( $this->text );
        if ( $this->position == $endPosition )
            return;

        // If we find a newline we adjust endPosition to this location,
        // if not we use the end of the buffer.
        if ( preg_match( "#\r\n|\r|\n#", $this->text, $matches, PREG_OFFSET_CAPTURE, $this->position ) )
        {
            $endPosition = $matches[0][1];
        }
        // Increase column and set end position
        $this->column += $endPosition - $this->position;
        $this->position = $endPosition;
    }

    /**
     * Moves the cursor n steps relatively to the current position.
     *
     * @param int $delta The number of characters to advance.
     * @return void
     */
    public function advance( $delta = 1 )
    {
        $this->gotoPosition( $this->position + $delta );
    }

    /**
     * Moves the cursor to the specified position.
     *
     * @see atBeginning(), atEnd()
     *
     * @param int $endPosition
     * @throws ezcTemplateCursorsException if the position is beyond the text.
     * @return void
     */
    public function gotoPosition( $endPosition )
    {
        if ( $endPosition > strlen( $this->text ) )
            throw new ezcTemplateCursorsException();

        if ( $this->position == $endPosition )
            return;

    /* Not supported yet, might not be needed
        if ( $this->position > $endPosition )
    */
        {
            $lines = preg_split( "#\r\n|\r|\n#", substr( $this->text, $this->position, $endPosition - $this->position ) );
            if ( count( $lines ) > 0 )
            {
                $endLine = $this->line + count( $lines ) - 1;
                $lastLine = $lines[count( $lines ) - 1];
                if ( count( $lines ) > 1 )
                    $endColumn = strlen( $lastLine );
                else
                    $endColumn = $this->column + strlen( $lastLine );
            }
            else
            {
                $endLine = $this->line;
                $endColumn = $this->column;
            }
        }
    /* Not supported yet, might not be needed
        else
        {
            $lines = preg_split( "#\r\n|\r|\n#", substr( $this->text, $endPosition, $this->position - $endPosition ) );
            if ( count( $lines ) > 0 )
            {
                $endLine = $this->line - count( $lines ) - 1;
                $lastLine = $lines[count( $lines ) - 1];
                if ( $endPosition > 0 )
                {
                    $endColumn = 0;
                    for ( $i = $endPosition - 1; $i > 0; --$i )
                    {
                        switch ( $this->text[$i] )
                        {
                            case "\n":
                            case "\r":
                                $endColumn = $endPosition - $i;
                                break 2;
                        }
                    }
                }
                else
                {
                    $endColumn = 0;
                }
            }
            else
            {
                $endLine = $this->line;
                $endColumn = $this->column;
            }
        }
    */
        $this->position = $endPosition;
        $this->line = $endLine;
        $this->column = $endColumn;
    }

    /**
     * Extracts a substring from the current position in the text and to a given
     * end position. If the position is at the end it returns false.
     *
     * @param string $endPosition The end position of the substring, if this is false
     *                            it will fetch the entire substring from the current
     *                            position.
     * @return string
     */
    public function subString( $endPosition = false )
    {
        if ( $endPosition === false )
            return substr( $this->text, $this->position );
        return substr( $this->text, $this->position, $endPosition - $this->position );
    }

    /**
     * Finds the first occurence of the string $searchString in the text block from
     * the current position.
     *
     * @param string $searchString The string to find in the text (case-sensitive).
     * @param bool $checkEscaped If this is true then it will not match text which
     *                           is preceded by the escape character \.
     * @return mixed The integer value of the position or false if it is not found.
     */
    public function findPosition( $searchString, $checkEscaped = false )
    {
        if ( $this->position === strlen( $this->text ) )
            return false;

        if ( !$checkEscaped )
            return strpos( $this->text, $searchString, $this->position );

        $position = $this->position;
        while ( ( $position = strpos( $this->text, $searchString, $position ) ) !== false )
        {

            $escapedPos = 1;
            while ( $position - $escapedPos >= 0 && $this->text[$position - $escapedPos] == "\\" )
            {
                $escapedPos++;
            }

            if ( $escapedPos % 2 == 1 )
            {
                break;
            }

          /*

            if ( $this->text[$position-1] != "\\" )
                break;
                */

            ++$position;
        }
        return $position;
    }

    /**
     * Creates a clone of the current cursor at the specified position and returns it.
     *
     * @param int $position The position for the new cursor, line and column will be recalculated accordingly.
     * @param int $newSize If this is non-false it will limit the text buffer for the new cursor.
     * @return ezcTemplateCursor
     */
    public function cursorAt( $position, $newSize = false )
    {
        if ( $position < $this->position )
            throw new ezcTemplateInternalException( "Cannot move position backwards yet, sorry" );

        $cursor = clone $this;
        if ( $newSize !== false )
            $cursor->text = substr( $cursor->text, 0, $newSize );
        $cursor->gotoPosition( $position );
        return $cursor;
    }

    /**
     * Returns the character(s) at the current position. If the position is at the
     * end it returns false.
     *
     * @param int $length The number of character to fetch from current position, negative values fetches in reverse.
     * @return mixed The current character/string or false if the position is beyond the text.
     * @see atEnd()
     */
    public function current( $length = 1 )
    {
        if ( $this->position === strlen( $this->text ) )
            return false;
        return substr( $this->text, $this->position, $length );
    }

    /**
     * Performs a preg_match() on the current position to figure out if the
     * pattern matches. The preg_match() will be called with PREG_OFFSET_CAPTURE
     * so the return matches will contain the offset as well, however the offset
     * will be relative to the starting position and not the start of the buffer.
     *
     * Note: To check that a pattern matches immediately at the start position use the
     *       ^ in the pattern string.
     *
     * @param string $pattern The pattern which is passed to preg_match().
     * @return mixed The result of the preg_match() if successful or false it it failed.
     */
    public function pregMatchComplete( $pattern )
    {
        if ( $this->position === strlen( $this->text ) )
            return false;

        if ( !preg_match( $pattern, substr( $this->text, $this->position ), $matches, PREG_OFFSET_CAPTURE ) )
            return false;

        return $matches;
    }

    /**
     * Does a pregMatchComplete and returns only the [0][0] part.
     *
     * @param string $pattern The pattern which is passed to preg_match().
     * @param string $advance If true it will advance the position to after matched text.
     * @return mixed The [0][0] entry of the preg_match() result if successful or false it it failed.
     */
    public function pregMatch( $pattern, $advance = true )
    {
        $matches = $this->pregMatchComplete( $pattern );

        if ( $matches === false )
        {
            return false;
        }

        if ( $advance )
        {
            $this->advance( strlen( $matches[0][0] ) );
        }

        return $matches[0][0];
    }

    /**
     * Matches the specified text with the text at the current position and returns the result.
     *
     * @param string $word The character/string to match at the current position.
     * @param string $advance If true it will advance the position to after matched text.
     * @return bool  True if the $word matches, otherwise false.
     */
    public function match( $word, $advance = true )
    {
        $len = strlen( $word );
        if ( $this->current( $len ) == $word )
        {
            if ( $advance ) $this->advance( $len );

            return true;
        }

        return false;
    }
}

?>


text:
Cmdlet|Description
:-----|:----------
**[Remove‑PnPContentTypeFromDocumentSet](RemovePnPContentTypeFromDocumentSet.md)** |Removes a content type from a document set
**[Add‑PnPContentTypeToDocumentSet](AddPnPContentTypeToDocumentSet.md)** |Adds a content type to a document set
**[Add‑PnPDocumentSet](AddPnPDocumentSet.md)** |Creates a new document set in a library.
**[Set‑PnPDocumentSetField](SetPnPDocumentSetField.md)** |Sets a site column from the available content types to a document set
**[Get‑PnPDocumentSetTemplate](GetPnPDocumentSetTemplate.md)** |Retrieves a document set template


text:
import React from 'react';
import { Story, Meta } from '@storybook/react';

import CustomMentionEditor from './CustomMentionEditor';

export default {
  title: 'Mentions/Editor with custom themed Mention Plugin',
  component: CustomMentionEditor,
} as Meta;

export const Default: Story = () => <CustomMentionEditor />;


text:
using Paragon.Container.Models;
using System;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;

namespace BuildSystem
{
    public class InAppTestConfigGenerator
    {
        public static void CreateInAppTestConfig(ProductsCatalog catalog)
        {
            ServiceLocator.Logger.Log(LogLevel.Info, "In app test config generation...");

            try
            {
                XNamespace xml = XNamespace.Xml;

                XElement rootElement = new XElement("CurrentApp");

                XElement listingInformationElement = new XElement("ListingInformation",
                    new XElement("App",
                        new XElement("AppId", "00000000-0000-0000-0000-000000000000"),
                        new XElement("LinkUri", "http://apps.microsoft.com/webpdp/app/00000000-0000-0000-0000-000000000000"),
                        new XElement("CurrentMarket", "en-US"),
                        new XElement("AgeRating", "3"),
                            new XElement("MarketData", new XAttribute(xml + "lang", "en-us"),
                                new XElement("Name", "AppName"),
                                new XElement("Description", "AppDescription"),
                                new XElement("Price", "42.00"),
                                new XElement("CurrencySymbol", "$"),
                                new XElement("CurrencyCode", "USD"))));

                foreach (Product product in catalog.Products)
                {
                    listingInformationElement.Add(new XElement("Product",
                        new XAttribute("ProductId", product.Id),
                        new XAttribute("LicenseDuration", "0"),
                        new XAttribute("ProductType", "Durable"),
                        new XElement("MarketData", new XAttribute(xml + "lang", "en-us"),
                            new XElement("Name", product.Id),
                            new XElement("Price", "42.00"),
                            new XElement("CurrencySymbol", "$"),
                            new XElement("CurrencyCode", "USD"))));
                }

                XElement licenseInformationElement = new XElement("LicenseInformation",
                    new XElement("App",
                        new XElement("IsActive", "true"),
                        new XElement("IsTrial", "false")));

                rootElement.Add(listingInformationElement);
                rootElement.Add(licenseInformationElement);

                File.WriteAllText(Config.InAppTestConfigFile, rootElement.ToString());

                ServiceLocator.Logger.Log(LogLevel.Info, "Done.");
            }
            catch(Exception ex)
            {
                ServiceLocator.Logger.Log(LogLevel.Warning, string.Format("Failed to generate InApp test config.\n{0}", ex));
            }
        }
    }
}


text:
wp-frontend-login
=================

Front-end account management (register/login/change password) for Wordpress.

More at
http://cubiq.org/front-end-user-registration-and-login-in-wordpress


text:
(function () {
    'use strict';

    angular.module('instangular', [])
        .factory('instangular', ['$http',
            function ($http) {

                function request(options) {
                    var baseurl = "https://api.instagram.com/v1/";
                    var clientid = "";

                    options = options || {};
                    options.data = options.data || {};
                    options.data.access_token = localStorage.getItem('instagram_access_token');
                    options.data.callback = "JSON_CALLBACK";

                    var queryString = serializeParams(options.data);

                    var endPoint = baseurl + options.url + "?" + queryString;

                    $http.jsonp(endPoint).success(function (response) {
                        options.success(response.data);
                    });
                }

                function serializeParams(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }

                return {
                    selfprofile: function (callback) {
                        request({
                            url: "users/self",
                            success: callback
                        });
                    },
                    profile: function (id, callback) {
                        request({
                            url: "users/" + id + "/",
                            success: callback
                        });
                    },
                    follows: function (id, callback) {
                        request({
                            url: "users/" + id + "/follows",
                            success: callback
                        });
                    },
                    followedby: function (id, callback) {
                        request({
                            url: "users/" + id + "/followed-by",
                            success: callback
                        });
                    },
                    usermedia: function (id, callback) {
                        request({
                            url: "users/" + id + "/media/recent/",
                            success: callback
                        });
                    },
                    media: function (id,callback) {
                        request({
                            url:"media/"+id,
                            success:callback
                        });
                    },
                    locationsearch: function (options, callback) {
                        request({
                            url: "locations/search",
                            data: options,
                            success: callback
                        });

                    },
                    locationmedia: function (id, callback) {
                        request({
                            url: "locations/" + id + "/media/recent",
                            success: callback
                        });
                    }

                }

}]);

})();


text:
package boofcv.abst.feature.detect.extract;

import boofcv.struct.QueueCorner;
import boofcv.struct.image.GrayF32;

/**
 *

 * Detects local minimums and/or maximums in an intensity image inside square regions.  This is known as non-maximum
 * suppression.  The detector can be configured to ignore pixels along the image border by a user specified distance.
 * Some implementations require candidate locations for the features.  This allows for a sparse algorithm to be used,
 * resulting in a significant speed boost.  Pixel values with a value of -Float.MAX_VALUE or Float.MAX_VALUE will
 * not be considered for local minimum/maximum, respectively.  This is a good way to ignore previously detected
 * features.
 *

 *
 *

 * Not all implementations will search for both minimums or maximums.  Be sure you are using the correct one.  If
 * you don't intend on detecting a minimum or maximum pass in null for the candidate list and the output found list.
 *

 *
 *

 * An extractor which uses candidate features must always be provided them.  However, an algorithm which does not
 * use candidate features will simply ignore that input and operate as usual.  Can check capabilities at runtime
 * using the {@link #canDetectMinimums()} and {@link #canDetectMaximums()} functions.
 *

 *
 *

 * A border can be specified around the outside of the image in which extremes can't be detected.  However, a pixel
 * outside this border can influence if a pixel is a maximum inside, if the local search radius extends that far.
 * This is specified by the border parameter and the valid region is defined as follows:

 * border ≤ x < width-border AND border ≤ y < height-border

 *
 * @author Peter Abeles
 */
public interface NonMaxSuppression {

	/**
	 * Process a feature intensity image to extract the point features.  If a pixel has an intensity
	 * value == -Float.MAX_VALUE  or Float.MAX_VALUE it will not be considered for a local min or max, respectively.
	 * If an algorithm only detect local minimums or maximums and null can be passed in for unused lists.  This is
	 * the recommended procedure since it will force an exception to be thrown if a mistake was made.
	 *
	 * @param intensity (Input) Feature intensity image.  Not modified.
	 * @param candidateMin  (Input) (Optional) List of candidate local minimum features. Can be null if not used.
	 * @param candidateMax  (Input) (Optional) List of candidate local maximum features  Can be null if not used.
	 * @param foundMin (Output) Storage for found minimums. Can be null if not used.
	 * @param foundMax (Output) Storage for found maximums. Can be null if not used.
	 */
	public void process(GrayF32 intensity,
						QueueCorner candidateMin, QueueCorner candidateMax,
						QueueCorner foundMin, QueueCorner foundMax );

	/**
	 * Returns true if the algorithm requires a candidate list of corners.
	 *
	 * @return true if candidates are required.
	 */
	public boolean getUsesCandidates();

	/**
	 * Maximum value for detected minimums
	 *
	 * @return threshold for feature selection
	 */
	public float getThresholdMinimum();

	/**
	 * Minimum value for detected maximums
	 *
	 * @return threshold for feature selection
	 */
	public float getThresholdMaximum();

	/**
	 * Change the feature selection threshold for finding local minimums.
	 *
	 * @param threshold The new selection threshold.
	 */
	public void setThresholdMinimum(float threshold);

	/**
	 * Change the feature selection threshold for finding local maximums.
	 *
	 * @param threshold The new selection threshold.
	 */
	public void setThresholdMaximum(float threshold);

	/**
	 * Defines the region inside the image in which a pixel can be an extreme.
	 * valid region is: border ≤ x < width-border AND border ≤ y < height-border
	 *
	 * @param border Border size in pixels.
	 */
	public void setIgnoreBorder(int border);

	/**
	 * Returns the size of the image border.
	 *
	 * @return border size
	 */
	public int getIgnoreBorder();

	/**
	 * Species the search radius for the feature
	 *
	 * @param radius Radius in pixels
	 */
	public void setSearchRadius(int radius);

	/**
	 * Describes how large the region is that is being searched.  The radius is the number of
	 * pixels away from the center.
	 *
	 * @return Search radius
	 */
	public int getSearchRadius();

	/**
	 * True if it can detect local maximums.
	 */
	public boolean canDetectMaximums();

	/**
	 * True if it can detect local minimums.
	 */
	public boolean canDetectMinimums();

}


text:
namespace MineAPI.Editor.ProcessHelper
{
    using System;

    /// <summary>
    ///     Event Arguments for above delegate
    /// </summary>
    public class DataReceivedEventArgs : EventArgs
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DataReceivedEventArgs"/> class.
        /// </summary>
        /// <param name="text">
        /// The text that was received for this event to be triggered.
        /// </param>
        public DataReceivedEventArgs(string text)
        {
            Text = text;
        }

        #endregion

        #region Public Properties

        /// <summary>
        ///     Gets or sets the text.
        /// </summary>
        /// <value>The text.</value>
        /// <returns>string.</returns>
        public string Text { get; set; }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- (c) 2011-2016 Evolveum, All rights reserved -->
<objects xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
	xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3">
	<role oid="f52cea12-8a50-4169-a71c-d747b0a4698f" version="1">
		<name>Drupal:Authenticated user</name>
		<description>Default role for any logged in user</description>
		<assignment id="1">
			<targetRef oid="bedffe37-72a4-48da-b3ea-0362039179b2" type="c:RoleType">
				<!-- Drupal Metarole for Roles -->
			</targetRef>
		</assignment>
		<!-- ID of your's Drupal role, copy this role and change this identifier if you need more Drupal roles -->
		<identifier>2</identifier>
		<requestable>false</requestable>
		<displayName>Drupal:Authenticated user</displayName>
		<roleType>drupal</roleType>
	</role>
</objects>


text:
//
// Created by ragnar on 23.6.17..
//
#include <iostream>

#define LINUX

using namespace std;

/**
 * Abstract base product. It should define an interface
 * which will be common to all products. Clients will
 * work with products through this interface, so it
 * should be sufficient to use all products.
 */
class Widget {
public:
    virtual void draw() = 0;
};

/**
 * Concrete product family 1.
 */
class LinuxButton : public Widget {
public:
    void draw() { cout << "LinuxButton\n"; }
};

class LinuxMenu : public Widget {
public:
    void draw() { cout << "LinuxMenu\n"; }
};

/**
 * Concrete product family 2.
 */
class WindowsButton : public Widget {
public:
    void draw() { cout << "WindowsButton\n"; }
};

class WindowsMenu : public Widget {
public:
    void draw() { cout << "WindowsMenu\n"; }
};

/**
 * Abstract factory defines methods to create all
 * related products.
 */
class Factory {
public:
    virtual Widget *create_button() = 0;

    virtual Widget *create_menu() = 0;
};

/**
 * Each concrete factory corresponds to one product
 * family. It creates all possible products of
 * one kind.
 */
class LinuxFactory : public Factory {
public:
    Widget *create_button() {
        return new LinuxButton;
    }

    Widget *create_menu() {
        return new LinuxMenu;
    }
};

/**
 * Concrete factory creates concrete products, but
 * returns them as abstract.
 */
class WindowsFactory : public Factory {
public:
    Widget *create_button() {
        return new WindowsButton;
    }

    Widget *create_menu() {
        return new WindowsMenu;
    }
};

/**
 * Client receives a factory object from its creator.
 *
 * All clients work with factories through abstract
 * interface. They don't know concrete classes of
 * factories. Because of this, you can interchange
 * concrete factories without breaking clients.
 *
 * Clients don't know the concrete classes of created
 * products either, since abstract factory methods
 * returns abstract products.
 */
class Client {
private:
    Factory *factory;

public:
    Client(Factory *f) : factory(f) {};

    void draw() {
        Widget *w = factory->create_button();
        w->draw();
        display_window_one();
        display_window_two();
    }

    void display_window_one() {
        Widget *w[]{
                factory->create_button(),
                factory->create_menu()
        };
        w[0]->draw();
        w[1]->draw();
    }

    void display_window_two() {
        Widget *w[]{
                factory->create_menu(),
                factory->create_button()
        };
        w[0]->draw();
        w[1]->draw();
    }
};

/**
 * Now the nasty switch statement is needed only once to
 * pick and create a proper factory. Usually that's
 * happening somewhere in program initialization code.
 */

/*
int main() {
    Factory *factory;
#ifdef LINUX
    factory = new LinuxFactory;
#else // WINDOWS
    factory = new WindowsFactory;
#endif

    Client *c = new Client(factory);
    c->draw();
}
*/


text:
package org.apache.hadoop.metrics2.lib;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.metrics2.MetricsInfo;
import org.apache.hadoop.metrics2.MetricsRecordBuilder;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * A mutable int counter for implementing metrics sources
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class MutableCounterInt extends MutableCounter {
  private AtomicInteger value = new AtomicInteger();

  MutableCounterInt(MetricsInfo info, int initValue) {
    super(info);
    this.value.set(initValue);
  }

  @Override
  public void incr() {
    incr(1);
  }

  /**
   * Increment the value by a delta
   * @param delta of the increment
   */
  public synchronized void incr(int delta) {
    value.addAndGet(delta);
    setChanged();
  }

  public int value() {
    return value.get();
  }

  @Override
  public void snapshot(MetricsRecordBuilder builder, boolean all) {
    if (all || changed()) {
      builder.addCounter(info(), value());
      clearChanged();
    }
  }

}


text:
#include <string>
#include <iostream>
#include <vector>
#include <set>
#include <fstream>
#include <getopt.h>
#include <unistd.h>
#include <time.h>
#include <tvmet/Vector.h>
#include <cmath>
#include "Node.h"
#include "SCElastic.h"
#include "EvansElastic.h"
#include "LoopShellBody.h"
#include "LoopShell.h"
#include "C0MembraneBody.h"
#include "StretchHexonBody.h"

#include "TriangleQuadrature.h"
#include "ShapeTri3.h"
#include "Model.h"
#include "Lbfgsb.h"
#include "CGfast.h"
#include "VoomMath.h"
#include "Utils/PrintingStretches.h"

using namespace voom;
using namespace std;

/*! This program creates a shell model with LoopShellBody for bending
  and 2 C0MembraneBodies for stretching, one of pentamers and one of
  hexamers.
 */
int main(int argc, char* argv[])
{
  time_t start, end;
  double dif;
  time(&start);

  if(argc < 2){
    cout << "Input file missing." << endl;
    return(0);
  }

  // File names
  string parameterFileName = argv[1];
  string modelName;
  string OutlineName;

  // Minimization constants
  int min = 0;            // Minimize with respect to eta and theta flag (3 -> both, 2 -> only theta, 1-> only eta, 0-> none)
  int Ns_eta = 1;         // Number of stretch magnitude dof
  int Ns_theta = 1;       // Number of stretch direction dof
  double in_eta = 0.0;    // eta initial guess
  double in_theta = 0.0;  // theta initial guess
  double in_phi = 0.0;    // phi initial value

  // Bending
  double KC = 1.0;
  double KG =-1.0;
  double C0 = 0.0;
  // Stretching
  double mu = 1.0;
  double kS = 1.0;

  // Output
  unsigned int NPout = 0; // Nodes needed to build the outline
  string OutFile;
  int refinement = 1;

  // Input file for refinement angle
  string AngleShiftFile;

  // Analysis Type
  int AnType = 0;      // 0 -> Shield analyses, 1 -> Energy analyses (three fold sites hexamers in T9), 2 -> Energy analyses (all hexamers)
  int NumEnergy = 1;  // number of energies to be computed for different three fold sites configurations

  // Reading input from file passed as argument
  ifstream inp;
  inp.open(parameterFileName.c_str(), ios::in);
  if (!inp) {
    cout << "Cannot open input file: " << parameterFileName << endl;
    return(0);
  }
  string dump;

  inp >> dump >> modelName;
  inp >> dump >> OutlineName;
  inp >> dump >> min;
  inp >> dump >> Ns_eta;
  inp >> dump >> Ns_theta;
  inp >> dump >> in_eta;
  inp >> dump >> in_theta;
  inp >> dump >> in_phi;
  inp >> dump >> KC;
  inp >> dump >> KG;
  inp >> dump >> C0;
  inp >> dump >> mu;
  inp >> dump >> kS;
  inp >> dump >> NPout;
  inp >> dump >> OutFile;
  inp >> dump >> refinement;
  inp >> dump >> AngleShiftFile;
  inp >> dump >> AnType;
  inp >> dump >> NumEnergy;

  inp.close();

  // Populate WcType, WcConst, HexonShift (not used in these analyses)
  int WcType = 0;
  double WcConst[4];
  WcConst[0] = 0.0;
  WcConst[1] = 0.0;
  WcConst[2] = 0.0;
  WcConst[3] = 0.0;
  double HexonShift = 0.1;

  // List input parameters
  cout << " modelName      : " << modelName      << endl
       << " OutlineName    : " << OutlineName    << endl
       << " min            : " << min            << endl
       << " Ns_eta         : " << Ns_eta         << endl
       << " Ns_theta       : " << Ns_theta       << endl
       << " in_eta         : " << in_eta         << endl
       << " in_theta       : " << in_theta       << endl
       << " in_phi         : " << in_phi         << endl
       << " KC             : " << KC             << endl
       << " KG             : " << KG             << endl
       << " C0             : " << C0             << endl
       << " mu             : " << mu             << endl
       << " kS             : " << kS             << endl
       << " NPout          : " << NPout          << endl
       << " OutFile        : " << OutFile        << endl
       << " Refinement     : " << refinement     << endl
       << " AngleShiftFile : " << AngleShiftFile << endl
       << " AnType         : " << AnType         << endl
       << " NumEnergy      : " << NumEnergy      << endl;

  // Analyses list
  vector<unsigned int> NearNeighList(4, 0);
  NearNeighList[0] = 3;    // Three fold site (TFS)
  NearNeighList[1] = 8;    // Surrounding three fold site
  NearNeighList[2] = 24;   // Surrounding three fold site
  NearNeighList[3] = 75;   // Surrounding three fold site

  vector<vector<unsigned int > > TestShift(81, vector<unsigned int >(4,0));
  unsigned int i = 0, j = 0, k = 0, l = 0, ind = 0;
  for (i = 0; i<3; i++) {
    for (j = 0; j<3; j++) {
      for (k = 0; k<3; k++) {
	for (l = 0; l<3; l++) {
	  TestShift[ind][0] = l;
	  TestShift[ind][1] = k;
	  TestShift[ind][2] = j;
	  TestShift[ind][3] = i;
	  ind++;
	}
      }
    }
  }

  // Read in the mesh, in (ascii) legacy vtk format.
  // Create input stream
  ifstream ifs;
  ifs.open(modelName.c_str(), ios::in);
  if (!ifs) {
    cout << "Cannot open input file: " << modelName << endl;
    exit(0);
  }

  // Create vector of nodes
  vector<NodeBase* > nodes;
  vector<DeformationNode<3>* > defNodes;
  double Ravg = 0;
  unsigned int dof = 0, npts = 0;
  // Input .vtk file containing nodes and connectivities
  string token;
  while( token != "POINTS" ) ifs >> token;
  ifs >> npts;
  defNodes.reserve(npts);
  ifs >> token;   // skip number type
  // read in points
  for(i = 0; i < npts; i++) {
    DeformationNode<3>::Point x;
    ifs >> x(0) >> x(1) >> x(2);
    Ravg += tvmet::norm2(x);
    NodeBase::DofIndexMap idx(3);

    for(j = 0; j < 3; j++) idx[j] = dof++;

    DeformationNode<3>* n = new DeformationNode<3>(i,idx,x);
    nodes.push_back( n );
    defNodes.push_back( n );
  }
  Ravg /= nodes.size();

  // Read in triangle connectivities
  while( token != "POLYGONS" ) ifs >> token;
  std::vector< tvmet::Vector<int,3> > connectivities;
  tvmet::Vector<int,3> ct;
  int ntri = 0, tmp = 0, a = 0;
  ifs >> ntri;
  connectivities.reserve(ntri);

  ifs >> tmp;
  for (i = 0; i < ntri; i++)
  {
    ifs >> tmp;
    if(tmp != 3) cout << "Some mistake reading the elements connectivity from file. Check again." << endl;
    for(a = 0; a < 3; a++) ifs >> ct[a];
    connectivities.push_back(ct);
  }
  cout << "Number of nodes    = " << nodes.size()          << endl
       << "Ravg               = " << Ravg                  << endl;
  cout << "Number of elements = " << connectivities.size() << endl;

  // Read capsomers to assign different stretch dof to each one
  // Assume that hexons are written before pentons in the vtk input file.
  vector<unsigned int > CapsomersNum(ntri, 0.0);
  while( token != "capsomer") ifs >> token;
  ifs >> token;
  ifs >> token;
  ifs >> token;
  ifs >> token;
  for (i = 0; i < ntri; i++)
  {
    ifs >> CapsomersNum[i];
  }
  cout << "Number of capsomers = " <<  CapsomersNum[ntri-1]+1 << endl;

  // Read in the stretch directions. These are vectors pointing from vertex to vertex in each hexon.
  // This vector should point roughly along one of the edges of each triangular element.
  // Since we will define a "canonical" equilateral triangle reference configuration for each element,
  // we need to find which edge the vector is closest to pointing along, and then choose that edge to
  // define the "stretch angle" defining the reference pre-stretch.

  while( token != "shear_direction") ifs >> token;
  double AvgEdgeLength = 0.0, stretch = 0.0, TOL = 2.5e-1, stretch_dir_norm = 0.0, factor = 0.0;
  vector<double> stretch_angle;
  vector<double > ZeroAngles;
  vector< std::vector<int> > pent_connectivities, hex_connectivities;
  std::vector<int> cm(3,0.0);
  tvmet::Vector<double,3> stretch_dir;
  ifs >> token;
  for (i = 0; i < ntri; i++)
  {
    ifs >> stretch_dir(0) >> stretch_dir(1) >> stretch_dir(2);
    stretch_dir_norm = tvmet::norm2(stretch_dir);

    for(j = 0; j < 3; j++) {
      cm[j] = connectivities[i](j);
    }

    // Edge vectors in current config.
    tvmet::Vector<double,3> e31(defNodes[cm[0]]->point()-defNodes[cm[2]]->point()),
                            e32(defNodes[cm[1]]->point()-defNodes[cm[2]]->point()),
                            e12(defNodes[cm[1]]->point()-defNodes[cm[0]]->point()),
                            eCent(defNodes[cm[2]]->point());
    // Compute averate edge length for each triangle
    AvgEdgeLength += (tvmet::norm2(e31) + tvmet::norm2(e32) + tvmet::norm2(e12))/3.0;

    // pentamers don't have stretch directions
    if(stretch_dir_norm == 0)
    {
      pent_connectivities.push_back(cm);
    }
    // hexamers do
    else
    {
      stretch_dir = stretch_dir/stretch_dir_norm;
      hex_connectivities.push_back(cm);
      // Calculate the stretch angle

      //normalize the edge vectors
      e31=e31/tvmet::norm2(e31);
      e32=e32/tvmet::norm2(e32);
      e12=e12/tvmet::norm2(e12);

      // Which edge is closest to the stretch vector?
      // Take cross product.  If zero (or < TOL) then two vectors are parallel or anti-parallel.
      // Compute angles in degrees.

      if(tvmet::norm2(tvmet::cross(stretch_dir,e31))<TOL) {

        if(tvmet::dot(stretch_dir,e31)>0) stretch=0.; // parallel with edge 31
        else stretch=180.; // anti-parallel

      } else if(tvmet::norm2(tvmet::cross(stretch_dir,e32))<TOL){

        if(tvmet::dot(stretch_dir,e32)>0) stretch=60.; // parallel with 32
        else stretch=240.; // anti-parallel

      } else if(tvmet::norm2(tvmet::cross(stretch_dir,e12))<TOL) {

        if(tvmet::dot(stretch_dir,e12)>0) stretch=120.; // parallel with 12
        else stretch=300.; // anti-parallel

      }
      // If TOL is too small, it bombs.
      /*else {
	std::cout<<"Problem. The stretch direction is not parallel to any triangle edge"<<std::endl; exit(1);
	}*/

      // Check that all the normals are defined in the same direction (inner or outward with respect to the capsid surface...
      // otherwise the theta dof does not make sense)
      tvmet::Vector<double,3> n = tvmet::cross(e31,e32);
      if (i==0) {
	factor = (tvmet::dot(n,eCent) > 0) - (tvmet::dot(n,eCent) < 0);
	cout << "tvmet::dot(n,eCent) = " << factor << endl;
      }

      if (factor*tvmet::dot(n,eCent) < 0.0 )
      {
	cout << "Theta dof are NOT consistently defined ... ABORT :( " << endl;
	exit(0);
      }

      // Convert from degrees to radians.
      // stretch_angle.push_back((stretch)*M_PI/180.);
      // cout << stretch << endl;
      ZeroAngles.push_back(0.0);
      stretch_angle.push_back(0.0);
    }
  }
  AvgEdgeLength /= ntri;
  cout << "Number of penton elements = " <<pent_connectivities.size() << endl
       << "Number of hexon elements = "  <<hex_connectivities.size() << endl;

  // Close mesh file in vtk format
  ifs.close();

  // Initialize stretch node (ScalarFieldNode type)
  vector<ScalarFieldNode<3>* > stretchNodes, directionNodes;
  stretchNodes.reserve(Ns_eta);   directionNodes.reserve(Ns_theta);

  NodeBase::DofIndexMap idE(1);
  ScalarFieldNode<3>::PositionVector pE(0.0);
  unsigned int id = nodes.size();

  // min = 3 -> both, 2 -> only theta, 1-> only eta, 0-> none
  ScalarFieldNode<3>* phiNode = NULL;
  // blitz::Array<double,1> LowerBound, UpperBound;
  // blitz::Array<int,1> BoundType;
  int NumDOF = 0;
  // Determine number of DOF we will solve for
  switch (min)
  {
    case 0:
      NumDOF = nodes.size()*3;
      break;
    case 1:
      NumDOF = nodes.size()*3 + Ns_eta;
      break;
    case 2:
      NumDOF = nodes.size()*3 + Ns_theta;
      if (WcType == 5 || WcType == 6) {
	NumDOF += 1; // including phi dof
      }
      break;
    case 3:
      NumDOF = nodes.size()*3 + Ns_eta + Ns_theta;
      if (WcType == 5 || WcType == 6) {
	NumDOF += 1; // including phi dof
      }
      break;
    default:
      cout << "Minimization case not implemented!" << endl;
      return(0);
  }

  if (min == 0 || min == 1 || min ==3)
  {
    // Initialize bound of dof
    // LowerBound.resize(NumDOF);
    // UpperBound.resize(NumDOF);
    // BoundType.resize(NumDOF);
    // LowerBound = 0.0;
    // UpperBound = 0.0;
    // BoundType  = 0;  // Default is no bound

    for (i = 0; i < Ns_eta; i++)
    {
      idE[0] = dof++;
      ScalarFieldNode<3>* stretchN = new ScalarFieldNode<3>(id, idE, pE, in_eta);
      // if (min != 0) {
	// BoundType(idE[0]) = 1;  // Only lower bound
	// LowerBound(idE[0]) = 1.0 + WcConst[1];
      // }
      id++;
      stretchNodes.push_back(stretchN);
    }
    // ! To keep some of the dof constant we can decide to not insert them in Model BUT
    // THIS ONLY WORKS IF the constant dof are numbered last
    for (i = 0; i < Ns_theta; i++)
    {
      idE[0] = dof++;
      ScalarFieldNode<3>* dirN = new ScalarFieldNode<3>(id, idE, pE, in_theta);
      id++;
      directionNodes.push_back(dirN);
    }
    if (WcType == 5 || WcType == 6) {
      idE[0] = dof++;
      phiNode = new ScalarFieldNode<3>(id, idE, pE, in_phi);
      id++;
    }
  }
  else
  {
    // ! To keep some of the dof constant we can decide to not insert them in Model BUT
    // THIS ONLY WORKS IF the constant dof are numbered last
    for (i = 0; i < Ns_theta; i++)
    {
      idE[0] = dof++;
      ScalarFieldNode<3>* dirN = new ScalarFieldNode<3>(id, idE, pE, in_theta);
      id++;
      directionNodes.push_back(dirN);
    }
    if (WcType == 5 || WcType == 6) {
       idE[0] = dof++;
       phiNode = new ScalarFieldNode<3>(id, idE, pE, in_phi);
       id++;
    }
    for (i = 0; i < Ns_eta; i++)
    {
      idE[0] = dof++;
      ScalarFieldNode<3>* stretchN = new ScalarFieldNode<3>(id, idE, pE, in_eta);
      id++;
      stretchNodes.push_back(stretchN);
    }
  }

  // Create bending body; SCElastic only has curvature terms, no in-plane strain terms
  int quadOrder = 1;

  // Bending material object, to be copied when body generates new elements
  typedef SCElastic BendingMaterial;
  BendingMaterial bending(KC,KG,C0);

  // Bending body will generate a mesh of Loop Subdivision shell elements from the connectivity and nodes
  typedef LoopShellBody<BendingMaterial> LSB;
  LSB * bending_body = new LSB(bending, connectivities, nodes, quadOrder);
  // Use the body's output routines to generate vtk files with results
  bending_body->setOutput(paraview);
  bending_body->compute(true, false, false);
  cout << "En_Bend = " << bending_body->totalStrainEnergy() << endl;
  cout << "En_Bend = " << bending_body->energy() << endl;
  // bending_body->checkConsistency();

  // Create two stretching bodies, one for pents and one for hex's, which don't have any bending energy
  // (bending moduli set to zero)
  // Use EvansElastic Material, which separates area strain from pure stretch strain (at constant area).

  // Pentamers
  typedef EvansElastic PentStretchingMaterial;
  PentStretchingMaterial PentStretch(0.0, 0.0, 0.0, mu, kS);

  // Use generic C0MembraneBody for stretching of pents, with the EvansElastic material.
  typedef C0MembraneBody<TriangleQuadrature, PentStretchingMaterial, ShapeTri3> pent_membrane;
  pent_membrane * pentamer_body = new pent_membrane(PentStretch, pent_connectivities, nodes, quadOrder);
  pentamer_body->setOutput(paraview);
  pentamer_body->compute(true, false, false);
  cout << "En_Pent = " << pentamer_body->totalStrainEnergy() << endl;
  cout << "En_Pent = " << pentamer_body->energy() << endl;
  // pentamer_body->checkConsistency();

  // Hexamers
  // Use specialezed StretchHexonBody (modified version of C0MembraneBody), which has material hard-coded as
  // ModifiedEvansElastic, which takes care of the multiplicative F=AG "Eigen-strain" decomposition.

  // Correct the stretch modulus if using double-well potential.
  // Not necessary if using single-well.
  // mu = mu/(2*(eta*eta+c2)+2*c1);
  TriangleQuadrature  HexQuad(1);
  const ShapeTri3::CoordinateArray dummy(0.0);
  ShapeTri3 HexShape(dummy);

  // Shift in initial hexamer configuration
  inp.open(AngleShiftFile.c_str(), ios::in);
  if (!inp) {
    cout << "Cannot open input file: " << AngleShiftFile << endl;
    return(0);
  }

  // For T9
  vector<double > VAngleShift(directionNodes.size(), 0.0);
  for (i = 0; i < VAngleShift.size(); i++)
  {
    inp >> VAngleShift[i];
    VAngleShift[i] *= (M_PI/3.0);
    // cout << VAngleShift[i] << endl;
  }

  unsigned int CurrentCap = 0;
  ind = 0;
  for (unsigned int elT = 0; elT < stretch_angle.size(); elT++)
  {
    if (CapsomersNum[elT] != CurrentCap) {
      ind++;
      CurrentCap = CapsomersNum[elT];
      // cout << CurrentCap << endl;
    }
    stretch_angle[elT] = VAngleShift[ind];
    // cout <<  stretch_angle[elT] << endl;
  }

  StretchHexonBody * hex_body = new StretchHexonBody(hex_connectivities, defNodes, stretchNodes, directionNodes, stretch_angle, mu, kS, WcType, WcConst, HexQuad, &HexShape, CapsomersNum, phiNode);
  hex_body->setOutput(paraview);
  hex_body->compute(true, false, false);
  cout << "En_Hex    = " << hex_body->totalStrainEnergy() << endl;
  cout << "En_Hex    = " << hex_body->energy() << endl;
  cout << "Wconf_Hex = " << hex_body->totalConformationalEnergy() << endl;
  // hex_body->checkConsistency();

  // Set reference configuration
  // Define the edge length of the canonical
  // const double EDGELEN = 2.0; - > AvgEdgeLength is used instead

  bending_body->SetRefConfiguration(AvgEdgeLength);
  pentamer_body->SetRefConfiguration(AvgEdgeLength);
  hex_body->SetRefConfiguration(AvgEdgeLength);

  cout << "Reference configuration has been imposed " << endl;

  //   pentamer_body->SetRefConfiguration(2.0);
  //   hex_body->SetRefConfiguration(2.0);

  /*
NearNeighList[3] = 75;   // Surrounding three fold site

  vector<vector<unsigned int > > TestShift(81, vector<unsigned int >(4,0));
  unsigned int i = 0, j = 0, k = 0, l = 0, ind = 0;
  for (j = 0; j<3, j++) {
    for (k = 0; k<3, k++) {
      for (l = 0; l<3, l++) {
	for (i = 0; i<3, i++) {
	  TestShift[ind]
  // Shift in initial hexamer configuration
  inp.open(RefAngleFile.c_str(), ios::in);
  if (!inp) {
    cout << "Cannot open input file: " << RefAngleFile << endl;
    return(0);
  }

  // For T9
  vector<double > VRefAngle(stretchNodes.size(), 0.0);
  for (i = 0; i < VRefAngle.size(); i++)
  {
    inp >> VRefAngle[i];
    VRefAngle[i] *= (M_PI/3.0);
    cout << VRefAngle[i] << endl;
  }

  vector<double > AngleOffset(stretch_angle.size(), 0.0);
  unsigned int CurrentCap = 0, ind = 0;
  for (unsigned int elT = 0; elT < stretch_angle.size(); elT++)
  {
    if (CapsomersNum[elT] != CurrentCap) {
      ind++;
      CurrentCap = CapsomersNum[elT];
      cout << CurrentCap << endl;
    }
    AngleOffset[elT] = VRefAngle[ind];
  }

  // assign new angle offset
  hex_body->setAngleOffset(AngleOffset);
  */

  switch (min) {
  case 1: // stretch magnitude is a dof
    nodes.insert(nodes.end(), stretchNodes.begin(), stretchNodes.end());
    break;
  case 2: // stretch direction is a dof
    nodes.insert(nodes.end(), directionNodes.begin(), directionNodes.end());
    if (WcType == 5 || WcType == 6) {
      nodes.push_back(phiNode);
    }
    break;
  case 3: // stretch direction is a dof
    nodes.insert(nodes.end(), stretchNodes.begin(), stretchNodes.end());
    nodes.insert(nodes.end(), directionNodes.begin(), directionNodes.end());
    if (WcType == 5 || WcType == 6) {
      nodes.push_back(phiNode);
    }
    break;
  }

  // Create Model
  Model::BodyContainer bdc;
  bdc.push_back(bending_body);
  bdc.push_back(pentamer_body);
  bdc.push_back(hex_body);

  Model model(bdc, nodes);
  // Consistency check
  // model.checkConsistency(true,false);
  // model.checkRank(model.dof()-6,true);

  // Set solver and solve
  int iprint = 0;
  double factr = 1.0e1;
  double pgtol = 1.0e-8; // Previously 1.0e-6
  int m = 10;            // Previously 5
  int maxIter = 30000;
  std::ifstream lbfgsbinp("lbfgsb.inp");
  lbfgsbinp >> iprint >> factr >> pgtol >> m;
  cout << endl << "Input iprint: " << iprint << endl
       << "Input factr:  " << factr  << endl
       << "Input pgtol:  " << pgtol  << endl
       << "Input m:      " << m      << endl;

  Lbfgsb solver(model.dof(), m, factr, pgtol, iprint, maxIter);
  // Set bounds on eta variables (if any)
  // if ((min == 1 || min ==3) && WcType == 6)
  // {
  //   solver.setBounds(BoundType, LowerBound, UpperBound);
  // }
  cout << "Bound  DOF = " << NumDOF << endl;
  cout << "Solver DOF = " << model.dof() << endl;

  // Fill in angle vectors needed for output
  vector<double > SymmIndex(6, 0.0);
  vector<vector<unsigned int > > NOTused;
  PrintingStretches PrintTvirus(modelName, OutlineName, NPout,
				OutFile+"iter", OutFile+"outline", OutFile+"directions", OutFile+"elemdir", 1,
				bdc, stretchNodes, directionNodes, CapsomersNum,
				VAngleShift, ZeroAngles, HexonShift, WcConst[1], AvgEdgeLength, refinement, false, NOTused, 0);
  SymmIndex = PrintTvirus.printMaster(0);
  cout << "Initial symmetry indices " << endl;
       cout << "Nodes index (hex) = " << std::setprecision(12) << SymmIndex[0] << endl;
       cout << "Eta index   (hex) = " << std::setprecision(12) << SymmIndex[1] << endl;
       cout << "Theta index (hex) = " << std::setprecision(12) << SymmIndex[2] << endl;
       cout << "Nodes index (el)  = " << std::setprecision(12) << SymmIndex[3] << endl;
       cout << "Eta index   (el)  = " << std::setprecision(12) << SymmIndex[4] << endl;
       cout << "Theta index (el)  = " << std::setprecision(12) << SymmIndex[5] << endl;

  PrintTvirus.setPrintingConfig(true);

   // Compute FvK number before solving
   double FvK = 0.0, Y = 0.0;
   Y = 4.0*kS*mu/(kS+mu);
   FvK = Y*Ravg*Ravg/KC;
   cout << " FvK number before solving = " << FvK           << endl;

   srand(time(NULL));
   // Solve to minimize the energy
   if (AnType == 0)  // Frustration case
   {

     // Other Three fold site hexamers
     set<unsigned int > OtherTFS;
     OtherTFS.insert(15); OtherTFS.insert(20); OtherTFS.insert(26); OtherTFS.insert(31);
     OtherTFS.insert(35); OtherTFS.insert(39); OtherTFS.insert(43); OtherTFS.insert(49);
     OtherTFS.insert(52); OtherTFS.insert(56); OtherTFS.insert(59); OtherTFS.insert(65);
     OtherTFS.insert(68); OtherTFS.insert(72); OtherTFS.insert(78); OtherTFS.insert(79);

     /*
     // Select 16 random numbers (equivalent to the number of other 3 fold sites)
     map<uint, double> randBackGround;

     cout << "Randnumber = ";
     for (set<uint>::iterator r = OtherTFS.begin(); r != OtherTFS.end(); r++) {
       double randnumber = double(rand()%3);
       randBackGround.insert(make_pair(*r, randnumber));
       VAngleShift[*r] = randnumber*M_PI/3.0;
       cout << *r << " " << randnumber << endl;
     }
     cout << endl;

     // Change randomly the background of T9
     for (j = 0; j < stretch_angle.size(); j++) {
       if (OtherTFS.find(CapsomersNum[j]) != OtherTFS.end())
       {
	 stretch_angle[j] = randBackGround[CapsomersNum[j]]*M_PI/3.0;
       }
     }
     */

     // Set all other 3 fold site to have zero stretch - An_I
     for (j = 0; j < stretchNodes.size(); j++) {
       if (OtherTFS.find(j) != OtherTFS.end())
       {
	 stretchNodes[j]->setPoint(1.0);
       }
     }

     // Explore 81 cases for one triplet
     for (i = 0; i < TestShift.size(); i++) {
       for (j = 0; j < stretch_angle.size(); j++) {
	 if (CapsomersNum[j] == NearNeighList[0])
	 {
	   stretch_angle[j]             = TestShift[i][0]*M_PI/3.0;
	   VAngleShift[CapsomersNum[j]] = TestShift[i][0]*M_PI/3.0;
	 }
	 else if (CapsomersNum[j] == NearNeighList[1])
	 {
	   stretch_angle[j]             = TestShift[i][1]*M_PI/3.0;
	   VAngleShift[CapsomersNum[j]] = TestShift[i][1]*M_PI/3.0;
	 }
	 else if (CapsomersNum[j] == NearNeighList[2])
	 {
	   stretch_angle[j]             = TestShift[i][2]*M_PI/3.0;
	   VAngleShift[CapsomersNum[j]] = TestShift[i][2]*M_PI/3.0;
	 }
	 else if (CapsomersNum[j] == NearNeighList[3])
	 {
	   stretch_angle[j]             = TestShift[i][3]*M_PI/3.0;
	   VAngleShift[CapsomersNum[j]] = TestShift[i][3]*M_PI/3.0;
	 }
       }

       // assign new angle offset
       hex_body->setAngleOffset(stretch_angle);

       // Solve
       solver.solve(&model);
       double Wtot = bending_body->totalStrainEnergy() +  pentamer_body->totalStrainEnergy() + hex_body->totalStrainEnergy();
       cout << "STATE = " << i << endl;
       cout << "State = " << TestShift[i][0] << " " << TestShift[i][1] << " " << TestShift[i][2] << " " << TestShift[i][3] << " " << Wtot << endl;
       cout << "Wconf = " <<  hex_body->totalConformationalEnergy() << endl;

       SymmIndex = PrintTvirus.printMaster(i);
       cout << "Symmetry Index " << endl;
       cout << "Nodes index (hex) = " << std::setprecision(12) << SymmIndex[0] << endl;
       cout << "Eta index   (hex) = " << std::setprecision(12) << SymmIndex[1] << endl;
       cout << "Theta index (hex) = " << std::setprecision(12) << SymmIndex[2] << endl;
     }

     // Testing far away shielding in 20 cases
         // Setting neighbor three fold sites in the 112 configuration
         // Setting neighbor three fold sites in the 002 configuration
         for (j = 0; j < stretch_angle.size(); j++) {
	   if (CapsomersNum[j] == NearNeighList[1])
	   {
	     stretch_angle[j]             = 0.0; // M_PI/3.0; // 0.0;
	     VAngleShift[CapsomersNum[j]] = 0.0; // M_PI/3.0; // 0.0;
	   }
	   else if (CapsomersNum[j] == NearNeighList[2])
	   {
	     stretch_angle[j]             = 0.0; // M_PI/3.0; // 0.0;
	     VAngleShift[CapsomersNum[j]] = 0.0; // M_PI/3.0; // 0.0;
	   }
	   else if (CapsomersNum[j] == NearNeighList[3])
	   {
	     stretch_angle[j]             = 2.0*M_PI/3.0;
	     VAngleShift[CapsomersNum[j]] = 2.0*M_PI/3.0;
	   }
	 }

	 /*
     // Look at 20 randomly generated cases
     srand(time(NULL));
     for (i=0; i<20; i++)
     {
       // Change one Three fold site in the background at the time
       /*
       set<unsigned int >::iterator OtherTFSit = OtherTFS.begin();
       advance(OtherTFSit, rand()%16);
       for (j = 0; j < stretch_angle.size(); j++) {
	 if ( *OtherTFSit == CapsomersNum[j] )
	 {
	   cout << "Changed TFS " << *OtherTFSit << endl;
	   double randNumber = double(rand()%3);
	   stretch_angle[j]             = randNumber*M_PI/3.0;
	   VAngleShift[CapsomersNum[j]] = randNumber*M_PI/3.0;
	 }
       }

       // Change All three fold sites in the background at once
       cout << "randnumber = ";
       randBackGround.clear();
       for (set<uint>::iterator r = OtherTFS.begin(); r != OtherTFS.end(); r++) {
	 double randnumber = double(rand()%3);
	 randBackGround.insert(make_pair(*r, randnumber));
	 VAngleShift[*r] = randnumber*M_PI/3.0;
	 cout << *r << " " << randnumber << endl;
       }
       cout << endl;

       // Change randomly the background of T9
       for (j = 0; j < stretch_angle.size(); j++) {
	 if (OtherTFS.find(CapsomersNum[j]) != OtherTFS.end())
	   {
	     stretch_angle[j] = randBackGround[CapsomersNum[j]]*M_PI/3.0;
	   }
       }

       for (k = 0; k < 3; k++) {
	 for (j = 0; j < stretch_angle.size(); j++) {
	   if (CapsomersNum[j] ==  NearNeighList[0])
	   {
	     stretch_angle[j]             = k*M_PI/3.0;
	     VAngleShift[CapsomersNum[j]] = k*M_PI/3.0;
	   }
	 }

	 // assign new angle offset
	 hex_body->setAngleOffset(stretch_angle);

	 // Solve
	 solver.solve(&model);
	 double Wtot = bending_body->totalStrainEnergy() +  pentamer_body->totalStrainEnergy() + hex_body->totalStrainEnergy();
	 cout << "STATE = " << i*3 + k + 81 << endl;
	 // cout << "State = " << k << " " << TestShift[80][1] << " " << TestShift[80][2] << " " << TestShift[80][3] << " " << Wtot << endl;
	 cout << "State = " << k << " 1 1 2 " << Wtot << endl;
	 cout << "Wconf = " << hex_body->totalConformationalEnergy() << endl;

	 SymmIndex = PrintTvirus.printMaster(i*3 + k + 81);
	 cout << "Symmetry Index " << endl;
	 cout << "Nodes index (hex) = " << std::setprecision(12) << SymmIndex[0] << endl;
	 cout << "Eta index   (hex) = " << std::setprecision(12) << SymmIndex[1] << endl;
	 cout << "Theta index (hex) = " << std::setprecision(12) << SymmIndex[2] << endl;
       }
     }*/

   }
   else if(AnType == 1)
   {
     // Three fold sites hexamers
     set<unsigned int > OtherTFS;
     OtherTFS.insert(3);  OtherTFS.insert(8);  OtherTFS.insert(24); OtherTFS.insert(75);
     OtherTFS.insert(15); OtherTFS.insert(20); OtherTFS.insert(26); OtherTFS.insert(31);
     OtherTFS.insert(35); OtherTFS.insert(39); OtherTFS.insert(43); OtherTFS.insert(49);
     OtherTFS.insert(52); OtherTFS.insert(56); OtherTFS.insert(59); OtherTFS.insert(65);
     OtherTFS.insert(68); OtherTFS.insert(72); OtherTFS.insert(78); OtherTFS.insert(79);
     // Look at NumEnergy randomly generated cases
     srand(time(NULL));
     for (i=0; i<NumEnergy; i++)
     {
       cout << "State " << i << " ";
       for (j = 0; j < stretch_angle.size(); j++) {
	 if (OtherTFS.find(CapsomersNum[j]) != OtherTFS.end())
	 {
	   double randNumber = double(rand()%3);
	   stretch_angle[j]             = randNumber*M_PI/3.0;
	   VAngleShift[CapsomersNum[j]] = randNumber*M_PI/3.0;
	   cout << randNumber << " ";
	 }
       }
       cout << endl;

       // assign new angle offset
       hex_body->setAngleOffset(stretch_angle);

       // Solve
       solver.solve(&model);
       double Wtot = bending_body->totalStrainEnergy() +  pentamer_body->totalStrainEnergy() + hex_body->totalStrainEnergy();
       cout << "State = " << i << " " << Wtot << endl;
       cout << "Wconf = " << hex_body->totalConformationalEnergy() << endl;

       // if ((i%100) == 0)
       // {
             SymmIndex = PrintTvirus.printMaster(i);
       // }

       cout << "Symmetry Index " << endl;
       cout << "Nodes index (hex) = " << std::setprecision(12) << SymmIndex[0] << endl;
       cout << "Eta index   (hex) = " << std::setprecision(12) << SymmIndex[1] << endl;
       cout << "Theta index (hex) = " << std::setprecision(12) << SymmIndex[2] << endl;
     }

   }
   else if(AnType == 2)
   {

   }

  // Calculate capsid center, average radius and asphericity
  tvmet::Vector<double,3> center(0.0);
  Ravg = 0.0;
  double deltaR = 0.0, Rtemp = 0.0, asphericity = 0.0;
  for(i = 0; i < defNodes.size(); i++)
  {
    center += defNodes[i]->point();
    Ravg += tvmet::norm2(defNodes[i]->point());
  }
  center /= defNodes.size();
  Ravg /= defNodes.size();
  cout << endl << "Center      = " << center  << endl;

  for(i = 0; i < defNodes.size(); i++)
  {
    Rtemp = tvmet::norm2(defNodes[i]->point());
    deltaR += pow(Rtemp-Ravg,2);
  }
  asphericity = sqrt( deltaR/defNodes.size() )/Ravg;

  // Compute max difference in eta and theta
  double EtaMaxDiff = 0.0, EtaTempDiff = 0.0;
  if (Ns_eta > 1)
  {
    EtaMaxDiff = abs(stretchNodes[1]->point()-stretchNodes[0]->point());
    for (i = 1; i < Ns_eta-1; i++)
    {
      EtaTempDiff = abs(stretchNodes[i+1]->point()-stretchNodes[i]->point());
      if ( EtaTempDiff > EtaMaxDiff ) EtaMaxDiff = EtaTempDiff;
    }
  }

  //---------------//
  // Print results //
  // Print the total energies of three bodies

  double  Wben = 0.0, Wpen = 0.0, Whex = 0.0, Wtot = 0.0, Wconf = 0.0;
  FvK = Y*Ravg*Ravg/KC;
  Wben  =  bending_body->totalStrainEnergy();
  Wpen  =  pentamer_body->totalStrainEnergy();
  Whex  =  hex_body->totalStrainEnergy();
  Wconf =  hex_body->totalConformationalEnergy();
  Wtot = Wben + Wpen + Whex;
  cout << "----------------------------------------" << endl;

    cout << " Stretch magnitude     = " << endl;
    for (i = 0; i < Ns_eta; i++)
    {
      cout << stretchNodes[i]->point() << "  ";
      if ( (i+1)%5 == 0 || i == Ns_eta-1 ) cout << endl;
    }

    cout << " Direction angle     = " << endl;
    for (i = 0; i < Ns_theta; i++)
    {
      cout << directionNodes[i]->point() << "  ";
      if ( (i+1)%5 == 0 || i == Ns_theta-1 ) cout << endl;
    }

  cout << " Max diff. in eta    = " << EtaMaxDiff       << endl;
  if (WcType == 5 || WcType == 6) {
    cout << " phiNode             = " << phiNode->point() << endl;
  }
  cout << " FvK number          = " << FvK              << endl;
  cout << " Bending energy      = " << Wben             << endl;
  cout << " Pent Stretch energy = " << Wpen             << endl;
  cout << " Hex  Stretch energy = " << Whex             << endl;
  cout << " Hex conform. energy = " << Wconf            << endl;
  cout << " Total energy        = " << Wtot             << endl;
  cout << " Total def. energy   = " << Wtot - Wconf     << endl;
  cout << " Asphericity         = " << asphericity      << endl;
  cout << " Ravg                = " << Ravg             << endl;
  cout << " AverageEdgeLength   = " << AvgEdgeLength    << endl;
  cout << "Final nodes symm index (hex) = " << std::setprecision(12) << SymmIndex[0] << endl;
  cout << "Final eta   symm index (hex) = " << std::setprecision(12) << SymmIndex[1] << endl;
  cout << "Final theta symm index (hex) = " << std::setprecision(12) << SymmIndex[2] << endl;
  cout << "Final nodes symm index (el)  = " << std::setprecision(12) << SymmIndex[3] << endl;
  cout << "Final eta   symm index (el)  = " << std::setprecision(12) << SymmIndex[4] << endl;
  cout << "Final theta symm index (el)  = " << std::setprecision(12) << SymmIndex[5] << endl;
  cout << "-----------------------------------------"   << endl;

  time (&end);
  dif = difftime (end,start);
  cout << endl << "All done :) in " << dif  << " s" << endl;

  // Clean up
  delete bending_body;
  delete pentamer_body;
  delete hex_body;

  for (i = 0; i<nodes.size(); i++)
  {
    delete nodes[i];
  }

  switch (min) {
  case 0:
    for (i = 0; i<Ns_eta; i++)
    {
      delete stretchNodes[i];
    }
    for (i = 0; i<Ns_theta; i++)
    {
      delete directionNodes[i];
    }
    break;
  case 1:
    for (i = 0; i<Ns_theta; i++)
    {
      delete directionNodes[i];
    }
    break;
  case 2:
    for (i = 0; i<Ns_eta; i++)
    {
      delete stretchNodes[i];
    }
    break;
  }

  return (0);

}


text:
{-# LANGUAGE CPP #-}

-- | Formatting of Haddock documentation.

module Haskell.Docs.Formatting where

import Haskell.Docs.Ghc
import Haskell.Docs.HaddockDoc
import Haskell.Docs.Types

import Control.Monad
import Data.List
import Documentation.Haddock
import GHC hiding (verbosity)
import GhcMonad (liftIO)

-- * Formatting

-- | Print docs as s-expressions.
printSexp :: [IdentDoc] -> Ghc ()
printSexp = mapM toSexp >=> liftIO . putStrLn . renderSexp . List

-- | Print an identifier' documentation.
printIdentDoc :: Bool -- ^ Print modules only?
              -> Bool -- ^ Print package?
              -> Bool -- ^ Print module?
              -> IdentDoc
              -> Ghc ()
printIdentDoc True _ _ idoc =
  do d <- getSessionDynFlags
     maybe (liftIO (putStrLn (showppr d (identDocModuleName idoc))))
           (\i -> liftIO (putStrLn (showppr d (moduleName (nameModule (getName i))))))
           (identDocIdent idoc)
printIdentDoc _ printPkg printModule idoc =
  do d <- getSessionDynFlags
     when printPkg
          (liftIO (putStrLn ("Package: " ++ showPackageName (identDocPackageName idoc))))
     when printModule
          (maybe (liftIO (putStrLn ("Module: " ++ showppr d (identDocModuleName idoc))))
                 (\i -> liftIO (putStrLn ("Module: " ++
                                          showppr d (moduleName (nameModule (getName i))))))
                 (identDocIdent idoc))
     case identDocIdent idoc of
       Nothing -> liftIO (putStrLn (unIdentifier (identDocIdentifier idoc)))
       Just i -> liftIO (putStrLn (showppr d i ++ " :: " ++ showppr d (idType i)))
     liftIO (putStrLn (formatDoc (identDocDocs idoc)))
     case identDocArgDocs idoc of
       Nothing -> return ()
       Just args -> liftIO (putStr (unlines (map (\(i,x) -> formatArg i x) args)))

-- | Format some documentation to plain text.
formatDoc :: Doc String -> String
formatDoc = trim . doc where

-- * Internal functions

-- | S-expression type.
data Sexp
  = Atom String
  | String String
  | List [Sexp]

-- | Render an s-expression to string.
renderSexp :: Sexp -> String
renderSexp (Atom string) = string
renderSexp (String string) = show string
renderSexp (List sexps) = "(" ++ intercalate " " (map renderSexp sexps) ++ ")"

-- | Convert docs to an s-expression.
toSexp :: IdentDoc -> Ghc Sexp
toSexp idoc =
  do d <- getSessionDynFlags
     return (List (concat (object d)))
  where
    object d =
      [[List [Atom "package",String (showPackageName (identDocPackageName idoc))]]
      ,[List [Atom "module",String (showppr d (moduleName (nameModule (getName i))))]
       |Just i <- [identDocIdent idoc]]
      ,[List [Atom "type",String (showppr d (idType i))]
       |Just i <- [identDocIdent idoc]]
      ,[List [Atom "arguments",List ((map (\(i,x) -> String (formatArg i x)) args))]
       |Just args <- [identDocArgDocs idoc]]
      ,[List [Atom "documentation",String (formatDoc (identDocDocs idoc))]]]

-- | Format an argument.
formatArg :: Show a => a -> Doc String -> String
formatArg i x = prefix ++
                indentAfter (length prefix) (formatDoc x)
  where prefix = show i ++ ": "

-- | Indent after the first line.
indentAfter :: Int -> String -> String
indentAfter i xs = intercalate "\n" (take 1 l ++ map (replicate (i-1) ' ' ++) (drop 1 l))
  where l = lines xs


text:
@implementation NSString (Extension)
- (NSString *)getUTF8String
{
   return (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef)self, nil,(CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
}

- (id)jsonValue;
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}

@end


text:
package org.jadira.usertype.dateandtime.joda;

import java.sql.Time;

import org.hibernate.usertype.ParameterizedType;
import org.jadira.usertype.dateandtime.joda.columnmapper.TimeColumnLocalTimeMapper;
import org.jadira.usertype.spi.shared.AbstractParameterizedTemporalUserType;
import org.jadira.usertype.spi.shared.IntegratorConfiguredType;
import org.joda.time.LocalTime;

/**
 * Persist {@link LocalTime} via Hibernate as a SQL TIME datatype - note that sub-second values will not
 * be retained. This type is basically compatible with org.joda.time.contrib.hibernate.PersistentLocalTimeAsTime.
 * However, note that org.joda.time.contrib.hibernate.PersistentLocalTimeAsTime contains a bug where times written
 * down will be offset from GMT due to its use of {@link java.sql.Time#setTime(long)}. This class is not affected by this
 * issue, but this means you cannot rely on the interpretation of this type to be the same for both classes.
 *
 * The type is stored using the timezone as configured
 * using Hibernate's configuration property 'hibernate.jdbc.time_zone' and presented in the
 * JVM using the JVM's default zone. You can optionally override or use as an alternative to this property the
 * parameter 'databaseZone' on this type.
 */
public class PersistentLocalTime extends AbstractParameterizedTemporalUserType<LocalTime, Time, TimeColumnLocalTimeMapper> implements ParameterizedType, IntegratorConfiguredType {

	private static final long serialVersionUID = 3987595078868454461L;
}


text:
try:
    import django
except ImportError:
    raise ImportError('devour requires django to be installed when using ProducerModel')
import os

os.environ.setdefault('KAFKA_SETTINGS_PATH', os.environ.get('DJANGO_SETTINGS_MODULE'))


text:
published: true
layout: post
title: Error en la operación de instantánea de volumen
date: 2015-02-27
categories: ti windows server 2008 r2
---

"Respalda y sobrevivirás". Existen tareas que los IT Manager simplemente no pueden dejar de hacer, una de ellas tiene que ver con realizar respaldos de los datos generados por los usuarios y los sistemas. En lo particular, esta buena práctica me ha salvado en mas de una ocasión de tener que pasar horas y horas recreando información de días anteriores dañada o borrada accidentalmente.

Una buena herramienta para asegurar el respaldo de información son las copias de seguridad que el Windows por defecto maneja, por lo que diariamente establezco una tarea que copia mis archivos mas importantes que la empresa genera en discos y cintas magneticas externas.

Esto para mi representa un gran alivio ya que permite contar con toda la información de un día anterior de manera segura, integra y confiable. Además permite olvidarme de realizar manualmente respaldos y ocuparme en cosas mas importantes.

Cierto día, uno de los discos duros de mi servidor se encontraba en el límite de espacio disponible, por lo que decidí incrementar su capacidad, gracias a la flexibilidad que me da el que mi servidor sea virtual, administrado con VMware; esto no era la primera vez que lo hacia, y no habia tenido problemas. Cuál fue mi sorpresa que al día siguiente (Windows tan bipolar), la copia de seguridad tan importante que les comentaba no se realizó. Lo relacione rápidamente con el ajuste de capacidad del disco que habia realizado una noche antes y me dije, bueno, es una de las tantas misiones a la que nos enfrentamos diariamente, pensé de manera optimista, siempre hay que enfrentar los problemas así, al final, es mas facil dar con las soluciones a los problemas.

El problema en cuestión estaba registrado en los logs como:

> "Error en una operación del servicio instantáneo del volumen. Error detallado: Error en la operación de instantánea de volumen 0x800423F4"

Despúes de investigar un buen rato en Internet, llegue a la conclusión de que lo primero que hay que verificar es la información que [Vssadmin](https://technet.microsoft.com/en-us/library/cc754968.aspx) proporciona y ponerle atención a los servicios o "writers" a través del comando:

``` console
Vssadmin list writers
```

El comando me desplegó la lista de servicios que operan la copia de seguridad, todos trabajando sin errores con excepción de uno con nombre "SqlServerWriter".

<img src="/img/sqlserverwriter-error.png" width="600">

``` console
Nombre de editor: 'SqlServerWriter'
   Id. de editor: {a65faa63-5ea8-4ebc-9dbd-a0c4db26912a}
   Id. de instancia de editor: {c6cf9ed4-3a9d-4fc0-ad7a-765baab12212}
   Estado: [8] Error
   Último error: Error. No puede volver a intentar la operación
```

Con este resultado bastó con reiniciar el servicio relacionado al Vssadmin en la consola de servicios de mi servidor; en la pantalla ejecutar escribimos services.msc, buscamos el servicio con el nombre SQL Server VSS Writer, lo detenemos y lo volvemos a iniciar. Verificamos de nuevo la lista con "list writers" y podemos observar que el servicio ya no marca error:

``` console
Nombre de editor: 'SqlServerWriter'
   Id. de editor: {a65faa63-5ea8-4ebc-9dbd-a0c4db26912a}
   Id. de instancia de editor: {28d5b58a-c12d-4466-aab9-50778c34fef8}
   Estado: [1] Estable
   Último error: Sin errores
```

Aplicamos el mismo procedimiento en cada servicio con errores.

Solo bastó de esto para que las copias volvieran a su normalidad y yo pudiera dormir tranquilo otra vez :)

__ACTUALIZACIÓN 28/07/2015:__

La opción anterior dejó de funcionar. En su lugar, opté por detener por completo el servicio **SqlServerWriter** y mis copias de seguridad volvieron a funcionar.

¿Tienes algún problema con aplicar esto? Sin problemas puedes preguntarme en [Twitter](http://twitter.com/JoseRobertoMx), con gusto podemos encontrar alguna solución.

Gracias por leerme!


text:
window.App = {
    namespace : function(namespace){

    }
};