text:
<!--
  ~ Copyright (C) 2015-present, Ant Financial Services Group
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ 	http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/control_float_title_width"
    android:focusable="false"
    android:paddingTop="@dimen/control_dp4"
    android:paddingBottom="@dimen/control_dp4"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/display_title"
        android:textSize="@dimen/control_float_per_item_text_size"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:textColor="@color/colorPrimary"
        android:layout_width="@dimen/control_float_per_item_title_width"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/display_content"
        android:layout_width="@dimen/control_float_per_item_info_width"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:focusable="false"
        android:layout_gravity="center_vertical"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="@dimen/control_float_per_item_text_size"
        />
    <TextView
        android:id="@+id/display_trigger"
        android:layout_height="wrap_content"
        android:layout_width="@dimen/control_float_per_item_trigger_width"
        android:gravity="center"
        android:layout_marginRight="@dimen/control_dp8"
        android:clickable="true"
        android:focusable="true"
        android:layout_gravity="center_vertical"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/control_float_per_item_trigger_text_size"
        />

</LinearLayout>


text:
from projecteuler.PrimeGenerator import generate_primes, primes

# generate more than 500500 primes
generate_primes(10000000)

result = 2
prime_index = 1

# {exponent: (base_index, computed), ...}
# "exponent" will be one of 2, 4, 8, ...
smallest = {2: (0, 4)}

for _ in range(500500 - 1):
    prime = primes[prime_index]
    m = min(smallest.items(), key=lambda x: x[1][1])
    exp, base_index, computed = [m[0], m[1][0], m[1][1]]
    val = prime
    if computed < prime:
        val = computed
        smallest[exp] = (base_index + 1, primes[base_index + 1] ** exp)
        if exp * 2 not in smallest:
            smallest[exp * 2] = (base_index, primes[base_index] ** (exp * 2))
    else:
        prime_index += 1
    result = (result * val) % 500500507

print(result)

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Eto.Parse;
using HtmlConsole.Extensions;

namespace HtmlConsole.Css
{
    public class RuleSet
    {
        public Selector Selector { get; set; }
        public Declaration[] Declarations { get; set; } = new Declaration[0];

        internal static RuleSet Create(Match rulesetMatch)
        {
            Debug.Assert(rulesetMatch.Name == "ruleset");

            return new RuleSet
            {
                Selector = Selector.Create(rulesetMatch["selectors"]),
                Declarations = CreateDeclarations(rulesetMatch["declarations"]).Values.ToArray()
            };
        }

        internal static Dictionary<string, Declaration> CreateDeclarations(Match declarationsMatch)
        {
            var allProperties = StyleProperties.All();

            Debug.Assert(declarationsMatch.Name == "declarations");

            var declarations = new Dictionary<string, Declaration>();
            foreach (var declarationMatch in declarationsMatch.Matches.ExceptWhitespace())
            {
                Debug.Assert(declarationMatch.Name == "declaration");

                bool isImportant = declarationMatch.Matches.Any(p => p.Name == "prio");

                var propertyName = declarationMatch["ident"].Text.ToLowerInvariant();
                if (!allProperties.ContainsKey(propertyName))
                {
                    continue;
                }

                var property = allProperties[propertyName];
                var styleValueSequence = StyleValue.Create(property, declarationMatch["expression"]);
                foreach (var mappedPropertyValue in property.MapStyleValues(styleValueSequence.ToArray()))
                {
                    declarations[mappedPropertyValue.Key] = new Declaration(propertyName, mappedPropertyValue.Value,
                        isImportant);
                }
            }

            return declarations;
        }
    }
}


text:
import itertools

from .code_generator_info import CodeGeneratorInfo
from .composition_parts import WithCodeGeneratorInfo
from .composition_parts import WithComponent
from .composition_parts import WithDebugInfo
from .composition_parts import WithExposure
from .composition_parts import WithExtendedAttributes
from .constant import Constant
from .ir_map import IRMap
from .make_copy import make_copy
from .operation import Operation
from .operation import OperationGroup
from .user_defined_type import UserDefinedType

class CallbackInterface(UserDefinedType, WithExtendedAttributes,
                        WithCodeGeneratorInfo, WithExposure, WithComponent,
                        WithDebugInfo):
    """https://heycam.github.io/webidl/#idl-interfaces"""

    class IR(IRMap.IR, WithExtendedAttributes, WithCodeGeneratorInfo,
             WithExposure, WithComponent, WithDebugInfo):
        def __init__(self,
                     identifier,
                     constants=None,
                     operations=None,
                     extended_attributes=None,
                     component=None,
                     debug_info=None):
            if constants is None:
                constants = []
            if operations is None:
                operations = []
            assert isinstance(constants, (list, tuple))
            assert isinstance(operations, (list, tuple))
            assert all(
                isinstance(constant, Constant.IR) for constant in constants)
            assert all(
                isinstance(operation, Operation.IR)
                for operation in operations)

            IRMap.IR.__init__(
                self,
                identifier=identifier,
                kind=IRMap.IR.Kind.CALLBACK_INTERFACE)
            WithExtendedAttributes.__init__(self, extended_attributes)
            WithCodeGeneratorInfo.__init__(self)
            WithExposure.__init__(self)
            WithComponent.__init__(self, component)
            WithDebugInfo.__init__(self, debug_info)

            self.attributes = []
            self.constants = constants
            self.constructors = []
            self.constructor_groups = []
            self.named_constructors = []
            self.named_constructor_groups = []
            self.operations = operations
            self.operation_groups = []

        def iter_all_members(self):
            list_of_members = [
                self.constants,
                self.operations,
            ]
            return itertools.chain(*list_of_members)

        def iter_all_overload_groups(self):
            return iter(self.operation_groups)

    def __init__(self, ir):
        assert isinstance(ir, CallbackInterface.IR)

        ir = make_copy(ir)
        UserDefinedType.__init__(self, ir.identifier)
        WithExtendedAttributes.__init__(self, ir, readonly=True)
        WithCodeGeneratorInfo.__init__(self, ir, readonly=True)
        WithExposure.__init__(self, ir, readonly=True)
        WithComponent.__init__(self, ir, readonly=True)
        WithDebugInfo.__init__(self, ir)
        self._constants = tuple([
            Constant(constant_ir, owner=self) for constant_ir in ir.constants
        ])
        self._operations = tuple([
            Operation(operation_ir, owner=self)
            for operation_ir in ir.operations
        ])
        self._operation_groups = tuple([
            OperationGroup(
                operation_group_ir,
                filter(lambda x: x.identifier == operation_group_ir.identifier,
                       self._operations),
                owner=self) for operation_group_ir in ir.operation_groups
        ])

    @property
    def attributes(self):
        """Returns attributes."""
        return ()

    @property
    def constants(self):
        """Returns constants."""
        return self._constants

    @property
    def constructors(self):
        """Returns constructors."""
        return ()

    @property
    def constructor_groups(self):
        """Returns groups of constructors."""
        return ()

    @property
    def named_constructors(self):
        """Returns named constructors."""
        return ()

    @property
    def named_constructor_groups(self):
        """Returns groups of overloaded named constructors."""
        return ()

    @property
    def operations(self):
        """Returns operations."""
        return self._operations

    @property
    def operation_groups(self):
        """Returns groups of overloaded operations."""
        return self._operation_groups

    # UserDefinedType overrides
    @property
    def is_callback_interface(self):
        return True


text:
#pragma once
#include <aws/globalaccelerator/GlobalAccelerator_EXPORTS.h>
#include <aws/globalaccelerator/model/EndpointGroup.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace GlobalAccelerator
{
namespace Model
{
  class AWS_GLOBALACCELERATOR_API UpdateEndpointGroupResult
  {
  public:
    UpdateEndpointGroupResult();
    UpdateEndpointGroupResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    UpdateEndpointGroupResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The information about the endpoint group that was updated.

     */
    inline const EndpointGroup& GetEndpointGroup() const{ return m_endpointGroup; }

    /**
     *
The information about the endpoint group that was updated.

     */
    inline void SetEndpointGroup(const EndpointGroup& value) { m_endpointGroup = value; }

    /**
     *
The information about the endpoint group that was updated.

     */
    inline void SetEndpointGroup(EndpointGroup&& value) { m_endpointGroup = std::move(value); }

    /**
     *
The information about the endpoint group that was updated.

     */
    inline UpdateEndpointGroupResult& WithEndpointGroup(const EndpointGroup& value) { SetEndpointGroup(value); return *this;}

    /**
     *
The information about the endpoint group that was updated.

     */
    inline UpdateEndpointGroupResult& WithEndpointGroup(EndpointGroup&& value) { SetEndpointGroup(std::move(value)); return *this;}

  private:

    EndpointGroup m_endpointGroup;
  };

} // namespace Model
} // namespace GlobalAccelerator
} // namespace Aws


text:
package com.esri.core.geometry;

import junit.framework.TestCase;
import org.junit.Test;

public class TestUnion extends TestCase {
	@Override
	protected void setUp() throws Exception {
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	@Test
	public static void testUnion() {
		Point pt = new Point(10, 20);

		Point pt2 = new Point();
		pt2.setXY(10, 10);

		Envelope env1 = new Envelope(10, 10, 30, 50);
		Envelope env2 = new Envelope(30, 10, 60, 50);
		Geometry[] geomArray = new Geometry[] { env1, env2 };
		SimpleGeometryCursor inputGeometries = new SimpleGeometryCursor(
				geomArray);
		OperatorUnion union = (OperatorUnion) OperatorFactoryLocal
				.getInstance().getOperator(Operator.Type.Union);

		SpatialReference sr = SpatialReference.create(4326);

		GeometryCursor outputCursor = union.execute(inputGeometries, sr, null);
		Geometry result = outputCursor.next();
	}
}


text:
package org.apache.sling.distribution.agent.impl;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyOption;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.jackrabbit.vault.packaging.Packaging;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.distribution.DistributionRequestType;
import org.apache.sling.distribution.component.impl.DistributionComponentConstants;
import org.apache.sling.distribution.component.impl.SettingsUtils;
import org.apache.sling.distribution.event.impl.DistributionEventFactory;
import org.apache.sling.distribution.log.impl.DefaultDistributionLog;
import org.apache.sling.distribution.packaging.DistributionPackageExporter;
import org.apache.sling.distribution.packaging.impl.exporter.LocalDistributionPackageExporter;
import org.apache.sling.distribution.queue.DistributionQueueProvider;
import org.apache.sling.distribution.queue.impl.DistributionQueueDispatchingStrategy;
import org.apache.sling.distribution.queue.impl.SingleQueueDispatchingStrategy;
import org.apache.sling.distribution.queue.impl.jobhandling.JobHandlingDistributionQueueProvider;
import org.apache.sling.distribution.serialization.DistributionPackageBuilder;
import org.apache.sling.distribution.trigger.DistributionTrigger;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An OSGi service factory for {@link org.apache.sling.distribution.agent.DistributionAgent}s which references already existing OSGi services.
 */
@Component(metatype = true,
        label = "Apache Sling Distribution Agent - Queue Agents Factory",
        description = "OSGi configuration factory for queueing agents",
        configurationFactory = true,
        specVersion = "1.1",
        policy = ConfigurationPolicy.REQUIRE
)
@Reference(name = "triggers", referenceInterface = DistributionTrigger.class,
        policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE,
        bind = "bindDistributionTrigger", unbind = "unbindDistributionTrigger")
public class QueueDistributionAgentFactory extends AbstractDistributionAgentFactory {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Property(label = "Name", description = "The name of the agent.")
    public static final String NAME = DistributionComponentConstants.PN_NAME;

    @Property(label = "Title", description = "The display friendly title of the agent.")
    public static final String TITLE = "title";

    @Property(label = "Details", description = "The display friendly details of the agent.")
    public static final String DETAILS = "details";

    @Property(boolValue = true, label = "Enabled", description = "Whether or not to start the distribution agent.")
    private static final String ENABLED = "enabled";

    @Property(label = "Service Name", description = "The name of the service used to access the repository.")
    public static final String SERVICE_NAME = "serviceName";

    @Property(options = {
            @PropertyOption(name = "debug", value = "debug"), @PropertyOption(name = "info", value = "info"), @PropertyOption(name = "warn", value = "warn"),
            @PropertyOption(name = "error", value = "error")},
            value = "info",
            label = "Log Level", description = "The log level recorded in the transient log accessible via http."
    )
    public static final String LOG_LEVEL = AbstractDistributionAgentFactory.LOG_LEVEL;

    @Property(cardinality = 100, label = "Allowed roots", description = "If set the agent will allow only distribution requests under the specified roots.")
    private static final String ALLOWED_ROOTS = "allowed.roots";

    @Property(name = "requestAuthorizationStrategy.target", label = "Request Authorization Strategy", description = "The target reference for the DistributionRequestAuthorizationStrategy used to authorize the access to distribution process," +
            "e.g. use target=(name=...) to bind to services by name.")
    @Reference(name = "requestAuthorizationStrategy")
    private DistributionRequestAuthorizationStrategy requestAuthorizationStrategy;

    @Property(name = "packageBuilder.target", label = "Package Builder", description = "The target reference for the DistributionPackageBuilder used to create distribution packages, " +
            "e.g. use target=(name=...) to bind to services by name.")
    @Reference(name = "packageBuilder")
    private DistributionPackageBuilder packageBuilder;

    @Property(value = DEFAULT_TRIGGER_TARGET, label = "Triggers", description = "The target reference for DistributionTrigger used to trigger distribution, " +
            "e.g. use target=(name=...) to bind to services by name.")
    public static final String TRIGGERS_TARGET = "triggers.target";

    @Reference
    private Packaging packaging;

    @Reference
    private DistributionEventFactory distributionEventFactory;

    @Reference
    private SlingSettingsService settingsService;

    @Reference
    private JobManager jobManager;

    @Reference
    private ResourceResolverFactory resourceResolverFactory;

    @Activate
    protected void activate(BundleContext context, Map<String, Object> config) {
        super.activate(context, config);
    }

    protected void bindDistributionTrigger(DistributionTrigger distributionTrigger, Map<String, Object> config) {
        super.bindDistributionTrigger(distributionTrigger, config);

    }

    protected void unbindDistributionTrigger(DistributionTrigger distributionTrigger, Map<String, Object> config) {
        super.unbindDistributionTrigger(distributionTrigger, config);
    }

    @Deactivate
    protected void deactivate(BundleContext context) {
        super.deactivate(context);
    }

    @Override
    protected SimpleDistributionAgent createAgent(String agentName, BundleContext context, Map<String, Object> config, DefaultDistributionLog distributionLog) {

        String serviceName = PropertiesUtil.toString(config.get(SERVICE_NAME), null);
        String[] allowedRoots = PropertiesUtil.toStringArray(config.get(ALLOWED_ROOTS), null);
        allowedRoots = SettingsUtils.removeEmptyEntries(allowedRoots);

        DistributionQueueProvider queueProvider = new JobHandlingDistributionQueueProvider(agentName, jobManager, context);
        DistributionQueueDispatchingStrategy exportQueueStrategy = new SingleQueueDispatchingStrategy();
        DistributionQueueDispatchingStrategy importQueueStrategy = null;

        DistributionPackageExporter packageExporter = new LocalDistributionPackageExporter(packageBuilder);
        DistributionRequestType[] allowedRequests = new DistributionRequestType[]{DistributionRequestType.ADD, DistributionRequestType.DELETE};
        Set<String> processingQueues = new HashSet<String>();
        processingQueues.addAll(exportQueueStrategy.getQueueNames());

        return new SimpleDistributionAgent(agentName, false, processingQueues,
                serviceName, null, packageExporter, requestAuthorizationStrategy,
                queueProvider, exportQueueStrategy, importQueueStrategy, distributionEventFactory, resourceResolverFactory, distributionLog, allowedRequests, allowedRoots, 0);
    }
}


text:
package studios.codelight.smartloginlibrary;

public class SmartLoginFactory {
    public static SmartLogin build(LoginType loginType) {
        switch (loginType) {
            case Facebook:
                return new FacebookLogin();
            case Google:
                return new GoogleLogin();
            case CustomLogin:
                return new CustomLogin();
            default:
                // To avoid null pointers
                return new CustomLogin();
        }
    }
}


text:
var helpers = require("yeoman-generator").test;
var expect  = require("chai").expect;
var path    = require("path");

describe("incubator travis generator", function () {
	var testDirectory = path.join(__dirname, "temp");
	var app;

	beforeEach(function (done) {
		helpers.testDirectory(testDirectory, function (err) {
			if (err) {
				return done(err);
			}

			app = helpers.createGenerator("incubator:travis", [
				"../../travis"
			]);

			done();
		});
	});

	it("can be imported without blowing up", function (done) {
		var app = require("../travis");
		expect(app).to.not.be.undefined;

		done();
	});
});


text:
package main_test

import (
	. "github.com/ebenoist/termo-api"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"testing"
)

func TestTermoApi(t *testing.T) {
	ENV = "TEST"
	RegisterFailHandler(Fail)
	RunSpecs(t, "TermoApi Suite")
}


text:
<?php

session_start();

$errors = array();

$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	if (strlen($email) < 1 || strlen($email) > 256) {
		$errors['email'] = true;
	}

	if (empty($errors)) {

		require_once 'includes/db.php';

		$sql = $db->prepare('
			INSERT INTO mep_users (email)
			VALUES (:email)
		');
		$sql->bindValue(':email', $email, PDO::PARAM_STR);
		$sql->execute();

		$result = $db->lastInsertId();
		//var_dump($sql->errorInfo());
		$_SESSION['user_id'] = $result;

		var_dump($_SESSION);

		header('Location:about.php');
		exit;
	}
}

?><!DOCTYPE HTML>

<meta charset="utf-8">
	<title>Registration Form Validation</title>
	<meta name="viewport" content="width=device-width">
	<link href="css/general.css" rel="stylesheet">

Sign up:

						<form method="post" action="sign-up.php">

									 Your Email
									<?php if (isset($errors['email'])): ?>
									is required
									<?php endif; ?>

								<input id="email" name="email" required value="<?php echo $email; ?>">

							<button types="submit">Sign up</button>
						</form>

<?php include 'includes/wrapper-bottom.php'; ?>


text:
SET(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
  "/home/saesha/Desktop/SSRR13/Andreas/slam6d/src/scanio/scan_io_ply.cc" "/home/saesha/Desktop/SSRR13/Andreas/slam6d/build/src/scanio/CMakeFiles/scan_io_ply.dir/scan_io_ply.cc.o"
  )
SET(CMAKE_CXX_COMPILER_ID "GNU")

# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
  "/home/saesha/Desktop/SSRR13/Andreas/slam6d/build/src/scanio/CMakeFiles/pointfilter.dir/DependInfo.cmake"
  )


text:
"use strict";

(function()
{
  var globalId = 0;

  /**
   * Models hold the current state of the application. This basic models provides
   * a simple key/value store and event based notifications.
   */
  core.Class("core.model.Model",
  {
    include: [core.property.MGeneric, core.event.MEventTarget, core.util.MLogging],
    implement : [core.model.IModel],

    /**
     * Initial data structure is imported from @data {any}.
     * Initial @parent {Object} can also be passed in.
     */
    construct: function(data, parent)
    {
      // Automatically created client-side ID
      this.__clientId = "model-" + (globalId++);

      // Attach parent when given (e.g. a collection or presenter)
      if (parent != null) {
        this.__parent = parent;
      }

      // Import given values with parse method
      if (data != null)
      {
        var values = this.parse(data);

        if (jasy.Env.isSet("debug")) {
          core.Assert.isType(values, "Map", "Invalid values to import!");
        }

        this.set(values);
      }
    },

    events :
    {
      /** Fired whenever the model is changed in a way that is interesting for listeners */
      change : core.event.Simple
    },

    properties :
    {
      /** Unique ID of the model instance */
      id :
      {
        type : "String",
        nullable : true
      }
    },

    members:
    {
      /** {String} Internal storage field for client ID */
      __clientId : null,

      /**
       * Returns the assigned parent
       */
      getEventParent : function() {
        return this.__parent;
      },

      setParent : function(parent) {
        this.__parent = parent;
      },

      getParent : function() {
        return this.__parent;
      },

      // Interface implementation
      parse : function(data) {
        return data;
      },

      // Interface implementation
      getClientId : function() {
        return this.__clientId;
      },

      // Interface implementation
      toJSON : function()
      {
        // Typically uses all existing properties
        // Override the method if you need to include other fields

        var values = this.get(core.Object.getKeys(core.Class.getProperties(this.constructor)));

        for (var name in values)
        {
          var value = values[name];
          if (value != null && value.toJSON) {
            values[name] = value.toJSON();
          }
        }

        return values;
      }
    }
  });
})();


text:
ruby_block 'conditional-monit-reload' do
  block do
    # Cherry-pick monit_check resources from the run_context
    checks = run_context.resource_collection.select do |r|
      r.is_a?(Chef::Resource::MonitCheck)
    end

    # Reload monit if any monit_check resources changed
    if checks.any?(&:updated_by_last_action?)
      Chef::Log.info('Found updated monit checks, issuing service reload.')
      resources(service: 'monit').run_action(:reload)
    end
  end
  action :nothing
end

# Notify the resource scanning/proactive reload block
# to run at the end of the converge cycle
ruby_block 'notify-conditional-monit-reload' do
  block do
    Chef::Log.info('Notifying ruby_block[conditional-monit-reload] to run.')
  end
  notifies :run, 'ruby_block[conditional-monit-reload]', :delayed
  only_if { node['monit']['proactive_reload'] }
  action :run
end


text:
import { expect } from 'chai';
import { describeModule, it } from 'ember-mocha';

describeModule('controller:s/media/albums/album', 'SMediaAlbumsAlbumController', {
    // needs: ['controller:foo']
}, function () {
    it('exists', function () {
        var controller = this.subject();
        expect(controller).to.be.ok;
    });
});


text:
A hubot script for tipping with Dogecoin.

![dogecoin](http://i.imgur.com/klX8aS3l.png)

## API

* `<user> +<n> doge` - tip <user> <n> dogecoin (user by mention name)
* `doge register` - get your dogecoin address
* `doge address`  - get your dogecoin address
* `doge balance`  - get your dogecoin balance
* `send <n|all> doge to <addr>` - withdraw <n> or all doge to a dogecoin address

You can swap the _doge_ keyword for one of _such_, _much_, _so_, _very_, or _dogecoin_. I.e. `such address`.

## Requirements

1. [Hubot brain](https://github.com/github/hubot/blob/master/docs/scripting.md#persistence)
2. A [dogecoind](https://github.com/dogecoin/dogecoin) instance running either locally or on another box with the JSON RPC port open (default: 22555).
3. Some dogecoin to give.

## Installation

Add `hubot-dogecoin` as a dependency in your Hubot `package.json`.
```
"dependencies": {
  "hubot": "*",
  "hubot-dogecoin": "~0.0.1"
}
```

Run the following to install the package and its dependencies.
```bash
$ npm install
```

Add `hubot-dogecoin` to the array in `external-scripts.json`, you may need to create this file.
```
['hubot-dogecoin']
```

Configure the following environment variables in `bin/hubot`.
```bash
export HUBOT_DOGECOIND_USER="dogecoindrpcuser"
export HUBOT_DOGECOIND_PASS="dogecoindrpcpass"

export HUBOT_DOGECOIND_HOST="localhost" # optional, default: localhost
export HUBOT_DOGECOIND_PORT=22555       # Optional, default: 22555
```

## Events

The following event hooks are emitted on successful dogecoind command
executions.

```coffee
@robot.emit 'dogecoin.getAddress', { user: user, address: result }
```

```coffee
@robot.emit 'dogecoin.getBalance', { user: user, balance: result }
```

```coffee
@robot.emit 'dogecoin.move', {
  sender:    sender
  recipient: recipient
  amount:    amount
}
```

```coffee
@robot.emit 'dogecoin.sendFrom', {
  user:    user
  address: address
  amount:  amount
  txid:    result
}
```

__Note:__ `user` is the entire user object from `@robot.brain` and `result` is
the result of the corresponding dogecoind command.


text:
package it.uniroma2.ember.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.io.IOException;

/**
 *  The class LumenData is the OO representation for the JSON object
 *  provided by light sensors on lamps.
 */
public class LumenData {

    private int id;
    private String address;
    private float ambient;
    private long retrieved;

    public int getId() {
        return id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public float getAmbient() {
        return ambient;
    }

    public void setAmbient(float ambient) {
        this.ambient = ambient;
    }

    public long getRetrieved() {
        return retrieved;
    }

    public void setRetrieved(long retrieved) {
        this.retrieved = retrieved;
    }

    /**
     * @param id unique identifier of light sensor (it is the same of the lamp)
     * @param address where the lamp is located
     * @param ambient luminosity level near the sensor
     */
    public LumenData(int id, String address, float ambient, long retrieved) {
        this.id = id;
        this.address   = address;
        this.ambient   = ambient;
        this.retrieved = retrieved;
    }

    public LumenData() { /* dummy constructor for jackson parsing */ }

    /**
     * Static method to parse the JSON string provided into a
     * LumenData class object.
     *
     * @param json a string defining the JSON input
     * @return {@link LumenData} or null in case of error
     */
    public static LumenData parseLumenData(String json) throws IOException {
        Gson gson = new Gson();
        return gson.fromJson(json, LumenData.class);

    }

}


text:
<?php
namespace Skrz\Meta\Fixtures\Constants;

class ClassWithProperties
{

	/** @var string */
	protected $property;

	/** @var string */
	protected $anotherProperty;

	/** @var string */
	protected $property_with_underscores;

}


text:
This directory is a transitional one for Dart source analysis and metadata
creation that might eventually exist in the `angular_ast` package but is easier
to keep within this package for the time being.


text:
//
//  CKFetchRecordChangesOperation.m
//  AgileCloudSDK
//
//  Copyright (c) 2015 AgileBits Inc. All rights reserved.
//

#import "CKFetchRecordChangesOperation.h"
#import "CKDatabaseOperation_Private.h"
#import "NSError+AgileCloudSDKExtensions.h"
#import "NSArray+AgileMap.h"
#import "CKRecordID+AgileDictionary.h"
#import "CKServerChangeToken+AgileDictionary.h"
#import "CKDatabase_Private.h"
#import "CKServerChangeToken_Private.h"
#import "CKRecord_Private.h"
#import "Defines.h"
#import "CKRecordZoneID.h"

@implementation CKFetchRecordChangesOperation

/* This operation will fetch all records changes in the given record zone.
 If a change anchor from a previous CKFetchRecordChangesOperation is passed in, only the records that have changed
 since that anchor will be fetched.
 If this is your first fetch or if you wish to re-fetch all records, pass nil for the change anchor.
 Change anchors are opaque tokens and clients should not infer any behavior based on their content. */
- (instancetype)initWithRecordZoneID:(CKRecordZoneID *)recordZoneID previousServerChangeToken:(CKServerChangeToken *)previousServerChangeToken {
	if (self = [super init]) {
		_recordZoneID = recordZoneID;
		_previousServerChangeToken = previousServerChangeToken;
	}
	return self;
}

- (void)start {
	[self setExecuting:YES];

	NSMutableDictionary *requestDictionary = [NSMutableDictionary dictionaryWithDictionary:@{
																							 @"zoneID": @{@"zoneName": _recordZoneID.zoneName}
																							 }];
	if (_desiredKeys) {
		requestDictionary[@"desiredKeys"] = _desiredKeys;
	}
	if (_resultsLimit) {
		requestDictionary[@"resultsLimit"] = @(_resultsLimit);
	}
	if (_previousServerChangeToken) {
		requestDictionary[@"syncToken"] = [_previousServerChangeToken asString];
	}

	[self.database sendPOSTRequestTo:@"records/changes" withJSON:requestDictionary completionHandler:^(id jsonResponse, NSError *operationError) {

		__block NSError* localOperationError;

		_moreComing = [jsonResponse[@"moreComing"] boolValue];
		CKServerChangeToken *serverChangeToken = [[CKServerChangeToken alloc] initWithString:jsonResponse[@"syncToken"]];

		if ([jsonResponse isKindOfClass:[NSDictionary class]] && jsonResponse[@"records"]) {
			[jsonResponse[@"records"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
				NSError* recordError = nil;

				if ([obj[@"deleted"] boolValue]) {
					CKRecordID* deletedRecordID = [[CKRecordID alloc] initWithRecordName:obj[@"recordName"] zoneID:_recordZoneID];
					if (self.recordWithIDWasDeletedBlock) {
						self.recordWithIDWasDeletedBlock(deletedRecordID);
					}
				}
				else {
					CKRecord* record = [[CKRecord alloc] initWithDictionary:obj inZone:_recordZoneID];
					CKRecordID* recordID = record.recordID;
					if (!record) {
						recordError = [[NSError alloc] initWithCKErrorDictionary:obj];
						if (obj[@"recordName"]) {
							recordID = [[CKRecordID alloc] initWithRecordName:obj[@"recordName"]  zoneID:_recordZoneID];
						}
					}
					else {
						NSArray* errs = [record synchronouslyDownloadAllAssetsWithProgressBlock:nil];
						if ([errs count]) {
							recordError = errs[0];
							record = nil;
						}
					}

					if (record) {
						if (self.recordChangedBlock) {
							self.recordChangedBlock(record);
						}
					}
					else if (!localOperationError) {
						localOperationError = recordError;
					}
				}
			}];
		}
		else if (!operationError) {
			operationError = [[NSError alloc] initWithCKErrorDictionary:jsonResponse];
		}
		if (localOperationError) {
			operationError = localOperationError;
		}

		if (self.fetchRecordChangesCompletionBlock) {
			self.fetchRecordChangesCompletionBlock(serverChangeToken, nil, operationError);
		}

		[self setExecuting:NO];
		[self setFinished:YES];
	}];
}

@end


text: i'm practicing html damnit


text:
var aboutctrl = angular.module('aboutctrl',[]);

aboutctrl.controller('aboutcontroller',function($scope,$http){

    $scope.alert = function(){
        alert("Alert is called from about page");
    };
});


text:
/*
  Routines for interfacing libuc with curl. Includes posting and getting
  UniversalContainers.
 */

#include <uc/ucontainer.h>
#include <uc/buffer.h>
#include <uc/uc_web.h>

namespace JAD {
  /*
    HTTP post to the given url. Request is encoded by send_type,
    which defaults to form encoding but may also be json. Parses the
    reutnr
   */
  UniversalContainer web_rpc_call(const char* url,
				  UniversalContainer& request,
				  const char* send_type)
  {
    UniversalContainer uc;

    if (!send_type) send_type = "application/x-www-form-urlencoded";
    Buffer* send = encode_by_mime_type(request,send_type);
    if (!send) throw ucexception(uce_Unknown_mime_type);

    string ret_type;
    Buffer* receive = http_post_buffer(url,send,ret_type,send_type);
    if (!receive) {uc = false; return uc;}
    uc = decode_by_mime_type(ret_type,receive);
    delete receive;
    return uc;
  }

  //pull a url, and try to interpret the results as a uc
  UniversalContainer web_fetch(const char* url)
  {
    UniversalContainer uc;
    string ret_type;
    Buffer* receive = http_get_buffer(url,ret_type);
    if (!receive) throw ucexception(uce_Communication_Error);
    uc = decode_by_mime_type(ret_type,receive);
    delete receive;
    return uc;
  }

}//end namespace


text:
> Allow parsing of decorators

See our website [@babel/plugin-syntax-decorators](https://babeljs.io/docs/en/babel-plugin-syntax-decorators) for more information.

## Install

Using npm:

```sh
npm install --save-dev @babel/plugin-syntax-decorators
```

or using yarn:

```sh
yarn add @babel/plugin-syntax-decorators --dev
```


text:
From https://asc.llnl.gov/coral-2-benchmarks:

    PENNANT is a mini-app for hydrodynamics on general unstructured
    meshes in 2D (arbitrary polygons). It makes heavy use of indirect
    addressing and irregular memory access patterns.

A detailed description of the algorithm can be found in the Pennant
repository (downloaded to integration/apps/pennant/PENNANT by the
build.sh script) under doc/pennantdoc.pdf.

# Number of Cores Reserved for Pennant

Pennant AppConfig file (pennant.py) reserves N physical cores per node
where N is the largest even number less than the total number of physical
cores in the node. This way, at least one physical core is reserved for
the OS and GEOPM.

# GEOPM Epoch Selection

Based on the problem size we choose a different build of pennant.
The difference between these builds is how GEOPM epochs are marked:

    epoch100: One epoch every 100 outer loop iterations.
    epoch1: One epoch every outer loop iteration.
    default: No epoch markup.

There is a known issue that epochs occuring too often causes GEOPM to hang due to
epoch handling overwhelming GEOPM control loop. Larger problem sizes are expected to
be able to handle a smaller number of outer loops per epoch since outer loop time
seems to increase with problem size.

The map of which dataset is run with which build is kept in the AppConfig file for
Pennant (pennant.py).


text:
(\_**DEFUNCT**\_)

CSVParser
========

A CSV Parser for iOS and OSX.

It can parse csv file into an array of arrays or an array of dictionaries.

The csv file can contain single quote ' or double quote ".

Usage
-----

Adding CSVParser.h and CSVParser.m to your Xcode project.

1. Import the CSVParser class header:

```objective-c
#import "CSVParser.h"
```

2. Create an array from file:

```objective-c
NSArray *arrayOfArrays = [CSVParser parseCSVIntoArrayOfArraysFromFile:filePath
                                         withSeparatedCharacterString:@","
                                                 quoteCharacterString:nil]; // nil, if csv dont have quote.

NSArray *arrayOfDictionaries = [CSVParser parseCSVIntoArrayOfDictionariesFromFile:filePath
                                                     withSeparatedCharacterString:@","
                                                             quoteCharacterString:@"\""]; // if csv contains ".
```

Example
-------

Assume you have a csv file:

```csv
name,email,address
"Lucky Star",lucky@abc.com,"1A street"
"Joe A",joe@abc.com,"2B street"
```

Array of arrays:

```objective-c
NSArray *arrayOfArrays = [CSVParser parseCSVIntoArrayOfArraysFromFile:filePath
                                         withSeparatedCharacterString:@","
                                                 quoteCharacterString:@"\""];

//    (("name","email","address"),
//     ("Lucky Star","lucky@abc.com","1A street"),
//     ("Joe A","joe@abc.com","2B street"))
```

Array of dictionaries:

```objective-c
NSArray *arrayOfDictionaries = [CSVParser parseCSVIntoArrayOfDictionariesFromFile:filePath
                                                     withSeparatedCharacterString:@","
                                                             quoteCharacterString:@"\""];

//    ({"name" = "Lucky Star";
//      "email" = "lucky@abc.com";
//      "address" = "1A street";},
//     {"name" = "Joe A";
//      "email" = "joe@abc.com";
//      "address" = "2B street";})
```

Contact
-------

vuong.haminh@gmail.com

License - BSD
-------

Copyright (c) 2012, Ha Minh Vuong.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
/**
 * ContentEditable internal item node.
 *
 * @class
 * @extends ve.ce.BranchNode
 * @constructor
 * @param {ve.dm.InternalItemNode} model Model to observe
 * @param {Object} [config] Configuration options
 */
ve.ce.InternalItemNode = function VeCeInternalItemNode( model, config ) {
	// Parent constructor
	ve.ce.BranchNode.call( this, model, config );
};

/* Inheritance */

OO.inheritClass( ve.ce.InternalItemNode, ve.ce.BranchNode );

/* Static Properties */

ve.ce.InternalItemNode.static.name = 'internalItem';

ve.ce.InternalItemNode.static.tagName = 'span';

/* Registration */

ve.ce.nodeFactory.register( ve.ce.InternalItemNode );


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace StorageTool.Resources
{
    public class RelayCommand : ICommand
    {
        private Action<object> execute;
        private Func<object, bool> canExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return this.canExecute == null || this.canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            this.execute(parameter);
        }

    }
}


text:
from __future__ import unicode_literals

import argparse
import locale
import os
import sys
from rock import __version__
from rock.exceptions import Error
from rock.project import Project
from rock.runtime import list as runtime_list
from rock.text import *

def argument_parser(*args, **kwargs):
    format_usage = kwargs.pop('format_usage', None)
    format_help = kwargs.pop('format_help', None)

    class ArgumentParser(argparse.ArgumentParser):

        def format_usage(self):
            return '%s\n' % format_usage

        def format_help(self):
            return '%s\n%s\n' % (self.format_usage(), format_help)

    kwargs['add_help'] = False

    p = ArgumentParser(*args, **kwargs)
    p.add_argument('--help', action='help')

    return p

def project(args):
    """
    Create and return project instance using cli arguments.
    """
    config = {'path': args.path}
    if args.verbose:
        config['verbose'] = True
    if args.dry_run:
        config['dry_run'] = True
        config['verbose'] = True
    if args.runtime:
        config['runtime'] = args.runtime
    return Project(config, env=args.env)

def config(args, argv):
    """
    Output project configuration (json, yaml).
    """
    parser = argument_parser(prog='rock config', format_usage=CONFIG_USAGE,
                             format_help=CONFIG_HELP)
    parser.add_argument('--format', choices=['json', 'yaml'], default='yaml')

    sub_args = parser.parse_args(argv)

    config = project(args).config
    config.setup()

    if sub_args.format == 'json':
        import json
        sys.stdout.write(u'' + json.dumps(config.data, indent=2))
    else:
        import yaml
        yaml.safe_dump(config.data, stream=sys.stdout, encoding=None)

def env(args, argv):
    """
    Output project environment.
    """
    parser = argument_parser(prog='rock env', format_usage=ENV_USAGE,
                             format_help=ENV_HELP)

    sub_args = parser.parse_args(argv)

    for name, value in project(args).config['env'].items():
        sys.stdout.write('export %s="%s"\n' % (name, value))

def runtime(args, argv):
    """
    List runtimes install on system.
    """
    parser = argument_parser(prog='rock runtime', format_usage=RUNTIME_USAGE,
                             format_help=RUNTIME_HELP)

    sub_args = parser.parse_args(argv)

    for r in runtime_list():
        sys.stdout.write('%s\n' % r.name)

def main(argv=None):
    """
    Handle command line arguments.
    """

    if argv is None:
        argv = sys.argv[1:]
        encoding = None
        try:
            encoding = locale.getdefaultlocale()[1]
        except ValueError:
            pass
        if encoding:
            argv = [a.decode(encoding) for a in sys.argv[1:]]

    # find command position
    pos, skip_next = 0, False
    for i, arg in enumerate(argv):
        if skip_next:
            skip_next = False
            continue
        elif arg.startswith('--'):
            if arg[2:] in ('env', 'path', 'runtime'):
                skip_next = True
        else:
            pos = i
            break

    parser = argument_parser(prog='rock', format_usage=USAGE, format_help=HELP)
    parser.add_argument('--verbose', action='store_true')
    parser.add_argument('--dry-run', action='store_true')
    parser.add_argument('--version', action='version', version=__version__)
    parser.add_argument('--env', default=os.environ.get('ROCK_ENV', 'local'))
    parser.add_argument('--path', default=os.environ.get('ROCK_PATH', ''))
    parser.add_argument('--runtime', default=os.environ.get('ROCK_RUNTIME'))
    parser.add_argument('command')

    try:
        # only parse up until command
        args = parser.parse_args(argv[:pos + 1])
        if args.command in ('config', 'env', 'runtime'):
            globals()[args.command](args, argv[pos + 1:])
        else:
            project(args).run(args.command, argv[pos + 1:])
    except Error as error:
        message = '%s' % error
        if not message.endswith('\n'):
            message += '\n'
        parser.exit(1, message)


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

 <!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
       "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">

<!--
     This is a blank Tiles definition file with a commented example.
-->

<tiles-definitions>

</tiles-definitions>


text:
* Navigate into the root directory of your local Jekyll site repository. The git repository is [here](https://github.com/Carlos-Liu/Github-pages.git)
* Run your Jekyll site locally
	    ```bundle exec jekyll serve```
* Preview your local Jekyll site in your web browser at the address specified in the output of above command

* Copy all the contents from the generated folder **_site**, then paste them to the local repository (*X:\Private\GitHubBlog\standalong-pages\carlos-liu.github.io*)

* In Git Bash, run command
```
	git add -A
	git commit -m "comments"
	git push origin master
```

# Note
## Keeping your site up to date with the GitHub Pages gem
* Open Git Bash.
* Run this update command:

    * If you followed our setup recommendations and installed Bundler, run ```bundle update github-pages``` or simply ```bundle update``` and all your gems will update to the latest versions.

    * If you don't have Bundler installed, run ```gem update github-pages```

# References
> [Build your local jekyll site](https://help.github.com/articles/setting-up-your-github-pages-site-locally-with-jekyll/#step-4-build-your-local-jekyll-site)

> [Online markdown editor](https://markable.in/editor/)


text:
<?php

declare(strict_types=1);

namespace Qandidate\Bundle\ToggleBundle\Twig;

use Qandidate\Toggle\ContextFactory;
use Qandidate\Toggle\ToggleManager;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Twig\TwigTest;

class ToggleTwigExtension extends AbstractExtension
{
    private $contextFactory;
    private $toggleManager;

    public function __construct(ToggleManager $toggleManager, ContextFactory $contextFactory)
    {
        $this->toggleManager = $toggleManager;
        $this->contextFactory = $contextFactory;
    }

    public function is_active(string $name): bool
    {
        return $this->toggleManager->active($name, $this->contextFactory->createContext());
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new TwigFunction('feature_is_active', [$this, 'is_active']),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getTests()
    {
        return [
            new TwigTest('active feature', [$this, 'is_active']),
        ];
    }

    public function getName(): string
    {
        return 'qandidate_toggle_twig_extension';
    }
}


text:
import React from 'react';

import styles from './MenuItem.module.css';

const MenuItem: React.FC<{}> = ({ children }) => (

{children}

);

export default MenuItem;


text:
*Fernanda Larraín Yunge*

División de proyectos en 3 áreas generales:
* Diseño gráfico
* Ilustraciones
* Diseño de productos

**Contacto vía mail a través de la misma página**
http://flarrain.disenoproyectos.cl/


text:
/**
 * @file This file defines the Root simobject and the methods used to control
 * the time syncing mechanism provided through it.
 *
 * Time syncing prevents simulated time from passing faster than real time. It
 * works by scheduling a periodic event that checks to see if its simulated
 * period is shorter than its real period. If it is, it stalls the simulation
 * until they're equal.
 */

#ifndef __SIM_ROOT_HH__
#define __SIM_ROOT_HH__

#include "base/time.hh"
#include "params/Root.hh"
#include "sim/eventq.hh"
#include "sim/sim_object.hh"

class Root : public SimObject
{
  private:
    static Root *_root;

  protected:
    bool _enabled;
    Time _period;
    Tick _periodTick;
    Time _spinThreshold;

    Time lastTime;

    void timeSync();
    EventWrapper<Root, &Root::timeSync> syncEvent;
    friend class EventWrapper<Root, &Root::timeSync>;

  public:
    /**
     * Use this function to get a pointer to the single Root object in the
     * simulation. This function asserts that such an object has actual been
     * constructed to avoid having to perform that check everywhere the root
     * is used. This is to allow calling the functions below.
     *
     * @return Pointer to the single root object.
     */
    static Root *
    root()
    {
        assert(_root);
        return _root;
    }

  public:

    /// Check whether time syncing is enabled.
    bool timeSyncEnabled() const { return _enabled; }
    /// Retrieve the period for the sync event.
    const Time timeSyncPeriod() const { return _period; }
    /// Retrieve the threshold for time remaining to spin wait.
    const Time timeSyncSpinThreshold() const { return _spinThreshold; }

    /// Enable or disable time syncing.
    void timeSyncEnable(bool en);
    /// Configure the period for time sync events.
    void timeSyncPeriod(Time newPeriod);
    /// Set the threshold for time remaining to spin wait.
    void timeSyncSpinThreshold(Time newThreshold);

    typedef RootParams Params;
    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }

    Root(Params *p);

    /** Schedule the timesync event at loadState() so that curTick is correct
     */
    void loadState(Checkpoint *cp);

    /** Schedule the timesync event at initState() when not unserializing
     */
    void initState();

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);

};

#endif // __SIM_ROOT_HH__


text:
Education

Master of Engineering in Software Engineering

            Beihang Univerity
            <address>Beijing, China</address><time>2019 to 2022</time>

Bachelor of Engineering in Software Engineering

            Nankai Univerity
            <address>Tianjin, China</address><time>2011 to 2015</time>

Bachelor of Management in Business Administration(Double degree)

            Tianjin University
            <address>Tianjin, China</address><time>2011 to 2015</time>


text:
set -ex

echo Testing num-integer on rustc ${TRAVIS_RUST_VERSION}

# num-integer should build and test everywhere.
cargo build --verbose
cargo test --verbose

# test `no_std`
cargo build --verbose --no-default-features
cargo test --verbose --no-default-features


text:
.class Landroid/widget/Editor$SelectionEndHandleView;
.super Landroid/widget/Editor$HandleView;
.source "Editor.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/Editor;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "SelectionEndHandleView"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/Editor;

# direct methods
.method public constructor <init>(Landroid/widget/Editor;Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;)V
    .locals 0
    .parameter
    .parameter "drawableLtr"
    .parameter "drawableRtl"

    .prologue
    .line 3377
    iput-object p1, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    .line 3378
    invoke-direct {p0, p1, p2, p3}, Landroid/widget/Editor$HandleView;-><init>(Landroid/widget/Editor;Landroid/graphics/drawable/Drawable;Landroid/graphics/drawable/Drawable;)V

    .line 3379
    return-void
.end method

# virtual methods
.method public getCurrentCursorOffset()I
    .locals 1

    .prologue
    .line 3392
    iget-object v0, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    #getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v0}, Landroid/widget/Editor;->access$600(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/TextView;->getSelectionEnd()I

    move-result v0

    return v0
.end method

.method protected getHotspotX(Landroid/graphics/drawable/Drawable;Z)I
    .locals 1
    .parameter "drawable"
    .parameter "isRtlRun"

    .prologue
    .line 3383
    if-eqz p2, :cond_0

    .line 3384
    invoke-virtual {p1}, Landroid/graphics/drawable/Drawable;->getIntrinsicWidth()I

    move-result v0

    mul-int/lit8 v0, v0, 0x3

    div-int/lit8 v0, v0, 0x4

    .line 3386
    :goto_0
    return v0

    :cond_0
    invoke-virtual {p1}, Landroid/graphics/drawable/Drawable;->getIntrinsicWidth()I

    move-result v0

    div-int/lit8 v0, v0, 0x4

    goto :goto_0
.end method

.method public setActionPopupWindow(Landroid/widget/Editor$ActionPopupWindow;)V
    .locals 0
    .parameter "actionPopupWindow"

    .prologue
    .line 3416
    iput-object p1, p0, Landroid/widget/Editor$HandleView;->mActionPopupWindow:Landroid/widget/Editor$ActionPopupWindow;

    .line 3417
    return-void
.end method

.method public updatePosition(FF)V
    .locals 4
    .parameter "x"
    .parameter "y"

    .prologue
    .line 3404
    iget-object v2, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    #getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v2}, Landroid/widget/Editor;->access$600(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, p1, p2}, Landroid/widget/TextView;->getOffsetForPosition(FF)I

    move-result v0

    .line 3407
    .local v0, offset:I
    iget-object v2, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    #getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v2}, Landroid/widget/Editor;->access$600(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2}, Landroid/widget/TextView;->getSelectionStart()I

    move-result v1

    .line 3408
    .local v1, selectionStart:I
    if-gt v0, v1, :cond_0

    .line 3409
    add-int/lit8 v2, v1, 0x1

    iget-object v3, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    #getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v3}, Landroid/widget/Editor;->access$600(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v3

    invoke-virtual {v3}, Landroid/widget/TextView;->getText()Ljava/lang/CharSequence;

    move-result-object v3

    invoke-interface {v3}, Ljava/lang/CharSequence;->length()I

    move-result v3

    invoke-static {v2, v3}, Ljava/lang/Math;->min(II)I

    move-result v0

    .line 3412
    :cond_0
    const/4 v2, 0x0

    invoke-virtual {p0, v0, v2}, Landroid/widget/Editor$SelectionEndHandleView;->positionAtCursorOffset(IZ)V

    .line 3413
    return-void
.end method

.method public updateSelection(I)V
    .locals 2
    .parameter "offset"

    .prologue
    .line 3397
    iget-object v0, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    #getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v0}, Landroid/widget/Editor;->access$600(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v0

    invoke-virtual {v0}, Landroid/widget/TextView;->getText()Ljava/lang/CharSequence;

    move-result-object v0

    check-cast v0, Landroid/text/Spannable;

    iget-object v1, p0, Landroid/widget/Editor$SelectionEndHandleView;->this$0:Landroid/widget/Editor;

    #getter for: Landroid/widget/Editor;->mTextView:Landroid/widget/TextView;
    invoke-static {v1}, Landroid/widget/Editor;->access$600(Landroid/widget/Editor;)Landroid/widget/TextView;

    move-result-object v1

    invoke-virtual {v1}, Landroid/widget/TextView;->getSelectionStart()I

    move-result v1

    invoke-static {v0, v1, p1}, Landroid/text/Selection;->setSelection(Landroid/text/Spannable;II)V

    .line 3399
    invoke-virtual {p0}, Landroid/widget/Editor$SelectionEndHandleView;->updateDrawable()V

    .line 3400
    return-void
.end method


text:
// inherit() returns a newly created object that inherits properties from the
// prototype object p. It uses the ECMAScript 5 function Object.create() if
// it is defined, and otherwise falls back to an older technique.
function inherit(p) {
	if (p == null) throw TypeError(); // p must be a non-null object
	if (Object.create) // If Object.create() is defined...
		return Object.create(p); // then just use it.
	var t = typeof p; // Otherwise do some more type checking
	if (t !== "object" && t !== "function")
		throw TypeError();
	function f() {}; // Define a dummy constructor function.
	f.prototype = p; // Set its prototype property to p.
	return new f(); // Use f() to create an "heir" of p.
}

function testSub() {
	//var expr = $('#exprfield').val() + ",*";
	var expr = "sys*:dc=dc1,host=WebServer1,*"
	console.info("Subscribing to expression [%s]", expr);
	ws.subscribe(expr);
	// .then(
	// 	function(data) {
	// 		console.info("SUB TERM: [%O]", data);
	// 	},
	// 	function(data) {
	// 		console.error("SUB ERROR: [%O]", arguments);
	// 	},
	// 	function(data) {
	// 		console.info("SUB EVENT: [%O]", data);
	// 	}
	// );
}

/*
	SUB STARTED:
	============
	id: 1486981487
	msg: Object
	subId: 1
	__proto__: Object
	op: "subst"
	rerid: 1
	t: "resp"

	SUB EVENT:
	==========
	metric: "sys.cpu"
	subid: 2
	tags: Object
	cpu: "1"
	dc: "dc4"
	host: "WebServer1"
	type: "sys"
	__proto__: Object
	ts: 1409783673
	type: "l"
	value: 17

	SUB TERM:
	=========
*/

function testIncremental(startingKey) {
	var ws = new WebSocketAPIClient();
	var q = QueryContext.newContext({timeout: 10000});

	var root = MetaTree.newInstance(startingKey);

	var onKey = function(data, tree, state) {
		console.group("================ onKey ================");
		try {
			if(data==null || data.data==null || data.data.length==0) {
				console.info("Key Exhausted at [%O]", state);
				return;
			}

			var key = data.data.last().name;
			state.keys.push(key);
			//console.info("Last Key: [%s]", key);
			var nextTree = tree.tag(tree, key);
			ws.getTagValues(QueryContext.newContext({timeout: 10000}), 'sys.cpu', key, state.tags).then(function(data) { onValue(data, nextTree, state); });
		} finally {
			console.groupEnd();
		}
		//ws.getTagKeys(q, 'sys.cpu', ['dc']).then(
	}
	var onValue = function(data, tree, state) {
		//ws.getTagValues(q, 'sys.cpu', 'type', {host:'*Server*', cpu:'*'}).then(
		//data.data[x].name
		console.group("================ onValue ================");
		//console.debug("Data: [%O], Tree: [%O], State: [%O]", data, tree, state);
		try {
			jQuery.each(data.data, function(index, uid){
				//console.info("value: [%s]", uid.name);
				var nextTree = tree.tag(tree, uid.name);
				state.tags[state.keys.last()];
				ws.getTagKeys(QueryContext.newContext({timeout: 10000}), 'sys.cpu', state.keys).then(function(data) { onKey(data, nextTree, state.clone()); });
			});
		} finally {
			console.groupEnd();
		}
	}
	var state = {
		tags: {},
		keys: [startingKey]
	}
	ws.getTagValues(QueryContext.newContext({timeout: 10000}), 'sys.cpu', startingKey, {}).then(function(data) { onValue(data, root, state); });

}

var ANNOTATION_URL = 'http://' + document.location.host + '/api/annotation';

function postGlobalAnnotations() {
	var callback = function(result) {
		console.info("Global Annotation Post Result: [%O]", result);
	}
	for(var i = 0; i < 100; i++) {
		var data = {
			startTime : new Date().getTime() - (i * 1000),
		  	description : "Test Annotation #" + i,
		  	notes : "This is a test annotation, with id [" + i + "]",
		  	custom : {
		    	type : "Global"
		  	}
		};
		$.post(ANNOTATION_URL, JSON.stringify(data), callback, "json");
	}
}

function postTSUIDAnnotations() {
	var callback = function(result) {
		console.info("TSUID Annotation Post Result: [%O]", result);
	}
	var ws = new WebSocketAPIClient();
	var q = QueryContext.newContext({pageSize: 100, maxSize: 100, timeout: 10000});
	ws.resolveTSMetas(q, "sys*:dc=dc1,host=WebServer*").then(
		function(result) {
			console.info("TSUID: [%O]", result);
			for(var i = 0, x = result.data.length; i < x; i++) {
				var t = result.data[i];
				var data = {
					startTime : new Date().getTime() - (i * 1000),
				  	description : "Test TSUID Annotation #" + i,
				  	notes : "This is a test annotation, with id [" + i + "]",
				  	tsuid : t.tsuid,
				  	custom : {
				    	type : "TSUID",
				    	tsuid : t.tsuid,
				    	name: t.name
				  	}
				};
				$.post(ANNOTATION_URL, JSON.stringify(data), callback, "json");
			}
		}
	);
}

function testAll() {
	if(ws==null) {
		ws = new WebSocketAPIClient();
	}
	var q = null;
	ws.findUids(q, "TAGV", "Web*").then(
		function(result) { console.info("findUids Result: [%O]", result); },
		function() { console.error("findUids Failed: [%O]", arguments);}
	);
	// ws.getAnnotations(q, "sys*:dc=dc1,host=WebServer1|WebServer5", 0).then(
	// 	function(result) { console.info("globalAnnotations Result: [%O]", result); },
	// 	function() { console.error("globalAnnotations Failed: [%O]", arguments);}
	// );

	// ws.getMetricNamesByKeys(q, ['host', 'type', 'cpu']).then(
	// 	function(result) { console.info("MetricNamesByKeys Result: [%O]", result);
	// 		//console.debug("JSON: [%s]", JSON.stringify(result));
	// 	},
	// 	function() { console.error("MetricNamesByKeys Failed: [%O]", arguments);}
	// );
	// ws.getMetricNamesByTags(q, {host:'WebServer1'}).then(
	// 	function(result) { console.info("MetricNamesByTags Result: [%O]", result);
	// 		//console.debug("JSON: [%s]", JSON.stringify(result));
	// 	},
	// 	function() { console.error("MetricNamesByTags Failed: [%O]", arguments);}
	// )
	// ws.getTSMetas(QueryContext.newContext({continuous:true, pageSize: 50, timeout: 60000}), 'sys.cpu', {host:'WebServer*', type:'combined', cpu:'*'}).then(
	// ws.getTSMetas(QueryContext.newContext({continuous:true, pageSize: 500, timeout: 60000, maxSize: 40000}), '*', {dc:'*'}).then(
	// 	function(result) { console.info("TSMetas FINAL Result: [%O]  --  cummulative: %s", result, result.q.cummulative);},
	// 	function() { console.error("TSMetas Failed: [%O]", arguments);},
	// 	function(result) { console.info("TSMetas INTERRIM Result: [%O]", result);}
	// );
	// ws.getTagKeys(q, 'sys.cpu', ['dc', 'host', 'cpu']).then(
	// 	function(result) { console.info("TagKeys Result: [%O]", result);
	// 		//console.debug("JSON: [%s]", JSON.stringify(result));
	// 	},
	// 	function() { console.error("TagKeys Failed: [%O]", arguments);}
	// );
	// ws.getTagValues(q, 'sys.cpu', 'type', {host:'*Server*', cpu:'*'}).then(
	// 	function(result) { console.info("TagValues Result: [%O]", result);
	// 		//console.debug("JSON: [%s]", JSON.stringify(result));
	// 	},
	// 	function() { console.error("TagValues Failed: [%O]", arguments);}
	// );
	// ws.resolveTSMetas(q, "sys*:dc=dc1,host=WebServer1|WebServer5").then(
	// 	function(result) { console.info("resolveTSMetas Result: [%O]", result);
	// 		//console.debug("JSON: [%s]", JSON.stringify(result));
	// 	},
	// 	function() { console.error("resolveTSMetas Failed: [%O]", arguments);}
	// );

};

var EXPR = "*:dc=*";

function testTree(expr) {
	var ws = new WebSocketAPIClient();
	var q = QueryContext.newContext({pageSize: 20000, maxSize: 20000, timeout: 10000});
	console.info("QC: %s", q.toString());
	if(EXPR == null) EXPR = "*:dc=*";

	// ws.d3TSMetas(q, "sys.cpu:dc=dc1,host=WebServer1|WebServer5").then(
	ws.d3TSMetas(q, expr || EXPR).then(
		function(d3Data) {
			console.info("D3 Data: [%O]", d3Data.data);
			dgo(d3Data.data);
			console.info("QC: %O", q);
		}
	);
}

function dgo(root) {

  var nodes = cluster.nodes(root),
      links = cluster.links(nodes);

  var link = svg.selectAll(".link")
      .data(links)
    .enter().append("path")
      .attr("class", "link")
      .attr("d", diagonal);

  var node = svg.selectAll(".node")
      .data(nodes)
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) {
      	//console.info("Transform: [%O]", d);
      	return "translate(" + d.y + "," + d.x + ")";
      })

  node.append("circle")
      .attr("r", 4.5);

  node.append("text")
      .attr("dx", function(d) { return d.children ? -8 : 8; })
      .attr("dy", 3)
      .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .text(function(d) { return d.name; });

}

/*

var ws = new WebSocketAPIClient();
var q = QueryContext.newContext();
ws.getMetricNames(q, ['host', 'type', 'cpu']);

var ws = new WebSocketAPIClient();
var q = QueryContext.newContext();
ws.serviceRequest("meta", "metricnames", {q: q, keys : ['host', 'type', 'cpu']})

function dgo(root) {

  var nodes = cluster.nodes(root),
      links = cluster.links(nodes);

  var link = svg.selectAll(".link")
      .data(links)
    .enter().append("path")
      .attr("class", "link")
      .attr("d", diagonal);

  var node = svg.selectAll(".node")
      .data(nodes)
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("circle")
      .attr("r", 4.5);

  node.append("text")
      .attr("dx", function(d) { return d.children ? -8 : 8; })
      .attr("dy", 3)
      .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .text(function(d) { return d.name; });

}

var ws = new WebSocketAPIClient();
var q = QueryContext.newContext();
ws.getTSMetas(q, 'sys.cpu', {host:'WebServer*', type:'combined', cpu:'*'}).then(
	function(result) { console.info("TSMetas Result: [%O]", result);

		var d3Data = {
			root: {
				children : [],
				name : "org"
			}
		}
		var root = d3Data.root;

		try {
			dgo(root);
		}  catch (e) {
			console.error(e);
		}
	},
	function() { console.error("TSMetas Failed: [%O]", arguments);}
);

 */

function flare() {
	var ws = new WebSocketAPIClient();
	var q = QueryContext.newContext();
	ws.getTSMetas(q, 'sys.cpu', {host:'WebServer*', type:'combined', cpu:'*'}).then(
		function(result) { console.info("TSMetas Result: [%O]", result);

			var d3Data = {
				root: {
					children : [],
					name : "org"
				}
			}
			var root = d3Data.root;

			try {
				dgo(root);
			}  catch (e) {
				console.error(e);
			}
		},
		function() { console.error("TSMetas Failed: [%O]", arguments);}
	);

}

//========================================================================
// jQuery init
//========================================================================

(function( $ ){
	$(function(){
		// jQuery Init Stuff Here.
		console.info("Initialized jQuery");
	});
})( jQuery );

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '' + match + '';
    });
}

/*

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));

=================== CSS  =====================

pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

 */


text:
package org.apache.ignite.yardstick.cache.model;

import org.apache.ignite.cache.query.annotations.QuerySqlField;

/**
 * Entity class for benchmark.
 */
public class Accounts {
    /** */
    @QuerySqlField
    private long val;

    /** */
    public Accounts() {
        // No-op.
    }

    /**
     * @param val Id.
     */
    public Accounts(long val) {
        this.val = val;
    }

    /**
     * @param val Val.
     */
    public Accounts setVal(long val) {
        this.val = val;

        return this;
    }

    /**
     * @return Val.
     */
    public long getVal() {
        return val;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return "Accounts [val=" + val + ']';
    }
}


text:
package ru.fizteh.fivt.students.kamilTalipov.database.commands;

import ru.fizteh.fivt.students.kamilTalipov.database.core.Database;
import ru.fizteh.fivt.students.kamilTalipov.database.core.NoTableSelectedException;
import ru.fizteh.fivt.students.kamilTalipov.shell.Shell;
import ru.fizteh.fivt.students.kamilTalipov.shell.SimpleCommand;

public class SizeCommand extends SimpleCommand {
    private final Database database;

    public SizeCommand(Database database) {
        super("size", 0);
        this.database = database;
    }

    @Override
    public void run(Shell shell, String[] args) throws IllegalArgumentException {
        if (numberOfArguments != args.length) {
            throw new IllegalArgumentException(name + ": expected " + numberOfArguments
                    + " but " + args.length + " got");
        }

        try {
            System.out.println(database.size());
        } catch (NoTableSelectedException e) {
            System.err.println("no table");
        }
    }
}


text:
package com.vladmihalcea.book.hpjp.hibernate.query;

import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;

import jakarta.persistence.*;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * @author Vlad Mihalcea
 */
public class ExtraSQLInjectionTest extends AbstractPostgreSQLIntegrationTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            Post.class,
            PostComment.class,
        };
    }

    @Override
    public void afterInit() {
        doInJPA(entityManager -> {

            Post post = new Post();
            post.setId(1L);
            post.setTitle("High-Performance Java Persistence");

            PostComment comment1 = new PostComment();
            comment1.setId(1L);
            comment1.setReview("Good");

            PostComment comment2 = new PostComment();
            comment2.setId(2L);
            comment2.setReview("Excellent");

            post.addComment(comment1);
            post.addComment(comment2);
            entityManager.persist(post);
        });
    }

    @Test
    @Ignore
    public void testStatementUpdateDropTable() {
        doInJPA(entityManager -> {
            PostComment comment = entityManager.find(PostComment.class, 1L);
            assertEquals("Good", comment.getReview());
        });

        updatePostCommentReviewUsingStatement(1L, "Awesome");

        doInJPA(entityManager -> {
            PostComment comment = entityManager.find(PostComment.class, 1L);
            assertEquals("Awesome", comment.getReview());
        });

        try {
            updatePostCommentReviewUsingStatement(1L, "'; DROP TABLE post_comment; -- '");
        } catch (Exception e) {
            LOGGER.error("Failure", e);
        }

        doInJPA(entityManager -> {
            PostComment comment = entityManager.find(PostComment.class, 1L);
            assertNotNull(comment);
        });
    }

    @Test
    @Ignore
    public void testPreparedStatementUpdateDropTable() {
        doInJPA(entityManager -> {
            PostComment comment = entityManager.find(PostComment.class, 1L);
            assertEquals("Good", comment.getReview());
        });

        updatePostCommentReviewUsingPreparedStatement(1L, "Awesome");

        doInJPA(entityManager -> {
            PostComment comment = entityManager.find(PostComment.class, 1L);
            assertEquals("Awesome", comment.getReview());
        });

        try {
            updatePostCommentReviewUsingPreparedStatement(1L, "'; DROP TABLE post_comment; -- '");
        } catch (Exception e) {
            LOGGER.error("Failure", e);
        }

        doInJPA(entityManager -> {
            PostComment comment = entityManager.find(PostComment.class, 1L);
            assertNotNull(comment);
        });
    }

    @Test
    public void testPreparedStatementSelectAndWait() {
        assertEquals("Good", getPostCommentReviewUsingPreparedStatement("1"));
        try {
            getPostCommentReviewUsingPreparedStatement("1 AND 1 >= ALL ( SELECT 1 FROM pg_locks, pg_sleep(2) )");
        } catch (Exception expected) {
            LOGGER.error("Failure", expected);
        }
        assertEquals("Good", getPostCommentReviewUsingPreparedStatement("1"));
    }

    @Test
    public void testStatementSelectDropTable() {
        assertEquals("Good", getPostCommentReviewUsingStatement("1"));
        try {
            getPostCommentReviewUsingStatement("1; DROP TABLE post_comment");
        } catch (Exception expected) {
            LOGGER.error("Failure", expected);
        }
        assertEquals("Good", getPostCommentReviewUsingStatement("1"));
    }

    @Test
    public void testPreparedStatementSelectDropTable() {
        assertEquals("Good", getPostCommentReviewUsingPreparedStatement("1"));
        try {
            getPostCommentReviewUsingPreparedStatement("1; DROP TABLE post_comment");
        } catch (Exception expected) {
            LOGGER.error("Failure", expected);
        }
        assertEquals("Good", getPostCommentReviewUsingPreparedStatement("1"));
    }

    @Test
    @Ignore
    public void testGetPostCommentByReview() {
        getPostCommentByReview("1 AND 1 >= ALL ( SELECT 1 FROM pg_locks, pg_sleep(2) )");
    }

    private void updatePostCommentReviewUsingStatement(Long id, String review) {
        doInJPA(entityManager -> {
            Session session = entityManager.unwrap(Session.class);
            session.doWork(connection -> {
                try(Statement statement = connection.createStatement()) {
                    statement.executeUpdate(
                        "UPDATE post_comment " +
                        "SET review = '" + review + "' " +
                        "WHERE id = " + id);
                }
            });
        });
    }

    private void updatePostCommentReviewUsingPreparedStatement(Long id, String review) {
        doInJPA(entityManager -> {
            Session session = entityManager.unwrap(Session.class);
            session.doWork(connection -> {
                try(PreparedStatement statement = connection.prepareStatement(
                    "UPDATE post_comment " +
                    "SET review = '" + review + "' " +
                    "WHERE id = " + id
                )) {
                    statement.executeUpdate();
                }
            });
        });
    }

    private String getPostCommentReviewUsingStatement(String id) {
        return doInJPA(entityManager -> {
            Session session = entityManager.unwrap(Session.class);
            return session.doReturningWork(connection -> {
                String sql =
                    "SELECT review " +
                    "FROM post_comment " +
                    "WHERE id = " + id;
                try(Statement statement = connection.createStatement()) {
                    try(ResultSet resultSet = statement.executeQuery(sql)) {
                        return resultSet.next() ? resultSet.getString(1) : null;
                    }
                }
            });
        });
    }

    private String getPostCommentReviewUsingPreparedStatement(String id) {
        return doInJPA(entityManager -> {
            Session session = entityManager.unwrap(Session.class);
            return session.doReturningWork(connection -> {
                String sql =
                    "SELECT review " +
                    "FROM post_comment " +
                    "WHERE id = " + id;
                try(PreparedStatement statement = connection.prepareStatement(sql)) {
                    try(ResultSet resultSet = statement.executeQuery()) {
                        return resultSet.next() ? resultSet.getString(1) : null;
                    }
                }
            });
        });
    }

    private PostComment getPostCommentByReview(String review) {
        return doInJPA(entityManager -> {
            return entityManager.createQuery(
                "select p " +
                "from PostComment p " +
                "where p.review = :review", PostComment.class)
            .setParameter("review", review)
            .getSingleResult();
        });
    }

    @Test
    @Ignore
    public void testSelectAllEntities() {
        doInJPA(entityManager -> {
            List<Post> posts = findAll("com.vladmihalcea.book.hpjp.hibernate.forum.Post");
            posts = findAll("java.lang.Object");
            posts.size();
        });
    }

    @Test
    public void testGetPostByTitleSuccess() {
        doInJPA(entityManager -> {
            List<Post> posts = getPostsByTitle("High-Performance Java Persistence");
        });
    }

    @Test
    public void testPostGetByTitleAndWait() {
        doInJPA(entityManager -> {
            List<Post> posts = getPostsByTitle(
                "High-Performance Java Persistence' and " +
                "FUNCTION('1 >= ALL ( SELECT 1 FROM pg_locks, pg_sleep(2) ) --',) is '"
            );
            assertEquals(1, posts.size());
        });
    }

    @Test
    public void testTuples() {
        doInJPA(entityManager -> {
            List<Tuple> tuples = getTuples();
            assertEquals(1, tuples.size());
        });
    }

    private List<Post> getPostsByTitle(String title) {
        return doInJPA(entityManager -> {
            return entityManager.createQuery(
                "select p " +
                "from Post p " +
                "where" +
                "   p.title = '" + title + "'", Post.class)
            .getResultList();
        });
    }

    private List<Tuple> getTuples() {
        return doInJPA(entityManager -> {
            Class<Post> entityClass = Post.class;
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Tuple> query = cb.createTupleQuery();
            Root<?> root = query.from(entityClass);
            query.select(
                cb.tuple(
                    root.get("id"),
                    cb.function("now", Date.class)
                )
            );

            return entityManager.createQuery(query).getResultList();
        });
    }

    private  <T> List<T> findAll(String entityName) {
        return (List<T>) doInJPA(entityManager -> {
            try {
                return entityManager.unwrap(Session.class).createQuery(
                    "select e " +
                    "from " + Class.forName(entityName).getName() + " e ")
                .getResultList();
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException(e);
            }
        });
    }

    @Entity(name = "Post")
    @Table(name = "post")
    public static class Post {

        @Id
        private Long id;

        private String title;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
        private List<PostComment> comments = new ArrayList<>();

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public List<PostComment> getComments() {
            return comments;
        }

        public void addComment(PostComment comment) {
            comments.add(comment);
            comment.setPost(this);
        }
    }

    @Entity(name = "PostComment")
    @Table(name = "post_comment")
    public static class PostComment {

        @Id
        private Long id;

        @ManyToOne(fetch = FetchType.LAZY)
        private Post post;

        private String review;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public Post getPost() {
            return post;
        }

        public void setPost(Post post) {
            this.post = post;
        }

        public String getReview() {
            return review;
        }

        public void setReview(String review) {
            this.review = review;
        }
    }
}


text:
'use strict';

var esprima = require('esprima');
var vscode = require('vscode');

var JAVASCRIPT_LANGUAGE_ID = 'javascript';

var lastValidSyntaxTree = null;
function resolveAst(text) {
    var result;
    try {
        result = esprima.parse(text);
        lastValidSyntaxTree = result;
    } catch (e) {
        result = lastValidSyntaxTree;
    }
    return result;
}

function loadSyntaxTree(document) {
    lastValidSyntaxTree = null;
    if (document.languageId === JAVASCRIPT_LANGUAGE_ID) {
        resolveAst(document.getText());
    }
}

function getThisVarNames() {
    return vscode.workspace.getConfiguration('jsthis.thisVarNames');
}

module.exports = {
    JAVASCRIPT_LANGUAGE_ID: JAVASCRIPT_LANGUAGE_ID,
    resolveAst: resolveAst,
    loadSyntaxTree: loadSyntaxTree,
    getThisVarNames: getThisVarNames
};


text:
    ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare)))
#  define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange)))

# endif

#elif defined(_WIN32_WCE)

#if _WIN32_WCE >= 0x600

extern "C" long __cdecl _InterlockedIncrement( long volatile * );
extern "C" long __cdecl _InterlockedDecrement( long volatile * );
extern "C" long __cdecl _InterlockedCompareExchange( long volatile *, long, long );
extern "C" long __cdecl _InterlockedExchange( long volatile *, long );
extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long );

# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement
# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement
# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange
# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange
# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd

#else // _WIN32_WCE >= 0x600

// under Windows CE we still have old-style Interlocked* functions

extern "C" long __cdecl InterlockedIncrement( long * );
extern "C" long __cdecl InterlockedDecrement( long * );
extern "C" long __cdecl InterlockedCompareExchange( long *, long, long );
extern "C" long __cdecl InterlockedExchange( long *, long );
extern "C" long __cdecl InterlockedExchangeAdd( long *, long );

# define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement
# define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement
# define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange
# define BOOST_INTERLOCKED_EXCHANGE InterlockedExchange
# define BOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd

#endif // _WIN32_WCE >= 0x600

# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \
    ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long*)(dest),(long)(exchange),(long)(compare)))
# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)BOOST_INTERLOCKED_EXCHANGE((long*)(dest),(long)(exchange)))

#elif defined( BOOST_MSVC ) || defined( BOOST_INTEL_WIN )

# if defined( __CLRCALL_PURE_OR_CDECL )
#  define BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL __CLRCALL_PURE_OR_CDECL
# else
#  define BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL __cdecl
# endif

extern "C" long BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL _InterlockedIncrement( long volatile * );
extern "C" long BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL _InterlockedDecrement( long volatile * );
extern "C" long BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL _InterlockedCompareExchange( long volatile *, long, long );
extern "C" long BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL _InterlockedExchange( long volatile *, long );
extern "C" long BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL _InterlockedExchangeAdd( long volatile *, long );

# undef BOOST_INTERLOCKED_CLRCALL_PURE_OR_CDECL

# if defined( BOOST_MSVC ) && BOOST_MSVC >= 1310
#  pragma intrinsic( _InterlockedIncrement )
#  pragma intrinsic( _InterlockedDecrement )
#  pragma intrinsic( _InterlockedCompareExchange )
#  pragma intrinsic( _InterlockedExchange )
#  pragma intrinsic( _InterlockedExchangeAdd )
# endif

# if defined(_M_IA64) || defined(_M_AMD64)

extern "C" void* __cdecl _InterlockedCompareExchangePointer( void* volatile *, void*, void* );
extern "C" void* __cdecl _InterlockedExchangePointer( void* volatile *, void* );

#  define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer
#  define BOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer

# else

#  define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \
    ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare)))
#  define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange)))

# endif

# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement
# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement
# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange
# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange
# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd

#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined( __CYGWIN__ )

#define BOOST_INTERLOCKED_IMPORT __declspec(dllimport)

namespace lslboost
{

namespace detail
{

extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedIncrement( long volatile * );
extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedDecrement( long volatile * );
extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedCompareExchange( long volatile *, long, long );
extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedExchange( long volatile *, long );
extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedExchangeAdd( long volatile *, long );

# if defined(_M_IA64) || defined(_M_AMD64)
extern "C" BOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedCompareExchangePointer( void* volatile *, void*, void* );
extern "C" BOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedExchangePointer( void* volatile *, void* );
# endif

} // namespace detail

} // namespace lslboost

# define BOOST_INTERLOCKED_INCREMENT ::lslboost::detail::InterlockedIncrement
# define BOOST_INTERLOCKED_DECREMENT ::lslboost::detail::InterlockedDecrement
# define BOOST_INTERLOCKED_COMPARE_EXCHANGE ::lslboost::detail::InterlockedCompareExchange
# define BOOST_INTERLOCKED_EXCHANGE ::lslboost::detail::InterlockedExchange
# define BOOST_INTERLOCKED_EXCHANGE_ADD ::lslboost::detail::InterlockedExchangeAdd

# if defined(_M_IA64) || defined(_M_AMD64)
#  define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER ::lslboost::detail::InterlockedCompareExchangePointer
#  define BOOST_INTERLOCKED_EXCHANGE_POINTER ::lslboost::detail::InterlockedExchangePointer
# else
#  define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \
    ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare)))
#  define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \
    ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange)))
# endif

#else

# error "Interlocked intrinsics not available"

#endif

#endif // #ifndef BOOST_DETAIL_INTERLOCKED_HPP_INCLUDED


text:
package interfaceGraphique;

import individu.Personne;

/**
 * Interface à intégrer à une classe héritée de {@link Personne} pour avoir une icone sur l'{@link IHM}
 */
public interface IAfficheImage {

	/**
	 * @return Le nom complet du fichier représentant la class
	 */
	public String getPictureFileName();

}


text:
from bearlibterminal import terminal as term
# sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../')
from spaceship.main import Main
from spaceship.options import Options
from spaceship.game import Start
from spaceship.load import Continue
from spaceship.make import Create
from spaceship.name import Name
from spaceship.strings import FONT_PATH

class Engine:
    def __init__(self):
        # initialize the terminal first or else windows cannot initialize size
        self.setup()

        self.scenes = {
            'main_menu': Main(),
            'options_menu': Options(),
            'start_game': Start(),
            'continue_menu': Continue(),
            'create_menu': Create(),
            'name_menu': Name(),
        }

        self.scene = self.scenes['main_menu']

    def setup(self):
        '''sets up instance of terminal'''
        term.open()
        # self.setup_font('VeraMono')
        # self.setup_font("Source", cx=8, cy=8)
        term.set('window: size=80x25, cellsize=auto, title="Spaceship", fullscreen=false')

    def setup_font(self, font, cx=8, cy=None):
        '''Determines font and cell size'''
        if font == "default":
            term.set('font: default, size=auto')

        else:
            term.set("window: cellsize=8x8")
            cy = 'x' + str(cy) if cy else ''
            term.set(f"font: {FONT_PATH}{font}.ttf, size={cx}{cy}")

    def run(self):
        '''Goes through the scenes until exit'''
        self.proceed = True

        while self.proceed:
            ret = self.scene.run()

            if not ret['scene']:
                self.proceed = False

            else:
                try:
                    self.scene = self.scenes[ret['scene']]
                    if ret['kwargs']:
                        self.scene.add_args(**ret['kwargs'])

                except KeyError:
                    self.proceed = False

                else:
                    self.scene.reset()

        term.close()

if __name__ == "__main__":
    e = Engine()
    e.run()


text:
layout: page
title: Pink Holdings Seminar
date: 2016-05-24
author: Judy Barry
tags: weekly links, java
status: published
summary: Proin consequat eu nisi eu volutpat. Etiam.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 05/05/2017
  endDate: 05/08/2017
  ctyhocn: ALBSYHX
  groupCode: PHS
published: true
---
Maecenas vulputate tempor augue. Quisque ex massa, tristique sit amet rhoncus vel, vehicula sed dui. Morbi eu quam mollis, porttitor quam et, commodo lacus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tristique est vel felis fermentum, sed lacinia magna efficitur. In mollis lectus nisi, vitae congue diam iaculis vestibulum. Praesent vulputate faucibus turpis in convallis.

1 Mauris id nulla pretium, cursus urna sed, facilisis risus
1 Curabitur semper est porta, aliquam ex at, lacinia lacus
1 Phasellus eu lacus efficitur, convallis augue vitae, viverra eros
1 Sed ac quam a risus dictum mattis et vulputate ipsum.

Phasellus nec luctus ante. Sed gravida iaculis ligula vel ultrices. Phasellus id vehicula augue. Sed viverra risus eu mi dapibus molestie. Aenean ac fringilla felis, quis vulputate nulla. Aliquam congue massa vel quam aliquet, vitae aliquam felis consectetur. Donec quis dui imperdiet, mollis nisl ac, mattis risus. Phasellus pellentesque ligula et ipsum mattis pretium. Suspendisse fermentum sem ut suscipit suscipit. Suspendisse posuere nisl eu lacus facilisis varius.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptosphaeria draconis Urries

### Remarks
null