text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Simple Error Handlers for NancyFX.")]
[assembly: AssemblyDescription("Some simple error handling for Nancy applications.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("World Domination Technologies Pty. Ltd.")]
[assembly: AssemblyProduct("Nancy.SimpleErrorHandlers")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("703090a8-b0c9-40dc-af83-7d629aaab8aa")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]


text:
from mythril.laser.ethereum.svm import LaserEVM
from mythril.laser.ethereum.state.account import Account
from mythril.laser.ethereum.state.world_state import WorldState
from mythril.disassembler.disassembly import Disassembly
from mythril.laser.ethereum.transaction.concolic import execute_message_call
from mythril.laser.smt import Expression, BitVec, symbol_factory
from mythril.analysis.solver import get_model
from datetime import datetime

import binascii
import json
import os
from pathlib import Path
import pytest
from z3 import ExprRef, simplify

evm_test_dir = Path(__file__).parent / "VMTests"

test_types = [
    "vmArithmeticTest",
    "vmBitwiseLogicOperation",
    "vmEnvironmentalInfo",
    "vmPushDupSwapTest",
    "vmTests",
    "vmSha3Test",
    "vmSystemOperations",
    "vmRandomTest",
    "vmIOandFlowOperations",
]

tests_with_gas_support = ["gas0", "gas1"]
tests_with_block_number_support = [
    "BlockNumberDynamicJumpi0",
    "BlockNumberDynamicJumpi1",
    "BlockNumberDynamicJump0_jumpdest2",
    "DynamicJumpPathologicalTest0",
    "BlockNumberDynamicJumpifInsidePushWithJumpDest",
    "BlockNumberDynamicJumpiAfterStop",
    "BlockNumberDynamicJumpifInsidePushWithoutJumpDest",
    "BlockNumberDynamicJump0_jumpdest0",
    "BlockNumberDynamicJumpi1_jumpdest",
    "BlockNumberDynamicJumpiOutsideBoundary",
    "DynamicJumpJD_DependsOnJumps1",
]
tests_with_log_support = ["log1MemExp"]
tests_not_relevent = [
    "loop_stacklimit_1020",  # We won't be looping till 1020 as we have a max_depth
    "loop_stacklimit_1021",
]
tests_to_resolve = ["jumpTo1InstructionafterJump", "sstore_load_2", "jumpi_at_the_end"]
ignored_test_names = (
    tests_with_gas_support
    + tests_with_log_support
    + tests_with_block_number_support
    + tests_with_block_number_support
    + tests_not_relevent
    + tests_to_resolve
)

def load_test_data(designations):
    """

    :param designations:
    :return:
    """
    return_data = []
    for designation in designations:
        for file_reference in (evm_test_dir / designation).iterdir():

            with file_reference.open() as file:
                top_level = json.load(file)

                for test_name, data in top_level.items():
                    pre_condition = data["pre"]

                    action = data["exec"]
                    gas_before = int(action["gas"], 16)
                    gas_after = data.get("gas")
                    gas_used = (
                        gas_before - int(gas_after, 16)
                        if gas_after is not None
                        else None
                    )

                    post_condition = data.get("post", {})
                    environment = data.get("env")

                    return_data.append(
                        (
                            test_name,
                            environment,
                            pre_condition,
                            action,
                            gas_used,
                            post_condition,
                        )
                    )

    return return_data

@pytest.mark.parametrize(
    "test_name, environment, pre_condition, action, gas_used, post_condition",
    load_test_data(test_types),
)
def test_vmtest(
    test_name: str,
    environment: dict,
    pre_condition: dict,
    action: dict,
    gas_used: int,
    post_condition: dict,
) -> None:

    # Arrange
    if test_name in ignored_test_names:
        return

    world_state = WorldState()

    for address, details in pre_condition.items():
        account = Account(address, concrete_storage=True)
        account.code = Disassembly(details["code"][2:])
        account.nonce = int(details["nonce"], 16)
        for key, value in details["storage"].items():
            key_bitvec = symbol_factory.BitVecVal(int(key, 16), 256)
            account.storage[key_bitvec] = symbol_factory.BitVecVal(int(value, 16), 256)

        world_state.put_account(account)
        account.set_balance(int(details["balance"], 16))

    laser_evm = LaserEVM()
    laser_evm.open_states = [world_state]

    # Act
    laser_evm.time = datetime.now()

    final_states = execute_message_call(
        laser_evm,
        callee_address=symbol_factory.BitVecVal(int(action["address"], 16), 256),
        caller_address=symbol_factory.BitVecVal(int(action["caller"], 16), 256),
        origin_address=symbol_factory.BitVecVal(int(action["origin"], 16), 256),
        code=action["code"][2:],
        gas_limit=int(action["gas"], 16),
        data=binascii.a2b_hex(action["data"][2:]),
        gas_price=int(action["gasPrice"], 16),
        value=int(action["value"], 16),
        track_gas=True,
    )

    # Assert
    if gas_used is not None and gas_used < int(environment["currentGasLimit"], 16):
        # avoid gas usage larger than block gas limit
        # this currently exceeds our estimations
        gas_min_max = [
            (s.mstate.min_gas_used, s.mstate.max_gas_used) for s in final_states
        ]
        gas_ranges = [g[0] <= gas_used for g in gas_min_max]
        assert all(map(lambda g: g[0] <= g[1], gas_min_max))
        assert any(gas_ranges)

    if post_condition == {}:
        # no more work to do if error happens or out of gas
        assert len(laser_evm.open_states) == 0
    else:
        assert len(laser_evm.open_states) == 1
        world_state = laser_evm.open_states[0]

        for address, details in post_condition.items():
            account = world_state[symbol_factory.BitVecVal(int(address, 16), 256)]

            assert account.nonce == int(details["nonce"], 16)
            assert account.code.bytecode == details["code"][2:]

            for index, value in details["storage"].items():
                expected = int(value, 16)
                actual = account.storage[symbol_factory.BitVecVal(int(index, 16), 256)]
                if isinstance(actual, Expression):
                    actual = actual.value
                    actual = 1 if actual is True else 0 if actual is False else actual
                else:
                    if type(actual) == bytes:
                        actual = int(binascii.b2a_hex(actual), 16)
                    elif type(actual) == str:
                        actual = int(actual, 16)
                assert actual == expected

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Indian Journal of Mycology and Plant Pathology 8: 178 (1902)

#### Original name
Exosporium caespitosum Ellis & Barthol.

### Remarks
null


text:
<?php
namespace Team\Model;

use Doctrine\ORM\Mapping\Entity;

use Team\Form\TeamForm;
use Team\Entity\TeamEntity;
use Team\Model\TeamDAO;

class Team
{
    private $_objTeamEntity;

    public function add($objRequest) {
        $arrData = array('redirect' => false, 'form' => '');

        $objTeamForm = new TeamForm();
        $objTeamForm->get('submit')->setValue('Add');

        if ($objRequest->isPost()) {
            $objTeamForm->setData($objRequest->getPost());

            if ($objTeamForm->isValid()) {
                $objTeamEntity = new TeamEntity();

                $objTeamEntity->exchangeArray($objTeamForm->getData());

                $this->_objTeamEntity->save($objTeamEntity);

                // Redirect to list of teams
                $arrData['redirect'] = 'team';
            }

        }

        $arrData['form'] = $objTeamForm;

        return $arrData;
    }

    public function edit($intId, $objRequest) {
        $arrData = array('redirect' => false, 'form' => '');

        if (!$this->_objTeamEntity) {
            $arrData['redirect'] = 'dashboard';
        } else {
            $objTeamValue = $this->_objTeamEntity->find($intId);

            $objForm = new TeamForm();

            $objForm->bind($objTeamValue);

            if ($objRequest->isPost()) {
                $objForm->setInputFilter($objTeamValue->getInputFilter())->setData($objRequest->getPost());

                if ($objForm->isValid()) {
                    $this->_objTeamEntity->flush();
                    $arrData['redirect'] = 'team';
                }
            }
            $arrData['form'] = $objForm;
        }

        return $arrData;
    }

    public function delete($id, $objRequest) {
        $arrData = array('redirect' => false, 'form' => '');

        if ($objRequest->isPost()) {
            $strDelete = $objRequest->getPost('del', 'No');

            if ($strDelete == 'Yes') {
                $objTeamValue = $this->_objTeamEntity->find($id);

                $this->_objTeamEntity->delete($objTeamValue);
            }

            $arrData['redirect'] = 'team';
        }

        return $arrData;
    }

    public function setEntity($objTeamEntity) {
        $this->_objTeamEntity = $objTeamEntity;
    }
}


text:
//
//  ImgBottomView.m
//  Peanut_Mark1
//
//  Created by 马君 on 14-5-25.
//  Copyright (c) 2014年 viking warlock. All rights reserved.
//

#import "ImgBottomView.h"
#import "CommentViewController.h"
#import "ShareViewController.h"

@implementation ImgBottomView{
    NSInteger feed_id;
    BOOL isPraised;
}

- (id)initWithGroupFeedId:(NSInteger)feedId
{
    self = [super init];
    if (self) {
        isPraised = NO;
        feed_id = feedId ;
        self.frame = CGRectMake(0, [UIScreen mainScreen].applicationFrame.size.height - 80, [UIScreen mainScreen].applicationFrame.size.width, 80);
        [self setBackgroundColor:[UIColor whiteColor]];
        self.alpha = 0.8;

        _praiseBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, (self.frame.size.width - 20)/3, self.frame.size.height)];
        _praiseBtn.contentEdgeInsets = UIEdgeInsetsMake(4, 30, 47, 30);
        [_praiseBtn setImage:[UIImage imageNamed:@"bottom_praise.png"] forState:UIControlStateNormal];
        [_praiseBtn setImage:[UIImage imageNamed:@"bottom_praise.png"] forState:UIControlStateHighlighted];
        [_praiseBtn setImage:[UIImage imageNamed:@"bottom_praise.png"] forState:UIControlStateSelected];

        CGRect rect = _praiseBtn.frame;
        rect.origin.x += rect.size.width;
        _commentBtn = [[UIButton alloc] initWithFrame:rect];
        _commentBtn.contentEdgeInsets = _praiseBtn.contentEdgeInsets;
        [_commentBtn setImage:[UIImage imageNamed:@"bottom_comment.png"] forState:UIControlStateNormal];
        [_commentBtn setImage:[UIImage imageNamed:@"bottom_comment.png"] forState:UIControlStateHighlighted];
        [_commentBtn setImage:[UIImage imageNamed:@"bottom_comment.png"] forState:UIControlStateSelected];

        rect.origin.x += rect.size.width;
        _shareBtn = [[UIButton alloc] initWithFrame:rect];
        _shareBtn.contentEdgeInsets = _praiseBtn.contentEdgeInsets;
        [_shareBtn setImage:[UIImage imageNamed:@"bottom_share.png"] forState:UIControlStateNormal];
        [_shareBtn setImage:[UIImage imageNamed:@"bottom_share.png"] forState:UIControlStateHighlighted];
        [_shareBtn setImage:[UIImage imageNamed:@"bottom_share.png"] forState:UIControlStateSelected];

        [self.praiseBtn addTarget:self action:@selector(bottomPraiseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.commentBtn addTarget:self action:@selector(bottomCommentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.shareBtn addTarget:self action:@selector(bottomShareBtnClick:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:_praiseBtn];
        [self addSubview:_commentBtn];
        [self addSubview:_shareBtn];

    }
    return self;
}

-(NSString *)getUid{
    UserInfEntity * entity = [CoreData_Helper GetSelfUserInfEntity];
    return entity.uid;
}

-(void)bottomCommentBtnClick:(UIButton *)sender{
    self.commentVC = [[CommentViewController alloc]initWithFeedId:feed_id];
    [self.delegate bottomCommentBtnClick];
}

-(void)bottomPraiseBtnClick:(UIButton *)sender{
    AFHTTPRequestOperationManager * NetworkManager = [[AFHTTPRequestOperationManager alloc]init];

        [NetworkManager POST:Peanut_Dig_Something parameters:@{@"PHPSESSID":USER_PHPSESSID,@"feed_id":[NSString stringWithFormat:@"%ld",feed_id]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([[responseObject objectForKey:@"status"] intValue] == 1) {
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:@"点赞成功!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alertView show];
                isPraised = 1;
                NSLog(@"%@",[[responseObject objectForKey:@"data"] objectForKey:@"diggNum"]);
            }else{
                [NetworkManager POST:Peanut_Cancel_Dig_Something parameters:@{@"PHPSESSID":USER_PHPSESSID,@"feed_id":[NSString stringWithFormat:@"%ld",feed_id]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    if ([[responseObject objectForKey:@"status"] intValue] == 1) {
                        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:@"取消成功!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                        [alertView show];
                        isPraised = 0;
                    }else{
                        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:@"取消失败!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                        [alertView show];
                    }
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:@"点赞失败!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alertView show];
                }];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        }];

}

-(void)bottomShareBtnClick:(UIButton *)sender{
    self.shareVC = [[ShareViewController alloc] initWithFeedId:feed_id];
    [self.delegate bottomShareBtnClick];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
class AddDiscTypeToMovies < ActiveRecord::Migration[5.0]
  def change
    add_column :movies, :disc_type, :text
  end
end


text:
#ifndef CUAUV_SIM_FORCE_H
#define CUAUV_SIM_FORCE_H

#include "entity.hpp"
#include "world.hpp"
#include "screw.hpp"

namespace cuauv {
namespace fishbowl {

class force {
public:
    /**
     * Returns the forces and torques on a given entity at the current timestep
     * in the world frame.
     */
    virtual screw on(entity_id id) = 0;

    /**
     * Advances to the next timestep.
     *
     * Should be called after relevant changes in world state. May cause cached
     * forces and torques on entities to be recalculated.
     */
    virtual void step(double delta) = 0;
    virtual ~force() {};
};

}
}

#endif // CUAUV_SIM_FORCE_H


text:
function url(check_tunnel)
{
    if (check_tunnel && tunnel.checked) {
        return "http://localhost:" +controller.defaultPort()
    } else {
        return "http://" + combo.currentText + ":" +controller.defaultPort()
    }
}

function getJobIndex(jobid)
{
    for(var j = 0; j < myjobModel.count; j++) {
        if (myjobModel.get(j).id == jobid) {
            return j
        }
    }
}

function policy()
{
    return comboPolicies.currentText
}

function guess_type(server)
{
    if (/nef-devel2/.test(server)) {
        return "oar"
    } else if (/nef/.test(server)) {
        return "torque"
    } else if (/grid5000/.test(server)) {
        return "oar"
    } else {
        return "local"
    }
}

function setWalltime(hours, min, sec)
{
    return hours + ":" + min +":" + sec ;
}

function submit(nodes, cores, walltime)
{
    console.debug("submit " + cores + " nodes " +nodes )
    var xhr = new XMLHttpRequest();
    xhr.open("PUT", url(true) +"/job", true);
    // timeout doesn't work in qml ?
    xhr.timeout = 5;
    xhr.ontimeout = function () { console.debug("Timeout !!!" )}
    xhr.onreadystatechange = function()
    {
        if ( xhr.readyState == xhr.DONE)
        {
            if ( xhr.status == 201)
            {
                var jobid = xhr.getResponseHeader("X-DTK-JobId");
                console.debug("jobid is " + jobid )
                // jobModel.append({"id": jobid,
                //                  "user": "me",
                //                  "nodes" : NaN,
                //                  "cores" : NaN,
                //                  "queue" : "unknown"})

            } else {
                console.debug("bad status " + xhr.status )
            }
        }
    }

    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    var resources = {  "resources": {"nodes": nodes, "cores": cores },
                       "walltime": walltime,
                       "application": slavePath.text +" --nw --server " + url(false) + " --policy " + policy()
                    }
    xhr.send(JSON.stringify(resources))
}

function show()
{
    console.debug("show")
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url(true) +"/status",true);
    xhr.onreadystatechange = function()
    {
        if ( xhr.readyState == xhr.DONE)
        {
            if ( xhr.status == 200)
            {
                console.debug("status OK, parse" )
                var jsonObject = JSON.parse(xhr.responseText);
                var cores = 0
                var cores_busy = 0
                var cores_free = 0
                var nodes_free = 0
                var nodes_busy = 0
                var nodes_down = 0
                for ( var index in jsonObject.nodes ) {
                    cores += jsonObject.nodes[index].cores.length;
                    cores_busy += jsonObject.nodes[index].cores_busy;
                    if (jsonObject.nodes[index].state == "free") {
                        nodes_free ++;
                    } else if (jsonObject.nodes[index].state == "down") {
                        nodes_down ++;
                    } else if (jsonObject.nodes[index].state == "busy") {
                        nodes_busy ++;
                    }
                }
                cores_free = cores - cores_busy
                cores_pie.chartData = [{value: cores_free, color: "green"}, {value: cores_busy, color: "orange"}];
                coresFree.text = "Free cores: " + cores_free
                coresTotal.text = "Total cores: " + cores
                coresBusy.text = "Busy cores: " + cores_busy
                nodesFree.text = "Free nodes: " + nodes_free
                nodesDead.text = "Dead nodes: " + nodes_down
                nodesBusy.text = "Busy nodes: " + nodes_busy
                nodesTotal.text = "Total nodes: " + (nodes_free+nodes_busy+nodes_down)
                cores_pie.repaint();
                nodes_pie.chartData = [{value: nodes_free, color: "green"},
                                       {value: nodes_busy, color: "orange"},
                                       {value: nodes_down, color: "red"}];
                nodes_pie.repaint();
                console.debug("cores " + cores )
                console.debug("cores busy " + cores_busy )
                console.debug("nodes free " + nodes_free )
                console.debug("nodes busy " + nodes_busy )
                console.debug("nodes dead " + nodes_down )

                jobModel.clear()
                for ( var index in jsonObject.jobs ) {
                    jobModel.append({"id": jsonObject.jobs[index].id,
                                     "user": jsonObject.jobs[index].username,
                                     "nodes" : jsonObject.jobs[index].resources.nodes,
                                     "cores" : jsonObject.jobs[index].resources.cores,
                                     "queue" : jsonObject.jobs[index].queue })
                }
            } else {
                console.debug("status NOK" + xhr.status)
            }
        }
    }
    xhr.send();
}


text:
package com.hazelcast.sql.impl.operation;

import com.hazelcast.sql.impl.SqlDataSerializerHook;
import com.hazelcast.sql.impl.SqlTestSupport;
import com.hazelcast.sql.impl.plan.node.MockPlanNode;
import com.hazelcast.sql.impl.plan.node.PlanNode;
import com.hazelcast.sql.impl.type.QueryDataType;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static com.hazelcast.sql.impl.operation.QueryExecuteOperationFragmentMapping.EXPLICIT;
import static org.junit.Assert.assertEquals;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class QueryExecuteOperationFragmentTest extends SqlTestSupport {
    @Test
    public void testFragment() {
        PlanNode node = MockPlanNode.create(1, QueryDataType.INT);
        List<UUID> memberIds = Arrays.asList(UUID.randomUUID(), UUID.randomUUID());

        QueryExecuteOperationFragment fragment = new QueryExecuteOperationFragment(node, EXPLICIT, memberIds);

        assertEquals(node, fragment.getNode());
        assertEquals(memberIds, fragment.getMemberIds());
    }

    @Test
    public void testSerialization() {
        QueryExecuteOperationFragment original = new QueryExecuteOperationFragment(
            MockPlanNode.create(1, QueryDataType.INT),
            EXPLICIT,
            Arrays.asList(UUID.randomUUID(), UUID.randomUUID())
        );

        QueryExecuteOperationFragment restored = serializeAndCheck(original, SqlDataSerializerHook.OPERATION_EXECUTE_FRAGMENT);

        assertEquals(original.getNode(), restored.getNode());
        assertEquals(original.getMapping(), restored.getMapping());
        assertEquals(original.getMemberIds(), restored.getMemberIds());
    }
}


text:
class Perk < ActiveRecord::Base
  belongs_to :brand

  has_many :user_perks
  has_many :users, :through => :user_perks
  has_many :brand_categories, :through => :brands

  validates :discount, :zipcode, presence: true
  validates :discount, numericality: { greater_than: 1, less_than: 100}
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print 2002</title>
</head>

<body >

  <img src="../graphics/covers/2002-front.jpg" />

</body>
</html>


text:
#import "NSObject-Protocol.h"

@protocol SBKTransactionControllerDelegate <NSObject>
- (void)transactionController:(id)arg1 transactionDidFinish:(id)arg2;
- (void)transactionController:(id)arg1 transactionDidCancel:(id)arg2 error:(id)arg3;
- (_Bool)transactionController:(id)arg1 transactionDidFail:(id)arg2 error:(id)arg3;

@optional
- (_Bool)transactionController:(id)arg1 shouldScheduleTransaction:(id)arg2;
@end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows.Forms;
using DeepdreamGui.ViewModel;

namespace DeepdreamGui.Model
{
    /// <summary>
    /// Class to generate HTML Reports.
    /// </summary>
    public class ReportWriter
    {
        private List<ResultImageViewModel> images;
        private string outputDir;
        private string creatorName;

        private string[] TableHeader= {Properties.Resources.param_picture, Properties.Resources.info_serial, Properties.Resources.param_name, Properties.Resources.param_achieved_change, Properties.Resources.param_comment};
        private string reportName;
        private string instanceOutputDir;

        private string OutputDir
        {
            get
            {
                //Check if folder exists, if not create.
                if (!String.IsNullOrEmpty(instanceOutputDir)) return instanceOutputDir;
                instanceOutputDir = Path.Combine(outputDir, DateTime.Now.ToString($"yyyyMMdd-HHmm") + $"_{reportName}");
                if (Directory.Exists(instanceOutputDir)) return instanceOutputDir;
                try
                {
                    Trace.WriteLine("ReportWriter.OutputDir; Try to create dir="+instanceOutputDir);
                    Directory.CreateDirectory(instanceOutputDir);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine($"ReportWriter.OutputDir; {ex}");
                    //Console.WriteLine(ex);
                    throw ex;
                }

                return instanceOutputDir;
            }
        }

        private string ImageDir
        {
            get
            {
                var outDir = Path.Combine(OutputDir, "img");
                if (Directory.Exists(outDir)) return outDir;
                try
                {
                    Trace.WriteLine("ReportWriter.ImageDir; Dir to create dir="+outDir);
                    Directory.CreateDirectory(outDir);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("ReportWriter.ImageDir; "+ex);
                    //Console.WriteLine(ex);
                    throw ex;
                }

                return outDir;
            }
        }

        /// <summary>
        /// Constructor for Report Writer.
        /// </summary>
        /// <param name="images">Collection of Image to output</param>
        /// <param name="outputDir">Directory to save Report</param>
        /// <param name="creatorName">Creator name</param>
        /// <param name="reportName">Report name</param>
        public ReportWriter(ICollection<ResultImageViewModel> images, string outputDir, string creatorName, string reportName)
        {
            this.images = images.ToList();
            this.outputDir = outputDir;
            this.creatorName = creatorName;
            this.reportName = reportName;
        }

        /// <summary>
        /// Get relative image path to Report's img/ directory
        /// C:/User/.../landscape.jpg to img/landscape.jpg
        /// </summary>
        /// <param name="path">Image Path</param>
        /// <returns>Relative path to img folder</returns>
        private string GetRelativeImagePath(string path)
        {
            if (!File.Exists(path)) return String.Empty;

            var filename = Path.GetFileName(path);
            if(String.IsNullOrEmpty(filename)) return String.Empty;

            return "img/" + filename;
        }

        /// <summary>
        /// Write CSS to Report
        /// </summary>
        /// <param name="writer">Current Writer</param>
        private void GenerateStyle(HtmlTextWriter writer)
        {
            string style = @"
body{
font-family: 'Helvetica', 'Arial', sans-serif;
color:white;
background-color: #252525;
}
table{
margin:auto;
width:100%;
}
tr{
background:rgba(255, 255, 255, 0.05);
margin-top:5px;
}
td{
text-align: center;
}
img{
max-width:300;
max-height:300;
}
    ";

            writer.RenderBeginTag(HtmlTextWriterTag.Style);
            writer.Write(style);
            writer.RenderEndTag();
        }

        private void GenerateFileHeader(HtmlTextWriter writer)
        {
            Trace.WriteLine($"ReportWriter.GenerateFileHeader; Write header Report: {reportName} by: {creatorName}.");
            writer.RenderBeginTag(HtmlTextWriterTag.H1);
            writer.WriteEncodedText($"{Properties.Resources.report_report}: {reportName} {Properties.Resources.report_by}: {creatorName}, {Properties.Resources.report_date}: {DateTime.Now.ToString(CultureInfo.CurrentCulture)}");
            writer.RenderEndTag();
        }

        private void GenerateTableRow(HtmlTextWriter writer, ResultImageViewModel vm)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            var img = ImageModel.SaveImageWithRandomName(vm.Image, ImageDir);
            img.Wait();
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "resultImage");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, GetRelativeImagePath(img.Result));
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag(); //img
            writer.RenderEndTag(); //td

            //IterationNumber
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.WriteEncodedText(vm.Iteration.ToString());
            writer.RenderEndTag();

            //Name
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.WriteEncodedText(vm.Name ?? String.Empty);
            writer.RenderEndTag();

            //SubjectiveVariation
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.WriteEncodedText(vm.SubjectiveVariation.ToString());
            writer.RenderEndTag();

            //Comment
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.WriteEncodedText(vm.Description ?? String.Empty);
            writer.RenderEndTag();

            writer.RenderEndTag(); //Tr
        }

        private void GenerateImageHeader(HtmlTextWriter writer, ResultImageViewModel firstInGroup)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "imageHeader");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.RenderBeginTag(HtmlTextWriterTag.H2);
            writer.WriteEncodedText(firstInGroup.ModeName + " " + Properties.Resources.report_series);
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.H3);
            writer.WriteEncodedText(Properties.Resources.report_parameter);
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            if (firstInGroup.Mode == Modes.Dream)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(Properties.Resources.param_source_picture);
                writer.RenderEndTag();

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(Properties.Resources.param_model);
                writer.RenderEndTag();

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(Properties.Resources.param_octave);
                writer.RenderEndTag();

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(Properties.Resources.param_intensity);
                writer.RenderEndTag();

                writer.RenderEndTag(); //tr
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                //Img
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                var img = ImageModel.SaveImageWithRandomName(firstInGroup.OriginalImage, ImageDir);
                img.Wait();
                writer.AddAttribute(HtmlTextWriterAttribute.Src, GetRelativeImagePath(img.Result));
                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag(); //img
                writer.RenderEndTag();  //td

                //Model
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.WriteEncodedText(firstInGroup.SelectedModelParameter.Name + " / " + firstInGroup.SelectedModelParameter.Key);
                writer.RenderEndTag(); //img

                //Octave
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.WriteEncodedText(firstInGroup.Octave.ToString());
                writer.RenderEndTag(); //img

                //Intensity
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.WriteEncodedText(firstInGroup.Intensity.ToString(CultureInfo.CurrentCulture));
                writer.RenderEndTag(); //img

                writer.RenderEndTag(); //Tr

            }
            else
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Table);
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(Properties.Resources.param_source_picture);
                writer.RenderEndTag();

                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(Properties.Resources.info_style_image);
                writer.RenderEndTag();

                writer.RenderEndTag(); //Tr
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                //Img
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                var img = ImageModel.SaveImageWithRandomName(firstInGroup.OriginalImage, ImageDir);
                img.Wait();
                writer.AddAttribute(HtmlTextWriterAttribute.Src, GetRelativeImagePath(img.Result));
                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag(); //img

                //Style Img
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                img = ImageModel.SaveImageWithRandomName(firstInGroup.StyleImage, ImageDir);
                img.Wait();
                writer.AddAttribute(HtmlTextWriterAttribute.Src, GetRelativeImagePath(img.Result));
                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag(); //img
                writer.RenderEndTag(); //td

                writer.RenderEndTag(); //Tr
            }
            writer.RenderEndTag(); //Table

            writer.RenderBeginTag(HtmlTextWriterTag.H3);
            writer.WriteEncodedText(Properties.Resources.report_results);
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            foreach (var s in TableHeader)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                writer.WriteEncodedText(s ?? "--");
                writer.RenderEndTag();
            }

            writer.RenderEndTag(); //tr

        }

        /// <summary>
        /// Generate Report.
        /// </summary>
        /// <returns>Return runing generator task</returns>
        public Task Generate()
        {
            return  Task.Factory.StartNew(() =>
            {

               // outputDir = @"D:\tmp";
                //var writer = new StringWriter();

                using (StreamWriter writer = new StreamWriter(Path.Combine(OutputDir, "report.html")))
                {
                    Trace.WriteLine($"ReportWriter.Generate; Generate html-report to={outputDir}");
                    var htmlWriter = new HtmlTextWriter(writer);

                    GenerateStyle(htmlWriter);
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Body);
                    GenerateFileHeader(htmlWriter);

                    //Get base Images
                    var grouped = images.GroupBy(img => img.SeriesId).ToList();

                    foreach (var group in grouped)
                    {
                        GenerateImageHeader(htmlWriter, group.First());
                        foreach (var resultImageViewModel in @group)
                        {
                            GenerateTableRow(htmlWriter,resultImageViewModel);
                        }
                        htmlWriter.RenderEndTag(); //table
                    }

                    htmlWriter.RenderEndTag(); //body
                    htmlWriter.RenderEndTag(); //html
                    Trace.WriteLine($"ReportWriter.Generate; Finish writing;");
                    writer.Flush();
                }
            });
        }
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>or-tools/src/util/: Member List - Doxy</title>
    <link rel="shortcut icon" href="../../../favicon.ico">

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

          Generated on: Thu Mar 29 07:46:58 PDT 2012
            for custom file set

        <tt>//
            doxy/
            or-tools/
            src/
            util/
            </tt>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

operations_research::IntTupleSet Member List
This is the complete list of members for operations_research::IntTupleSet, including all inherited members.

Arity() const 	operations_research::IntTupleSet	 [inline]

Clear()	operations_research::IntTupleSet	 [inline]

Contains(const std::vector< int > &tuple)	operations_research::IntTupleSet	 [inline]

Contains(const std::vector< int64 > &tuple)	operations_research::IntTupleSet	 [inline]

Insert(const std::vector< int > &tuple)	operations_research::IntTupleSet	 [inline]

Insert(const std::vector< int64 > &tuple)	operations_research::IntTupleSet	 [inline]

Insert2(int64 v0, int64 v1)	operations_research::IntTupleSet	 [inline]

Insert3(int64 v0, int64 v1, int64 v2)	operations_research::IntTupleSet	 [inline]

Insert4(int64 v0, int64 v1, int64 v2, int64 v3)	operations_research::IntTupleSet	 [inline]

InsertAll(const std::vector< std::vector< int64 > > &tuples)	operations_research::IntTupleSet	 [inline]

InsertAll(const std::vector< std::vector< int > > &tuples)	operations_research::IntTupleSet	 [inline]

IntTupleSet(int arity)	operations_research::IntTupleSet	 [inline, explicit]

IntTupleSet(const IntTupleSet &set)	operations_research::IntTupleSet	 [inline]

NumTuples() const 	operations_research::IntTupleSet	 [inline]

RawData() const 	operations_research::IntTupleSet	 [inline]

Value(int tuple_index, int pos_in_tuple) const 	operations_research::IntTupleSet	 [inline]

~IntTupleSet()	operations_research::IntTupleSet	 [inline]


text:
module ApiClients
  module Cran
    class PackageVersion < Base

      def initialize(attrs = {})
        @name = attrs[:name] || fail('no :name passed')
        @version = attrs[:version] || fail('no :version passed')
      end

      protected

      def fetch_uri
        "#{@name}_#{@version}.tar.gz"
      end
    end
  end
end


text:
<?php
use Larabook\Forms\PublishStatusForm;
use Larabook\Statuses\PublishStatusCommand;
use Larabook\Statuses\StatusRepository;

/**
 * Class StatusController
 */
class StatusesController extends BaseController
{

    /**
     * @var
     */
    protected $statusRepository;
    /**
     * @var \Larabook\Forms\PublishStatusForm
     */
    protected $publishStatusForm;

    /**
     * @param \Larabook\Forms\PublishStatusForm   $publishStatusForm
     * @param \Larabook\Statuses\StatusRepository $statusRepository
     */
    public function __construct(PublishStatusForm $publishStatusForm, StatusRepository $statusRepository)
    {
        $this->statusRepository = $statusRepository;
        $this->publishStatusForm = $publishStatusForm;
    }

    /**
     * Display a listing of the resource.
     * GET /status
     *
     * @return Response
     */
    public function index()
    {
        $statuses = $this->statusRepository->getFeedForUser(Auth::user());

        return View::make('statuses.index', compact('statuses'));
    }

    /**
     * Store a newly created resource in storage.
     * POST /status
     *
     * @return Response
     */
    public function store()
    {
        $input = Input::all();
        $input['userId'] = Auth::id();

        $this->publishStatusForm->validate($input);

        $this->execute(PublishStatusCommand::class, $input);
        Flash::message('Your Status has been updated');

        return Redirect::back();
    }
}