text:
package user

import org.joda.time.DateTime
import org.scalatest.Matchers
import utils.FlatSpecWithSql

import scala.concurrent.ExecutionContext.Implicits.global

class UserRepositorySpec extends FlatSpecWithSql with Matchers {
  behavior of "UserRepository"

  val userRepo = new UserRepository

  it should "add new user" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get
    userRepo.findByUserId(userId).futureValue should equal(Some(user.copy(id = Some(userId))))
  }

  it should "get users" in {
    for (i <- 1 to 30) {
      val now = DateTime.now().getMillis
      userRepo.insert(User(None, now, "Jan", "Kowalski" + i, 1, None, None, None, 0)).futureValue
    }

    userRepo.getUsers(0, 20).futureValue should have size 20
  }

  it should "get users with offset greater than 0" in {
    for (i <- 1 to 50) {
      val now = DateTime.now().getMillis
      userRepo.insert(User(None, now, "Jan", "Kowalski" + i, 1, None, None, None, 0)).futureValue
    }

    userRepo.getUsers(23, 20).futureValue.last.lastName should be("Kowalski43")
  }

  it should "update user" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, Some("Marszalkowska 12/123"), Some("12-345"), Some("Warsaw"), 0)
    val userId = userRepo.insert(user).futureValue.id.get

    val newUser = user.copy(
      id = Some(userId),
      firstName = "Kasia",
      lastName = "Nowak",
      gender = 0,
      streetAddress = Some("Krucza 12"),
      postalCode = Some("65-432"),
      postalCity = Some("Radom")
    )
    userRepo.update(userId, newUser.firstName, newUser.lastName, newUser.gender, newUser.streetAddress, newUser.postalCode, newUser.postalCity).futureValue

    userRepo.findByUserId(userId).futureValue should equal(Some(newUser))
  }

  it should "update user role" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 0)
    val userId = userRepo.insert(user).futureValue.id.get

    userRepo.update(userId, 1).futureValue

    userRepo.findByUserId(userId).futureValue.map(_.role).get should be(1)
  }

  it should "delete user" in {
    val user = User(None, DateTime.now().getMillis, "Jan", "Kowalski", 1, None, None, None, 1)
    val userId = userRepo.insert(user).futureValue.id.get

    userRepo.delete(userId).futureValue

    userRepo.findByUserId(userId).futureValue should be(None)
  }
}

redpajama_set_name: RedPajamaGithub


text:
default: build test

fmt:
	go fmt github.com/DimensionDataResearch/terraform-octopus/...

build: fmt
	go build -o _bin/terraform-provider-octopus
	cp _bin/terraform-provider-octopus _bin/terraform-provisioner-octopus

test: fmt
	go test -v github.com/DimensionDataResearch/terraform-octopus/vendor/octopus


text:
"""Component to count within automations."""
import logging

import voluptuous as vol

from homeassistant.const import CONF_ICON, CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import ENTITY_SERVICE_SCHEMA
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import RestoreEntity

_LOGGER = logging.getLogger(__name__)

ATTR_INITIAL = "initial"
ATTR_STEP = "step"
ATTR_MINIMUM = "minimum"
ATTR_MAXIMUM = "maximum"

CONF_INITIAL = "initial"
CONF_RESTORE = "restore"
CONF_STEP = "step"

DEFAULT_INITIAL = 0
DEFAULT_STEP = 1
DOMAIN = "counter"

ENTITY_ID_FORMAT = DOMAIN + ".{}"

SERVICE_DECREMENT = "decrement"
SERVICE_INCREMENT = "increment"
SERVICE_RESET = "reset"
SERVICE_CONFIGURE = "configure"

SERVICE_SCHEMA_CONFIGURE = ENTITY_SERVICE_SCHEMA.extend(
    {
        vol.Optional(ATTR_MINIMUM): vol.Any(None, vol.Coerce(int)),
        vol.Optional(ATTR_MAXIMUM): vol.Any(None, vol.Coerce(int)),
        vol.Optional(ATTR_STEP): cv.positive_int,
    }
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: cv.schema_with_slug_keys(
            vol.Any(
                {
                    vol.Optional(CONF_ICON): cv.icon,
                    vol.Optional(
                        CONF_INITIAL, default=DEFAULT_INITIAL
                    ): cv.positive_int,
                    vol.Optional(CONF_NAME): cv.string,
                    vol.Optional(CONF_MAXIMUM, default=None): vol.Any(
                        None, vol.Coerce(int)
                    ),
                    vol.Optional(CONF_MINIMUM, default=None): vol.Any(
                        None, vol.Coerce(int)
                    ),
                    vol.Optional(CONF_RESTORE, default=True): cv.boolean,
                    vol.Optional(CONF_STEP, default=DEFAULT_STEP): cv.positive_int,
                },
                None,
            )
        )
    },
    extra=vol.ALLOW_EXTRA,
)

async def async_setup(hass, config):
    """Set up the counters."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        if not cfg:
            cfg = {}

        name = cfg.get(CONF_NAME)
        initial = cfg.get(CONF_INITIAL)
        restore = cfg.get(CONF_RESTORE)
        step = cfg.get(CONF_STEP)
        icon = cfg.get(CONF_ICON)
        minimum = cfg.get(CONF_MINIMUM)
        maximum = cfg.get(CONF_MAXIMUM)

        entities.append(
            Counter(object_id, name, initial, minimum, maximum, restore, step, icon)
        )

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_INCREMENT, ENTITY_SERVICE_SCHEMA, "async_increment"
    )
    component.async_register_entity_service(
        SERVICE_DECREMENT, ENTITY_SERVICE_SCHEMA, "async_decrement"
    )
    component.async_register_entity_service(
        SERVICE_RESET, ENTITY_SERVICE_SCHEMA, "async_reset"
    )
    component.async_register_entity_service(
        SERVICE_CONFIGURE, SERVICE_SCHEMA_CONFIGURE, "async_configure"
    )

    await component.async_add_entities(entities)
    return True

class Counter(RestoreEntity):
    """Representation of a counter."""

    def __init__(self, object_id, name, initial, minimum, maximum, restore, step, icon):
        """Initialize a counter."""
        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self._name = name
        self._restore = restore
        self._step = step
        self._state = self._initial = initial
        self._min = minimum
        self._max = maximum
        self._icon = icon

    @property
    def should_poll(self):
        """If entity should be polled."""
        return False

    @property
    def name(self):
        """Return name of the counter."""
        return self._name

    @property
    def icon(self):
        """Return the icon to be used for this entity."""
        return self._icon

    @property
    def state(self):
        """Return the current value of the counter."""
        return self._state

    @property
    def state_attributes(self):
        """Return the state attributes."""
        ret = {ATTR_INITIAL: self._initial, ATTR_STEP: self._step}
        if self._min is not None:
            ret[CONF_MINIMUM] = self._min
        if self._max is not None:
            ret[CONF_MAXIMUM] = self._max
        return ret

    def compute_next_state(self, state):
        """Keep the state within the range of min/max values."""
        if self._min is not None:
            state = max(self._min, state)
        if self._max is not None:
            state = min(self._max, state)

        return state

    async def async_added_to_hass(self):
        """Call when entity about to be added to Home Assistant."""
        await super().async_added_to_hass()
        # __init__ will set self._state to self._initial, only override
        # if needed.
        if self._restore:
            state = await self.async_get_last_state()
            if state is not None:
                self._state = self.compute_next_state(int(state.state))

    async def async_decrement(self):
        """Decrement the counter."""
        self._state = self.compute_next_state(self._state - self._step)
        await self.async_update_ha_state()

    async def async_increment(self):
        """Increment a counter."""
        self._state = self.compute_next_state(self._state + self._step)
        await self.async_update_ha_state()

    async def async_reset(self):
        """Reset a counter."""
        self._state = self.compute_next_state(self._initial)
        await self.async_update_ha_state()

    async def async_configure(self, **kwargs):
        """Change the counter's settings with a service."""
        if CONF_MINIMUM in kwargs:
            self._min = kwargs[CONF_MINIMUM]
        if CONF_MAXIMUM in kwargs:
            self._max = kwargs[CONF_MAXIMUM]
        if CONF_STEP in kwargs:
            self._step = kwargs[CONF_STEP]

        self._state = self.compute_next_state(self._state)
        await self.async_update_ha_state()


text:
api_major_version = 5   # bumped on incompatible changes
api_minor_version = 0   # bumped on compatible changes

from gps import *
from misc import *

# The 'client' module exposes some C utility functions for Python clients.
# The 'packet' module exposes the packet getter via a Python interface.


text: require('jquery')(require('../apps/commits/client.js').init)


text:
using Castle.Core;
using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Shinetechchina.Employee.Repository.Shared;
using Shinetechchina.Employee.Infrastructure.Logging;

namespace Shinetechchina.Employee.Repository.Core
{
    public class RepositoryCoreInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Component.For<IEmployeeRepository>()
                .ImplementedBy<EmployeeRepository>().LifestyleTransient()
                .Interceptors(new InterceptorReference(typeof(LoggingInterceptor))).First);

            container.Register(Component.For<EmployeeDbContext>().ImplementedBy<EmployeeDbContext>().LifestyleTransient());
            container.Register(Component.For<IUnitOfWork>().ImplementedBy<UnitOfWork>().LifestyleTransient());
        }
    }
}


text:
package datafu.hourglass.avro;

import java.io.IOException;

import org.apache.avro.Schema;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.avro.mapreduce.AvroKeyRecordReader;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.CombineFileRecordReader;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.log4j.Logger;

import datafu.hourglass.jobs.AbstractPartitionPreservingIncrementalJob;

/**
 * A combined input format for reading Avro data.
 *
 * @param <T> Type of data to be read
 */
public class CombinedAvroKeyInputFormat<T> extends CombineFileInputFormat<AvroKey<T>, NullWritable>
{
  private final Logger LOG = Logger.getLogger(AbstractPartitionPreservingIncrementalJob.class);

  public static class CombinedAvroKeyRecordReader<T> extends AvroKeyRecordReader<T>
  {
    private CombineFileSplit inputSplit;
    private Integer idx;

    public CombinedAvroKeyRecordReader(CombineFileSplit inputSplit, TaskAttemptContext context, Integer idx)
    {
      super(AvroJob.getInputKeySchema(context.getConfiguration()));
      this.inputSplit = inputSplit;
      this.idx = idx;
    }

    @Override
    public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException,
        InterruptedException
    {
      this.inputSplit = (CombineFileSplit)inputSplit;

      FileSplit fileSplit = new FileSplit(this.inputSplit.getPath(idx),
                                          this.inputSplit.getOffset(idx),
                                          this.inputSplit.getLength(idx),
                                          this.inputSplit.getLocations());

      super.initialize(fileSplit, context);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public RecordReader<AvroKey<T>, NullWritable> createRecordReader(InputSplit inputSplit,
                                                                   TaskAttemptContext context) throws IOException
  {
    Schema readerSchema = AvroJob.getInputKeySchema(context.getConfiguration());
    if (null == readerSchema) {
      LOG.warn("Reader schema was not set. Use AvroJob.setInputKeySchema() if desired.");
      LOG.info("Using a reader schema equal to the writer schema.");
    }

    Object c = CombinedAvroKeyRecordReader.class;
    return new CombineFileRecordReader<AvroKey<T>, NullWritable>((CombineFileSplit) inputSplit, context, (Class<? extends RecordReader<AvroKey<T>, NullWritable>>)c);
  }

}


text:
angular.module('common')
    .factory('SubjectDataProvider', ['$http', '$q', function ($http, $q) {

        var getSubject = function(subjectId) {
            var defered = $q.defer();
            var thePromise = defered.promise;
            $http({
                method: "GET",
                url: "/subjects/" + subjectId
            }).success(function(subject){
                defered.resolve(subject);
            }).error(function(err){
                defered.reject(err);
            });
            return thePromise;
        };

        var getAllSubjects = function () {
            var defered = $q.defer();
            var thePromise = defered.promise;
            $http({
                method: "GET",
                url: "/subjects"
            }).success(function (subjects) {
                defered.resolve(subjects);
            }).error(function (err) {
                defered.reject(err);
                console.log(err);
            });
            return thePromise;
        };

        var createSubject = function(name) {
            return $http({
                method: "POST",
                url: '/subjects',
                data: {
                    name: name
                }
            })
        };

        var editSubject = function(info) {
            var defered = $q.defer();
            var thePromise = defered.promise;
            $http({
                method: "PUT",
                url: '/subjects/' + info._id,
                data: {
                    name: info.name
                }
            }).success(function(){
                defered.resolve(true);
            }).error(function(err){
                console.error(err);
                defered.reject('科目已存在');
            });
            return thePromise;
        };

        var deleteSubject = function(subjectId) {
            return $http({
                method: "DELETE",
                url: '/subjects/' + subjectId
            })
        };

        return {
            getSubject: getSubject,
            getAllSubjects: getAllSubjects,
            createSubject: createSubject,
            editSubject: editSubject,
            deleteSubject: deleteSubject

        };
    }]);


text:
#import <Foundation/Foundation.h>

@protocol IJKAudioSessionDelegate <NSObject>

- (void)ijkAudioBeginInterruption;
- (void)ijkAudioEndInterruption;

@end

@interface IJKAudioKit : NSObject

+ (IJKAudioKit *)sharedInstance;
- (void)setupAudioSession:(id<IJKAudioSessionDelegate>) delegate;

@end


text:
package OpenstaackAndJclods.deployer;

import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.getOnlyElement;

import java.util.Properties;
import java.util.Set;

import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;

import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;

public class Deployer {

	public static void main(String[] args) {

		Iterable<Module> modules = ImmutableSet.<Module>of(new SLF4JLoggingModule());

	    Properties overrides = new Properties();

	    String provider = "openstack-nova";
	    String identity =Configuration.KEYSTONE_USERNAME+":"+Configuration.TENANT_NAME;// ExamplesConfiguration.KEYSTONE_USERNAME;
	    String credential = "openstack";//ExamplesConfiguration.KEYSTONE_PASSWORD;
	    String groupName = "default";

	   //Connection to Compute Service
	    ComputeServiceContext context = ContextBuilder.newBuilder("openstack-nova")
	    		.endpoint(Configuration.NOVA_ENDPOINT)
	    		 .credentials(identity, credential)
	            .modules(modules)
	            .overrides(overrides)
                .buildView(ComputeServiceContext.class);

	    ComputeService computeService = context.getComputeService();
	    org.jclouds.compute.domain.Image img = computeService.getImage("RegionOne/7402865e-9c64-409d-b977-2d760788b321");
	    System.out.println(img.getId());

	    Set<? extends org.jclouds.compute.domain.Image> imgs = computeService.listImages();
	    for(org.jclouds.compute.domain.Image i:imgs){
	    	System.out.println(i.getId());
	    }

	      //NovaClient client = context.getApi();

	    TemplateBuilder tb = computeService.templateBuilder();
	    tb.minRam(Integer.parseInt("512"));
	    tb.imageId("RegionOne/f72885a5-e681-4219-b931-bb062d74c591");
	    NodeMetadata node1=null;
		try {
			node1 = getOnlyElement(computeService.createNodesInGroup(groupName, 1, tb.build()));
		} catch (RunNodesException e) {

			e.printStackTrace();
		}
	    System.out.printf("<< node %s: %s%n", node1.getId(),
                concat(node1.getPrivateAddresses(), node1.getPublicAddresses()));

	    Set<? extends ComputeMetadata> cc=computeService.listNodes();
	    for (ComputeMetadata node : cc) {
	    	   System.out.println("\n\n\n\n\nMACHINE:"+node.getId());
	    	   System.out.println(node.getProviderId());
	    	   System.out.println(node.getName());
	    	   System.out.println(node.getLocation());
	    	   NodeMetadata metadata = computeService.getNodeMetadata(node.getId());
	    	   System.out.println(metadata.getId());
	    	   System.out.println( metadata.getProviderId());
	    	   System.out.println(metadata.getLocation());
	    	   System.out.println(metadata.getName());
	    	   System.out.println(metadata.getGroup());
	    	   System.out.println( metadata.getHardware());
	    	   System.out.println( metadata.getImageId());
	    	   System.out.println(metadata.getOperatingSystem());
	    	   System.out.println("CREDENTIAL:"+metadata.getCredentials());
	    	   System.out.println(metadata.getPrivateAddresses());
	    	   System.out.println(metadata.getPublicAddresses());
	    	   System.out.println(metadata.getCredentials());
	    	}

	}

}


text:
package bsp1;

import server.Server;

public class ServerConsoleStarter {
	public static void main(String[] args) {

		try{
			Server s = new Server(Integer.valueOf(args[0]).intValue(),Integer.valueOf(args[1]).intValue());
		} catch(Exception e) {
			System.out.println("Usage: ServerConsoleStarter TCPPort UDPPort");
			System.err.println("[ServerConsoleStarter]: Error while retrieving the arguments:"+e);
			System.exit(0);
		}
	}
}


text:
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/glue/model/SchemaStatus.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Glue
{
namespace Model
{

  /**
   *
An object that contains minimal details for a schema.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_GLUE_API SchemaListItem
  {
  public:
    SchemaListItem();
    SchemaListItem(Aws::Utils::Json::JsonView jsonValue);
    SchemaListItem& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
the name of the registry where the schema resides.

     */
    inline const Aws::String& GetRegistryName() const{ return m_registryName; }

    /**
     *
the name of the registry where the schema resides.

     */
    inline bool RegistryNameHasBeenSet() const { return m_registryNameHasBeenSet; }

    /**
     *
the name of the registry where the schema resides.

     */
    inline void SetRegistryName(const Aws::String& value) { m_registryNameHasBeenSet = true; m_registryName = value; }

    /**
     *
the name of the registry where the schema resides.

     */
    inline void SetRegistryName(Aws::String&& value) { m_registryNameHasBeenSet = true; m_registryName = std::move(value); }

    /**
     *
the name of the registry where the schema resides.

     */
    inline void SetRegistryName(const char* value) { m_registryNameHasBeenSet = true; m_registryName.assign(value); }

    /**
     *
the name of the registry where the schema resides.

     */
    inline SchemaListItem& WithRegistryName(const Aws::String& value) { SetRegistryName(value); return *this;}

    /**
     *
the name of the registry where the schema resides.

     */
    inline SchemaListItem& WithRegistryName(Aws::String&& value) { SetRegistryName(std::move(value)); return *this;}

    /**
     *
the name of the registry where the schema resides.

     */
    inline SchemaListItem& WithRegistryName(const char* value) { SetRegistryName(value); return *this;}

    /**
     *
The name of the schema.

     */
    inline const Aws::String& GetSchemaName() const{ return m_schemaName; }

    /**
     *
The name of the schema.

     */
    inline bool SchemaNameHasBeenSet() const { return m_schemaNameHasBeenSet; }

    /**
     *
The name of the schema.

     */
    inline void SetSchemaName(const Aws::String& value) { m_schemaNameHasBeenSet = true; m_schemaName = value; }

    /**
     *
The name of the schema.

     */
    inline void SetSchemaName(Aws::String&& value) { m_schemaNameHasBeenSet = true; m_schemaName = std::move(value); }

    /**
     *
The name of the schema.

     */
    inline void SetSchemaName(const char* value) { m_schemaNameHasBeenSet = true; m_schemaName.assign(value); }

    /**
     *
The name of the schema.

     */
    inline SchemaListItem& WithSchemaName(const Aws::String& value) { SetSchemaName(value); return *this;}

    /**
     *
The name of the schema.

     */
    inline SchemaListItem& WithSchemaName(Aws::String&& value) { SetSchemaName(std::move(value)); return *this;}

    /**
     *
The name of the schema.

     */
    inline SchemaListItem& WithSchemaName(const char* value) { SetSchemaName(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline const Aws::String& GetSchemaArn() const{ return m_schemaArn; }

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline bool SchemaArnHasBeenSet() const { return m_schemaArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline void SetSchemaArn(const Aws::String& value) { m_schemaArnHasBeenSet = true; m_schemaArn = value; }

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline void SetSchemaArn(Aws::String&& value) { m_schemaArnHasBeenSet = true; m_schemaArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline void SetSchemaArn(const char* value) { m_schemaArnHasBeenSet = true; m_schemaArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline SchemaListItem& WithSchemaArn(const Aws::String& value) { SetSchemaArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline SchemaListItem& WithSchemaArn(Aws::String&& value) { SetSchemaArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) for the schema.

     */
    inline SchemaListItem& WithSchemaArn(const char* value) { SetSchemaArn(value); return *this;}

    /**
     *
A description for the schema.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
A description for the schema.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
A description for the schema.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
A description for the schema.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
A description for the schema.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
A description for the schema.

     */
    inline SchemaListItem& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
A description for the schema.

     */
    inline SchemaListItem& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
A description for the schema.

     */
    inline SchemaListItem& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The status of the schema.

     */
    inline const SchemaStatus& GetSchemaStatus() const{ return m_schemaStatus; }

    /**
     *
The status of the schema.

     */
    inline bool SchemaStatusHasBeenSet() const { return m_schemaStatusHasBeenSet; }

    /**
     *
The status of the schema.

     */
    inline void SetSchemaStatus(const SchemaStatus& value) { m_schemaStatusHasBeenSet = true; m_schemaStatus = value; }

    /**
     *
The status of the schema.

     */
    inline void SetSchemaStatus(SchemaStatus&& value) { m_schemaStatusHasBeenSet = true; m_schemaStatus = std::move(value); }

    /**
     *
The status of the schema.

     */
    inline SchemaListItem& WithSchemaStatus(const SchemaStatus& value) { SetSchemaStatus(value); return *this;}

    /**
     *
The status of the schema.

     */
    inline SchemaListItem& WithSchemaStatus(SchemaStatus&& value) { SetSchemaStatus(std::move(value)); return *this;}

    /**
     *
The date and time that a schema was created.

     */
    inline const Aws::String& GetCreatedTime() const{ return m_createdTime; }

    /**
     *
The date and time that a schema was created.

     */
    inline bool CreatedTimeHasBeenSet() const { return m_createdTimeHasBeenSet; }

    /**
     *
The date and time that a schema was created.

     */
    inline void SetCreatedTime(const Aws::String& value) { m_createdTimeHasBeenSet = true; m_createdTime = value; }

    /**
     *
The date and time that a schema was created.

     */
    inline void SetCreatedTime(Aws::String&& value) { m_createdTimeHasBeenSet = true; m_createdTime = std::move(value); }

    /**
     *
The date and time that a schema was created.

     */
    inline void SetCreatedTime(const char* value) { m_createdTimeHasBeenSet = true; m_createdTime.assign(value); }

    /**
     *
The date and time that a schema was created.

     */
    inline SchemaListItem& WithCreatedTime(const Aws::String& value) { SetCreatedTime(value); return *this;}

    /**
     *
The date and time that a schema was created.

     */
    inline SchemaListItem& WithCreatedTime(Aws::String&& value) { SetCreatedTime(std::move(value)); return *this;}

    /**
     *
The date and time that a schema was created.

     */
    inline SchemaListItem& WithCreatedTime(const char* value) { SetCreatedTime(value); return *this;}

    /**
     *
The date and time that a schema was updated.

     */
    inline const Aws::String& GetUpdatedTime() const{ return m_updatedTime; }

    /**
     *
The date and time that a schema was updated.

     */
    inline bool UpdatedTimeHasBeenSet() const { return m_updatedTimeHasBeenSet; }

    /**
     *
The date and time that a schema was updated.

     */
    inline void SetUpdatedTime(const Aws::String& value) { m_updatedTimeHasBeenSet = true; m_updatedTime = value; }

    /**
     *
The date and time that a schema was updated.

     */
    inline void SetUpdatedTime(Aws::String&& value) { m_updatedTimeHasBeenSet = true; m_updatedTime = std::move(value); }

    /**
     *
The date and time that a schema was updated.

     */
    inline void SetUpdatedTime(const char* value) { m_updatedTimeHasBeenSet = true; m_updatedTime.assign(value); }

    /**
     *
The date and time that a schema was updated.

     */
    inline SchemaListItem& WithUpdatedTime(const Aws::String& value) { SetUpdatedTime(value); return *this;}

    /**
     *
The date and time that a schema was updated.

     */
    inline SchemaListItem& WithUpdatedTime(Aws::String&& value) { SetUpdatedTime(std::move(value)); return *this;}

    /**
     *
The date and time that a schema was updated.

     */
    inline SchemaListItem& WithUpdatedTime(const char* value) { SetUpdatedTime(value); return *this;}

  private:

    Aws::String m_registryName;
    bool m_registryNameHasBeenSet;

    Aws::String m_schemaName;
    bool m_schemaNameHasBeenSet;

    Aws::String m_schemaArn;
    bool m_schemaArnHasBeenSet;

    Aws::String m_description;
    bool m_descriptionHasBeenSet;

    SchemaStatus m_schemaStatus;
    bool m_schemaStatusHasBeenSet;

    Aws::String m_createdTime;
    bool m_createdTimeHasBeenSet;

    Aws::String m_updatedTime;
    bool m_updatedTimeHasBeenSet;
  };

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
package com.timgroup.stanislavski.interpreters;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AddressesProperty {
    String value();
}


text:
using System;
using AutoMapper;
using CSF.Entities;
using CSF.ORM;

namespace Agiil.ObjectMaps.Resolvers
{
    public class GetEntityByIdentityResolver<TEntity> : IMemberValueResolver<object, object, IIdentity<TEntity>, TEntity>
      where TEntity : class, IEntity
    {
        readonly IEntityData repo;

        public TEntity Resolve(object source,
                               object destination,
                               IIdentity<TEntity> sourceMember,
                               TEntity destMember,
                               ResolutionContext context)
        {
            return (sourceMember != null) ? repo.Get(sourceMember) : null;
        }

        public GetEntityByIdentityResolver(IEntityData repo)
        {
            this.repo = repo ?? throw new ArgumentNullException(nameof(repo));
        }
    }
}


text:
package engine

import (
	"fmt"
	"strconv"

	"github.com/Wikia/influxdb/parser"
	"github.com/Wikia/influxdb/protocol"
)

func getExpressionValue(values []*parser.Value, fields []string, point *protocol.Point) ([]*protocol.FieldValue, error) {
	fieldValues := []*protocol.FieldValue{}
	for _, value := range values {
		switch value.Type {
		case parser.ValueFunctionCall:
			return nil, fmt.Errorf("Cannot process function call %s in expression", value.Name)
		case parser.ValueInt:
			value, err := strconv.ParseInt(value.Name, 10, 64)
			if err == nil {
				fieldValues = append(fieldValues, &protocol.FieldValue{Int64Value: &value})
				continue
			}
			// an error will happen only if the integer is out of range
			fallthrough
		case parser.ValueFloat:
			value, _ := strconv.ParseFloat(value.Name, 64)
			fieldValues = append(fieldValues, &protocol.FieldValue{DoubleValue: &value})
		case parser.ValueBool:
			value, _ := strconv.ParseBool(value.Name)
			fieldValues = append(fieldValues, &protocol.FieldValue{BoolValue: &value})
		case parser.ValueString:
			fieldValues = append(fieldValues, &protocol.FieldValue{StringValue: &value.Name})
		case parser.ValueRegex:
			regex, _ := value.GetCompiledRegex()
			regexStr := regex.String()
			fieldValues = append(fieldValues, &protocol.FieldValue{StringValue: &regexStr})

		case parser.ValueTableName, parser.ValueSimpleName:

			// TODO: optimize this so we don't have to lookup the column everytime
			fieldIdx := -1
			for idx, field := range fields {
				if field == value.Name {
					fieldIdx = idx
					break
				}
			}

			if fieldIdx == -1 {
				return nil, fmt.Errorf("Cannot find column %s", value.Name)
			}
			fieldValues = append(fieldValues, point.Values[fieldIdx])

		case parser.ValueExpression:
			v, err := GetValue(value, fields, point)
			if err != nil {
				return nil, err
			}
			fieldValues = append(fieldValues, v)
		default:
			return nil, fmt.Errorf("Cannot evaluate expression")
		}
	}

	return fieldValues, nil
}

func matchesExpression(expr *parser.Value, fields []string, point *protocol.Point) (bool, error) {
	leftValue, err := getExpressionValue(expr.Elems[:1], fields, point)
	if err != nil {
		return false, err
	}
	rightValue, err := getExpressionValue(expr.Elems[1:], fields, point)
	if err != nil {
		return false, err
	}

	operator := registeredOperators[expr.Name]
	if operator == nil {
		return false, fmt.Errorf("Invalid boolean operator %s", expr.Name)
	}

	ok, err := operator(leftValue[0], rightValue)
	return ok == MATCH, err
}

func matches(condition *parser.WhereCondition, fields []string, point *protocol.Point) (bool, error) {
	if expr, ok := condition.GetBoolExpression(); ok {
		return matchesExpression(expr, fields, point)
	}

	left, _ := condition.GetLeftWhereCondition()
	leftResult, err := matches(left, fields, point)
	if err != nil {
		return false, err
	}

	// short circuit
	if !leftResult && condition.Operation == "AND" ||
		leftResult && condition.Operation == "OR" {
		return leftResult, nil
	}

	return matches(condition.Right, fields, point)
}

func getColumns(values []*parser.Value, columns map[string]bool) {
	for _, v := range values {
		switch v.Type {
		case parser.ValueSimpleName:
			columns[v.Name] = true
		case parser.ValueWildcard:
			columns["*"] = true
			return
		case parser.ValueFunctionCall:
			getColumns(v.Elems, columns)
		}
	}
}

func filterColumns(columns map[string]struct{}, fields []string, point *protocol.Point) {
	if _, ok := columns["*"]; ok {
		return
	}

	newValues := []*protocol.FieldValue{}
	newFields := []string{}
	for idx, f := range fields {
		if _, ok := columns[f]; !ok {
			continue
		}

		newValues = append(newValues, point.Values[idx])
		newFields = append(newFields, f)
	}
	point.Values = newValues
}

func Filter(query *parser.SelectQuery, series *protocol.Series) (*protocol.Series, error) {
	if query.GetWhereCondition() == nil {
		return series, nil
	}

	columns := map[string]struct{}{}
	if query.GetFromClause().Type == parser.FromClauseInnerJoin {
	outer:
		for t, cs := range query.GetResultColumns() {
			for _, c := range cs {
				// if this is a wildcard select, then drop all columns and
				// just use '*'
				if c == "*" {
					columns = make(map[string]struct{}, 1)
					columns[c] = struct{}{}
					break outer
				}
				columns[t.Name+"."+c] = struct{}{}
			}
		}
	} else {
		for _, cs := range query.GetResultColumns() {
			for _, c := range cs {
				columns[c] = struct{}{}
			}
		}
	}

	points := series.Points
	series.Points = nil
	for _, point := range points {
		ok, err := matches(query.GetWhereCondition(), series.Fields, point)

		if err != nil {
			return nil, err
		}

		if ok {
			filterColumns(columns, series.Fields, point)
			series.Points = append(series.Points, point)
		}
	}

	if _, ok := columns["*"]; !ok {
		newFields := []string{}
		for _, f := range series.Fields {
			if _, ok := columns[f]; !ok {
				continue
			}

			newFields = append(newFields, f)
		}
		series.Fields = newFields
	}
	return series, nil
}


text:
layout: vitae_layout
---

{% include vitae/employment.html %}

{% include vitae/education.html %}

{% include vitae/skills.html %}

<!--{% include vitae/initiatives.html %}-->
{% include vitae/interests.html %}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `MapOption` enum in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, MapOption">

    <title>std::os::MapOption - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

std::<wbr>os

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Enum std::<wbr>os::<wbr>MapOption<wbr>Unstable
            [-] [+]
        [src]

pub enum MapOption {
    MapReadable,
    MapWritable,
    MapExecutable,
    MapAddr(*const u8),
    MapFd(HANDLE),
    MapOffset(usize),
    MapNonStandardFlags(c_int),
}

Options the memory map is created with

Variants

MapReadable

The memory should be readable

MapWritable

The memory should be writable

MapExecutable

The memory should be executable

MapAddr

Create a map for a specific address range. Corresponds to MAP_FIXED on
POSIX.

MapFd

Create a memory mapping for a file with a given HANDLE.

MapOffset

When using MapFd, the start of the map is uint bytes from the start
of the file.

MapNonStandardFlags

On POSIX, this can be used to specify the default flags passed to
mmap. By default it uses MAP_PRIVATE and, if not using MapFd,
MAP_ANON. This will override both of those. This is platform-specific
(the exact values used) and ignored on Windows.

Trait Implementations

Derived Implementations

impl Copy for MapOption

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
var mongoose = require('mongoose');
var config = require('../config/database.json');
module.exports = {
    init: function () {
        mongoose.connect('mongodb://' + config.address + ':' + config.port + '/' + config.schema);
    }
};


text:
namespace DiscUtils.LogicalDiskManager
{
    using System;

    internal sealed class VolumeRecord : DatabaseRecord
    {
        public string GenString;
        public string NumberString; // 8000000000000000 sometimes...
        public string ActiveString;
        public ulong UnknownA; // Zero
        public ulong UnknownB; // 00 .. 03
        public ulong DupCount; // ??Seen once after adding 'foreign disk', from broken mirror (identical links(P/V/C))
        public uint UnknownC; // 00 00 00 11
        public ulong ComponentCount;
        public uint UnknownD; // Zero
        public uint PartitionComponentLink;
        public ulong Unknown1; // Zero
        public long Size;
        public uint Unknown2; // Zero
        public byte BiosType;
        public Guid VolumeGuid;
        public string MountHint;

        protected override void DoReadFrom(byte[] buffer, int offset)
        {
            base.DoReadFrom(buffer, offset);

            int pos = offset + 0x18;

            Id = ReadVarULong(buffer, ref pos);
            Name = ReadVarString(buffer, ref pos);
            GenString = ReadVarString(buffer, ref pos);
            NumberString = ReadVarString(buffer, ref pos);
            ActiveString = ReadString(buffer, 6, ref pos);
            UnknownA = ReadVarULong(buffer, ref pos);
            UnknownB = ReadULong(buffer, ref pos);
            DupCount = ReadVarULong(buffer, ref pos);
            UnknownC = ReadUInt(buffer, ref pos);
            ComponentCount = ReadVarULong(buffer, ref pos);
            UnknownD = ReadUInt(buffer, ref pos);
            PartitionComponentLink = ReadUInt(buffer, ref pos);
            Unknown1 = ReadULong(buffer, ref pos);
            Size = ReadVarLong(buffer, ref pos);
            Unknown2 = ReadUInt(buffer, ref pos);
            BiosType = ReadByte(buffer, ref pos);
            VolumeGuid = Utilities.ToGuidBigEndian(buffer, pos);
            pos += 16;

            if ((Flags & 0x0200) != 0)
            {
                MountHint = ReadVarString(buffer, ref pos);
            }
        }
    }
}


text:
Title: Commenting part 3
Date: 2017-01-25 19:11
Category: Blog

I missed writing blog for two days in a row. I'll make up for it tonight with some thoughts on random subjects. Regarding the comments, looks like firebase deprecated the 2.x projects, so I'll have to make a new comments webapp in 3.x That might take some time, but I want to get done by this weekend, otherwise I'll add the email one (I think it was #5).


text:
RSpec.shared_examples 'template checks' do
  it 'has no missing translations' do
    html = mail.html_part.body
    expect(html).not_to match(/translation missing/)
  end
end

RSpec.shared_examples 'noreply checks' do
  it "sets a noreply subdomain for the 'from' header" do
    expect(mail.from.first).to match(/@robot./)
  end
end

RSpec.shared_examples 'skipping email for the trial' do
  it 'does not send emails for prisons in the dashboard trial' do
    allow(Rails.configuration).
      to receive(:dashboard_trial).
      and_return([visit.prison.estate.name])

    expect(mail.to).to be_nil
  end
end

RSpec.shared_examples 'when the prison is not on prison finder' do
  it 'does not display the link to the Prison Finder service' do
    medway_prison.name = 'Medway Secure Training Centre'
    medway_prison.save

    expect(mail.html_part.body).not_to match(%r{http:\/\/www.justice.gov.uk\/contacts\/prison-finder})
  end
end


text:
package zutil.net.ws;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 *
 * Specifies web service definitions. Which methods that will
 * be published and other related metadata.
 * Only public and non static methods will be published or
 * the WSIgnore annotation can be used to ignore the specific method.
 *
 * Example:
 * <pre>
 *	private static class Test implements WSInterface{
 *		public Test() {}
 *
 *		@WSDocumentation("This is a description of the method")
 *		@WSParamDocumentation("arg1 = variable description?")
 *		public void pubZ(
 *				@WSParamName("arg1") int randomName)
 *				throws Exception{
 *			....
 *		}
 *
 *		@WSReturnName("param")
 *		public String pubA(
 *				@WSParamName(value="optArg", optional=true) String optionalParam)
 *				throws Exception{
 *			....
 *		}
 *
 *		@WSIgnore()
 *		public void privatZ(....) {
 *			...
 *		}
 *	}
 *
 * </pre>
 * @author Ziver
 */
public interface WSInterface {

    enum RequestType {
        GET,
        POST,
        PUT,
        DELETE,
        PATCH
    }

    /**
     * Annotation that assigns a name to an parameters
     * in an method.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.PARAMETER, ElementType.FIELD})
    @interface WSParamName {
        String value();
        boolean optional() default false;
    }

    /**
     * Annotation that assigns a name to the return value
     * in an method.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface WSReturnName {
        String value();
    }

    /**
     * Skipp publication of the given method
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface WSIgnore {}

    /**
     * Method or Parameter comments for the WSDL.
     * These comments are put in the message part of the WSDL
     */
    @Retention(RetentionPolicy.RUNTIME)
    @interface WSDocumentation {
        String value();
    }

    /**
     * This method will be used in the SOAP header.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface WSHeader {}

    /**
     * Specifies the request type.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface WSRequestType {
        RequestType value();
    }

    /**
     * Sets a specific URL path for the method overriding the auto generated path. This will also be used as the namespace.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.METHOD})
    @interface WSPath {
        String value();
    }
}


text:
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import DeviseTokenAuth from '../components/DeviseTokenAuth.vue'
import Top from '../components/Top.vue'
import NotificationsIndex from '../components/notifications/Index.vue'
import SubscriptionsIndex from '../components/subscriptions/Index.vue'

Vue.use(VueRouter)

const routes = [
  // Routes for common components
  { path: '/', component: Top },
  { path: '/login', component: DeviseTokenAuth },
  { path: '/logout', component: DeviseTokenAuth, props: { isLogout: true } },
  // Routes for single page application working with activity_notification REST API backend for users
  {
    path: '/notifications',
    name: 'AuthenticatedUserNotificationsIndex',
    component: NotificationsIndex,
    props: () => ({ target_type: 'users', target: store.getters.currentUser }),
    meta: { requiresAuth: true }
  },
  {
    path: '/subscriptions',
    name: 'AuthenticatedUserSubscriptionsIndex',
    component: SubscriptionsIndex,
    props: () => ({ target_type: 'users', target: store.getters.currentUser }),
    meta: { requiresAuth: true }
  },
  // Routes for single page application working with activity_notification REST API backend for admins
  {
    path: '/admins/notifications',
    name: 'AuthenticatedAdminNotificationsIndex',
    component: NotificationsIndex,
    props: () => ({ target_type: 'admins', targetApiPath: 'admins', target: store.getters.currentUser.admin }),
    meta: { requiresAuth: true }
  },
  {
    path: '/admins/subscriptions',
    name: 'AuthenticatedAdminSubscriptionsIndex',
    component: SubscriptionsIndex,
    props: () => ({ target_type: 'admins', targetApiPath: 'admins', target: store.getters.currentUser.admin }),
    meta: { requiresAuth: true }
  },
  // Routes for single page application working with activity_notification REST API backend for unauthenticated targets
  {
    path: '/:target_type/:target_id/notifications',
    name: 'UnauthenticatedTargetNotificationsIndex',
    component: NotificationsIndex,
    props : true
  },
  {
    path: '/:target_type/:target_id/subscriptions',
    name: 'UnauthenticatedTargetSubscriptionsIndex',
    component: SubscriptionsIndex,
    props : true
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && !store.getters.userSignedIn) {
      next({ path: '/login', query: { redirect: to.fullPath }});
  } else {
    next();
  }
})

export default router


text:
package stubrn.stubs;

import org.testng.annotations.Test;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static stubrn.stubs.TypeCoercion.isConvertible;

/*
*
*/
public class TypeCoercionTest {

    interface Interface {

    }

    class InterfaceImpl implements Interface {

    }

    class MyClass {

    }

    class DerivedClass extends MyClass {

    }

    @Test
    public void testIsConvertibleEqualPrimitive(){
        assertIsConvertible(Integer.TYPE,Integer.TYPE);
    }

    @Test
    public void testIsConvertibleOfPrimitivesToWrapper() throws Exception {
        assertIsConvertible(Boolean.TYPE, Boolean.class);
        assertIsConvertible(Boolean.class, Boolean.TYPE);
        assertIsConvertible(Byte.TYPE, Byte.class);
        assertIsConvertible(Byte.class, Byte.TYPE);
        assertIsConvertible(Character.TYPE, Character.class);
        assertIsConvertible(Character.class, Character.TYPE);
        assertIsConvertible(Short.TYPE, Short.class);
        assertIsConvertible(Short.class, Short.TYPE);
        assertIsConvertible(Integer.TYPE, Integer.class);
        assertIsConvertible(Integer.class, Integer.TYPE);
        assertIsConvertible(Long.TYPE, Long.class);
        assertIsConvertible(Long.class, Long.TYPE);
        assertIsConvertible(Double.TYPE, Double.class);
        assertIsConvertible(Double.class, Double.TYPE);
        assertIsConvertible(Float.TYPE, Float.class);
        assertIsConvertible(Float.class, Float.TYPE);
        assertIsConvertible(Integer.TYPE,Integer.class);
    }

    @Test
    public void testIsConvertibleOfClasses() {
        assertIsConvertible(MyClass.class, MyClass.class);
        assertIsConvertible(DerivedClass.class, MyClass.class);
        assertIsNotConvertible(MyClass.class, DerivedClass.class);

        assertIsConvertible(Interface.class,Interface.class);
        assertIsConvertible(InterfaceImpl.class, Interface.class);
        assertIsNotConvertible(Interface.class, InterfaceImpl.class);
    }

    private void assertIsConvertible(Class<?> from, Class<?> to){
        assertTrue( isConvertible(from, to) );
    }

    private void assertIsNotConvertible(Class<?> from, Class<?> to){
        assertFalse( isConvertible(from, to) );
    }

}


text:
namespace research_scann {

size_t GfvStorage(const GenericFeatureVector& gfv) {
  size_t result = sizeof(gfv);
  result += gfv.feature_index().Capacity() * sizeof(gfv.feature_index(0));
  result +=
      gfv.feature_value_int64().Capacity() * sizeof(gfv.feature_value_int64(0));
  result +=
      gfv.feature_value_float().Capacity() * sizeof(gfv.feature_value_float(0));
  result += gfv.feature_value_double().Capacity() *
            sizeof(gfv.feature_value_double(0));
  if (gfv.has_data_id_str()) {
    result += gfv.data_id_str().size();
  }

  return result;
}

size_t GfvStorage(const vector<GenericFeatureVector>& gfvs) {
  size_t result = sizeof(gfvs);
  for (const auto& gfv : gfvs) {
    result += GfvStorage(gfv);
  }

  return result;
}

std::string GetTcMallocLogString() {
  size_t allocated_bytes = *tcmalloc::MallocExtension::GetNumericProperty(
      "generic.current_allocated_bytes");
  size_t free_bytes = *tcmalloc::MallocExtension::GetNumericProperty(
      "tcmalloc.pageheap_free_bytes");
  size_t unmapped_bytes = *tcmalloc::MallocExtension::GetNumericProperty(
      "tcmalloc.pageheap_unmapped_bytes");
  size_t heap_size =
      *tcmalloc::MallocExtension::GetNumericProperty("generic.heap_size");

  return absl::StrCat("From TCMalloc:  ", allocated_bytes / bytes_in_mb,
                      "MB allocated, ", free_bytes / bytes_in_mb,
                      "MB free on page heap, ", unmapped_bytes / bytes_in_mb,
                      "MB unmapped.  Heap size = ", heap_size / bytes_in_mb,
                      "MB.");
}

}  // namespace research_scann


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

namespace ES5.Script.EcmaScript.Objects
{
    public partial class GlobalObject : EcmaScriptObject
    {
        public EcmaScriptObject CreateJSON()
        {
            var result = Get("JSON") as EcmaScriptObject;
            if (result != null)
                return result;

            result = new EcmaScriptObject(this, ObjectPrototype) { Class = "JSON" };
            Values.Add("JSON", PropertyValue.NotEnum(result));
            result.Values.Add("parse", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "parse", JSONParse, 2, false)));
            result.Values.Add("stringify", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "stringify", JSONStringify, 3, false)));

            result.Prototype = ObjectPrototype;
            return result;
        }

        public object JSONParse(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lTok = new Tokenizer();
            lTok.JSON = true;
            lTok.Error += (Tokenizer caller, TokenizerErrorKind kind, string parameter) =>
                          {
                              RaiseNativeError(NativeErrorType.SyntaxError, "Error in json data at " + caller.Row + ":" + caller.Col);
                          };

            lTok.SetData(Utilities.GetArgAsString(args, 0, aCaller), "");

            var result = JSONParse(lTok);
            if (lTok.Token != TokenKind.EOF)
                RaiseNativeError(NativeErrorType.SyntaxError, "EOF expected " + lTok.Row + ":" + lTok.Col);

            var lReviver = Utilities.GetArg(args, 1) as EcmaScriptBaseFunctionObject;
            if (lReviver != null)
            {
                var lWork = new EcmaScriptObject(this);
                lWork.DefineOwnProperty("", new PropertyValue(PropertyAttributes.None, result), false);
                result = Walk(aCaller, lWork, lReviver, "", lWork);
            }
            return result;
        }

        public object JSONParse(Tokenizer aTok)
        {
            object result = null;
            switch (aTok.Token)
            {
                case TokenKind.K_null:
                    {
                        result = null;
                        aTok.Next();
                    }
                    break;
                case TokenKind.K_true:
                    {
                        result = true;
                        aTok.Next();
                    }
                    break;
                case TokenKind.K_false:
                    {
                        result = false;
                        aTok.Next();
                    }
                    break;
                case TokenKind.OpeningBracket:
                    {
                        aTok.Next();
                        EcmaScriptArrayObject o;
                        result = o = new EcmaScriptArrayObject(this, 0);
                        if (aTok.Token == TokenKind.ClosingBracket)
                        {
                            aTok.Next();
                            break;
                        }

                        while (true)
                        {
                            o.AddValue(JSONParse(aTok));
                            if (aTok.Token == TokenKind.ClosingBracket)
                            {
                                aTok.Next();
                                return o;
                            }

                            if (aTok.Token != TokenKind.Comma)
                                RaiseNativeError(NativeErrorType.SyntaxError, "Comma expected at " + aTok.Row + ":" + aTok.Col);

                            aTok.Next();
                        }
                    }
                case TokenKind.CurlyOpen:
                    {
                        aTok.Next();
                        EcmaScriptObject o;
                        result = o = new EcmaScriptObject(this);
                        if (aTok.Token == TokenKind.CurlyClose)
                        {
                            aTok.Next();
                            return o;
                        }

                        while (true)
                        {
                            if (aTok.Token != TokenKind.String)
                                RaiseNativeError(NativeErrorType.SyntaxError, "String expected at " + aTok.Row + ":" + aTok.Col);

                            var lKey = Tokenizer.DecodeString(aTok.TokenStr);
                            aTok.Next();

                            if (aTok.Token != TokenKind.Colon)
                                RaiseNativeError(NativeErrorType.SyntaxError, "Colon expected at " + aTok.Row + ":" + aTok.Col);
                            aTok.Next();

                            var lValue = JSONParse(aTok);
                            o.AddValue(lKey, lValue);
                            if (aTok.Token == TokenKind.CurlyClose)
                            {
                                aTok.Next();
                                return o;
                            }

                            if (aTok.Token != TokenKind.Comma)
                                RaiseNativeError(NativeErrorType.SyntaxError, "Comma expected at " + aTok.Row + ":" + aTok.Col);

                            aTok.Next();
                        }
                    }
                case TokenKind.String:
                    {
                        result = Tokenizer.DecodeString(aTok.TokenStr);
                        aTok.Next();
                    }
                    break;
                case TokenKind.Float:
                    {
                        double d;
                        if (!Double.TryParse(aTok.TokenStr, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out d))
                            RaiseNativeError(NativeErrorType.SyntaxError, "Number expected at " + aTok.Row + ":" + aTok.Col);

                        aTok.Next();
                        result = d;
                    }
                    break;
                case TokenKind.Number:
                    {
                        var i = 0;
                        if (!Int32.TryParse(aTok.TokenStr, out i))
                        {
                            var i6 = 0L;
                            if (Int64.TryParse(aTok.TokenStr, out i6))
                            {
                                aTok.Next();
                                return (i6);
                            }

                            RaiseNativeError(NativeErrorType.SyntaxError, "Number expected at " + aTok.Row + ":" + aTok.Col);
                        }

                        aTok.Next();
                        result = i;
                    }
                    break;
                default:
                    RaiseNativeError(NativeErrorType.SyntaxError, "JSON object expected at " + aTok.Row + ":" + aTok.Col); break
                   ;
            }
            return result;
        }

        public object JSONStringify(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lStack = new List<Object>();
            var lIndent = String.Empty;
            var lGap = String.Empty;
            var lReplacerFunction = Utilities.GetArg(args, 1) as EcmaScriptBaseFunctionObject;
            List<String> lPropList = null;

            if (lReplacerFunction == null)
            {
                var lItem = Utilities.GetArg(args, 1) as EcmaScriptArrayObject;
                lPropList = new List<String>();
                if (lItem != null)
                {
                    for (uint i = 0, l = lItem.Length; i < l; i++)
                    {
                        var lEl = lItem.Get(i.ToString(), aCaller, 0);
                        if ((lEl == null) || (lEl == Undefined.Instance))
                            continue;

                        lPropList.Add(lEl.ToString());
                    }
                }
            }

            var lSpace = Utilities.GetArg(args, 2);
            var e = lSpace as EcmaScriptObject;
            if (e != null)
            {
                if (e.Class == "Number")
                    lGap = new String(' ', Utilities.GetObjAsInteger(lSpace, aCaller));
                else if (e.Class == "String")
                    lGap = Utilities.GetObjAsString(lSpace, aCaller);
            }
            else if (lSpace is String)
                lGap = (String)lSpace;
            else if ((lSpace is Int32) || (lSpace is Double))
                lGap = new String(' ', Utilities.GetObjAsInteger(lSpace, aCaller));

            if (lGap.Length > 10)
                lGap = lGap.Substring(0, 10);

            var lWork = new EcmaScriptObject(this);
            lWork.DefineOwnProperty("", new PropertyValue(PropertyAttributes.All, Utilities.GetArg(args, 0)), false);

            return (this.JSONStr(aCaller, lStack, lGap, lIndent, lReplacerFunction, lPropList, lWork, ""));
        }

        public object Walk(ExecutionContext aCaller, EcmaScriptObject aRoot, EcmaScriptBaseFunctionObject aReviver, string aName, EcmaScriptObject aCurrent)
        {
            var lItem = aCurrent.Get(aName, aCaller, 2);
            var lEc = lItem as EcmaScriptObject;
            if (lEc != null)
            {
                var lArr = lEc as EcmaScriptArrayObject;
                if (lArr != null)
                {
                    var i = 0;
                    var lLen = (Int32)lArr.Length;
                    while (i < lLen)
                    {
                        var lNewVal = Walk(aCaller, aRoot, aReviver, i.ToString(), lArr);
                        if (lNewVal == Undefined.Instance)
                        {
                            lArr.Delete(i.ToString(), false);
                        }
                        else
                        {
                            lArr.Put(i.ToString(), lNewVal, aCaller);
                            ++i;
                        }
                    }
                }
                else
                {
                    foreach (var el in System.Linq.Enumerable.ToArray(lEc.Values.Keys))
                    { // copy it first
                        var lNewVal = Walk(aCaller, aRoot, aReviver, el, lArr);
                        if (lNewVal == Undefined.Instance)
                            lEc.Delete(el, false);
                        else
                            lEc.DefineOwnProperty(el, new PropertyValue(PropertyAttributes.None, lNewVal), false);
                    }
                }
            }
            return (aReviver.CallEx(aCaller, aRoot, aName, lItem));
        }

        string JSONStr(ExecutionContext aExecutionContext, List<Object> aStack, string aGap, string aIndent,
                           EcmaScriptBaseFunctionObject aReplacerFunction,
                           List<String> aProplist, EcmaScriptObject aWork,
                           string aValue)
        {
            var Value = aWork.Get(aValue, aExecutionContext);

            var lObj = Value as EcmaScriptObject;
            if (lObj != null)
            {
                var lCall = lObj.Get("toJSON", aExecutionContext) as EcmaScriptBaseFunctionObject;
                if (lCall != null)
                {
                    Value = lCall.CallEx(aExecutionContext, lObj, aValue);
                    if (Value is string)
                    {
                        return Value as string;
                    }
                }
            }

            if (aReplacerFunction != null)
                Value = aReplacerFunction.CallEx(aExecutionContext, aWork, aValue, Value);

            lObj = Value as EcmaScriptObject;
            if (lObj != null)
            {
                if (lObj.Class == "Number")
                    Value = lObj.Value;
                else if (lObj.Class == "String")
                    Value = lObj.Value;
                else if (lObj.Class == "Boolean")
                    Value = lObj.Value;
            }

            var lResult = JSON.ToString(Value);
            if (lResult != null)
                return (lResult);

            if (lObj == null)
                return (null);

            if ((lObj is EcmaScriptBaseFunctionObject) && !(lObj is EcmaScriptObjectWrapper))
                return (null);

            var wrapper = lObj as EcmaScriptObjectWrapper;

            if (null != wrapper && typeof(Delegate).IsAssignableFrom(wrapper.Value.GetType().BaseType))
                return ("function");

            if (aStack.Contains(lObj))
                RaiseNativeError(NativeErrorType.TypeError, "Recursive JSON structure");

            aStack.Add(lObj);
            var lWork = new StringBuilder();
            if (lObj.Class == "Array")
            {
                var arr = lObj as EcmaScriptArrayObject;
                if (arr.Length == 0)
                    lWork.Append("[]");

                aIndent = aIndent + aGap;

                for (uint i = 0, l = arr.Length; i < l; i++)
                {
                    var el = JSONStr(aExecutionContext, aStack, aGap, aIndent, aReplacerFunction, aProplist, lObj, i.ToString());
                    if (el == null) el = "null";
                    if (i == 0)
                    {
                        if (aGap == "")
                            lWork.Append("[");
                        else
                        {
                            lWork.Append("[\n");
                            lWork.Append(aIndent);
                        }
                    }
                    lWork.Append(el);
                    if (i == arr.Length - 1)
                    {
                        if (aGap == "")
                        {
                            lWork.Append("]");
                        }
                        else
                        {
                            lWork.Append("\n");
                            lWork.Append(aIndent.Substring(0, aIndent.Length - aGap.Length));
                            lWork.Append("]");
                        }
                    }
                    else
                    {
                        if (aGap == "") lWork.Append(",");
                        else
                        {
                            lWork.Append(",\n");
                            lWork.Append(aIndent);
                        }
                    }
                }
            }
            else
            {
                aIndent = aIndent + aGap;
                var k = aProplist?.ToArray();
                if (k == null || k.Length == 0)
                {
                    if (lObj is EcmaScriptObjectWrapper)
                        k = ((EcmaScriptObjectWrapper)lObj).GetOwnNames().ToArray();
                    else
                        k = lObj.Values.Where(a => (PropertyAttributes.Enumerable & a.Value.Attributes) != 0)
                            .Select(a => a.Key)
                            .ToArray();
                }

                var lItems = new List<String>();
                if (null != k)
                {
                    foreach (var el in k)
                    {
                        var lVal = JSONStr(aExecutionContext, aStack, aGap, aIndent, aReplacerFunction, aProplist, lObj, el);
                        if (lVal != null)
                        {
                            if (aGap == "")
                                lItems.Add(JSON.QuoteString(el) + ":" + lVal);
                            else
                                lItems.Add(JSON.QuoteString(el) + ": " + lVal);
                        }
                    }
                }

                if (lItems.Count == 0)
                    lWork.Append("{}");
                else
                {
                    if (aGap == "")
                    {
                        lWork.Append("{");
                        for (int i = 0, l = lItems.Count; i < l; i++)
                        {
                            if (i != 0) lWork.Append(",");
                            lWork.Append(lItems[i]);
                        }
                        lWork.Append("}");
                    }
                    else
                    {
                        lWork.Append("{\n");
                        lWork.Append(aIndent);
                        for (int i = 0, l = lItems.Count; i < l; i++)
                        {
                            if (i != 0)
                            {
                                lWork.Append(",\n");
                                lWork.Append(aIndent);
                            }
                            lWork.Append(lItems[i]);
                        }
                        lWork.Append("\n");
                        lWork.Append(aIndent.Substring(0, aIndent.Length - aGap.Length));
                        lWork.Append("}");
                    }
                }
            }
            aStack.Remove(lObj);

            return (lWork.ToString());
        }
    }
}


text:
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'map-section-form',
	'enableAjaxValidation'=>false,
)); ?>

Fields with * are required.

	<?= $form->errorSummary($model); ?>

		<?= $form->labelEx($model,'leftSectionId'); ?>
		<?= $form->textField($model,'leftSectionId'); ?>
		<?= $form->error($model,'leftSectionId'); ?>

		<?= $form->labelEx($model,'rightSectionId'); ?>
		<?= $form->textField($model,'rightSectionId'); ?>
		<?= $form->error($model,'rightSectionId'); ?>

		<?= $form->labelEx($model,'worldId'); ?>
		<?= $form->textField($model,'worldId'); ?>
		<?= $form->error($model,'worldId'); ?>

		<?= CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

<?php $this->endWidget(); ?>


text:
    <?php include '_includes/head.php' ?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/scripts/header.php' ?>

        		<form class = "lift_submission" method = "POST" action = "<?php echo $ROOT_URL ?>index.php/lifts/submit">
					Excercise:

					Sets:<input type="number" name="sets">

					Reps:<input type="number" name="reps">

					Weight<input type="number" name="weight">

					<select name="lift_type_id">
        			<?php foreach($lift_names as $lift): ?>
        				<option value="<?php echo $lift['lift_type_id'] ?>"><?php echo $lift['lift_name'] ?></option>
        			<?php endforeach; ?>
        			</select>
					<input type="submit" value="Submit">
				</form>
				<?php echo $message ?>

				<?php echo $result ?>

				<a href="<?php echo $ROOT_URL ?>index.php/welcome"><== HOME

        	<form class = "delete_lifts" method = "POST" action = "<?php echo $ROOT_URL ?>index.php/lifts/delete">

						<?php foreach($lifts as $instance): ?>

								<input type="checkbox" name="lifts[]"
								value="<?php echo $instance->lift_id ?>"
								id="<?php echo $instance->lift_id ?>">
								<label for="<?php echo $instance->lift_id ?>">
								<?php $lift = Arr::get($lift_names,$instance->lift_type_id) ? $lift_names[$instance->lift_type_id]['lift_name'] : "unknown" ?>
								<?php echo $instance->sets ."x".$instance->reps."@".$instance->weight."
".$lift." on
".$instance->date ?>

						<?php endforeach; ?>

        	<input type="submit" value="Delete">
			</form>


text:
ROOT = ../../../../..

DIR = Providers/ManagedSystem/UNIXProviders/CollectionInSystem

include $(ROOT)/mak/config.mak

LIBRARY = UNIX_CollectionInSystemProvider

EXTRA_INCLUDES += -I/usr/local/include -I./..

SOURCES = \
	../CIMHelper.cpp \
	UNIX_CollectionInSystemMain.cpp \
	UNIX_CollectionInSystem.cpp \
	UNIX_CollectionInSystemProvider.cpp

ifeq ($(OS), aix)
	SOURCES += UNIX_CollectionInSystem_AIX.cpp
endif
ifeq ($(OS), darwin)
	SOURCES += UNIX_CollectionInSystem_DARWIN.cpp
endif
ifeq ($(OS), freebsd)
	SOURCES += UNIX_CollectionInSystem_FREEBSD.cpp
endif
ifeq ($(OS), hpux)
	SOURCES += UNIX_CollectionInSystem_HPUX.cpp
endif
ifeq ($(OS), linux)
	SOURCES += UNIX_CollectionInSystem_LINUX.cpp
endif
ifeq ($(OS), solaris)
	SOURCES += UNIX_CollectionInSystem_SOLARIS.cpp
endif
ifeq ($(OS), tru64)
	SOURCES += UNIX_CollectionInSystem_TRU64.cpp
endif
ifeq ($(OS), vms)
	SOURCES += UNIX_CollectionInSystem_VMS.cpp
endif
ifeq ($(OS), win32)
	SOURCES += UNIX_CollectionInSystem_WIN32.cpp
endif
ifeq ($(OS), zos)
	SOURCES += UNIX_CollectionInSystem_ZOS.cpp
endif
ifeq (, $(filter aix,darwin,freebsd,hpux,linux,solaris,tru64,vms,win32,zos $(OS)))

else
	SOURCES += UNIX_CollectionInSystem_STUB.cpp
endif

LIBRARIES = \
	pegprovider \
	pegclient \
	pegcommon \
	pegquerycommon \
	pegqueryexpression \
	pegcql \
	pegwql

EXTRA_LIBRARIES = \
	-pthread \
	-lutil \
	-lgeom \
	-lkvm \
	-lcam

include $(ROOT)/mak/dynamic-library.mak


text:
<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\Breadcrumbs;

/* @var $this yii\web\View */
/* @var $model app\modules\technologies\models\TechnologyCategories */

$this->title = 'Create category';
$this->params['breadcrumbs'][] = ['label' => 'Admin panel', 'url' => Url::toRoute(['/admin'])];
$this->params['breadcrumbs'][] = ['label' => 'Categories', 'url' => Url::toRoute(['/admin/technology-categories'])];
$this->params['breadcrumbs'][] = 'Create category';

echo Breadcrumbs::widget(['homeLink' => false,'links' => $this->params['breadcrumbs']]);
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
'use strict';

module.exports = {
  stringifyPart: function(part) {
    switch (typeof part) {
      case 'boolean':
      case 'number':
        return String(part);
      case 'string':
        return '"' + part.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
      case 'undefined':
        return 'NULL';
      default:
        if (part === null)
          return 'NULL';
        else
          return '"' + JSON.stringify(part).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
    }
  },
  stringifyObject: function(data) {
    var self = this;

    return Object.keys(data).map(function(key) {
      return self.stringifyPart(key) + '=>' + self.stringifyPart(data[key]);
    }).join(',');
  },
  stringifyArray: function(data) {
    return data.map(this.stringifyObject, this);
  },
  stringify: function(data) {
    if (Array.isArray(data)) {
      return this.stringifyArray(data);
    }

    return this.stringifyObject(data);
  },
  parsePart: function(part) {
    part = part.replace(/\\\\/g, '\\').replace(/\\"/g, '"');

    switch (part[0]) {
      case '{':
      case '[':
        return JSON.parse(part);
      default:
        return part;
    }
  },
  parseObject: function(string) {
    var self = this,
        object = { };

    if (0 === string.length) {
      return object;
    }

    var rx = /\"((?:\\\"|[^"])*)\"\s*\=\>\s*((?:true|false|NULL|\d+|\d+\.\d+|\"((?:\\\"|[^"])*)\"))/g;

    string = string || '';

    string.replace(rx, function(match, key, value, innerValue) {
      switch (value) {
        case 'true':
          object[self.parsePart(key)] = true;
          break;
        case 'false':
          object[self.parsePart(key)] = false;
          break;
        case 'NULL':
          object[self.parsePart(key)] = null;
          break;
        default:
          object[self.parsePart(key)] = self.parsePart(innerValue || value);
          break;
      }
    });

    return object;
  },
  parseArray: function(string) {
    var matches = string.match(/{(.*)}/);
    var array = JSON.parse('['+ matches[1] +']');

    return array.map(this.parseObject, this);
  },
  parse: function(value) {
    if ('string' !== typeof value) {
      return value;
    }

    if ('{' === value[0] && '}' === value[value.length - 1]) {
      return this.parseArray(value);
    }

    return this.parseObject(value);
  }
};


text:
require 'spec_helper_acceptance'

describe 'fqdn_rand_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
  describe 'success' do
    let(:facts_d) do
      if fact('is_pe', '--puppet') == "true"
        if fact('osfamily') =~ /windows/i
          if fact('kernelmajversion').to_f < 6.0
            'c:/documents and settings/all users/application data/puppetlabs/facter/facts.d'
          else
            'c:/programdata/puppetlabs/facter/facts.d'
          end
        else
          '/etc/puppetlabs/facter/facts.d'
        end
      else
        '/etc/facter/facts.d'
      end
    end
    after :each do
      shell("if [ -f '#{facts_d}/fqdn.txt' ] ; then rm '#{facts_d}/fqdn.txt' ; fi")
    end
    before :each do
      #no need to create on windows, pe creates by default
      if fact('osfamily') !~ /windows/i
        shell("mkdir -p '#{facts_d}'")
      end
    end
    it 'generates random alphanumeric strings' do
      shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
      pp = <<-eos
      $l = 10
      $o = fqdn_rand_string($l)
      notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
      eos

      apply_manifest(pp, :catch_failures => true) do |r|
        expect(r.stdout).to match(/fqdn_rand_string is "7oDp0KOr1b"/)
      end
    end
    it 'generates random alphanumeric strings with custom seeds' do
      shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
      pp = <<-eos
      $l = 10
      $s = 'seed'
      $o = fqdn_rand_string($l, undef, $s)
      notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
      eos

      apply_manifest(pp, :catch_failures => true) do |r|
        expect(r.stdout).to match(/fqdn_rand_string is "3HS4mbuI3E"/)
      end
    end
  end
  describe 'failure' do
    it 'handles improper argument counts'
    it 'handles non-numbers for length argument'
  end
end


text:
$(document).ready(function(){
  $('.contact-block .widget-user-header :not(.expand-button)').click(function(){
    console.log('click');
    $(this).parent().find('.expand-button').click();
  });
});


text:
import "regenerator-runtime/runtime";
import { Meteor } from "meteor/meteor";
import moment from "moment";
import { takeLatest, takeEvery, fork, take, put, select, call } from "redux-saga/effects";
import gql from "graphql-tag";

import { GraphQL } from "../../../graphql";
import { addSaga } from "../../utilities";
import modalActions from "../../modal";

import types from "./../types";
import actions from "../actions";

import RecoverSchedule from "../../../../components/giving/recover-schedules";

import validate from "./validate";
import chargeTransaction from "./chargeTransaction";
import submitPaymentDetails from "./submitPaymentDetails";
import submitPersonDetails from "./submitPersonDetails";

export {
  validate,
  chargeTransaction,
  submitPaymentDetails,
  submitPersonDetails,
};

// transaction processing flow controller
function* createOrder() {
  /*

    steps to give

    Full Steps
    1. add person data
    2. submit person data to NMI
    3. get back transaction code
    4. submit payment details to NMI
    5. process transaction
    6. handle success / errors

    Saved Account
    1. submit person code to NMI
    2. get back transaction code
    3. process transaction
    4. handle success / errors

  */
  const { give } = yield select();
  if ((give.step - 1) === 2) {
    // set people data and store transaction id
    yield* submitPersonDetails(give, false);
  } else if ((give.step - 1) === 3) {
    yield* submitPaymentDetails(give.data, give.url);
  }
}

/*

  During the transition from F1 to Rock, we have schedules that need
  to be recovered from our imported data

  The criteria for a `recoverable schedule` is the following:
    IsActive (active: false on GQL query) === false
    GatewayCode (gateway on GQL) === null

  When the schedule is reactivated, the GatewayCode is set and it is set back
  to active.

  If the schedule is canceled permantly, and it doesn't have a GatewayCode,
  it is safe to delete it as no auditable information exists.

*/

let hasRecovered = false;
// recover transactions
function* recoverTransactions() {
  if (hasRecovered) return;

  let user = Meteor.userId();

  if (!user) yield take("ACCOUNTS.IS_AUTHORIZED");

  const query = gql`
    query GetInActiveSchedules($isActive: Boolean, $cache: Boolean) {
      schedules: scheduledTransactions(isActive: $isActive, cache: $cache) {
        id: entityId
        start
        next
        gateway
        date
        schedule { value, description }
        details {
          amount
          account { name, id, description }
        }
      }
    }
  `;

  const variables = { isActive: false, cache: false };

  const { data } = yield GraphQL.query({ query, variables });

  let { schedules } = data;
  if (!schedules) schedules = [];
  hasRecovered = true;
  const bulkUpdate = {};
  schedules = schedules.filter(x => !x.gateway);
  if (schedules.length) {
    for (const schedule of schedules) {
      // only recover schedules that are missing info (i.e. not turned off in Rock)
      if (schedule.gateway) continue; // eslint-disable-line

      if (schedule.schedule.value === "Twice a Month") {
        schedule.schedule.value = null;
      }
      bulkUpdate[schedule.id] = {
        ...{
          start: moment(schedule.start).format("YYYYMMDD"),
          frequency: schedule.schedule.value,
        },
        ...schedule,
      };
    }

    yield put(actions.saveSchedules(bulkUpdate));

    // delay to wait for published meteor user
    yield call(() => new Promise(r => setTimeout(r, 1000)));
    user = Meteor.user();
    if (user && user.profile && user.profile.reminderDate) {
      yield put(actions.setReminder(user.profile.reminderDate));
      const time = new Date(user.profile.reminderDate);
      const now = new Date();
      // only update the store if it is past the reminder date
      if (now < time) return;
    }

    const state = yield select();
    const { pathname } = state.routing.location;

    if (pathname.split("/").length === 4 && pathname.split("/")[3] === "recover") {
      return;
    }

    yield put(modalActions.render(RecoverSchedule));
  }
}

// ensure we are on a /give route
function* watchRoute({ payload }) {
  if (Meteor.isServer) return;

  function isGive(path) {
    return path.split("/")[1] === "give";
  }

  if (isGive(payload.pathname)) yield* recoverTransactions();
}

// clear out data on user change
export function* clearGiveData({ authorized }) {
  if (!authorized) yield put(actions.clearData());
}

addSaga(function* accountsSaga() {
  yield fork(takeEvery, types.SET_STATE, chargeTransaction);
  yield fork(takeEvery, types.SET_PROGRESS, createOrder);
  yield fork(takeEvery, "ACCOUNTS.IS_AUTHORIZED", clearGiveData);
  yield fork(takeLatest, "@@router/UPDATE_LOCATION", watchRoute);

  const state = yield select();
  const payload = state.routing.location;

  function isGive(path) {
    return path.split("/")[1] === "give";
  }

  if (isGive(payload.pathname)) yield* recoverTransactions();
});


text:
package com.typesafe.jenkins;

@hudson.Extension // TODO: the annotation doesn't work in scala...
public class EC2StartStopComputerListenerX extends EC2StartStopComputerListener {}


text:
@interface LevelMeterView : UIView {
	CGFloat leftValue;
	CGFloat rightValue;
}

- (void)updateMeterWithLeftValue:(CGFloat)left rightValue:(CGFloat)right;

@end


text:
package com.gzlk.android.isp.fragment.base;

import android.os.Bundle;
import android.view.View;

import com.gzlk.android.isp.activity.BaseActivity;

/**
 * 功能描述:提供Activity透明化方法的fragment基类

 * 创建作者:Hsiang Leekwok

 * 创建时间:2017/04/14 14:26

 * 作者邮箱:xiang.l.g@gmail.com

 * 最新版本:Version: 1.0.0

 * 修改时间:2017/04/14 14:26

 * 修改人员:

 * 修改备注:

 */

public abstract class BaseTransparentSupportFragment extends BaseLocationSupportFragment {

    private static final String PARAM_INITIALIZED = "bmf_initialized";
    protected static final String PARAM_QUERY_ID = "btsf_param_query";
    /**
     * fragment是否已经初始化了,为false时,需要设置顶部的padding
     */
    private boolean isInitialized = false;
    /**
     * 基本queryId
     */
    protected String mQueryId;

    @Override
    protected void getParamsFromBundle(Bundle bundle) {
        isInitialized = bundle.getBoolean(PARAM_INITIALIZED, false);
        mQueryId = bundle.getString(PARAM_QUERY_ID, "");
    }

    @Override
    protected void saveParamsToBundle(Bundle bundle) {
        bundle.putBoolean(PARAM_INITIALIZED, isInitialized);
        bundle.putString(PARAM_QUERY_ID, mQueryId);
    }

    /**
     * 标记fragment是否是在ViewPager里正显示的页面
     */
    private boolean isDisplayedInViewPager = false;

    /**
     * 设置是否当前所显示的内容
     */
    public void setViewPagerDisplayedCurrent(boolean displayed) {
        if (isDisplayedInViewPager != displayed) {
            isDisplayedInViewPager = displayed;
            onViewPagerDisplayedChanged(displayed);
        }
    }

    /**
     * 当前ViewPager显示的是否是本fragment
     */
    public boolean isViewPagerDisplayedCurrent() {
        return isDisplayedInViewPager;
    }

    /**
     * 当前页面在ViewPager中显示或隐藏事件
     */
    protected void onViewPagerDisplayedChanged(boolean visible) {

    }

    /**
     * 设置根内容布局的顶部padding以便正常显示
     */
    protected void tryPaddingContent(boolean includeActionBar) {
        tryPaddingContent(mRootView, includeActionBar);
    }

    /**
     * 设置指定布局的顶部padding以便正常显示
     */
    public void tryPaddingContent(View view, boolean includeActionBar) {
        if (!isInitialized) {
            isInitialized = true;
            int padding = BaseActivity.getStatusHeight(Activity());
            if (includeActionBar) {
                int actionBarHeight = Activity().getActionBarSize();
                padding += actionBarHeight;
            }
            int left = view.getPaddingLeft();
            int top = view.getPaddingTop();
            int right = view.getPaddingRight();
            int bottom = view.getPaddingBottom();
            if (top < padding) {
                view.setPadding(left, top + padding, right, bottom);
            }
        }
    }

    public void transparentStatusBar() {
        Activity().transparentStatusBar();
    }
}


text:
layout: post
title: How to Effortlessly Succeed (for ordinary people)
date: 2011-05-30 00:06
author: Kevin Olega
comments: true
categories: [ergonomics, Well Roundedness and Balance]
---
Have you ever wondered why some people seem to do thins effortlessly?

Sometimes you watch people and they seem to pick strategies that work and get things done when they move.

For almost 10 years I've been pondering how I can reach this point. I tried multiple strategies and techniques that I thought were the answers. I ended up finding ingredients that helped but weren't too dependable as advertised.

Positive mental attitude.

Law of attraction

the millionaire mindset

Rich dad's thinking

7 habits of highly effective people

etc.

They all seemed to be starting points and support. Nothing more. When I decided to rethink my life I came upon the term ergonomics.

Ergonomics is working with how your body is support to work and basing your plans and actions on it.

In an earlier post we wanted to increase our skills, confidence and time management so we can do great work that funds our passions and make a dent in the universe.

If you are faithful with the small things you'll be entrusted with much. – The Bible

Before taking on Business, Spiritual, Extreme and a whole bunch of other disciplines let's first master the basics.

1. Sleep Right – Get enough sleep 8 hours a day and nothing less. You need all the energy you need to get great work done.

2. Drink Right – Get 10 glasses of water every day. You can't think when you lack water.

3. Eat Right – More vegetables, less rice, a bit more food and less junk.

4. Breathe right – Take long deep breaths every time you can. Clean air only please.

5. Stay Clean – Change your bedsheets. Take a shower Twice a day. Wear fresh clothes all the time. Avoid reusing clothes.

I hope I don't have to convince you. If you can do this regularly for a few days to a few months, I bet you'll be able to work well with what you're trying to do.

In fact, after completing this habits all the other good habits seem to be easier to gain.


text:
module Sitemap::Node
  class Base
    include Cms::Node::Model

    default_scope ->{ where(route: /^sitemap\//) }
  end

  class Page
    include Cms::Node::Model

    default_scope ->{ where(route: "sitemap/page") }
  end
end


text:
package org.twig4j.core.syntax.parser.node.type;

import org.twig4j.core.compiler.ClassCompiler;
import org.twig4j.core.exception.LoaderException;
import org.twig4j.core.exception.Twig4jRuntimeException;
import org.twig4j.core.syntax.parser.node.Node;
import org.twig4j.core.syntax.parser.node.Output;

public class BlockReference extends Node implements Output {
    public BlockReference(String name, Integer line, String tag) {
        super(line);
        setTag(tag);

        putAttribute("name", name);
    }

    @Override
    public void compile(ClassCompiler compiler) throws LoaderException, Twig4jRuntimeException {
        compiler
            .addDebugInfo(this)
            .writeLine("output.append(displayBlock(\"" + getAttribute("name") + "\", context, blocks, true));");
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.15"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>reVision: Settings Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

reVision
    5.0.0

Video game engine project.

Public Member Functions |
List of all members

Settings Class Referencefinal

A level editor dialogue allowing the user to modify level editor settings.
 More...

#include <Settings.h>

Inheritance diagram for Settings:

  <map id="Settings_map" name="Settings_map">
<area href="struct_im_g_u_i___element.html" title="UI element representing an ImGUI element." alt="ImGUI_Element" shape="rect" coords="0,0,95,24"/>
  </map>

Public Member Functions

 	Settings (Engine &engine, LevelEditor_Module &editor) noexcept

 	Construct a settings dialogue.  More...

void 	tick (const float &deltaTime) final

 	Tick this element, updating it and rendering it.  More...

 Public Member Functions inherited from ImGUI_Element

virtual 	~ImGUI_Element ()=default

 	Virtual Destructor.  More...

 	ImGUI_Element () noexcept=default

 	Default constructor.  More...

 	ImGUI_Element (ImGUI_Element &&) noexcept=default

 	Move constructor.  More...

 	ImGUI_Element (const ImGUI_Element &) noexcept=default

 	Copy constructor.  More...

ImGUI_Element & 	operator= (ImGUI_Element &&) noexcept=default

 	Move assignment.  More...

ImGUI_Element & 	operator= (const ImGUI_Element &) noexcept=default

 	Copy assignment.  More...

void 	open () noexcept

 	Open this element.  More...

void 	close () noexcept

 	Close this element.  More...

Additional Inherited Members

 Public Attributes inherited from ImGUI_Element

bool 	m_open = true

Detailed Description

A level editor dialogue allowing the user to modify level editor settings.

Constructor & Destructor Documentation

◆ Settings()

          Settings::Settings
          (
          Engine &
          engine,

          LevelEditor_Module &
          editor

          )

noexcept

Construct a settings dialogue.

Parameters

engine	reference to the engine to use.

editor	reference to the level-editor to use.

Member Function Documentation

◆ tick()

          void Settings::tick
          (
          const float &
          deltaTime	)

finalvirtual

Tick this element, updating it and rendering it.

Parameters

deltaTime	the amount of time since last frame.

Reimplemented from ImGUI_Element.

The documentation for this class was generated from the following files:

src/Modules/Editor/UI/Settings.h

src/Modules/Editor/UI/Settings.cpp

<address class="footer">
Generated by

 1.8.15
</address>


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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.pozo</groupId>
    <artifactId>lastfm-dashboard</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <dropwizard.version>0.8.4</dropwizard.version>
        <h2.version>1.4.187</h2.version>
    </properties>

    <dependencies>
        <!-- dropwizard -->
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-assets</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-core</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-db</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-jdbi</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <!-- /dropwizard -->
        <!-- H2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
        </dependency>
        <!-- /H2 -->
        <!-- HTTP -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4.1</version>
        </dependency>
        <!-- /HTTP -->
        <!-- JAXB -->
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.2.11</version>
        </dependency>
        <dependency>
            <groupId>javax.xml</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.1</version>
        </dependency>
        <!-- /JAXB-->
        <!-- test -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- test -->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!--  use mvn versions:display-dependency-updates versions:display-plugin-updates -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>1.3.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.2</version>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <excludes>
                        <exclude>**/*LiveTest.java</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.github.pozo.lastfm.DashboardApplication</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>
</project>


text:
#ifndef XWALK_COMMON_FILE_UTILS_H_
#define XWALK_COMMON_FILE_UTILS_H_

#include <string>

namespace common {
namespace utils {

bool Exists(const std::string& path);

std::string BaseName(const std::string& path);

std::string DirName(const std::string& path);

std::string SchemeName(const std::string& uri);

std::string ExtName(const std::string& path);

std::string GetUserRuntimeDir();

}  // namespace utils
}  // namespace common

#endif  // XWALK_COMMON_FILE_UTILS_H_


text:
boot2docker up
cd vagrant
vagrant up
cd ..
./stop_vamp.sh
./start_vamp.sh