text:
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import styled from 'styled-components';

import FriendlyTime from '../shared/FriendlyTime';
import RevealableDownChevron from '../shared/Icon/RevealableDownChevron';
import Panel from '../shared/Panel';
import UserAvatar from '../shared/UserAvatar';

import AuditLogDrawer from './Drawer';

import { indefiniteArticleFor } from '../../lib/words';

import cssVariables from '../../css';

const TransitionMaxHeight = styled.div`
  transition: max-height 400ms;
`;

class AuditLogRow extends React.PureComponent {
  static propTypes = {
    auditEvent: PropTypes.shape({
      uuid: PropTypes.string.isRequired,
      type: PropTypes.string.isRequired,
      occurredAt: PropTypes.string.isRequired,
      actor: PropTypes.shape({
        name: PropTypes.string,
        node: PropTypes.shape({
          name: PropTypes.string,
          avatar: PropTypes.shape({
            url: PropTypes.string
          })
        })
      }).isRequired,
      subject: PropTypes.shape({
        type: PropTypes.string.isRequired,
        name: PropTypes.string,
        node: PropTypes.shape({
          name: PropTypes.string
        })
      }).isRequired,
      context: PropTypes.shape({
        __typename: PropTypes.string.isRequired
      }).isRequired
    }).isRequired,
    relay: PropTypes.object.isRequired
  };

  state = {
    isExpanded: false,
    loading: false
  };

  getContextName() {
    return this.props.auditEvent.context.__typename.replace(/^Audit|Context$/g, '');
  }

  render() {
    const actorName = this.props.auditEvent.actor.name || this.props.auditEvent.actor.node && this.props.auditEvent.actor.node.name;

    return (
      <Panel.Row>

          <div
            className="flex items-center cursor-pointer hover-bg-silver mxn3 py2 px3"
            style={{
              marginTop: -10,
              // this is a hack to give the expandable section
              // a top border, without it taking up any space
              boxShadow: `0 1px 0 ${cssVariables['--gray']}`
            }}
            onClick={this.handleHeaderClick}
          >

              {this.props.auditEvent.actor.node && (

                  <UserAvatar
                    style={{ width: 39, height: 39 }}
                    user={this.props.auditEvent.actor.node}
                  />

              )}

                  {actorName}

                  {this.renderEventSentence()}

                <FriendlyTime
                  className="flex-none dark-gray"
                  value={this.props.auditEvent.occurredAt}
                />

              <RevealableDownChevron
                className="dark-gray"
                revealed={this.state.isExpanded}
              />

          <TransitionMaxHeight
            className="mxn3 overflow-hidden"
            style={{
              marginBottom: -10,
              maxHeight: this.state.isExpanded ? '80vh' : 0,
              overflowY: 'auto',
              overflowScrolling: 'touch',
              WebkitOverflowScrolling: 'touch'
            }}
          >
            <AuditLogDrawer
              auditEvent={this.props.auditEvent}
              hasExpanded={this.props.relay.variables.hasExpanded}
              loading={this.state.loading}
            />
          </TransitionMaxHeight>

      </Panel.Row>
    );
  }

  renderEventSentence() {
    const { type, subject } = this.props.auditEvent;

    // Take a guess at the verb. Usually the event type is subject type + event
    // verb, so strip off the subject type if it matches or just take the last
    // word, then sentence case the verb.

    let eventVerb;

    if (type.indexOf(`${subject.type}_`) === 0) {
      // "ORGANIZATION_TEAMS_ENABLED" with an "ORGANIZATION" subject => "TEAMS ENABLED"
      eventVerb = type.slice(subject.type.length + 1).replace('_', ' ');
    } else {
      // "PIPELINE_CREATED" => "CREATED"
      eventVerb = type.split('_').pop();
    }

    eventVerb = eventVerb.charAt(0).toUpperCase() + eventVerb.slice(1).toLowerCase();

    const renderedSubject = this.renderEventObject(subject);

    if (type === 'ORGANIZATION_CREATED') {
      // Welcome!
      return `Created ${renderedSubject} 🎉`;
    } else if (type === 'ORGANIZATION_TEAMS_ENABLED') {
      return `Enabled teams for ${renderedSubject}`;
    } else if (type === 'ORGANIZATION_TEAMS_DISABLED') {
      return `Disabled teams for ${renderedSubject}`;
    } else if (subject.type === 'TEAM_MEMBER') {
      const renderedTeam = this.renderEventObject({ type: 'TEAM', node: subject.node && subject.node.team });
      const renderedUser = this.renderEventObject({ type: 'USER', node: subject.node && subject.node.user });

      if (type === 'TEAM_MEMBER_CREATED') {
        return `Added ${renderedUser} to ${renderedTeam}`;
      } else if (type === 'TEAM_MEMBER_DELETED') {
        return `Removed ${renderedUser} from ${renderedTeam}`;
      }

      return `${eventVerb} ${renderedUser} in ${renderedTeam}`;
    } else if (subject.type === 'TEAM_PIPELINE') {
      const renderedTeam = this.renderEventObject({ type: 'TEAM', node: subject.node && subject.node.team });
      const renderedPipeline = this.renderEventObject({ type: 'PIPELINE', node: subject.node && subject.node.pipeline });

      if (type === 'TEAM_PIPELINE_CREATED') {
        return `Added ${renderedPipeline} to ${renderedTeam}`;
      } else if (type === 'TEAM_PIPELINE_DELETED') {
        return `Removed ${renderedPipeline} from ${renderedTeam}`;
      }

      return `${eventVerb} ${renderedPipeline} in ${renderedTeam}`;
    }

    return `${eventVerb} ${renderedSubject}`;
  }

  renderEventObject({ type, name, node }) {
    // "ORGANIZATION_INVITATION" => "organzation invitation"
    const friendlyType = type && type.split('_').pop().toLowerCase();

    // Check if we can still see the node and its current name, fall back to
    // the name recorded at the time of the event if present, or just an
    // indefinite type name
    if (node && node.name) {
      return `${friendlyType} "${node.name}"`;
    } else if (name) {
      return `${friendlyType} "${name}"`;
    } else if (type === "USER") {
      // "an user" feels weird
      return 'a user';
    }
    return `${indefiniteArticleFor(friendlyType)} ${friendlyType}`;

  }

  handleHeaderClick = () => {
    const isExpanded = !this.state.isExpanded;

    this.setState({
      loading: true,
      isExpanded
    }, () => {
      this.props.relay.setVariables(
        {
          hasExpanded: true
        },
        (readyState) => {
          if (readyState.done) {
            this.setState({ loading: false });
          }
        }
      );
    });
  };
}

export default Relay.createContainer(AuditLogRow, {
  initialVariables: {
    hasExpanded: false
  },

  fragments: {
    auditEvent: ({ hasExpanded }) => Relay.QL`
      fragment on AuditEvent {
        ${AuditLogDrawer.getFragment('auditEvent', { hasExpanded })}
        uuid
        type
        occurredAt
        actor {
          name
          node {
            ...on User {
              name
              avatar {
                url
              }
            }
          }
        }
        subject {
          type
          name
          node {
            ...on Organization {
              name
            }
            ...on Pipeline {
              name
            }
            ...on Team {
              name
            }
            ...on TeamMember {
              team {
                name
              }
              user {
                name
              }
            }
            ...on TeamPipeline {
              team {
                name
              }
              pipeline {
                name
              }
            }
          }
        }
        context {
          __typename
        }
      }
    `
  }
});


text:
#ifndef PX_FOUNDATION_PSINLINEALLOCATOR_H
#define PX_FOUNDATION_PSINLINEALLOCATOR_H

#include "PsUserAllocated.h"

namespace physx
{
namespace shdfnd
{
	// this is used by the array class to allocate some space for a small number
	// of objects along with the metadata
	template<PxU32 N, typename BaseAllocator>
	class InlineAllocator : private BaseAllocator
	{
	public:
		InlineAllocator(const PxEmpty& v) : BaseAllocator(v)	{}

		InlineAllocator(const BaseAllocator& alloc = BaseAllocator())
			: BaseAllocator(alloc), mBufferUsed(false)
		{}

		void* allocate(PxU32 size, const char* filename, int line)
		{
			if(!mBufferUsed && size<=N)
			{
				mBufferUsed = true;
				return mBuffer;
			}
			return BaseAllocator::allocate(size, filename, line);
		}

		void deallocate(void* ptr)
		{
			if(ptr == mBuffer)
				mBufferUsed = false;
			else
				BaseAllocator::deallocate(ptr);
		}

		PX_FORCE_INLINE	PxU8*	getInlineBuffer()		{ return mBuffer;	  }
		PX_FORCE_INLINE	bool	isBufferUsed()	const	{ return mBufferUsed; }

	protected:
		PxU8 mBuffer[N];
		bool mBufferUsed;
	};
} // namespace shdfnd
} // namespace physx

#endif

redpajama_set_name: RedPajamaGithub


text:
package ro.uvt.boundary;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.Data;
import org.primefaces.event.CellEditEvent;
import ro.uvt.controller.beans.FlightBean;
import ro.uvt.controller.beans.ItineraryBean;

@Named("itinerary")
@Data
@ViewScoped
public class Itinerary implements Serializable {

    @Inject
    private ItineraryBean itineraryBean;

    @Inject
    private FlightBean flightBean;

    private ro.uvt.entity.Itinerary entity = new ro.uvt.entity.Itinerary();

    List<ro.uvt.entity.Itinerary> itineraryList;

    private ro.uvt.entity.Itinerary selectedItinerary;

    private boolean isSelected = selectedItinerary != null;

    private Map<String, Long> flights = new HashMap<>();

    private String selectedFlight;

    public void submit() {
        itineraryBean.create(entity);
        entity = new ro.uvt.entity.Itinerary();
    }

    public void clear() {
        entity.setName("");
    }

    @PostConstruct
    public void init() {
        itineraryList = itineraryBean.findAll();

        for (ro.uvt.entity.Flight flight : flightBean.findAll()) {
            flights.put(flight.toString(), flight.getId());
        }

    }

    public void onCellEdit(CellEditEvent event) {
        itineraryBean.update((ro.uvt.entity.Itinerary) itineraryList.get(event.getRowIndex()));
    }

    public void onRowDelete() {
        if (selectedItinerary != null) {
            itineraryBean.removeById(selectedItinerary.getId());
            itineraryList.remove(selectedItinerary);
            selectedItinerary = null;
        }
    }

    public void rowSelectionEvent() {
        isSelected = selectedItinerary != null;
    }

    public void addFlightToItinerary() {
        if (selectedItinerary != null && selectedFlight != null) {
            ro.uvt.entity.Flight flight = flightBean.findById(Long.decode(selectedFlight));
            selectedItinerary.getFlights().add(flight);
            itineraryBean.update(selectedItinerary);
            selectedFlight = null;
        }
    }

    public void removeFlightFromItinerary() {
        if (!selectedItinerary.getFlights().isEmpty()) {
            ro.uvt.entity.Flight lastFlight = getLastFlightForSelectedItinerary();
            if (lastFlight != null) {
                selectedItinerary.getFlights().remove(lastFlight);
                itineraryBean.update(selectedItinerary);
            }
        }
    }

    private ro.uvt.entity.Flight getLastFlightForSelectedItinerary() {
        ro.uvt.entity.Flight lastFlight = null;

        if (selectedItinerary != null) {
            for (Iterator<ro.uvt.entity.Flight> iter = selectedItinerary.getFlights().iterator(); iter.hasNext();) {
                lastFlight = iter.next();
            }
        } else {
            throw new RuntimeException("No Itinerary is selected, cannot get latest flight");

        }
        return lastFlight;
    }

    public Map<String, Long> getFilteredFlights() {
        if (selectedItinerary != null && selectedItinerary.getFlights().size() > 0) {
            Map<String, Long> filteredFlights = new HashMap<>();

            for (ro.uvt.entity.Flight flight : flightBean.findAll()) {
                if (flight.getDeparture_airport().getId().equals(getLastFlightForSelectedItinerary().getArival_airport().getId())) {
                    filteredFlights.put(flight.toString(), flight.getId());
                }
            }
            return filteredFlights;
        }
        return flights;
    }
}


text: package positional


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="service_station">
        <item>Schedule for Caltrain</item>
        <item>Schedule for Bart</item>
    </string-array>
</resources>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using NFluent;

using Xunit;

namespace CSJ.NET.Tests
{
    public class CsjDeserializerTests
    {
        private sealed class SimpleObject
        {
            public int Integer { get; set; }
            public double Double { get; set; }
            public string String { get; set; }
            public DateTime Date { get; set; }
        }

        [Fact]
        public void DeserializeSimpleObject()
        {
            var subject = new CsjDeserializer<SimpleObject>();
            const string csj = @"""Integer"",""Double"",""String"",""Date""
2,42.23,""foobar"",""2015-02-03T10:37:15Z""
15,12.43,""bazbox"",""2015-02-03T10:37:15Z""";

            var results = subject.Deserialize(csj).ToArray();

            Check.That(results).HasSize(2);
            Check.That(results[0]).HasFieldsWithSameValues(new SimpleObject()
            {
                Integer = 2,
                Double = 42.23,
                String = "foobar",
                Date = new DateTime(2015, 2, 3, 10, 37, 15, DateTimeKind.Utc),
            });
            Check.That(results[1]).HasFieldsWithSameValues(new SimpleObject()
            {
                Integer = 15,
                Double = 12.43,
                String = "bazbox",
                Date = new DateTime(2015, 2, 3, 10, 37, 15, DateTimeKind.Utc),
            });
        }

        [Fact]
        public void DeserializesFromStream()
        {
            var subject = new CsjDeserializer<SimpleObject>();
            const string csj = @"""Integer"",""Double"",""String"",""Date""
2,42.23,""foobar"",""2015-02-03T10:37:15Z""
15,12.43,""bazbox"",""2015-02-03T10:37:15Z""";
            var stream = new StringReader(csj);

            var results = subject.Deserialize(stream).ToArray();

            Check.That(results).HasSize(2);
            Check.That(results[0]).HasFieldsWithSameValues(new SimpleObject()
            {
                Integer = 2,
                Double = 42.23,
                String = "foobar",
                Date = new DateTime(2015, 2, 3, 10, 37, 15, DateTimeKind.Utc),
            });
            Check.That(results[1]).HasFieldsWithSameValues(new SimpleObject()
            {
                Integer = 15,
                Double = 12.43,
                String = "bazbox",
                Date = new DateTime(2015, 2, 3, 10, 37, 15, DateTimeKind.Utc),
            });
        }

        [Fact]
        public void AllowsReorderingOfHeaders()
        {
            var subject = new CsjDeserializer<SimpleObject>();
            const string csj = @"""Date"",""String"",""Double"",""Integer""
""2015-02-03T10:37:15Z"",""foobar"",42.23,2
""2015-02-03T10:37:15Z"",""bazbox"",12.43,15";

            var results = subject.Deserialize(csj).ToArray();

            Check.That(results).HasSize(2);
            Check.That(results[0]).HasFieldsWithSameValues(new SimpleObject()
            {
                Integer = 2,
                Double = 42.23,
                String = "foobar",
                Date = new DateTime(2015, 2, 3, 10, 37, 15, DateTimeKind.Utc),
            });
            Check.That(results[1]).HasFieldsWithSameValues(new SimpleObject()
            {
                Integer = 15,
                Double = 12.43,
                String = "bazbox",
                Date = new DateTime(2015, 2, 3, 10, 37, 15, DateTimeKind.Utc),
            });
        }

        public class NestedArrayExample
        {
            public string Name { get; set; }
            public string[] Tags { get; set; }
        }

        [Fact]
        public void DeserializesNestedArrays()
        {
            var subject = new CsjDeserializer<NestedArrayExample>();
            const string csj = @"""Name"",""Tags""
""Foo"",[""three"",""fake""]";

            var results = subject.Deserialize(csj).ToArray();

            Check.That(results).HasSize(1);
            Check.That(results[0]).HasFieldsWithSameValues(new NestedArrayExample()
            {
                Name = "Foo",
                Tags = new[] { "three", "fake" }
            });
        }

    }
}


text:
using LL.MDE.Components.Qvt.Metamodel.EMOF;
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;

namespace LL.MDE.Components.Qvt.Metamodel.EssentialOCL
{

    /// <summary>
    /// The default implementation of the NumericLiteralExp class
    /// </summary>
    [XmlNamespaceAttribute("http://www.omg.org/spec/QVT/20140401/EssentialOCL")]
    [XmlNamespacePrefixAttribute("essentialocl")]
    [DebuggerDisplayAttribute("NumericLiteralExp {Name}")]
    public abstract class NumericLiteralExp : PrimitiveLiteralExp, INumericLiteralExp, IModelElement
    {

        private static NMF.Models.Meta.IClass _classInstance;

        /// <summary>
        /// Gets the Class for this model element
        /// </summary>
        public override NMF.Models.Meta.IClass GetClass()
        {
            throw new NotSupportedException();
        }
    }
}


text:
var config = require('./config.json');
var gulp = require('gulp');
var clean = require('gulp-clean');
var usemin = require('gulp-usemin');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var open_browser = require('gulp-open');
var refresh = require('gulp-livereload');

/* Server */

var connect = require('connect');
var connect_livereload = require('connect-livereload');
var lr_port = config.options.livereload.port;
var lr_server = require('tiny-lr')();
var lh_vars = config.env.localhost;
var lh_port = lh_vars.url.port;
var lh_url = lh_vars.url.protocol + '://' + lh_vars.url.domain + ':' + lh_port + '/';

gulp.task('sass', function() {
  gulp.src('demo/source/sass/**/*.scss')
    .pipe(sass({
      loadPath: ['vendor', 'library']
    }))
    .pipe(autoprefixer.apply(undefined, config.options.autoprefixer.browsers))
    .pipe(gulp.dest('demo/build/css'))
    .pipe(refresh(lr_server));
});

gulp.task('usemin', function() {

  gulp.src('demo/source/index.html')
    .pipe(usemin({
      // in this case css will be only concatenated (like css: ['concat']).
    }))
    .pipe(gulp.dest('demo/build'))
    .pipe(refresh(lr_server));
});

gulp.task('img', function() {

  gulp.src('demo/build/img/**/*', {
    read: false
  })
    .pipe(clean({
      force: true
    }));

  gulp.src('demo/source/img/**/*.jpg', {
    base: 'demo/source/img'
  })
    .pipe(gulp.dest('demo/build/img'))
    .pipe(refresh(lr_server));
});

gulp.task('server_livereload', function() {
  lr_server.listen(lr_port, function(err) {
    if (err) return gutil.log(err);
  });
});

gulp.task('server_connect', function() {
  connect()
    .use(connect_livereload({
      port: lr_port
    }))
    .use(connect.static('demo/build'))
    .listen(lh_port);
});

gulp.task('open', function() {
  // return gulp.src('demo/build/index.html')
  //   .pipe(open_browser('', {
  //     url: lh_url
  //   }));
});

gulp.task('watch', function() {
  gulp.watch(['demo/source/**/*.html', 'demo/source/js/**/*.js', 'library/**/*.js'], ['usemin']);
  gulp.watch(['demo/source/sass/**/*.scss', 'library/**/*.scss'], ['sass']);
  gulp.watch(['demo/source/img/**/*'], ['img']);
});

gulp.task('build', ['sass', 'usemin', 'img']);

gulp.task('server', ['server_livereload', 'server_connect']);

gulp.task('demo', ['server', 'build', 'watch', 'open']);

gulp.task('default', ['demo']);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.guvnor</groupId>
    <artifactId>guvnor-inbox</artifactId>
    <version>6.3.0-SNAPSHOT</version>
  </parent>

  <artifactId>guvnor-inbox-api</artifactId>
  <packaging>jar</packaging>

  <name>Guvnor - Inbox API</name>
  <description>Guvnor - Inbox API</description>

  <dependencies>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-bus</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-common</artifactId>
    </dependency>

  </dependencies>

  <build>
    <resources>
      <!-- Include src/main/java in order not to break the Eclipse GWT plug-in -->
      <resource>
        <directory>src/main/java</directory>
      </resource>
      <!-- Include module descriptors from src/main/resources in order not to break the Intellij GWT plug-in -->
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
  </build>

</project>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Supereclipse</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
	<link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                supereclipse

                        Services

                        Portfolio

                        About

                        Team

                        Contact

Welcome To Supereclipse!

It's Nice To Meet You

		Contact Us

Services

We specialise in providing tailored solutions to meet the need of our users.

Creative

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Responsive

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Mobile

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Portfolio

Work that we have undertaken for our clients

Round Icons

Graphic Design

Startup Framework

Website Design

Treehouse

Website Design

Golden

Website Design

Escape

Website Design

Dreams

Website Design

About

Our design process

Discover

Sub-heading

Develop a thorough understanding of the project, audience, and objects to formulate a digital strategy to meet our client's needs.

Design

Sub-heading

Craft a design to reflect the objectives that have been set and indicate the direction
for the entire project.

Implement

Sub-heading

Bring the design to life in the form of an interactive and functional prototype.
Review, refine and optimise.

Develop

Sub-heading

Incorporate implementation and technical components into a highly functional
system, ready for review.

Deliver

Sub-heading

Review, refine, test and prepare final
product for delivery. Launch and
continue to evolve over time.

Be Part

Of Our

Story!

Our Amazing Team

Lorem ipsum dolor sit amet consectetur.

Kay Garland

Lead Designer

Larry Parker

Lead Marketer

Diana Pertersen

Lead Developer

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.

Contact Us

Let's chat about your ideas and how we can help you create the website of your dreams.

You can expect to hear from us within 24 hours.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © Supereclipse 2015

Privacy Policy

Terms of Use

Project Name

Lorem ipsum dolor sit amet consectetur.

Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!

                                Want these icons in this portfolio item sample?You can download 60 of them for free, courtesy of RoundIcons.com, or you can purchase the 1500 icon set here.

Date: July 2014

Client: Round Icons

Category: Graphic Design

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Heading

Lorem ipsum dolor sit amet consectetur.

Startup Framework is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.

You can preview Startup Framework here.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Treehouse is a free PSD web template built by Mathavan Jaya. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by Mathavan Jaya. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Escape is a free PSD web template built by Mathavan Jaya. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Dreams is a free PSD web template built by Mathavan Jaya. Dreams is a modern one page web template designed for almost any purpose. It's a beautiful template that's designed with the Bootstrap framework in mind.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
package Expect::LogFile;
our $VERSION = '0.90';

=head1 NAME

Expect::LogFile - add ability to send Expect.pm debug logs to a file

=head1 SYNOPSIS

  use Expect::LogFile;      # MUST be loaded before Expect.pm
  use Expect;

  Expect::LogFile::logto("/tmp/somefilename");
  $Expect::Exp_Internal = 1;
  my $exp = Expect->spawn($command, @params);

=head1 DESCRIPTION

Expect.pm has built-in debug logging:

  $Expect::Exp_Internal = 1;
  # or
  $Expect::Debug = 3;

However, it sends its debug logs to STDERR and cluck().  This module adds the ability to
redirect the debug logs to a file instead.

Unfortunately, it's not possible to log messages from only one $exp object -- parts of Expect.pm
operate across multiple Expect objects at once.  As such, ALL log messages generated are sent to the
same file.

=head1 AUTHOR

Dee Newcum

=cut

    use strict;
    use File::Spec;
    use Symbol;

our $log_filehandle;

BEGIN {
    if (exists $INC{'Expect.pm'}) {
        # too late
        warn "ERROR:  Expect::LogFile *must* be loaded before loading Expect.pm.\n";
        exit;
    }
}

# inspired by https://metacpan.org/module/everywhere
use lib sub {
    my ($self, $file) = @_;
    if ($file =~ /^Expect\.pm$/) {
        foreach my $dir (@INC) {
            next if ref $dir;
            my $full = File::Spec->catfile($dir, $file);
            if(open my $fh, "<", $full) {
                my @lines = <$fh>;
                close $fh;
                unshift @lines, "#line 1 \"$full\"\n";
                @lines = modify_file(@lines);
                my $changed = join('', @lines);
                open my $fh_changed, '<', \$changed or die $!;
                return $fh_changed;
            }
        }
    }
    return undef;
};

sub modify_file {
    my @lines = @_;

    for (my $ctr=0; $ctr<=$#lines; $ctr++) {
        local $_ = $lines[$ctr];
        if (/^\s*package\s+Expect\b/) {
            $ctr++;
            splice(@lines, $ctr, 0,
                    q{      sub STDERR_logger {Expect::LogFile::log(@_)}      } . "\n");
        }
        $lines[$ctr] =~ s/^(\s*)print\s+STDERR\s/$1STDERR_logger /;
        $lines[$ctr] =~ s/^(\s*)cluck\b/$1STDERR_logger /;
    }

    #print $fout join('', @lines); exit;

    return @lines;
}

sub logto {
    my ($filename) = @_;
    open $log_filehandle, '>>', $filename   or die $!;
    $log_filehandle->autoflush(1);
}

sub log {
    print $log_filehandle @_;
}

1;


text:
#import "ABI44_0_0RCTAnimationDriver.h"

@interface ABI44_0_0RCTFrameAnimation : NSObject<ABI44_0_0RCTAnimationDriver>

@end


text:
NSString * const kAdTypeHeaderKey = @"X-Adtype";
NSString * const kClickthroughHeaderKey = @"X-Clickthrough";
NSString * const kCustomSelectorHeaderKey = @"X-Customselector";
NSString * const kCustomEventClassNameHeaderKey = @"X-Custom-Event-Class-Name";
NSString * const kCustomEventClassDataHeaderKey = @"X-Custom-Event-Class-Data";
NSString * const kFailUrlHeaderKey = @"X-Failurl";
NSString * const kHeightHeaderKey = @"X-Height";
NSString * const kImpressionTrackerHeaderKey = @"X-Imptracker";
NSString * const kInterceptLinksHeaderKey = @"X-Interceptlinks";
NSString * const kLaunchpageHeaderKey = @"X-Launchpage";
NSString * const kNativeSDKParametersHeaderKey = @"X-Nativeparams";
NSString * const kNetworkTypeHeaderKey = @"X-Networktype";
NSString * const kRefreshTimeHeaderKey = @"X-Refreshtime";
NSString * const kScrollableHeaderKey = @"X-Scrollable";
NSString * const kWidthHeaderKey = @"X-Width";

NSString * const kInterstitialAdTypeHeaderKey = @"X-Fulladtype";
NSString * const kOrientationTypeHeaderKey = @"X-Orientation";

NSString * const kAdTypeHtml = @"html";
NSString * const kAdTypeInterstitial = @"interstitial";
NSString * const kAdTypeMraid = @"mraid";
NSString * const kAdTypeClear = @"clear";

@interface MPAdConfiguration ()

@property (nonatomic, copy) NSString *adResponseHTMLString;

- (MPAdType)adTypeFromHeaders:(NSDictionary *)headers;
- (NSString *)networkTypeFromHeaders:(NSDictionary *)headers;
- (NSTimeInterval)refreshIntervalFromHeaders:(NSDictionary *)headers;
- (NSDictionary *)dictionaryFromHeaders:(NSDictionary *)headers forKey:(NSString *)key;
- (NSURL *)URLFromHeaders:(NSDictionary *)headers forKey:(NSString *)key;
- (Class)setUpCustomEventClassFromHeaders:(NSDictionary *)headers;

@end

////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation MPAdConfiguration

@synthesize adType = _adType;
@synthesize networkType = _networkType;
@synthesize preferredSize = _preferredSize;
@synthesize clickTrackingURL = _clickTrackingURL;
@synthesize impressionTrackingURL = _impressionTrackingURL;
@synthesize failoverURL = _failoverURL;
@synthesize interceptURLPrefix = _interceptURLPrefix;
@synthesize shouldInterceptLinks = _shouldInterceptLinks;
@synthesize scrollable = _scrollable;
@synthesize refreshInterval = _refreshInterval;
@synthesize adResponseData = _adResponseData;
@synthesize adResponseHTMLString = _adResponseHTMLString;
@synthesize nativeSDKParameters = _nativeSDKParameters;
@synthesize orientationType = _orientationType;
@synthesize customEventClass = _customEventClass;
@synthesize customEventClassData = _customEventClassData;
@synthesize customSelectorName = _customSelectorName;

- (id)initWithHeaders:(NSDictionary *)headers data:(NSData *)data
{
    self = [super init];
    if (self) {
        self.adResponseData = data;

        self.adType = [self adTypeFromHeaders:headers];

        self.networkType = [self networkTypeFromHeaders:headers];
        self.networkType = self.networkType ? self.networkType : @"";

        self.preferredSize = CGSizeMake([[headers objectForKey:kWidthHeaderKey] floatValue],
                                        [[headers objectForKey:kHeightHeaderKey] floatValue]);

        self.clickTrackingURL = [self URLFromHeaders:headers
                                              forKey:kClickthroughHeaderKey];
        self.impressionTrackingURL = [self URLFromHeaders:headers
                                                   forKey:kImpressionTrackerHeaderKey];
        self.failoverURL = [self URLFromHeaders:headers
                                         forKey:kFailUrlHeaderKey];
        self.interceptURLPrefix = [self URLFromHeaders:headers
                                                forKey:kLaunchpageHeaderKey];

        NSNumber *shouldInterceptLinks = [headers objectForKey:kInterceptLinksHeaderKey];
        self.shouldInterceptLinks = shouldInterceptLinks ? [shouldInterceptLinks boolValue] : YES;
        self.scrollable = [[headers objectForKey:kScrollableHeaderKey] boolValue];
        self.refreshInterval = [self refreshIntervalFromHeaders:headers];

        self.nativeSDKParameters = [self dictionaryFromHeaders:headers
                                                        forKey:kNativeSDKParametersHeaderKey];
        self.customSelectorName = [headers objectForKey:kCustomSelectorHeaderKey];

        self.orientationType = [self orientationTypeFromHeaders:headers];

        self.customEventClass = [self setUpCustomEventClassFromHeaders:headers];

        self.customEventClassData = [self customEventClassDataFromHeaders:headers];
    }
    return self;
}

- (Class)setUpCustomEventClassFromHeaders:(NSDictionary *)headers
{
    NSString *customEventClassName = [headers objectForKey:kCustomEventClassNameHeaderKey];

    NSMutableDictionary *convertedCustomEvents = [NSMutableDictionary dictionary];
    if (self.adType == MPAdTypeBanner) {
        [convertedCustomEvents setObject:@"MPiAdBannerCustomEvent" forKey:@"iAd"];
        [convertedCustomEvents setObject:@"MPGoogleAdMobBannerCustomEvent" forKey:@"admob_native"];
        [convertedCustomEvents setObject:@"MPMillennialBannerCustomEvent" forKey:@"millennial_native"];
        [convertedCustomEvents setObject:@"MPHTMLBannerCustomEvent" forKey:@"html"];
        [convertedCustomEvents setObject:@"MPMRAIDBannerCustomEvent" forKey:@"mraid"];
    } else if (self.adType == MPAdTypeInterstitial) {
        [convertedCustomEvents setObject:@"MPiAdInterstitialCustomEvent" forKey:@"iAd_full"];
        [convertedCustomEvents setObject:@"MPGoogleAdMobInterstitialCustomEvent" forKey:@"admob_full"];
        [convertedCustomEvents setObject:@"MPMillennialInterstitialCustomEvent" forKey:@"millennial_full"];
        [convertedCustomEvents setObject:@"MPHTMLInterstitialCustomEvent" forKey:@"html"];
        [convertedCustomEvents setObject:@"MPMRAIDInterstitialCustomEvent" forKey:@"mraid"];
    }
    if ([convertedCustomEvents objectForKey:self.networkType]) {
        customEventClassName = [convertedCustomEvents objectForKey:self.networkType];
    }

    Class customEventClass = NSClassFromString(customEventClassName);

    if (customEventClassName && !customEventClass) {
        MPLogWarn(@"Could not find custom event class named %@", customEventClassName);
    }

    return customEventClass;
}

- (NSDictionary *)customEventClassDataFromHeaders:(NSDictionary *)headers
{
    NSDictionary *result = [self dictionaryFromHeaders:headers forKey:kCustomEventClassDataHeaderKey];
    if (!result) {
        result = [self dictionaryFromHeaders:headers forKey:kNativeSDKParametersHeaderKey];
    }
    return result;
}

- (void)dealloc
{
    self.networkType = nil;
    self.clickTrackingURL = nil;
    self.impressionTrackingURL = nil;
    self.failoverURL = nil;
    self.interceptURLPrefix = nil;
    self.adResponseData = nil;
    self.adResponseHTMLString = nil;
    self.nativeSDKParameters = nil;
    self.customSelectorName = nil;
    self.customEventClassData = nil;

    [super dealloc];
}

- (BOOL)hasPreferredSize
{
    return (self.preferredSize.width > 0 && self.preferredSize.height > 0);
}

- (NSString *)adResponseHTMLString
{
    if (!_adResponseHTMLString) {
        self.adResponseHTMLString = [[[NSString alloc] initWithData:self.adResponseData
                                                           encoding:NSUTF8StringEncoding] autorelease];
    }

    return _adResponseHTMLString;
}

- (NSString *)clickDetectionURLPrefix
{
    return self.interceptURLPrefix.absoluteString ? self.interceptURLPrefix.absoluteString : @"";
}

#pragma mark - Private

- (MPAdType)adTypeFromHeaders:(NSDictionary *)headers
{
    NSString *adTypeString = [headers objectForKey:kAdTypeHeaderKey];

    if ([adTypeString isEqualToString:@"interstitial"]) {
        return MPAdTypeInterstitial;
    } else if (adTypeString &&
               [headers objectForKey:kOrientationTypeHeaderKey]) {
        return MPAdTypeInterstitial;
    } else if (adTypeString) {
        return MPAdTypeBanner;
    } else {
        return MPAdTypeUnknown;
    }
}

- (NSString *)networkTypeFromHeaders:(NSDictionary *)headers
{
    NSString *adTypeString = [headers objectForKey:kAdTypeHeaderKey];
    if ([adTypeString isEqualToString:@"interstitial"]) {
        return [headers objectForKey:kInterstitialAdTypeHeaderKey];
    } else {
        return adTypeString;
    }
}

- (NSURL *)URLFromHeaders:(NSDictionary *)headers forKey:(NSString *)key
{
    NSString *URLString = [headers objectForKey:key];
    return URLString ? [NSURL URLWithString:URLString] : nil;
}

- (NSDictionary *)dictionaryFromHeaders:(NSDictionary *)headers forKey:(NSString *)key
{
    NSData *data = [(NSString *)[headers objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding];
    CJSONDeserializer *deserializer = [CJSONDeserializer deserializerWithNullObject:NULL];
    return [deserializer deserializeAsDictionary:data error:NULL];
}

- (NSTimeInterval)refreshIntervalFromHeaders:(NSDictionary *)headers
{
    NSString *intervalString = [headers objectForKey:kRefreshTimeHeaderKey];
    NSTimeInterval interval = -1;
    if (intervalString) {
        interval = [intervalString doubleValue];
        if (interval < MINIMUM_REFRESH_INTERVAL) {
            interval = MINIMUM_REFRESH_INTERVAL;
        }
    }
    return interval;
}

- (MPInterstitialOrientationType)orientationTypeFromHeaders:(NSDictionary *)headers
{
    NSString *orientation = [headers objectForKey:kOrientationTypeHeaderKey];
    if ([orientation isEqualToString:@"p"]) {
        return MPInterstitialOrientationTypePortrait;
    } else if ([orientation isEqualToString:@"l"]) {
        return MPInterstitialOrientationTypeLandscape;
    } else {
        return MPInterstitialOrientationTypeAll;
    }
}

@end


text:
author: "Adam Presley"
date: 2011-03-29T05:47:00Z
tags: ["development", "csharp"]
title: "MD5 Hash a String in C#"
slug: "md5-hash-a-string-in-c"
---

Here's a small function to hash a string in C# using the MD5 algorithm.

{{< highlight csharp >}}
using System;
using System.Text;
using System.Security.Cryptography;

public String md5Hash(String input) {
    String result = "";

    using (MD5 md5 = new MD5CryptoServiceProvider()) {
        result = BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(input)));
    }

    return result.Replace("-", String.Empty);
}
{{< / highlight >}}

Note that the **Replace()** at the end is optional and you may remove it
should you want the dashes in your hash string.

Happy coding!


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

import com.facebook.presto.Session;
import com.facebook.presto.execution.buffer.TestingPagesSerdeFactory;
import com.facebook.presto.memory.context.LocalMemoryContext;
import com.facebook.presto.operator.Driver;
import com.facebook.presto.operator.DriverContext;
import com.facebook.presto.operator.Operator;
import com.facebook.presto.operator.OperatorContext;
import com.facebook.presto.operator.OutputFactory;
import com.facebook.presto.operator.TableScanOperator;
import com.facebook.presto.operator.TaskContext;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.QueryId;
import com.facebook.presto.spi.memory.MemoryPoolId;
import com.facebook.presto.spiller.SpillSpaceTracker;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.facebook.presto.testing.LocalQueryRunner;
import com.facebook.presto.testing.PageConsumerOperator.PageConsumerOutputFactory;
import com.facebook.presto.tpch.TpchConnectorFactory;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.stats.TestingGcMonitor;
import io.airlift.units.DataSize;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

import static com.facebook.presto.testing.LocalQueryRunner.queryRunnerWithInitialTransaction;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static com.facebook.presto.testing.TestingTaskContext.createTaskContext;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.GIGABYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

@Test(singleThreaded = true)
public class TestMemoryPools
{
    private static final DataSize TEN_MEGABYTES = new DataSize(10, MEGABYTE);
    private static final DataSize TEN_MEGABYTES_WITHOUT_TWO_BYTES = new DataSize(TEN_MEGABYTES.toBytes() - 2, BYTE);
    private static final DataSize ONE_BYTE = new DataSize(1, BYTE);

    private QueryId fakeQueryId;
    private LocalQueryRunner localQueryRunner;
    private MemoryPool userPool;
    private List<Driver> drivers;
    private TaskContext taskContext;

    private void setUp(Supplier<List<Driver>> driversSupplier)
    {
        checkState(localQueryRunner == null, "Already set up");

        Session session = testSessionBuilder()
                .setCatalog("tpch")
                .setSchema("tiny")
                .setSystemProperty("task_default_concurrency", "1")
                .build();

        localQueryRunner = queryRunnerWithInitialTransaction(session);

        // add tpch
        localQueryRunner.createCatalog("tpch", new TpchConnectorFactory(1), ImmutableMap.of());

        userPool = new MemoryPool(new MemoryPoolId("test"), TEN_MEGABYTES);
        fakeQueryId = new QueryId("fake");
        SpillSpaceTracker spillSpaceTracker = new SpillSpaceTracker(new DataSize(1, GIGABYTE));
        DefaultQueryContext queryContext = new DefaultQueryContext(new QueryId("query"),
                TEN_MEGABYTES,
                new DataSize(20, MEGABYTE),
                userPool,
                new TestingGcMonitor(),
                localQueryRunner.getExecutor(),
                localQueryRunner.getScheduler(),
                TEN_MEGABYTES,
                spillSpaceTracker);
        taskContext = createTaskContext(queryContext, localQueryRunner.getExecutor(), session);
        drivers = driversSupplier.get();
    }

    private void setUpCountStarFromOrdersWithJoin()
    {
        // query will reserve all memory in the user pool and discard the output
        setUp(() -> {
            OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> {}));
            return localQueryRunner.createDrivers("SELECT COUNT(*) FROM orders JOIN lineitem ON CAST(orders.orderkey AS VARCHAR) = CAST(lineitem.orderkey AS VARCHAR)", outputFactory, taskContext);
        });
    }

    private RevocableMemoryOperator setupConsumeRevocableMemory(DataSize reservedPerPage, long numberOfPages)
    {
        AtomicReference<RevocableMemoryOperator> createOperator = new AtomicReference<>();
        setUp(() -> {
            DriverContext driverContext = taskContext.addPipelineContext(0, false, false).addDriverContext();
            OperatorContext revokableOperatorContext = driverContext.addOperatorContext(
                    Integer.MAX_VALUE,
                    new PlanNodeId("revokable_operator"),
                    TableScanOperator.class.getSimpleName());

            OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> {}));
            Operator outputOperator = outputFactory.createOutputOperator(2, new PlanNodeId("output"), ImmutableList.of(), Function.identity(), new TestingPagesSerdeFactory()).createOperator(driverContext);
            RevocableMemoryOperator revocableMemoryOperator = new RevocableMemoryOperator(revokableOperatorContext, reservedPerPage, numberOfPages);
            createOperator.set(revocableMemoryOperator);

            Driver driver = Driver.createDriver(driverContext, revocableMemoryOperator, outputOperator);
            return ImmutableList.of(driver);
        });
        return createOperator.get();
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown()
    {
        if (localQueryRunner != null) {
            localQueryRunner.close();
            localQueryRunner = null;
        }
    }

    @Test
    public void testBlockingOnUserMemory()
    {
        setUpCountStarFromOrdersWithJoin();
        assertTrue(userPool.tryReserve(fakeQueryId, TEN_MEGABYTES.toBytes()));
        runDriversUntilBlocked(waitingForUserMemory());
        assertTrue(userPool.getFreeBytes() <= 0, String.format("Expected empty pool but got [%d]", userPool.getFreeBytes()));
        userPool.free(fakeQueryId, TEN_MEGABYTES.toBytes());
        assertDriversProgress(waitingForUserMemory());
    }

    @Test
    public void testNotifyListenerOnMemoryReserved()
    {
        setupConsumeRevocableMemory(ONE_BYTE, 10);
        AtomicReference<MemoryPool> notifiedPool = new AtomicReference<>();
        AtomicLong notifiedBytes = new AtomicLong();
        userPool.addListener(MemoryPoolListener.onMemoryReserved(pool -> {
            notifiedPool.set(pool);
            notifiedBytes.set(pool.getReservedBytes());
        }));

        userPool.reserve(fakeQueryId, 3);
        assertEquals(notifiedPool.get(), userPool);
        assertEquals(notifiedBytes.get(), 3L);
    }

    @Test
    public void testMemoryFutureCancellation()
    {
        setUpCountStarFromOrdersWithJoin();
        ListenableFuture future = userPool.reserve(fakeQueryId, TEN_MEGABYTES.toBytes());
        assertTrue(!future.isDone());
        try {
            future.cancel(true);
            fail("cancel should fail");
        }
        catch (UnsupportedOperationException e) {
            assertEquals(e.getMessage(), "cancellation is not supported");
        }
        userPool.free(fakeQueryId, TEN_MEGABYTES.toBytes());
        assertTrue(future.isDone());
    }

    @Test
    public void testBlockingOnRevocableMemoryFreeUser()
    {
        setupConsumeRevocableMemory(ONE_BYTE, 10);
        assertTrue(userPool.tryReserve(fakeQueryId, TEN_MEGABYTES_WITHOUT_TWO_BYTES.toBytes()));

        // we expect 2 iterations as we have 2 bytes remaining in memory pool and we allocate 1 byte per page
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2);
        assertTrue(userPool.getFreeBytes() <= 0, String.format("Expected empty pool but got [%d]", userPool.getFreeBytes()));

        // lets free 5 bytes
        userPool.free(fakeQueryId, 5);
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 5);
        assertTrue(userPool.getFreeBytes() <= 0, String.format("Expected empty pool but got [%d]", userPool.getFreeBytes()));

        // 3 more bytes is enough for driver to finish
        userPool.free(fakeQueryId, 3);
        assertDriversProgress(waitingForRevocableSystemMemory());
        assertEquals(userPool.getFreeBytes(), 10);
    }

    @Test
    public void testBlockingOnRevocableMemoryFreeViaRevoke()
    {
        RevocableMemoryOperator revocableMemoryOperator = setupConsumeRevocableMemory(ONE_BYTE, 5);
        assertTrue(userPool.tryReserve(fakeQueryId, TEN_MEGABYTES_WITHOUT_TWO_BYTES.toBytes()));

        // we expect 2 iterations as we have 2 bytes remaining in memory pool and we allocate 1 byte per page
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2);
        revocableMemoryOperator.getOperatorContext().requestMemoryRevoking();

        // 2 more iterations
        assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2);
        revocableMemoryOperator.getOperatorContext().requestMemoryRevoking();

        // 3 more bytes is enough for driver to finish
        assertDriversProgress(waitingForRevocableSystemMemory());
        assertEquals(userPool.getFreeBytes(), 2);
    }

    @Test
    public void testTaggedAllocations()
    {
        QueryId testQuery = new QueryId("test_query");
        MemoryPool testPool = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE));

        testPool.reserve(testQuery, Optional.of("test_tag"), 10);

        Map<String, Long> allocations = testPool.getTaggedMemoryAllocations().get(testQuery);
        assertEquals(allocations, ImmutableMap.of("test_tag", 10L));

        // free 5 bytes for test_tag
        testPool.free(testQuery, Optional.of("test_tag"), 5);
        assertEquals(allocations, ImmutableMap.of("test_tag", 5L));

        testPool.reserve(testQuery, Optional.of("test_tag2"), 20);
        assertEquals(allocations, ImmutableMap.of("test_tag", 5L, "test_tag2", 20L));

        // free the remaining 5 bytes for test_tag
        testPool.free(testQuery, Optional.of("test_tag"), 5);
        assertEquals(allocations, ImmutableMap.of("test_tag2", 20L));

        // free all for test_tag2
        testPool.free(testQuery, Optional.of("test_tag2"), 20);
        assertEquals(testPool.getTaggedMemoryAllocations().size(), 0);
    }

    @Test
    public void testMoveQuery()
    {
        QueryId testQuery = new QueryId("test_query");
        MemoryPool pool1 = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE));
        MemoryPool pool2 = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE));
        pool1.reserve(testQuery, Optional.of("test_tag"), 10);

        Map<String, Long> allocations = pool1.getTaggedMemoryAllocations().get(testQuery);
        assertEquals(allocations, ImmutableMap.of("test_tag", 10L));

        pool1.moveQuery(testQuery, pool2);
        assertNull(pool1.getTaggedMemoryAllocations().get(testQuery));
        allocations = pool2.getTaggedMemoryAllocations().get(testQuery);
        assertEquals(allocations, ImmutableMap.of("test_tag", 10L));

        assertEquals(pool1.getFreeBytes(), 1000);
        assertEquals(pool2.getFreeBytes(), 990);

        pool2.free(testQuery, 10);
        assertEquals(pool2.getFreeBytes(), 1000);
    }

    private long runDriversUntilBlocked(Predicate<OperatorContext> reason)
    {
        long iterationsCount = 0;

        // run driver, until it blocks
        while (!isOperatorBlocked(drivers, reason)) {
            for (Driver driver : drivers) {
                driver.process();
            }
            iterationsCount++;
        }

        // driver should be blocked waiting for memory
        for (Driver driver : drivers) {
            assertFalse(driver.isFinished());
        }
        return iterationsCount;
    }

    private void assertDriversProgress(Predicate<OperatorContext> reason)
    {
        do {
            assertFalse(isOperatorBlocked(drivers, reason));
            boolean progress = false;
            for (Driver driver : drivers) {
                ListenableFuture<?> blocked = driver.process();
                progress = progress | blocked.isDone();
            }
            // query should not block
            assertTrue(progress);
        }
        while (!drivers.stream().allMatch(Driver::isFinished));
    }

    private Predicate<OperatorContext> waitingForUserMemory()
    {
        return (OperatorContext operatorContext) -> !operatorContext.isWaitingForMemory().isDone();
    }

    private Predicate<OperatorContext> waitingForRevocableSystemMemory()
    {
        return (OperatorContext operatorContext) ->
                !operatorContext.isWaitingForRevocableMemory().isDone() &&
                        !operatorContext.isMemoryRevokingRequested();
    }

    private static boolean isOperatorBlocked(List<Driver> drivers, Predicate<OperatorContext> reason)
    {
        for (Driver driver : drivers) {
            for (OperatorContext operatorContext : driver.getDriverContext().getOperatorContexts()) {
                if (reason.apply(operatorContext)) {
                    return true;
                }
            }
        }
        return false;
    }

    private class RevocableMemoryOperator
            implements Operator
    {
        private final DataSize reservedPerPage;
        private final long numberOfPages;
        private final OperatorContext operatorContext;
        private long producedPagesCount;
        private final LocalMemoryContext revocableMemoryContext;

        public RevocableMemoryOperator(OperatorContext operatorContext, DataSize reservedPerPage, long numberOfPages)
        {
            this.operatorContext = operatorContext;
            this.reservedPerPage = reservedPerPage;
            this.numberOfPages = numberOfPages;
            this.revocableMemoryContext = operatorContext.localRevocableMemoryContext();
        }

        @Override
        public ListenableFuture<?> startMemoryRevoke()
        {
            return Futures.immediateFuture(null);
        }

        @Override
        public void finishMemoryRevoke()
        {
            revocableMemoryContext.setBytes(0);
        }

        @Override
        public OperatorContext getOperatorContext()
        {
            return operatorContext;
        }

        @Override
        public void finish()
        {
            revocableMemoryContext.setBytes(0);
        }

        @Override
        public boolean isFinished()
        {
            return producedPagesCount >= numberOfPages;
        }

        @Override
        public boolean needsInput()
        {
            return false;
        }

        @Override
        public void addInput(Page page)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public Page getOutput()
        {
            revocableMemoryContext.setBytes(revocableMemoryContext.getBytes() + reservedPerPage.toBytes());
            producedPagesCount++;
            if (producedPagesCount == numberOfPages) {
                finish();
            }
            return new Page(10);
        }
    }
}


text:
<component name="libraryTable">
  <library name="huaweiU3d">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/huawei/libs/huaweiU3d.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package net.vdrinkup.alpaca.protocol;

public interface Reconnected {

	public void reconnect( Connection connector ) throws Exception;

}


text:
require 'timeout'
require File.dirname(__FILE__) + "/background_process/background_process"
require File.dirname(__FILE__) + "/background_process/pty_background_process"
require File.dirname(__FILE__) + "/background_process/io_helpers"


text:
using namespace KLib;

template <typename T>
bool test_is_numeric(T, typename Traits::enable_if<Traits::is_integer<T>>::type* = nullptr)
{
    return true;
}

bool test_is_numeric(...)
{
    return false;
}

int main(int, char**)
{
    static_assert(Traits::is_signed<int>::value, "");
    static_assert(Traits::is_signed<unsigned int>::value == false, "");
    return (test_is_numeric(1234) == true) ? EXIT_SUCCESS : EXIT_FAILURE;
}


text:
import os
import sys

class ExampleRemoteLibrary:
    """Example library to be used with Robot Framework's remote server.

    This documentation is visible in docs generated by _libdoc.py_
    starting from Robot Framework 2.6.2.
    """

    def __init__(self):
        """Also this doc should be in shown in library doc."""

    def count_items_in_directory(self, path):
        """Returns the number of items in the directory specified by `path`."""
        return len([i for i in os.listdir(path) if not i.startswith('.')])

    def strings_should_be_equal(self, str1, str2):
        print "Comparing '%s' to '%s'" % (str1, str2)
        if str1 != str2:
            raise AssertionError("Given strings are not equal")

if __name__ == '__main__':
    from robotremoteserver import RobotRemoteServer
    RobotRemoteServer(ExampleRemoteLibrary(), *sys.argv[1:])


text:
namespace net {

class IPEndPoint;
class NetLogWithSource;
class SSLCertRequestInfo;
class SSLInfo;
class SocketTag;

class NET_EXPORT StreamSocket : public Socket {
 public:
  using BeforeConnectCallback = base::RepeatingCallback<int()>;

  ~StreamSocket() override {}

  // Sets a callback to be invoked before establishing a connection. This allows
  // setting options, like receive and send buffer size, when they will take
  // effect. The callback should return net::OK on success, and an error on
  // failure. It must not return net::ERR_IO_PENDING.
  //
  // If multiple connection attempts are made, the callback will be invoked for
  // each one.
  virtual void SetBeforeConnectCallback(
      const BeforeConnectCallback& before_connect_callback);

  // Called to establish a connection.  Returns OK if the connection could be
  // established synchronously.  Otherwise, ERR_IO_PENDING is returned and the
  // given callback will run asynchronously when the connection is established
  // or when an error occurs.  The result is some other error code if the
  // connection could not be established.
  //
  // The socket's Read and Write methods may not be called until Connect
  // succeeds.
  //
  // It is valid to call Connect on an already connected socket, in which case
  // OK is simply returned.
  //
  // Connect may also be called again after a call to the Disconnect method.
  //
  virtual int Connect(CompletionOnceCallback callback) = 0;

  // Called to confirm the TLS handshake, if any, indicating that replay
  // protection is ready. Returns OK if the handshake could complete
  // synchronously or had already been confirmed. Otherwise, ERR_IO_PENDING is
  // returned and the given callback will run asynchronously when the connection
  // is established or when an error occurs.  The result is some other error
  // code if the connection could not be completed.
  //
  // This operation is only needed if TLS early data is enabled, in which case
  // Connect returns early and Write initially sends early data, which does not
  // have TLS's usual security properties. The caller must call this function
  // and wait for handshake confirmation before sending data that is not
  // replay-safe.
  //
  // ConfirmHandshake may run concurrently with Read or Write, but, as with Read
  // and Write, at most one pending ConfirmHandshake operation may be in
  // progress at a time.
  virtual int ConfirmHandshake(CompletionOnceCallback callback);

  // Called to disconnect a socket.  Does nothing if the socket is already
  // disconnected.  After calling Disconnect it is possible to call Connect
  // again to establish a new connection.
  //
  // If IO (Connect, Read, or Write) is pending when the socket is
  // disconnected, the pending IO is cancelled, and the completion callback
  // will not be called.
  virtual void Disconnect() = 0;

  // Called to test if the connection is still alive.  Returns false if a
  // connection wasn't established or the connection is dead.  True is returned
  // if the connection was terminated, but there is unread data in the incoming
  // buffer.
  virtual bool IsConnected() const = 0;

  // Called to test if the connection is still alive and idle.  Returns false
  // if a connection wasn't established, the connection is dead, or there is
  // unread data in the incoming buffer.
  virtual bool IsConnectedAndIdle() const = 0;

  // Copies the peer address to |address| and returns a network error code.
  // ERR_SOCKET_NOT_CONNECTED will be returned if the socket is not connected.
  virtual int GetPeerAddress(IPEndPoint* address) const = 0;

  // Copies the local address to |address| and returns a network error code.
  // ERR_SOCKET_NOT_CONNECTED will be returned if the socket is not bound.
  virtual int GetLocalAddress(IPEndPoint* address) const = 0;

  // Gets the NetLog for this socket.
  virtual const NetLogWithSource& NetLog() const = 0;

  // Returns true if the socket ever had any reads or writes.  StreamSockets
  // layered on top of transport sockets should return if their own Read() or
  // Write() methods had been called, not the underlying transport's.
  virtual bool WasEverUsed() const = 0;

  // Returns true if ALPN was negotiated during the connection of this socket.
  virtual bool WasAlpnNegotiated() const = 0;

  // Returns the protocol negotiated via ALPN for this socket, or
  // kProtoUnknown will be returned if ALPN is not applicable.
  virtual NextProto GetNegotiatedProtocol() const = 0;

  // Get data received from peer in ALPS TLS extension.
  // Returns a (possibly empty) value if a TLS version supporting ALPS was used
  // and ALPS was negotiated, nullopt otherwise.
  virtual absl::optional<base::StringPiece> GetPeerApplicationSettings() const;

  // Gets the SSL connection information of the socket.  Returns false if
  // SSL was not used by this socket.
  virtual bool GetSSLInfo(SSLInfo* ssl_info) = 0;

  // Gets the SSL CertificateRequest info of the socket after Connect failed
  // with ERR_SSL_CLIENT_AUTH_CERT_NEEDED.  Must not be called on a socket that
  // does not support SSL.
  virtual void GetSSLCertRequestInfo(
      SSLCertRequestInfo* cert_request_info) const;

  // Overwrites |out| with the connection attempts made in the process of
  // connecting this socket.
  virtual void GetConnectionAttempts(ConnectionAttempts* out) const = 0;

  // Clears the socket's list of connection attempts.
  virtual void ClearConnectionAttempts() = 0;

  // Adds |attempts| to the socket's list of connection attempts.
  virtual void AddConnectionAttempts(const ConnectionAttempts& attempts) = 0;

  // Returns the total number of number bytes read by the socket. This only
  // counts the payload bytes. Transport headers are not counted. Returns
  // 0 if the socket does not implement the function. The count is reset when
  // Disconnect() is called.
  virtual int64_t GetTotalReceivedBytes() const = 0;

  // Apply |tag| to this socket. If socket isn't yet connected, tag will be
  // applied when socket is later connected. If Connect() fails or socket
  // is closed, tag is cleared. If this socket is layered upon or wraps an
  // underlying socket, |tag| will be applied to the underlying socket in the
  // same manner as if ApplySocketTag() was called on the underlying socket.
  // The tag can be applied at any time, in other words active sockets can be
  // retagged with a different tag. Sockets wrapping multiplexed sockets
  // (e.g. sockets who proxy through a QUIC or Spdy stream) cannot be tagged as
  // the tag would inadvertently affect other streams; calling ApplySocketTag()
  // in this case will result in CHECK(false).
  virtual void ApplySocketTag(const SocketTag& tag) = 0;
};

}  // namespace net

#endif  // NET_SOCKET_STREAM_SOCKET_H_


text:
describe('DirectFtpTest', function() {
  it('some timing tests', function() {
    timerCallback = jasmine.createSpy("timerCallback");
    jasmine.clock().install();

    setTimeout(function() {
      timerCallback();
    }, 100);

    expect(timerCallback).not.toHaveBeenCalled();
    jasmine.clock().tick(101);
    expect(timerCallback).toHaveBeenCalled();

    jasmine.clock().uninstall();
  });
});


text:
package "qemu-kvm"
package "qemu-utils"


text:
module Y2016.M12.D21.Exercise where

import Data.Array

-- below imports available via @1HaskellADay git repository

import Data.SAIPE.USStates
import Data.SAIPE.USCounties

import Graph.ScoreCard
import Graph.KMeans

{--
So, now that we have the US county data, and as ScoreCard values.

Cluster these data.
--}

data Axes = Population | Poverty
   deriving (Eq, Ord, Show, Enum, Bounded, Ix)

clusterSAIPE :: [ScoreCard USCounty Axes Float]
             -> SCClusters Int USCounty Axes Float
clusterSAIPE counties = undefined

{--
And do this study:

1) what is the 'optimal'/most-makes-sense number of clusters?
2) what is the most populous cluster, county-population-wise and number of
   ScoreCard values-wise? What is the least populous cluster, same criteria?

Further study:
3) what associations do you see? Are there obvious City vs. Country differences?
   Other differences that are obvious?
4) Where do major cities fall? Together in one cluster? Or do they appear along
   more geographically divided lines?
--}


text:
require "cocoa"
local o = cocoa.NSConnection:rootProxyForConnectionWithRegisteredName_host_("lua-server",nil)
print("server object:",o)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SlimDX.Direct3D11;

using VVVV.DX11.Internals.Effects;
using VVVV.DX11;

using VVVV.PluginInterfaces.V2;

using FeralTic.Resources.Geometry;
using FeralTic.DX11;
using FeralTic.DX11.Resources;
using SlimDX.D3DCompiler;

namespace VVVV.DX11.Lib.Effects
{
    public class DX11ShaderData : IDX11Resource, IDisposable
    {
        private DX11RenderContext context;

        private DX11ShaderInstance shaderinstance;

        private EffectTechnique technique;
        private EffectPass pass;
        private PrimitiveTopology forcedTopology = PrimitiveTopology.Undefined;

        private DX11Effect shader;

        //Geometry/Layout Cache
        private List<InputLayout> layouts = new List<InputLayout>();
        private List<bool> layoutvalid = new List<bool>();
        private List<string> layoutmsg = new List<string>();

        private int passid;
        private int techid;

        //private DX11ShaderVariableManager varmanager;

        public bool IsValid { get { return this.shaderinstance != null; } }

        public List<bool> LayoutValid { get { return this.layoutvalid; } }
        public List<string> LayoutMsg { get { return this.layoutmsg; } }

        public DX11ShaderInstance ShaderInstance { get { return this.shaderinstance; } }

        public int PassCount
        {
            get
            {
                return this.technique.Description.PassCount;
            }
        }

        public DX11ShaderData(DX11RenderContext context, DX11Effect effect)
        {
            this.context = context;
            this.passid = 0;
            this.techid = 0;
            this.SetEffect(effect);
        }

        #region Set Effect
        private void SetEffect(DX11Effect shader)
        {
            //Create
            if (this.shader == null)
            {
                this.shader = shader;

                if (shader.IsCompiled)
                {
                    this.shaderinstance = new DX11ShaderInstance(this.context, shader.ByteCode);
                    this.UpdateTechnique();
                }
            }
            else
            {
                if (shader.IsCompiled)
                {
                    //Update shader
                    if (shader != this.shader)
                    {
                        //Dispose old effect if applicable
                        this.shader = shader;
                        if (this.shaderinstance != null) { this.shaderinstance.Dispose(); }
                        this.shaderinstance = new DX11ShaderInstance(this.context, shader.ByteCode);
                        this.UpdateTechnique();

                        this.DisposeLayouts();
                    }
                }
            }
        }
        #endregion

        #region Update
        public void Update(int techid, int passid, ISpread<DX11Resource<IDX11Geometry>> geoms)
        {
            this.techid = techid;
            this.passid = passid;
            this.UpdateTechnique();

            //Rebuild Layout
            this.DisposeLayouts();

            for (int i = 0; i < geoms.SliceCount; i++)
            {
                try
                {
                    if (pass.Description.Signature != null)
                    {
                        InputLayout layout = new InputLayout(this.context.Device, pass.Description.Signature, geoms[i][this.context].InputLayout);
                        this.layouts.Add(layout);
                        this.layoutvalid.Add(true);
                        this.layoutmsg.Add("OK");
                    }
                    else
                    {
                        this.layouts.Add(null);
                        this.layoutvalid.Add(true);
                        this.layoutmsg.Add("OK");
                    }
                }
                catch
                {
                    try
                    {
                        //Do bit of reflection work to get missing semantic
                        EffectShaderVariable vs = pass.VertexShaderDescription.Variable;
                        int inputcount = vs.GetShaderDescription(0).InputParameterCount;
                        string missingsemantics = "Geometry is missing semantics: ";

                        bool first = true;

                        for (int vip = 0; vip < inputcount; vip++)
                        {
                            ShaderParameterDescription sd = vs.GetInputParameterDescription(0, vip);

                            if (sd.SystemType == SystemValueType.Undefined) //Ignore SV semantics
                            {
                                bool found = false;
                                foreach (InputElement e in geoms[i][this.context].InputLayout)
                                {
                                    if (sd.SemanticName == e.SemanticName && sd.SemanticIndex == e.SemanticIndex)
                                    {
                                        found = true;
                                    }
                                }

                                if (!found)
                                {
                                    string sem = sd.SemanticIndex == 0 ? "" : sd.SemanticIndex.ToString();
                                    if (first) { first = false; } else { missingsemantics += " : "; }
                                    missingsemantics += sd.SemanticName + sem;
                                }
                            }
                        }

                        this.layouts.Add(null);
                        this.layoutvalid.Add(false);
                        this.layoutmsg.Add(missingsemantics);
                    }
                    catch (Exception ex)
                    {
                        //Just in case
                        this.layouts.Add(null);
                        this.layoutvalid.Add(false);
                        this.layoutmsg.Add(ex.Message);
                    }
                }
            }
        }
        #endregion

        #region Dispose
        public void DisposeLayouts()
        {
            for (int i = 0; i < this.layouts.Count; i++)
            {
                if (this.layouts[i] != null) { this.layouts[i].Dispose(); }
            }
            this.layouts.Clear();
            this.layoutvalid.Clear();
            this.layoutmsg.Clear();
        }

        public void Dispose()
        {
            this.DisposeLayouts();

            if (this.shaderinstance != null) { this.shaderinstance.Dispose(); }
        }
        #endregion

        #region Reset Shader Stages
        public void ResetShaderStages(DeviceContext ctx)
        {
            ctx.HullShader.Set(null);
            ctx.DomainShader.Set(null);
            ctx.VertexShader.Set(null);
            ctx.PixelShader.Set(null);
            ctx.GeometryShader.Set(null);
            ctx.ComputeShader.Set(null);
            ctx.ComputeShader.SetUnorderedAccessView(null, 0);
        }
        #endregion

        private void UpdateTechnique()
        {
            this.technique = this.shaderinstance.Effect.GetTechniqueByIndex(this.techid);
            this.pass = this.technique.GetPassByIndex(this.passid);
            this.forcedTopology = pass.Topology();
        }

        public bool IsLayoutValid(int slice)
        {
            return this.layoutvalid[slice % this.layoutvalid.Count];
        }

        public void SetInputAssembler(DeviceContext ctx, IDX11Geometry geom, int slice)
        {
            geom.Bind(this.layouts[slice % this.layouts.Count]);
            if (this.forcedTopology != PrimitiveTopology.Undefined)
            {
                ctx.InputAssembler.PrimitiveTopology = this.forcedTopology;
            }
        }

        #region Apply Pass
        public void ApplyPass(DeviceContext ctx, int passIndex= 0)
        {
            var cpass = this.technique.GetPassByIndex(passIndex);
            this.shaderinstance.ApplyPass(cpass);
        }
        #endregion
    }
}


text:
package org.javacc.parser;

/**
 * Describes a match, within a given lookahead.
 */
public class MatchInfo {
  public static int laLimit;
  int[] match = new int[laLimit];
  int firstFreeLoc;
  public static void reInit()
  {
    laLimit = 0;
  }
}


text:
/** Capitalize first character */
export function capitalize(str) {
  if (!str) {
    return undefined;
  }
  return str[0].toUpperCase() + str.substring(1);
}


text:
using System;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;

namespace Smartcard
{
    static class ChallengeResponseAlgorithm
    {
        /// <summary>
        /// Calculates the response by encrypting the challenge by using Triple DES (3DES).
        /// If the resulting values are the same, the authentication is successful.
        /// </summary>
        /// <param name="challenge">a block of challenge data generated by smart card using its admin key</param>
        /// <param name="adminkey">the admin key of the smart card, which is normally saved on the server side or management tool.</param>
        /// <returns>the response</returns>
        public static IBuffer CalculateResponse(IBuffer challenge, IBuffer adminkey)
        {
            if (challenge == null)
            {
                throw new ArgumentNullException("challenge");
            }
            if (adminkey == null)
            {
                throw new ArgumentNullException("adminkey");
            }

            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesCbc);
            var symmetricKey = objAlg.CreateSymmetricKey(adminkey);
            var buffEncrypted = CryptographicEngine.Encrypt(symmetricKey, challenge, null);
            return buffEncrypted;
        }
    }
}


text:
/**
 * @file mmap_file.h
 * @author Sean Massung
 *
 * All files in META are dual-licensed under the MIT and NCSA licenses. For more
 * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the
 * project.
 */

#ifndef META_MMAP_FILE_H_
#define META_MMAP_FILE_H_

#include <stdexcept>
#include <string>

namespace meta
{
namespace io
{

/**
 * Memory maps a text file readonly.
 */
class mmap_file
{
  public:
    /**
     * Constructor.
     * @param path Path to the text file to open
     */
    mmap_file(const std::string& path);

    /**
     * Move constructor.
     */
    mmap_file(mmap_file&&);

    /**
     * Move assignment operator.
     */
    mmap_file& operator=(mmap_file&&);

    /**
     * Destructor; deallocates memory used to store this object, closing the
     * text file.
     */
    ~mmap_file();

    /**
     * @param index The byte in the memory-mapped file to access
     * @return the requested byte; an exception is thrown if the index is
     * out of bounds of the mapped region
     */
    char operator[](uint64_t index) const;

    /**
     * @return the length of the file in bytes
     */
    uint64_t size() const;

    /**
     * @return the title of the text file (the parameter given to the
     * contructor)
     */
    std::string path() const;

    /**
     * @return a pointer to the beginning of the file
     */
    char* begin() const;

  private:
    /// Filename of the text file
    std::string path_;

    /// Pointer to the beginning of the text file
    char* start_;

    /// Size of the current text file
    uint64_t size_;

    /// File descriptor for the open text file
    int file_descriptor_;

    /// No copying */
    mmap_file(const mmap_file& other) = delete;

    /// no copying */
    const mmap_file& operator=(const mmap_file& other) = delete;

  public:
    /**
     * Basic exception for mmap_file interactions.
     */
    class mmap_file_exception : public std::runtime_error
    {
      public:
        using std::runtime_error::runtime_error;
    };
};
}
}

#endif


text:
package com.zheng.cms.rpc.service.impl;

import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.cms.dao.mapper.CmsCategoryTagMapper;
import com.zheng.cms.dao.model.CmsCategoryTag;
import com.zheng.cms.dao.model.CmsCategoryTagExample;
import com.zheng.cms.rpc.api.CmsCategoryTagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* CmsCategoryTagService实现
* Created by shuzheng on 2017/3/20.
*/
@Service
@Transactional
@BaseService
public class CmsCategoryTagServiceImpl extends BaseServiceImpl<CmsCategoryTagMapper, CmsCategoryTag, CmsCategoryTagExample> implements CmsCategoryTagService {

    private static Logger _log = LoggerFactory.getLogger(CmsCategoryTagServiceImpl.class);

    @Autowired
    CmsCategoryTagMapper cmsCategoryTagMapper;

}


text:
module Roroacms

  class Admin::SettingsController < AdminController

    add_breadcrumb I18n.t("generic.settings"), :admin_settings_path, :title => I18n.t("controllers.admin.settings.general.breadcrumb_title")

    # This controller is used for the settings page. This simply relates to all of the settings that are set in the database

    def index
      Setting.reload_settings
      @settings = Setting.get_all
      set_title(I18n.t("generic.settings"))
    end

    def create
      # To do update this table we loop through the fields and update the key with the value.
      # In order to do this we need to remove any unnecessary keys from the params hash
      remove_unwanted_keys

      # loop through the param fields and update the key with the value
      validation = Setting.manual_validation(params)

      respond_to do |format|
        if validation.blank?
          Setting.save_data(params)
          clear_cache
          format.html { redirect_to admin_settings_path, notice: I18n.t("controllers.admin.settings.general.create.flash.success") }
        else
          format.html {
            # add breadcrumb and set title
            @settings = params
            @settings['errors'] = validation
            @settings['user_groups'] = @json.encode(@settings['user_groups'])
            add_breadcrumb I18n.t("controllers.admin.comments.edit.breadcrumb")
            flash[:error] = I18n.t('generic.validation.no_passed')
            render action: "index"
          }
        end
      end

    end

    # creates a user group via an ajax call and returns the HTML for that user group

    def create_user_group
      @key = params[:key]
      print render :partial => 'roroacms/admin/partials/user_group_view'
    end

    private

    # removes any unnecessary param field ready for the loop in the create function

    def remove_unwanted_keys
      params.delete :utf8
      params.delete :authenticity_token
      params.delete :commit
      params.delete :redirect
    end

    # Strong parameters

    def settings_params
      params.permit(:setting_name, :setting)
    end

  end

end


text:
#include <complex.h>
#include <assert.h>

#include "misc/types.h"
#include "misc/misc.h"
#include "misc/debug.h"

#include "num/ops.h"
#include "num/ops_p.h"
#include "num/iovec.h"
#include "num/multind.h"
#include "num/flpmath.h"

#include "iter/iter.h"

#include "nlops/nlop.h"

#include "prox2.h"

/**
 * Data for computing prox_normaleq_fun:
 * Proximal function for f(z) = 0.5 || y - A z ||_2^2.
 *
 * @param op operator that applies A^H A
 * @param cgconf conf file for conjugate gradient iter interface
 * @param adj A^H y
 * @param size size of z
 */
struct prox_normaleq_data {

	INTERFACE(operator_data_t);

	const struct linop_s* op;
	void* cgconf;
	float* adj;

	long size;
};

static DEF_TYPEID(prox_normaleq_data);

/**
 * Proximal function for f(z) = 0.5 || y - A z ||_2^2.
 * Solution is (A^H A + (1/mu) I)z = A^H y + (1/mu)(x_plus_u)
 *
 * @param prox_data should be of type prox_normaleq_data
 * @param mu proximal penalty
 * @param z output
 * @param x_plus_u input
 */
static void prox_normaleq_fun(const operator_data_t* prox_data, float mu, float* z, const float* x_plus_u)
{
	auto pdata = CAST_DOWN(prox_normaleq_data, prox_data);

	if (0 == mu) {

		md_copy(1, MD_DIMS(pdata->size), z, x_plus_u, FL_SIZE);

	} else {

		float rho = 1. / mu;

		float* b = md_alloc_sameplace(1, MD_DIMS(pdata->size), FL_SIZE, x_plus_u);

		md_copy(1, MD_DIMS(pdata->size), b, pdata->adj, FL_SIZE);
		md_axpy(1, MD_DIMS(pdata->size), b, rho, x_plus_u);

		if (NULL == pdata->op->norm_inv) {

			struct iter_conjgrad_conf* cg_conf = pdata->cgconf;
			cg_conf->l2lambda = rho;

			iter_conjgrad(CAST_UP(cg_conf), pdata->op->normal, NULL, pdata->size, z, (float*)b, NULL);

		} else {

			linop_norm_inv_unchecked(pdata->op, rho, (complex float*)z, (const complex float*)b);
		}

		md_free(b);
	}
}

static void prox_normaleq_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
	prox_normaleq_fun(_data, mu, (float*)dst, (const float*)src);
}

static void prox_normaleq_del(const operator_data_t* _data)
{
	auto pdata = CAST_DOWN(prox_normaleq_data, _data);

	xfree(pdata->cgconf);
	md_free(pdata->adj);
	xfree(pdata);
}

const struct operator_p_s* prox_normaleq_create(const struct linop_s* op, const complex float* y)
{
	PTR_ALLOC(struct prox_normaleq_data, pdata);
	SET_TYPEID(prox_normaleq_data, pdata);
	PTR_ALLOC(struct iter_conjgrad_conf, cgconf);

	*cgconf = iter_conjgrad_defaults;
	cgconf->maxiter = 10;
	cgconf->l2lambda = 0;

	pdata->cgconf = PTR_PASS(cgconf);
	pdata->op = op;

	pdata->size = 2 * md_calc_size(linop_domain(op)->N, linop_domain(op)->dims);

	pdata->adj = md_alloc_sameplace(1, &(pdata->size), FL_SIZE, y);

	linop_adjoint_unchecked(op, (complex float*)pdata->adj, y);

	return operator_p_create(linop_domain(op)->N, linop_domain(op)->dims,
			linop_domain(op)->N, linop_domain(op)->dims,
			CAST_UP(PTR_PASS(pdata)), prox_normaleq_apply, prox_normaleq_del);
}

/**
 * Data for computing prox_lineq_fun:
 * Proximal function for f(z) = 1{ A z = y }
 * Assumes AA^T = I
 * Solution is z = x - A^T A x + A^T y
 *
 * @param op linop A
 * @param adj A^H y
 * @param tmp tmp
 */
struct prox_lineq_data {

	INTERFACE(operator_data_t);

	const struct linop_s* op;
	complex float* adj;
	complex float* tmp;
};

static DEF_TYPEID(prox_lineq_data);

static void prox_lineq_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
	UNUSED(mu);
	auto pdata = CAST_DOWN(prox_lineq_data, _data);

	const struct linop_s* op = pdata->op;
	linop_normal(op, linop_domain(op)->N, linop_domain(op)->dims, pdata->tmp, src);

	md_zsub(linop_domain(op)->N, linop_domain(op)->dims, dst, src, pdata->tmp);
	md_zadd(linop_domain(op)->N, linop_domain(op)->dims, dst, dst, pdata->adj);
}

static void prox_lineq_del(const operator_data_t* _data)
{
	auto pdata = CAST_DOWN(prox_lineq_data, _data);

	md_free(pdata->adj);
	md_free(pdata->tmp);
	xfree(pdata);
}

const struct operator_p_s* prox_lineq_create(const struct linop_s* op, const complex float* y)
{
	PTR_ALLOC(struct prox_lineq_data, pdata);
	SET_TYPEID(prox_lineq_data, pdata);

	unsigned int N = linop_domain(op)->N;
	const long* dims = linop_domain(op)->dims;

	pdata->op = op;

	pdata->adj = md_alloc_sameplace(N, dims, CFL_SIZE, y);
	linop_adjoint(op, N, dims, pdata->adj, N, linop_codomain(op)->dims, y);

	pdata->tmp = md_alloc_sameplace(N, dims, CFL_SIZE, y);

	return operator_p_create(N, dims, N, dims, CAST_UP(PTR_PASS(pdata)), prox_lineq_apply, prox_lineq_del);
}

/*
 * proximal function for a differentiable f(x) given \grad f(x)
 *
 */
struct prox_nlgrad_data {

	INTERFACE(operator_data_t);

	const struct nlop_s* op;

	float step_size;
	float lambda;
	int steps;
};

DEF_TYPEID(prox_nlgrad_data);

static void prox_nlgrad_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
	auto data = CAST_DOWN(prox_nlgrad_data, _data);

	mu *= data->lambda;

	auto dom = nlop_domain(data->op);
	auto cod = nlop_codomain(data->op);

	complex float* grd = md_alloc_sameplace(dom->N, dom->dims, dom->size, dst);

	complex float out[1];
	complex float grad_ys[1] = { 1. };

	md_copy(dom->N, dom->dims, dst, src, dom->size);

	for (int i = 0; i < data->steps; i++) {

		nlop_apply(data->op, cod->N, cod->dims, out, dom->N, dom->dims, dst);

		debug_printf(DP_DEBUG1, "Loss: %f\n", crealf(out[0]));

		nlop_adjoint(data->op, dom->N, dom->dims, grd, cod->N, cod->dims, grad_ys);

		if (0 < i) {

			md_zaxpy(dom->N, dom->dims, dst, -1. * data->step_size, dst);
			md_zaxpy(dom->N, dom->dims, dst, +1. * data->step_size, src);
		}

		md_zaxpy(dom->N, dom->dims, dst, -1. * data->step_size * mu, grd);		// xp <- x - s (x - y + l \grad f)
	}

	md_free(grd);
}

static void prox_nlgrad_del(const operator_data_t* _data)
{
	auto data = CAST_DOWN(prox_nlgrad_data, _data);

	nlop_free(data->op);

	xfree(data);
}

extern const struct operator_p_s* prox_nlgrad_create(const struct nlop_s* op, int steps, float step_size, float lambda)
{
	PTR_ALLOC(struct prox_nlgrad_data, data);
	SET_TYPEID(prox_nlgrad_data, data);

	auto dom = nlop_domain(op);
	auto cod = nlop_codomain(op);

	assert(CFL_SIZE == dom->size);
	assert(CFL_SIZE == cod->size);
	assert(1 == md_calc_size(cod->N, cod->dims));

	data->op = nlop_clone(op);
	data->lambda = lambda;
	data->step_size = step_size;
	data->steps = steps;

	return operator_p_create(dom->N, dom->dims, dom->N, dom->dims, CAST_UP(PTR_PASS(data)), prox_nlgrad_apply, prox_nlgrad_del);
}

struct auto_norm_s {

	INTERFACE(operator_data_t);

	enum norm norm;

	long flags;
	const struct operator_p_s* op;
};

DEF_TYPEID(auto_norm_s);

static void auto_norm_apply(const operator_data_t* _data, float mu, complex float* y, const complex float* x)
{
	auto data = CAST_DOWN(auto_norm_s, _data);

	auto io = operator_p_domain(data->op);

	unsigned int N = io->N;

	long sdims[N];
	md_select_dims(N, ~data->flags, sdims, io->dims);

	long sstrs[N];
	md_calc_strides(N, sstrs, sdims, CFL_SIZE);

#if 0
	complex float* scale = md_alloc_sameplace(N, sdims, CFL_SIZE, x);

	md_zrss(N, io->dims, data->flags, scale, x);
	md_zdiv2(N, io->dims, io->strs, y, io->strs, x, sstrs, scale);
#else
	long pos[N];
	for (unsigned int i = 0; i < N; i++)
		pos[i] = 0;

	long xdims[N];
	md_select_dims(N, data->flags, xdims, io->dims);

	complex float* scale = md_alloc(N, sdims, CFL_SIZE);

	typeof(md_znorm2)* norm2[] = {
		[NORM_L2] = md_znorm2,
		[NORM_MAX] = md_zmaxnorm2,
	};

	do {
		MD_ACCESS(N, sstrs, pos, scale) = norm2[data->norm](N, xdims, io->strs, &MD_ACCESS(N, io->strs, pos, x));

		complex float val = MD_ACCESS(N, sstrs, pos, scale);

		debug_printf(DP_DEBUG4, "auto normalize %f\n", crealf(val));

		md_zsmul2(N, xdims, io->strs, &MD_ACCESS(N, io->strs, pos, y),
				io->strs, &MD_ACCESS(N, io->strs, pos, x),
				(0. == val) ? 0. : (1. / val));

	} while (md_next(N, io->dims, ~data->flags, pos));
#endif

	operator_p_apply_unchecked(data->op, mu, y, y);	// FIXME: input == output
#if 0
	md_zmul2(N, io->dims, io->strs, y, io->strs, y, sstrs, scale);
#else
	for (unsigned int i = 0; i < N; i++)
		pos[i] = 0;

	do {
		complex float val = MD_ACCESS(N, sstrs, pos, scale);

		md_zsmul2(N, xdims, io->strs, &MD_ACCESS(N, io->strs, pos, y),
				io->strs, &MD_ACCESS(N, io->strs, pos, y),
				val);

	} while (md_next(N, io->dims, ~data->flags, pos));
#endif

	md_free(scale);
}

static void auto_norm_del(const operator_data_t* _data)
{
	auto data = CAST_DOWN(auto_norm_s, _data);

	operator_p_free(data->op);

	xfree(data);
}

/* This functor normalizes data along given dimensions and undoes
 * the normalization after application of the operator.
 *
 */
const struct operator_p_s* op_p_auto_normalize(const struct operator_p_s* op, long flags, enum norm norm)
{
	PTR_ALLOC(struct auto_norm_s, data);
	SET_TYPEID(auto_norm_s, data);

	data->flags = flags;
	data->op = operator_p_ref(op);
	data->norm = norm;

	auto io_in = operator_p_domain(op);
	auto io_out = operator_p_codomain(op);

	int N = io_in->N;
	long dims[N];
	md_copy_dims(N, dims, io_in->dims);

	long strs[N];
	md_calc_strides(N, strs, dims, CFL_SIZE);

	assert(N == io_out->N);
	assert(md_check_compat(N, 0L, dims, io_out->dims));
	assert(md_check_compat(N, 0L, strs, io_in->strs));
	assert(md_check_compat(N, 0L, strs, io_out->strs));

	return operator_p_create(N, dims, N, dims, CAST_UP(PTR_PASS(data)), auto_norm_apply, auto_norm_del);
}

const struct operator_p_s* op_p_conjugate(const struct operator_p_s* op, const struct linop_s* lop)
{
	return operator_p_pst_chain(operator_p_pre_chain(lop->forward, op), lop->adjoint);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Morthiera thuemenii Cooke

### Remarks
null


text:
from django.forms import Textarea, TextInput
from findingaids.fa.models import Deleted
from django.forms import ModelForm

class DeleteForm(ModelForm):
    class Meta:
        model = Deleted
        # NOTE: not excluding date from edit form because on an update it MAY
        # need to be changed, but only a person can determine that
        widgets = {
            'note': Textarea(attrs={'cols': 80, 'rows': 10}),
            # display eadid and title, but don't allow them to be edited
            'eadid': TextInput(attrs={'readonly': 'readonly'}),
            'title': TextInput(attrs={'size': '80', 'readonly': 'readonly'})
        }