text:
namespace base {
namespace {

void TestTask(int* result) {
  *result = 123;
}

}  // namespace

TEST(TaskAnnotatorTest, QueueAndRunTask) {
  int result = 0;
  PendingTask pending_task(FROM_HERE, BindOnce(&TestTask, &result));

  TaskAnnotator annotator;
  annotator.WillQueueTask("TaskAnnotatorTest::Queue", &pending_task, "?");
  EXPECT_EQ(0, result);
  annotator.RunTask("TaskAnnotatorTest::Queue", &pending_task);
  EXPECT_EQ(123, result);
}

// Test task annotator integration in base APIs and ensuing support for
// backtraces. Tasks posted across multiple threads in this test fixture should
// be synchronized as BeforeRunTask() and VerifyTraceAndPost() assume tasks are
// observed in lock steps, one at a time.
class TaskAnnotatorBacktraceIntegrationTest
    : public ::testing::Test,
      public TaskAnnotator::ObserverForTesting {
 public:
  using ExpectedTrace = std::vector<const void*>;

  TaskAnnotatorBacktraceIntegrationTest() = default;

  ~TaskAnnotatorBacktraceIntegrationTest() override = default;

  // TaskAnnotator::ObserverForTesting:
  void BeforeRunTask(const PendingTask* pending_task) override {
    AutoLock auto_lock(on_before_run_task_lock_);
    last_posted_from_ = pending_task->posted_from;
    last_task_backtrace_ = pending_task->task_backtrace;
    last_ipc_hash_ = pending_task->ipc_hash;
  }

  void SetUp() override { TaskAnnotator::RegisterObserverForTesting(this); }

  void TearDown() override { TaskAnnotator::ClearObserverForTesting(); }

  void VerifyTraceAndPost(const scoped_refptr<SequencedTaskRunner>& task_runner,
                          const Location& posted_from,
                          const Location& next_from_here,
                          const ExpectedTrace& expected_trace,
                          uint32_t expected_ipc_hash,
                          OnceClosure task) {
    SCOPED_TRACE(StringPrintf("Callback Depth: %zu", expected_trace.size()));

    EXPECT_EQ(posted_from, last_posted_from_);
    for (size_t i = 0; i < last_task_backtrace_.size(); i++) {
      SCOPED_TRACE(StringPrintf("Trace frame: %zu", i));
      if (i < expected_trace.size())
        EXPECT_EQ(expected_trace[i], last_task_backtrace_[i]);
      else
        EXPECT_EQ(nullptr, last_task_backtrace_[i]);
    }
    EXPECT_EQ(expected_ipc_hash, last_ipc_hash_);

    task_runner->PostTask(next_from_here, std::move(task));
  }

  void VerifyTraceAndPostWithIpcContext(
      const scoped_refptr<SequencedTaskRunner>& task_runner,
      const Location& posted_from,
      const Location& next_from_here,
      const ExpectedTrace& expected_trace,
      uint32_t expected_ipc_hash,
      OnceClosure task,
      uint32_t new_ipc_hash) {
    TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(new_ipc_hash);
    VerifyTraceAndPost(task_runner, posted_from, next_from_here, expected_trace,
                       expected_ipc_hash, std::move(task));
  }

  // Same as VerifyTraceAndPost() with the exception that it also posts a task
  // that will prevent |task| from running until |wait_before_next_task| is
  // signaled.
  void VerifyTraceAndPostWithBlocker(
      const scoped_refptr<SequencedTaskRunner>& task_runner,
      const Location& posted_from,
      const Location& next_from_here,
      const ExpectedTrace& expected_trace,
      uint32_t expected_ipc_hash,
      OnceClosure task,
      WaitableEvent* wait_before_next_task) {
    DCHECK(wait_before_next_task);

    // Need to lock to ensure the upcoming VerifyTraceAndPost() runs before the
    // BeforeRunTask() hook for the posted WaitableEvent::Wait(). Otherwise the
    // upcoming VerifyTraceAndPost() will race to read the state saved in the
    // BeforeRunTask() hook preceding the current task.
    AutoLock auto_lock(on_before_run_task_lock_);
    task_runner->PostTask(
        FROM_HERE,
        BindOnce(&WaitableEvent::Wait, Unretained(wait_before_next_task)));
    VerifyTraceAndPost(task_runner, posted_from, next_from_here, expected_trace,
                       expected_ipc_hash, std::move(task));
  }

 protected:
  static void RunTwo(OnceClosure c1, OnceClosure c2) {
    std::move(c1).Run();
    std::move(c2).Run();
  }

 private:
  // While calls to VerifyTraceAndPost() are strictly ordered in tests below
  // (and hence non-racy), some helper methods (e.g. Wait/Signal) do racily call
  // into BeforeRunTask(). This Lock ensures these unobserved writes are not
  // racing. Locking isn't required on read per the VerifyTraceAndPost()
  // themselves being ordered.
  Lock on_before_run_task_lock_;

  Location last_posted_from_ = {};
  std::array<const void*, PendingTask::kTaskBacktraceLength>
      last_task_backtrace_ = {};

  uint32_t last_ipc_hash_ = 0;

  DISALLOW_COPY_AND_ASSIGN(TaskAnnotatorBacktraceIntegrationTest);
};

// Ensure the task backtrace populates correctly.
TEST_F(TaskAnnotatorBacktraceIntegrationTest, SingleThreadedSimple) {
  test::TaskEnvironment task_environment;
  const uint32_t dummy_ipc_hash = 0xDEADBEEF;
  const Location location0 = FROM_HERE;
  const Location location1 = FROM_HERE;
  const Location location2 = FROM_HERE;
  const Location location3 = FROM_HERE;
  const Location location4 = FROM_HERE;
  const Location location5 = FROM_HERE;

  RunLoop run_loop;

  // Task 0 executes with no IPC context. Task 1 executes under an explicitly
  // set IPC context, and tasks 2-5 inherit that context.

  // Task 5 has tasks 4/3/2/1 as parents (task 0 isn't visible as only the
  // last 4 parents are kept).
  OnceClosure task5 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location5, FROM_HERE,
      ExpectedTrace({location4.program_counter(), location3.program_counter(),
                     location2.program_counter(), location1.program_counter()}),
      dummy_ipc_hash, run_loop.QuitClosure());

  // Task i=4/3/2/1/0 have tasks [0,i) as parents.
  OnceClosure task4 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location4, location5,
      ExpectedTrace({location3.program_counter(), location2.program_counter(),
                     location1.program_counter(), location0.program_counter()}),
      dummy_ipc_hash, std::move(task5));
  OnceClosure task3 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location3, location4,
      ExpectedTrace({location2.program_counter(), location1.program_counter(),
                     location0.program_counter()}),
      dummy_ipc_hash, std::move(task4));
  OnceClosure task2 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location2, location3,
      ExpectedTrace({location1.program_counter(), location0.program_counter()}),
      dummy_ipc_hash, std::move(task3));
  OnceClosure task1 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPostWithIpcContext,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location1, location2,
      ExpectedTrace({location0.program_counter()}), 0, std::move(task2),
      dummy_ipc_hash);
  OnceClosure task0 =
      BindOnce(&TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
               Unretained(this), ThreadTaskRunnerHandle::Get(), location0,
               location1, ExpectedTrace({}), 0, std::move(task1));

  ThreadTaskRunnerHandle::Get()->PostTask(location0, std::move(task0));

  run_loop.Run();
}

// Ensure it works when posting tasks across multiple threads managed by //base.
TEST_F(TaskAnnotatorBacktraceIntegrationTest, MultipleThreads) {
  test::TaskEnvironment task_environment;

  // Use diverse task runners (a task environment main thread, a ThreadPool
  // based SequencedTaskRunner, and a ThreadPool based
  // SingleThreadTaskRunner) to verify that TaskAnnotator can capture backtraces
  // for PostTasks back-and-forth between these.
  auto main_thread_a = ThreadTaskRunnerHandle::Get();
  auto task_runner_b = ThreadPool::CreateSingleThreadTaskRunner({});
  auto task_runner_c = ThreadPool::CreateSequencedTaskRunner(
      {base::MayBlock(), base::WithBaseSyncPrimitives()});

  const Location& location_a0 = FROM_HERE;
  const Location& location_a1 = FROM_HERE;
  const Location& location_a2 = FROM_HERE;
  const Location& location_a3 = FROM_HERE;

  const Location& location_b0 = FROM_HERE;
  const Location& location_b1 = FROM_HERE;

  const Location& location_c0 = FROM_HERE;

  RunLoop run_loop;

  // All tasks below happen in lock step by nature of being posted by the
  // previous one (plus the synchronous nature of RunTwo()) with the exception
  // of the follow-up local task to |task_b0_local|. This WaitableEvent ensures
  // it completes before |task_c0| runs to avoid racy invocations of
  // BeforeRunTask()+VerifyTraceAndPost().
  WaitableEvent lock_step(WaitableEvent::ResetPolicy::AUTOMATIC,
                          WaitableEvent::InitialState::NOT_SIGNALED);

  // Here is the execution order generated below:
  //  A: TA0 -> TA1 \                                    TA2
  //  B:            TB0L \ + TB0F \  Signal \           /
  //                      ---------\--/      \         /
  //                                \         \       /
  //  C:                            Wait........ TC0 /

  // IPC contexts:
  // TA0 and TA1 execute with no IPC context.
  // TB0L is the first task to execute with an explicit IPC context.
  // TB0F inherits no context.
  // TC0 is posted with a new IPC context from TB0L.
  // TA2 inherits that IPC context.
  const uint32_t dummy_ipc_hash0 = 0xDEADBEEF;
  const uint32_t dummy_ipc_hash1 = 0xBAADF00D;

  // On task runner c, post a task back to main thread that verifies its trace
  // and terminates after one more self-post.
  OnceClosure task_a2 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), main_thread_a, location_a2, location_a3,
      ExpectedTrace(
          {location_c0.program_counter(), location_b0.program_counter(),
           location_a1.program_counter(), location_a0.program_counter()}),
      dummy_ipc_hash1, run_loop.QuitClosure());
  OnceClosure task_c0 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPostWithIpcContext,
      Unretained(this), main_thread_a, location_c0, location_a2,
      ExpectedTrace({location_b0.program_counter(),
                     location_a1.program_counter(),
                     location_a0.program_counter()}),
      0, std::move(task_a2), dummy_ipc_hash1);

  // On task runner b run two tasks that conceptually come from the same
  // location (managed via RunTwo().) One will post back to task runner b and
  // another will post to task runner c to test spawning multiple tasks on
  // different message loops. The task posted to task runner c will not get
  // location b1 whereas the one posted back to task runner b will.
  OnceClosure task_b0_fork = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPostWithBlocker,
      Unretained(this), task_runner_c, location_b0, location_c0,
      ExpectedTrace(
          {location_a1.program_counter(), location_a0.program_counter()}),
      0, std::move(task_c0), &lock_step);
  OnceClosure task_b0_local = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPostWithIpcContext,
      Unretained(this), task_runner_b, location_b0, location_b1,
      ExpectedTrace(
          {location_a1.program_counter(), location_a0.program_counter()}),
      0, BindOnce(&WaitableEvent::Signal, Unretained(&lock_step)),
      dummy_ipc_hash0);

  OnceClosure task_a1 =
      BindOnce(&TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
               Unretained(this), task_runner_b, location_a1, location_b0,
               ExpectedTrace({location_a0.program_counter()}), 0,
               BindOnce(&TaskAnnotatorBacktraceIntegrationTest::RunTwo,
                        std::move(task_b0_local), std::move(task_b0_fork)));
  OnceClosure task_a0 =
      BindOnce(&TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
               Unretained(this), main_thread_a, location_a0, location_a1,
               ExpectedTrace({}), 0, std::move(task_a1));

  main_thread_a->PostTask(location_a0, std::move(task_a0));

  run_loop.Run();
}

// Ensure nesting doesn't break the chain.
TEST_F(TaskAnnotatorBacktraceIntegrationTest, SingleThreadedNested) {
  test::TaskEnvironment task_environment;
  uint32_t dummy_ipc_hash = 0xDEADBEEF;
  uint32_t dummy_ipc_hash1 = 0xBAADF00D;
  uint32_t dummy_ipc_hash2 = 0x900DD099;
  const Location location0 = FROM_HERE;
  const Location location1 = FROM_HERE;
  const Location location2 = FROM_HERE;
  const Location location3 = FROM_HERE;
  const Location location4 = FROM_HERE;
  const Location location5 = FROM_HERE;

  RunLoop run_loop;

  // Task execution below looks like this, w.r.t. to RunLoop depths:
  // 1 : T0 \ + NRL1 \                                 ---------> T4 -> T5
  // 2 :     ---------> T1 \ -> NRL2 \ ----> T2 -> T3 / + Quit /
  // 3 :                    ---------> DN /

  // NRL1 tests that tasks that occur at a different nesting depth than their
  // parent have a sane backtrace nonetheless (both ways).

  // NRL2 tests that posting T2 right after exiting the RunLoop (from the same
  // task) results in NRL2 being its parent (and not the DoNothing() task that
  // just ran -- which would have been the case if the "current task" wasn't
  // restored properly when returning from a task within a task).

  // In other words, this is regression test for a bug in the previous
  // implementation. In the current implementation, replacing
  //   tls_for_current_pending_task->Set(previous_pending_task);
  // by
  //   tls_for_current_pending_task->Set(nullptr);
  // at the end of TaskAnnotator::RunTask() makes this test fail.

  // This test also validates the IPC contexts are propagated appropriately, and
  // then a context in an outer loop does not color tasks posted from a nested
  // loop.

  RunLoop nested_run_loop1(RunLoop::Type::kNestableTasksAllowed);

  // Expectations are the same as in SingleThreadedSimple test despite the
  // nested loop starting between tasks 0 and 1 and stopping between tasks 3 and
  // 4.
  OnceClosure task5 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location5, FROM_HERE,
      ExpectedTrace({location4.program_counter(), location3.program_counter(),
                     location2.program_counter(), location1.program_counter()}),
      dummy_ipc_hash, run_loop.QuitClosure());
  OnceClosure task4 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location4, location5,
      ExpectedTrace({location3.program_counter(), location2.program_counter(),
                     location1.program_counter(), location0.program_counter()}),
      dummy_ipc_hash, std::move(task5));
  OnceClosure task3 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location3, location4,
      ExpectedTrace({location2.program_counter(), location1.program_counter(),
                     location0.program_counter()}),
      dummy_ipc_hash, std::move(task4));

  OnceClosure run_task_3_then_quit_nested_loop1 =
      BindOnce(&TaskAnnotatorBacktraceIntegrationTest::RunTwo, std::move(task3),
               nested_run_loop1.QuitClosure());

  OnceClosure task2 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPost,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location2, location3,
      ExpectedTrace({location1.program_counter(), location0.program_counter()}),
      dummy_ipc_hash, std::move(run_task_3_then_quit_nested_loop1));

  // Task 1 is custom. It enters another nested RunLoop, has it do work and exit
  // before posting the next task. This confirms that |task1| is restored as the
  // current task before posting |task2| after returning from the nested loop.
  RunLoop nested_run_loop2(RunLoop::Type::kNestableTasksAllowed);
  OnceClosure task1 = BindOnce(
      BindLambdaForTesting([dummy_ipc_hash1](RunLoop* nested_run_loop,
                                             const Location& location2,
                                             OnceClosure task2) {
        {
          // Run the nested message loop with an explicitly set IPC context.
          // This context should not leak out of the inner loop and color the
          // tasks in the outer loop.
          TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(dummy_ipc_hash1);
          ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
          nested_run_loop->RunUntilIdle();
        }
        ThreadTaskRunnerHandle::Get()->PostTask(location2, std::move(task2));
      }),
      Unretained(&nested_run_loop2), location2, std::move(task2));

  OnceClosure task0 = BindOnce(
      &TaskAnnotatorBacktraceIntegrationTest::VerifyTraceAndPostWithIpcContext,
      Unretained(this), ThreadTaskRunnerHandle::Get(), location0, location1,
      ExpectedTrace({}), 0, std::move(task1), dummy_ipc_hash);

  ThreadTaskRunnerHandle::Get()->PostTask(location0, std::move(task0));

  {
    TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(dummy_ipc_hash2);
    ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, BindOnce(&RunLoop::Run, Unretained(&nested_run_loop1)));
  }

  run_loop.Run();
}

}  // namespace base


text:
import {
  GraphQLSchema as Schema,
  GraphQLObjectType as ObjectType,
} from 'graphql';

import me from './queries/me';
import news from './queries/news';

const schema = new Schema({
  query: new ObjectType({
    name: 'Query',
    fields: {
      me,
      news,
    },
  }),
});

export default schema;

redpajama_set_name: RedPajamaGithub


text:
This repository contains the source code for the adapter used to connect to https://github.com/perandersson/everstore-server . It also contains examples on how to use it.

## Projects

### core

This project contains the Java API for using Everstore.

### vanilla

This is the default data-storage implementation

### java8-adapter

This is the java8 specific adapter. Instanciate the core adapter using configuration backed by this project. The examples included in this repository uses the java8-adapter project.

## Examples

### example-console

This is a simple console application where we try to save the same type of event to the same journal at the same time.
This shows us what happens when a conflict happens. The example itself do not try to resolve the conflict.

### example-grizzly-rest

Example where we start a simple a simple REST HTTP server using Grizzly and Jersey2. This example makes full use of the
custom `Optional<T>` type that exists in this project. The reason for it is that all requests are handled asynchronously
and the interface `CompletableFuture<T>` is simply not good enough.


text:
require_relative '../ext/nmsg/nmsg'

socket = Nmsg::Socket.new Nmsg::AF_SP, Nmsg::NN_REQ
puts "fd: #{socket.get_fd}  sysfd: #{socket.get_sysfd}"

addr = ARGV.shift || "tcp://127.0.0.1:4000"
endpoint_id = socket.connect addr
puts "address: #{addr}  endpoint id: #{endpoint_id}"

trap("SIGINT") do
  puts "Exiting..."
  socket.shutdown endpoint_id
  socket.close
  exit!
end

sent = false
msg = ''
loop do
  puts "loop (sent: #{sent})"
  unless sent
    ev = socket.poll Nmsg::NN_POLLOUT, 1000
    next if ev.nil?
    if ev
      msg = (0...8).map { ('a'..'z').to_a[rand(26)] }.join
      sent = socket.send_msg_block msg
    end
    if sent
      puts "message sent: #{msg}"
    else
      sleep 1
    end
  else
    ev = socket.poll Nmsg::NN_POLLIN, 1000
    next if ev.nil?
    if ev
      data = socket.recv_msg
      puts "message received: #{data}" if data
      raise "Error: Wrong message! (expected '#{msg.reverse}' and got '#{data}')" unless data && data.reverse.eql?(msg)
      sent = false
    end
  end
end


text:
layout: firsthome
---

Cognition and Computational Brain Lab

Swansea | Cardiff | United Kingdom

Welcome to the Cognition and Computational Brain Lab. We are based in the Swansea University Computational Foundry and Cardiff University Brain Research Imaging Centre.

Our lab focuses on human and machine intelligence. We combines computational modelling, machine learning, brain imaging, and experimental approaches to understand human cognition, ageing, and cognitive deficits in neurological and psychiatric disorders. On machine intelligence, we are interested in developing artificial agents to mimic the human capacity of complex cognitive operation and social interaction.

More about our Research


text:
layout: post
title: "Playground"
categories:
  - Links
tags:
  - research
  - hacks
  - study
  - playground
  - links
---

* [DigitalOcean (Referral)](https://m.do.co/c/71a107e34a58)
* [JuliaBox](http://juliabox.org)
* [WolframAlpha](http://www.wolframalpha.com)
* [Udacity](https://www.udacity.com)
* [SPOJ](http://www.spoj.pl)
* [Codeforces](http://codeforces.com)
* [ACM-ICPC Live Archive](http://livearchive.onlinejudge.org)
* [Virtual Online Contests](http://ahmed-aly.com)
* [MS ML Azure](https://studio.azureml.net)
* [DataKind](http://www.datakind.org)
* [Kaggle](https://www.kaggle.com)
* [IBM Swift](https://swiftlang.ng.bluemix.net)


text:
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
from urllib.parse import parse_qs, urljoin, urlparse

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from .. import models as _models
from .._serialization import Serializer
from .._vendor import _convert_request, _format_url_section

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False

def build_list_request(
    resource_group_name: str,
    workspace_name: str,
    subscription_id: str,
    *,
    kind: Optional[Union[str, "_models.Enum13"]] = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str", max_length=90, min_length=1),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    if kind is not None:
        _params["kind"] = _SERIALIZER.query("kind", kind, "str")
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_get_request(
    resource_group_name: str, workspace_name: str, entity_query_id: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str", max_length=90, min_length=1),
        "entityQueryId": _SERIALIZER.url("entity_query_id", entity_query_id, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)

def build_create_or_update_request(
    resource_group_name: str, workspace_name: str, entity_query_id: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str", max_length=90, min_length=1),
        "entityQueryId": _SERIALIZER.url("entity_query_id", entity_query_id, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)

def build_delete_request(
    resource_group_name: str, workspace_name: str, entity_query_id: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str", max_length=90, min_length=1),
        "entityQueryId": _SERIALIZER.url("entity_query_id", entity_query_id, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)

class EntityQueriesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.securityinsight.SecurityInsights`'s
        :attr:`entity_queries` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs):
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        resource_group_name: str,
        workspace_name: str,
        kind: Optional[Union[str, "_models.Enum13"]] = None,
        **kwargs: Any
    ) -> Iterable["_models.EntityQuery"]:
        """Gets all entity queries.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :param kind: The entity query kind we want to fetch. Known values are: "Expansion" and
         "Activity". Default value is None.
        :type kind: str or ~azure.mgmt.securityinsight.models.Enum13
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either EntityQuery or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securityinsight.models.EntityQuery]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.EntityQueryList]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_request(
                    resource_group_name=resource_group_name,
                    workspace_name=workspace_name,
                    subscription_id=self._config.subscription_id,
                    kind=kind,
                    api_version=api_version,
                    template_url=self.list.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urlparse(next_link)
                _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query))
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params)
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize("EntityQueryList", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries"}  # type: ignore

    @distributed_trace
    def get(
        self, resource_group_name: str, workspace_name: str, entity_query_id: str, **kwargs: Any
    ) -> _models.EntityQuery:
        """Gets an entity query.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :param entity_query_id: entity query ID. Required.
        :type entity_query_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: EntityQuery or the result of cls(response)
        :rtype: ~azure.mgmt.securityinsight.models.EntityQuery
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.EntityQuery]

        request = build_get_request(
            resource_group_name=resource_group_name,
            workspace_name=workspace_name,
            entity_query_id=entity_query_id,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.get.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize("EntityQuery", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}"}  # type: ignore

    @overload
    def create_or_update(
        self,
        resource_group_name: str,
        workspace_name: str,
        entity_query_id: str,
        entity_query: _models.CustomEntityQuery,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.EntityQuery:
        """Creates or updates the entity query.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :param entity_query_id: entity query ID. Required.
        :type entity_query_id: str
        :param entity_query: The entity query we want to create or update. Required.
        :type entity_query: ~azure.mgmt.securityinsight.models.CustomEntityQuery
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: EntityQuery or the result of cls(response)
        :rtype: ~azure.mgmt.securityinsight.models.EntityQuery
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def create_or_update(
        self,
        resource_group_name: str,
        workspace_name: str,
        entity_query_id: str,
        entity_query: IO,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.EntityQuery:
        """Creates or updates the entity query.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :param entity_query_id: entity query ID. Required.
        :type entity_query_id: str
        :param entity_query: The entity query we want to create or update. Required.
        :type entity_query: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: EntityQuery or the result of cls(response)
        :rtype: ~azure.mgmt.securityinsight.models.EntityQuery
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def create_or_update(
        self,
        resource_group_name: str,
        workspace_name: str,
        entity_query_id: str,
        entity_query: Union[_models.CustomEntityQuery, IO],
        **kwargs: Any
    ) -> _models.EntityQuery:
        """Creates or updates the entity query.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :param entity_query_id: entity query ID. Required.
        :type entity_query_id: str
        :param entity_query: The entity query we want to create or update. Is either a model type or a
         IO type. Required.
        :type entity_query: ~azure.mgmt.securityinsight.models.CustomEntityQuery or IO
        :keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
         Default value is None.
        :paramtype content_type: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: EntityQuery or the result of cls(response)
        :rtype: ~azure.mgmt.securityinsight.models.EntityQuery
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.EntityQuery]

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(entity_query, (IO, bytes)):
            _content = entity_query
        else:
            _json = self._serialize.body(entity_query, "CustomEntityQuery")

        request = build_create_or_update_request(
            resource_group_name=resource_group_name,
            workspace_name=workspace_name,
            entity_query_id=entity_query_id,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self.create_or_update.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize("EntityQuery", pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize("EntityQuery", pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}"}  # type: ignore

    @distributed_trace
    def delete(  # pylint: disable=inconsistent-return-statements
        self, resource_group_name: str, workspace_name: str, entity_query_id: str, **kwargs: Any
    ) -> None:
        """Delete the entity query.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Required.
        :type workspace_name: str
        :param entity_query_id: entity query ID. Required.
        :type entity_query_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[None]

        request = build_delete_request(
            resource_group_name=resource_group_name,
            workspace_name=workspace_name,
            entity_query_id=entity_query_id,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.delete.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}"}  # type: ignore


text:
package org.jclouds.blobstore;

import org.jclouds.blobstore.internal.BaseBlobStoreApiMetadataTest;
import org.testng.annotations.Test;

@Test(groups = "unit", testName = "TransientApiMetadataTest")
public class TransientApiMetadataTest extends BaseBlobStoreApiMetadataTest {

   public TransientApiMetadataTest() {
      super(new TransientApiMetadata());
   }
}


text:
<?php

namespace IBMWatson\Connection\Exceptions;

use GuzzleHttp\Message\ResponseInterface;

abstract class VisualRecognitionException extends \Exception
{
    public function __construct(
        $reponse_code = 400,
        ResponseInterface $response = null
    ) {
        $message = '';
        if ($response) {

            $data             = (string)$response->getBody();
            $jsonResponseData = json_decode($data, true);

            $message = isset($jsonResponseData['message']) ? $jsonResponseData['message'] : $this->getDefaultMessage();
        }
        parent::__construct($message, $reponse_code);
    }

    /**
     * @return string return default exception message
     */
    public abstract function getDefaultMessage();
}


text:
const int ROWS = 20;
const int COLS = 10;

//The actual object that the game grid is constructed of. Each has a filled atribute, an active for designating which is the current piece,
//a toBeDeleted boolean that sets whether it is to be cleared, and color designations.
struct Square {
	bool filled;
	bool isActive;
	bool toBeDeleted;
	float red, green, blue;
};

//the game class where everything takes place
class Game {
public:
	//Constructor
	Game();
	//Game methods
	void clearGrid();
	void nextPiece();
	void restart();
	void move(int dir);
	void rotateShape(int rot);
	bool canRotate(Piece p);
	bool collision(int dir);
	void updatePiece();
	void updateActive();
	void update();
	void updateActiveAfterCollision();
	bool gameOver();
	void checkLine();
	void clearLine();

	//the game pieces that are put onto the board
	Piece active;
	Piece next;
	Piece activeCopy;

	//The actual game board
	Square grid[ROWS][COLS];

	//Game data
	int lines;
	int shapesProc;
	bool deleteLines;
	bool killed;	// has the game ended
	bool paused;	// is the game paused
	int timer;		// timer
};


text:
package com.webcohesion.ofx4j.domain.data.tax1099;

import com.webcohesion.ofx4j.meta.Aggregate;
import com.webcohesion.ofx4j.meta.ChildAggregate;

import com.webcohesion.ofx4j.meta.Element;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Aparna Gawali
 * aparna.gawali@sungard.com
 */

@Aggregate ( "TAX1099R_V100")
public class Tax1099R  {

	private String srvrtId;
	private String taxYear;
	private String grossDist;

	private String taxAmt;
	private String taxAmtNd;
	private String totalDist;
	private String capGain;
	private String fedTaxWh;
	private String empContins;
	private String netUnapEmp;
	private List<String> distCodes;
	private String iraSepSimp;
	private String annCtrctDist;
	private String totEmpCount;
	private String firstYearDesignatedRoth;

	private StateTaxWithheldAggregate stateTaxWithheldAggregate;
	private PayerAddress payerAddress;
	private String payerId;
	private RecAddress recAddress;
	private String recId;
	private String recAcct;

	@Element ( name = "SRVRTID",required = true , order = 0 )
	public String getSrvrtId() {
	    return srvrtId;
	  }

	public void setSrvrtId(String srvrtId) {
	    this.srvrtId = srvrtId;
	  }

	@Element ( name = "TAXYEAR", required = true, order = 1 )
	public String getTaxYear() {
	    return taxYear;
	  }

	public void setTaxYear(String taxYear) {
	    this.taxYear = taxYear;
	  }

	/**
	 * @return the grossDist
	 */
	@Element ( name = "GROSSDIST", required = true, order = 2 )
	public String getGrossDist() {
			return grossDist;
		}

	/**
	 * @param grossDist the grossDist to set
	 */
	public void setGrossDist(String grossDist) {
			this.grossDist = grossDist;
		}

	/**
	 * @return the taxAmt
	 */
	@Element ( name = "TAXAMT", required = false, order = 3 )
	public String getTaxAmt() {
			return taxAmt;
		}

	/**
	 * @param taxAmt the taxAmt to set
	 */
	public void setTaxAmt(String taxAmt) {
			this.taxAmt = taxAmt;
		}

    /**
	 * @return the taxAmtNd
	 */
	@Element ( name = "TAXAMTND", required = false, order = 4 )
    public String getTaxAmtNd() {
			return taxAmtNd;
		}

	/**
	 * @param taxAmtNd the taxAmtNd to set
	 */
	public void setTaxAmtNd(String taxAmtNd) {
			this.taxAmtNd = taxAmtNd;
		}

    /**
     * @return the totalDist
     */
    @Element ( name = "TOTALDIST", required = false, order = 5 )
    public String getTotalDist() {
        return totalDist;
    }

    /**
     * @param totalDist the totalDist to set
     */
    public void setTotalDist(String totalDist) {
        this.totalDist = totalDist;
    }

	/**
	 * @return the capGain
	 */
	@Element ( name = "CAPGAIN", required = false, order = 6 )
	public String getCapGain() {
			return capGain;
		}

	/**
	 * @param capGain the capGain to set
	 */
	public void setCapGain(String capGain) {
			this.capGain = capGain;
		}

	/**
	 * @return the fedTaxWh
	 */
	@Element ( name = "FEDTAXWH", required = false, order = 7 )
	public String getFedTaxWh() {
		return fedTaxWh;
	}

	/**
	 * @param fedTaxWh the fedTaxWh to set
	 */
	public void setFedTaxWh(String fedTaxWh) {
		this.fedTaxWh = fedTaxWh;
	}

	/**
	 * @return the empContins
	 */
	@Element ( name = "EMPCONTINS", required = false, order = 8 )
	public String getEmpContins() {
		return empContins;
	}

	/**
	 * @param empContins the empContins to set
	 */
	public void setEmpContins(String empContins) {
		this.empContins = empContins;
	}

	/**
	 * @return the netUnapEmp
	 */
	@Element ( name = "NETUNAPEMP", required = false, order = 9 )
	public String getNetUnapEmp() {
		return netUnapEmp;
	}

	/**
	 * @param netUnapEmp the netUnapEmp to set
	 */
	public void setNetUnapEmp(String netUnapEmp) {
		this.netUnapEmp = netUnapEmp;
	}

	/**
	 * @return the distCode
	 */
	@Element ( name = "DISTCODE", required = true, order = 10 )
	public List<String> getDistCodes() {
		return distCodes;
	}

	public String getDistCode() {
	    return distCodes == null || distCodes.isEmpty() ? null : distCodes.get(0);
    }

	/**
	 * @param distCode the distCode to set
	 */
	public void setDistCode(String distCode) {
		this.distCodes = Collections.singletonList(distCode);
	}

    public void setDistCodes(List<String> distCodes) {
        this.distCodes = distCodes;
    }

	/**
	 * @return the iraSepSimp
	 */
	@Element ( name = "IRASEPSIMP", required = true, order = 11 )
	public String getIraSepSimp() {
		return iraSepSimp;
	}

	/**
	 * @param iraSepSimp the iraSepSimp to set
	 */
	public void setIraSepSimp(String iraSepSimp) {
		this.iraSepSimp = iraSepSimp;
	}

	/**
	 * @return the annCtrctDist
	 */
	@Element ( name = "ANNCTRCTDIST", required = false, order = 12 )
	public String getAnnCtrctDist() {
		return annCtrctDist;
	}

	/**
	 * @param annCtrctDist the annCtrctDist to set
	 */
	public void setAnnCtrctDist(String annCtrctDist) {
		this.annCtrctDist = annCtrctDist;
	}

	/**
	 * @return the totEmpCount
	 */
	@Element ( name = "TOTEMPCONT", required = false, order = 13 )
	public String getTotEmpCount() {
		return totEmpCount;
	}

	/**
	 * @param totEmpCount the totEmpCount to set
	 */
	public void setTotEmpCount(String totEmpCount) {
		this.totEmpCount = totEmpCount;
	}

    /**
     * @return the firstYearDesignatedRoth
     */
    @Element ( name = "FIRSTYEARDESIGROTH", required = false, order = 14 )
    public String getFirstYearDesignatedRoth() {
        return firstYearDesignatedRoth;
    }

    /**
     * @param firstYearDesignatedRoth the firstYearDesignatedRoth to set
     */
    public void setFirstYearDesignatedRoth(String firstYearDesignatedRoth) {
        this.firstYearDesignatedRoth = firstYearDesignatedRoth;
    }

    /**
     * @return the stateTaxWithheldAggregate
     */
    @ChildAggregate(required=false, order = 15)
    public StateTaxWithheldAggregate getStateTaxWithheldAggregate() {
        return stateTaxWithheldAggregate;
    }

    /**
     * @param stateTaxWithheldAggregate the stateTaxWithheldAggregate to set
     */
    public void setStateTaxWithheldAggregate(StateTaxWithheldAggregate stateTaxWithheldAggregate) {
        this.stateTaxWithheldAggregate = stateTaxWithheldAggregate;
    }

    /**
	 * @return the payerAddress
	 */
	@ChildAggregate(required=true, order = 16)
	public PayerAddress getPayerAddress() {
		return payerAddress;
	}

	/**
	 * @param payerAddress the payerAddress to set
	 */
	public void setPayerAddress(PayerAddress payerAddress) {
		this.payerAddress = payerAddress;
	}

	/**
	 * @return the payerId
	 */
	@Element ( name = "PAYERID", required = true, order = 17 )
	public String getPayerId() {
		return payerId;
	}

	/**
	 * @param payerId the payerId to set
	 */
	public void setPayerId(String payerId) {
		this.payerId = payerId;
	}

	/**
	 * @return the recAddress
	 */
	@ChildAggregate(order = 18)
	public RecAddress getRecAddress() {
		return recAddress;
	}

	/**
	 * @param recAddress the recAddress to set
	 */
	public void setRecAddress(RecAddress recAddress) {
		this.recAddress = recAddress;
	}

	/**
	 * @return the recId
	 */
	@Element ( name = "RECID", required = true, order = 19 )
	public String getRecId() {
		return recId;
	}

	/**
	 * @param recId the recId to set
	 */
	public void setRecId(String recId) {
		this.recId = recId;
	}

	/**
	 * @return the recAcct
	 */
	@Element ( name = "RECACCT", required = true, order = 20 )
	public String getRecAcct() {
		return recAcct;
	}

	/**
	 * @param recAcct the recAcct to set
	 */
	public void setRecAcct(String recAcct) {
		this.recAcct = recAcct;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Issue STEP-MINIMAL Writeup</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="../Issues/iss325-writeup.html">
<LINK REL=UP HREF="../Issues/iss326.html">
<LINK REL=NEXT HREF="../Issues/iss327-writeup.html">

Issue STEP-MINIMAL Writeup

Issue:        STEP-MINIMAL

Forum:	      Editorial

References:   STEP (p441)

Category:     CLARIFICATION

Edit history: 04-Mar-91, Version 1 by Pitman

Status:	      For X3J13 consideration

Problem Description:

  What is the minimal interpretation of STEP?  Specifically, must it

  pause for some user interaction, or can it just proceed without

  pausing in implementations (probably `compiled-only' implementations)

  which do not choose to implement this feature?

  In particular, are either of the following implementations valid?

  (DEFMACRO STEP (FORM) `(PROGN ,FORM))

  or

  (DEFMACRO STEP (FORM)

    `(LET ((VALUES (MULTIPLE-VALUE-LIST ,FORM)))

       (FORMAT T "~&~S => ~{~S~^, ~}~%" ',FORM VALUES)

       (VALUES-LIST VALUES)))

Proposal (STEP-MINIMAL:PERMIT-PROGN):

  Clarify that it is permissible to implement (STEP x) as (PROGN x)

  in implementations which do not wish to provide more elaborate

  functionality.

  Rationale:

  For a delivery Lisp, this would be a minimal amount of work.

Proposal (STEP-MINIMAL:REQUIRE-PAUSE):

  Clarify that (STEP x) must, at minimum, pause in some way that permits

  user intervention.

  This also implies that in implementaions which do have a query loop,

  some form of query must occur even for constant forms, like (STEP 5).

  Rationale:

  Users who introduce STEP into a program might do so on the assumption

  that execution will not proceed beyond that point (e.g., into some

  dangerous code that follows) without offering them a way to intervene

  first.

Current Practice:

  Symbolics Genera requires intervention.

  Symbolics Cloe Runtime (the part that runs on the 386) behaves like PROGN

  in the example I tried (a couple of nested arithmetic operations).

Cost to Implementors:

  REQUIRE-PAUSE:  Probably none.  If there are any minimalist

   implementations which do not currently require a pause now, they

   would need a very small amount of additional code.

  PERMIT-PROGN:  None.

Cost to Users:

  None.  This is a debugging feature that affects -how- Lisp is used in

  subtle ways, but is not likely to be present in stable code so wouldn't

  have a direct cost.  It might be argued that there was a slight cost

  to PERMIT-PROGN for users who wanted the pause and didn't get it in

  some implementation; there is also a risk of larger cost with

  PERMIT-PROGN of users who expect a pause and don't get it and fall

  through to code they didn't intend to run.

Cost of Non-Adoption:

  Unclear specification.  Implementors of certain implementations won't

  know what to do.  Users won't know what to expect.

Benefits:

  See above.

Aesthetics:

  Probably negligible.

Discussion:

  Pitman has a slight preference for REQUIRE-PAUSE, but supports any

  interpretation that makes this clear.

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
#include <iostream>

#include "dart/dart.hpp"

#include "examples/vehicle/MyWindow.hpp"

int main(int argc, char* argv[])
{
  using namespace dart;
  using namespace dynamics;
  using namespace simulation;
  using namespace utils;

  // create and initialize the world
  WorldPtr myWorld = SkelParser::readWorld(DART_DATA_PATH"/skel/vehicle.skel");
  assert(myWorld != nullptr);
  Eigen::Vector3d gravity(0.0, -9.81, 0.0);
  myWorld->setGravity(gravity);

  // create a window and link it to the world
  MyWindow window;
  window.setWorld(myWorld);

  std::cout << "space bar: simulation on/off" << std::endl;
  std::cout << "'p': playback/stop" << std::endl;
  std::cout << "'[' and ']': play one frame backward and forward" << std::endl;
  std::cout << "'v': visualization on/off" << std::endl;
  std::cout << "'1'--'4': programmed interaction" << std::endl;
  std::cout << "'w': move forward" << std::endl;
  std::cout << "'s': stop" << std::endl;
  std::cout << "'x': move backward" << std::endl;
  std::cout << "'a': rotate steering wheels to left" << std::endl;
  std::cout << "'d': rotate steering wheels to right" << std::endl;

  glutInit(&argc, argv);
  window.initWindow(640, 480, "Vehicle");
  glutMainLoop();

  return 0;
}


text:
import time

class DataCompressor():
    def compress(data):
        compressedData = bytearray()
        pointer = 0
        posByteList = []
        posBitList = []
        while (pointer < len(data)):
            behind = []
            front = []
            lengthCandidates = []
            lengthResults = []
            if (len(posBitList) >= 8):
                posByteList.append(DataCompressor.bitsIntoByte(posBitList))
                posBitList.clear()

            for pos in range(0, 16):
                if (pointer-pos-1 >= 0):
                    behind.insert(0, data[pointer-pos-1])
                else:
                    behind.insert(0, 0)
                    break

            for pos in range(0, 16):
                if (pointer+pos < len(data)):
                    front.append(data[pointer+pos])
                    indexList = DataCompressor.checkForSublistInList(behind, front)
                    if indexList:
                        lengthCandidates.append((pos+1, len(behind) - indexList[0]))

            if lengthCandidates:
                for frontLength, behindLength in lengthCandidates:
                    frontLengthCandidate = frontLength
                    frontCandidate = front[:frontLengthCandidate]
                    behindCandidate = behind[len(behind)-behindLength:]
                    while (frontLengthCandidate < 0x10000):
                        if (pointer+frontLengthCandidate >= len(data)):
                            break
                        frontCandidate.append(data[pointer+frontLengthCandidate])
                        if (DataCompressor.checkListRepetitionFromSublist(frontCandidate, behindCandidate)):
                            frontLengthCandidate += 1
                        else:
                            break
                    lengthResults.append((frontLengthCandidate, behindLength))

                lengthResults.sort(key=lambda result: result[0], reverse=True)
                frontLength = (lengthResults[0])[0]
                behindLength = (lengthResults[0])[1]
                if (frontLength <= 16):
                    lengthResults.sort(key=lambda result: 100000*result[0]-result[1], reverse=True)
                    frontLength = (lengthResults[0])[0]
                    behindLength = (lengthResults[0])[1]
                else:
                    lengthResults.sort(key=lambda result: 100000*result[0]+result[1], reverse=True)
                    frontLength = (lengthResults[0])[0]
                    behindLength = (lengthResults[0])[1]

                if (frontLength > 256):
                    posBitList.append(1)
                    compressedByte = 0
                    compressedByte += 0x10 - behindLength
                    compressedData.append(compressedByte)
                    compressedData.append(0)
                    compressedData.append(frontLength-1 & 0x00FF)
                    compressedData.append((frontLength-1)//256)
                    pointer += frontLength
                elif (frontLength > 16):
                    posBitList.append(1)
                    compressedByte = 0
                    compressedByte += 0x10 - behindLength
                    compressedData.append(compressedByte)
                    compressedData.append(frontLength-1)
                    pointer += frontLength
                elif (frontLength > 1):
                    posBitList.append(1)
                    compressedByte = 0
                    compressedByte += 0x10 - behindLength
                    compressedByte += ((frontLength-1 & 0x000F) << 4)
                    compressedData.append(compressedByte)
                    pointer += frontLength
                else:
                    posBitList.append(0)
                    compressedData.append(data[pointer])
                    pointer += 1
            else:
                posBitList.append(0)
                compressedData.append(data[pointer])
                pointer += 1
        if (len(posBitList) == 8):
            posByteList.append(DataCompressor.bitsIntoByte(posBitList))
            posBitList.clear()
        posBitList.append(1)
        posByteList.append(DataCompressor.bitsIntoByte(posBitList))
        for x in range(0, 4):
            compressedData.append(0)
        DataCompressor.insertPosBytesIntoData(compressedData, posByteList)
        return compressedData

    def decompress(data, address=0):
        assert(address >= 0)
        assert(address < len(data))
        pointer = address
        writtenData = bytearray()
        for xx in range(0,16):
            writtenData.append(0)
        endCondition = False

        while (not endCondition):
            currByte = data[pointer]
            pointer += 1
            posBitList = []
            andbyte = 0x80
            for xx in range(0,8):
                posBit = currByte & andbyte
                if (posBit > 0):
                    posBit = 1
                andbyte = andbyte >> 1
                posBitList.append(posBit)
            for posBit in posBitList:
                currByte = data[pointer]
                pointer += 1
                if posBit == 0:
                    writtenData.append(currByte)
                    if (endCondition):
                        break
                else:
                    totalBytes = ((currByte & 0b11110000) >> 4) + 1
                    bytesBehind = 0b10000 - (currByte & 0b00001111)
                    behindBuffer = writtenData[len(writtenData)-bytesBehind:]
                    if totalBytes == 1:
                        totalBytes = data[pointer] + 1
                        pointer += 1
                        if (totalBytes == 1):
                            if ((data[pointer] == 0) and (data[pointer+1] == 0)):
                                endCondition = True
                                break
                            totalBytes = 256*data[pointer+1] + data[pointer] + 1
                            pointer += 2
                    xx = 0
                    while (xx < totalBytes):
                        for yy in behindBuffer:
                            writtenData.append(yy)
                            if (endCondition):
                                xx = totalBytes
                            xx += 1
                            if (xx >= totalBytes):
                                break
        del writtenData[:16]
        return writtenData

    def insertPosBytesIntoData(data, posByteList):
        pointer = 0
        andbyte = 0x80
        posBitList = []
        for posByte in posByteList:
            andbyte = 0x80
            data.insert(pointer, posByte)
            pointer += 1
            for xx in range(0,8):
                posBit = posByte & andbyte
                if (posBit > 0):
                    posBit = 1
                andbyte = andbyte >> 1
                posBitList.append(posBit)
            for posBit in posBitList:
                if (posBit == 1):
                    if ((data[pointer] & 0xF0) == 0):
                        pointer += 1
                        if (data[pointer] == 0):
                            pointer += 1
                            if ((data[pointer] == 0) and (data[pointer+1] == 0)):
                                return data
                            pointer += 1
                pointer += 1
            del posBitList[:]
        return data

    def bitsIntoByte(bitList):
        assert(len(bitList) <= 8)
        myByte = 0;
        for x in range(0, len(bitList)):
            if (bitList[x] == 1):
                myByte += 0x80 >> x
        return myByte

    def byteListIntoBitList(byteList, leftToRight=True):
        bitList = []
        for byteValue in byteList:
            if leftToRight:
                andbyte = 0x80
                for xx in range(0,8):
                    posBit = byteValue & andbyte
                    if (posBit > 0):
                        posBit = 1
                    andbyte = andbyte >> 1
                    bitList.append(posBit)
            else:
                andbyte = 0x01
                for xx in range(0,8):
                    posBit = byteValue & andbyte
                    if (posBit > 0):
                        posBit = 1
                    andbyte = andbyte << 1
                    bitList.append(posBit)
        return bitList

    def checkListRepetitionFromSublist(list_, sublist):
        for xx in range(0, len(list_)):
            if (list_[xx] != sublist[xx % len(sublist)]):
                return False
        return True

    def checkForSublistInList(list_, sublist):
        indexList = []
        for xx in range(len(list_) - len(sublist), -1, -1):
            count = 0
            for yy in range(0, len(sublist)):
                if (list_[xx+yy] == sublist[yy]):
                    count += 1
                else:
                    break
            if (count == len(sublist)):
                indexList.append(xx)
        indexList.sort(reverse=True)
        return indexList

    def readLittleEndian(data, offset):
        assert(offset >= 0)
        assert(offset+1 < len(data))
        value = data[offset+1]*0x100
        value += data[offset]
        return value

    def convertSnesPointer(bank, pointer):
        return ((bank - 0x80)*0x8000) + (pointer - 0x8000)

    def readSnesPointer(data, offset):
        assert(offset+2 < len(data))
        bank = data[offset+2]
        pointer = DataCompressor.readLittleEndian(data, offset)
        return DataCompressor.convertSnesPointer(bank, pointer)


text:
<?php

namespace Oro\Bundle\EntityConfigBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\Index;

/**
 * @ORM\Table(name="oro_entity_config_index_value", indexes={
 *  @Index(name="idx_entity_config_index_entity", columns={"scope", "code", "value", "entity_id"}),
 *  @Index(name="idx_entity_config_index_field", columns={"scope", "code", "value", "field_id"})
 * })
 * @ORM\Entity
 */
class ConfigModelIndexValue
{
    const ENTITY_NAME = 'OroEntityConfigBundle:ConfigModelIndexValue';

    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var EntityConfigModel
     * @ORM\ManyToOne(targetEntity="EntityConfigModel", inversedBy="indexedValues", cascade={"persist"})
     * @ORM\JoinColumn(name="entity_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $entity;

    /**
     * @var FieldConfigModel
     * @ORM\ManyToOne(targetEntity="FieldConfigModel", inversedBy="indexedValues", cascade={"persist"})
     * @ORM\JoinColumn(name="field_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $field;

    /**
     * @var string
     * @ORM\Column(name="code", type="string", length=255)
     */
    protected $code;

    /**
     * @var string
     * @ORM\Column(name="scope", type="string", length=255)
     */
    protected $scope;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $value;

    /**
     * @param string|null $scope
     * @param string|null $code
     * @param string|null $value
     */
    public function __construct($scope = null, $code = null, $value = null)
    {
        $this->scope = $scope;
        $this->code  = $code;
        $this->value = $value;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set code
     *
     * @param string $code
     * @return ConfigModelIndexValue
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * Get code
     *
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set scope
     *
     * @param string $scope
     * @return ConfigModelIndexValue
     */
    public function setScope($scope)
    {
        $this->scope = $scope;

        return $this;
    }

    /**
     * Get scope
     *
     * @return string
     */
    public function getScope()
    {
        return $this->scope;
    }

    /**
     * Set value
     *
     * @param string $value
     * @return ConfigModelIndexValue
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Set owning entity
     *
     * @param EntityConfigModel $entity
     * @return $this
     */
    public function setEntity($entity)
    {
        $this->entity = $entity;

        return $this;
    }

    /**
     * Get owning entity
     *
     * @return EntityConfigModel
     */
    public function getEntity()
    {
        return $this->entity;
    }

    /**
     * Set owning field
     *
     * @param FieldConfigModel $field
     * @return $this
     */
    public function setField($field)
    {
        $this->field = $field;

        return $this;
    }

    /**
     * Get owning field
     *
     * @return FieldConfigModel
     */
    public function getField()
    {
        return $this->field;
    }
}


text:
import logging
import datetime
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from django.utils.translation import ugettext_lazy as _
from django.db import models
from apps.core.constants import TEAM_TYPES, MARKER_TYPES, NOTIFICATION_TYPE, GAME_STATUSES, GAME_TYPES, ITEM_TYPES
from apps.core.exceptions import AlreadyExistException, GameAlreadyStartedException, GameAlreadyFinishedException
from apps.core.models import PortalUser, GeoModel
from apps.core.notifications import Notification
from apps.core.utils import calculate_distance

logger = logging.getLogger("root")

class Marker(GeoModel):
    type = models.IntegerField(choices=MARKER_TYPES, verbose_name=_("Type"))
    distance = models.FloatField(verbose_name=_("Distance"))
    url = models.URLField(verbose_name=_("URL"))

    def __unicode__(self):
        return "%s, %.2f m, url: %s" % (self.type, self.distance, self.url)

    class Meta:
        managed = False

class Item(GeoModel):
    name = models.CharField(max_length=100, verbose_name=_("Name"))
    type = models.IntegerField(choices=ITEM_TYPES, verbose_name=_("Type"))
    value = models.FloatField(blank=True, null=True, verbose_name=_("Value"))
    description = models.TextField(blank=True, null=True, max_length=255, verbose_name=_("Description"))
    game = models.ForeignKey("Game", related_name="items", verbose_name=_("Game"))

    last_captured_by = models.ForeignKey(PortalUser, blank=True, null=True, verbose_name=_("Last captured by"))
    when_captured = models.DateTimeField(blank=True, null=True, verbose_name=_("When captured"))

    last_modified = models.DateTimeField(auto_now=True, verbose_name=_("Last modified"))
    created = models.DateTimeField(auto_now_add=True, verbose_name=_("Created"))

    def __unicode__(self):
        return "%s" % self.name

    class Meta:
        app_label = "ctf"

class Game(GeoModel):
    name = models.CharField(max_length=100, verbose_name=_("Name"))
    description = models.TextField(null=True, blank=True, max_length=255, verbose_name=_("Description"))

    radius = models.FloatField(verbose_name=_("Radius"))
    start_time = models.DateTimeField(verbose_name=_("Start time"))
    max_players = models.IntegerField(null=True, blank=True, verbose_name=_("Max players"))
    status = models.IntegerField(choices=GAME_STATUSES, default=GAME_STATUSES.CREATED, verbose_name=_("Status"))
    type = models.IntegerField(choices=GAME_TYPES, default=GAME_TYPES.BASED_ON_POINTS, verbose_name=_("Type"))

    visibility_range = models.FloatField(default=200.00, verbose_name=_("Visibility range"))  # in meters
    action_range = models.FloatField(default=5.00, verbose_name=_("Action range"))  # in meters
    capture_time = models.IntegerField(default=10, verbose_name=_("Capture time"))  # in seconds

    time_limit = models.IntegerField(default=15, verbose_name=_("Time limit"))
    points_limit = models.IntegerField(default=12, verbose_name=_("Points limit"))

    red_team_points = models.IntegerField(default=0, verbose_name=_("Red team points"))
    blue_team_points = models.IntegerField(default=0, verbose_name=_("Blue team points"))

    players = models.ManyToManyField(PortalUser, verbose_name=_("Players"), related_name="joined_games")
    invited_users = models.ManyToManyField(PortalUser, verbose_name=_("Invited users"), related_name="pending_games")

    owner = models.ForeignKey(PortalUser, null=True, blank=True, verbose_name=_("Owner"))
    last_modified = models.DateTimeField(auto_now=True, verbose_name=_("Last modified"))
    created = models.DateTimeField(auto_now_add=True, verbose_name=_("Created"))

    @property
    def red_base(self):
        return self._get_item(MARKER_TYPES.RED_BASE)

    @property
    def blue_base(self):
        return self._get_item(MARKER_TYPES.BLUE_BASE)

    def add_player(self, user):
        if self.max_players and self.max_players == self.players.count():
            raise Exception("Max value of players exceeded")

        logger.debug("user: %s", user)

        is_user_already_exist = self.players.filter(pk=user.id).exists()
        logger.debug("is_user_already_exist: %s", is_user_already_exist)

        if is_user_already_exist:
            logger.info("User '%s' already joined into the game '%s: %s'", user.username, self.id, self.name)
            raise AlreadyExistException("User '%s' already joined into the game '%s: %s'" % (
                user.username, self.id, self.name))
        else:
            logger.info("Setting current game id: '%d' into the user: '%s'", self.id, user.username)
            logger.info("User: '%s' prev game: '%s'", user.username, user.current_game_id)

            if user.current_game_id is not None:
                game = Game.objects.get(pk=user.current_game_id)
                user.joined_games.remove(game)
                logger.info("User: '%s' was removed from prev game: '%s'", user.username, user.current_game_id)

            user.current_game_id = self.id
            user.save()

            logger.info("User '%s' is joining into the game '%s'...", user.username, self.name)
            self.players.add(user)
            self.save()

    def remove_player(self, user):
        if not self.players.filter(pk=user.id).exists():
            raise PortalUser.DoesNotExist("User '%s' doesn't exist in selected game '%s: %s'" % (
                user.username, self.id, self.name))

        self.players.remove(user)
        logger.info("User '%s' is removing from game '%s'...", user.username, self.name)
        self.save()

        logger.info("Cleaning current game id: '%d' from the user: '%s'", self.id, user.username)
        user.current_game_id = None
        user.save()

    def get_neighbours(self, user):
        location = user.location
        point = Point(location.lon, location.lat)
        max_dist = D(m=self.visibility_range)

        logger.debug("user: %s", user)
        logger.debug("location: %s", location)
        logger.debug("max_dist: %s", max_dist)

        sqs = SearchQuerySet().dwithin('location', point, max_dist).distance('location', point).filter(game=self.id)

        logger.debug("Query: %s", sqs.query)
        logger.debug("Query distance: %s", sqs.distance)

        return sqs

    def get_time_to_end(self):
        if self.status == GAME_STATUSES.IN_PROGRESS:
            when_started = self.start_time.replace(tzinfo=None)
            delta = (datetime.datetime.now() - when_started).seconds
            return delta
        return None

    def validate_game(self):
        """ Checks if games is finished or not (based on time or points).
        """

        if self.type == GAME_TYPES.BASED_ON_POINTS:
            if self.red_team_points >= self.points_limit or self.blue_team_points >= self.points_limit:
                logger.info("Game over! Max points limit achieved!")
                self.stop()
        else:
            time_to_end = self.get_time_to_end()
            logger.debug("time to end: %s s", time_to_end)

            if time_to_end and time_to_end <= 0:
                logger.info("Game over! Time limit achieved!")
                self.stop()

    def get_markers(self, user, context):
        from apps.ctf.api.serializers.common import ItemSerializer
        from apps.core.api.serializers import PortalUserSerializer

        neighbours = self.get_neighbours(user)

        markers = []

        for instance in neighbours:
            distance_in_meters = instance.distance.m if instance.distance is not None else None
            obj = instance.object
            logger.debug("object: %s, distance: %s m", obj, distance_in_meters)
            logger.debug("object type: %s", type(obj))

            if isinstance(obj, Item) or isinstance(obj, PortalUser):
                logger.debug("[PLAY]: user: %s, distance: '%f', action_range: '%f'", user, distance_in_meters,
                             self.action_range)

                if isinstance(obj, Item):
                    serializer = ItemSerializer(obj, context=context)
                    json_data = serializer.data

                    url = json_data["url"]
                    marker_type = obj.type

                    if user.team is not None and distance_in_meters <= self.action_range:
                        logger.debug("[PLAY]: distance: '%f' <= action_range: '%f'", distance_in_meters,
                                     self.action_range)

                        if obj.type in [MARKER_TYPES.RED_FLAG, MARKER_TYPES.BLUE_FLAG]:
                            self.capture_the_flag(obj, user, distance_in_meters)

                    marker = Marker(
                        distance=distance_in_meters,
                        type=marker_type,
                        url=url,
                        location=obj.location)

                    logger.debug("marker was created: %s", marker)
                    markers.append(marker)
                elif isinstance(obj, PortalUser) and obj.id is not user.id:
                    serializer = PortalUserSerializer(obj, context=context)
                    json_data = serializer.data

                    url = json_data["url"]
                    marker_type = MARKER_TYPES.PLAYER

                    marker = Marker(
                        distance=distance_in_meters,
                        type=marker_type,
                        url=url,
                        location=obj.location)

                    logger.debug("marker was created: %s", marker)
                    markers.append(marker)
        return markers

    def capture_the_flag(self, flag, user, distance_in_meters):
        """ This method contains a logic for capture the flag from other user, enemy base or from another
        place on the map.
        """
        logger.debug("Trying to capture the flag...")
        logger.debug("Distance to flag: %.2f m ", distance_in_meters)

        if flag.last_captured_by == user and distance_in_meters > 0:
            when_captured = flag.when_captured.replace(tzinfo=None)
            delta = (datetime.datetime.now() - when_captured).seconds
            logger.debug("delta: %d s", delta)
            if delta <= self.capture_time:
                # do nothing - user cannot captured the flag
                logger.debug("do nothing - user '%s' cannot captured the flag once again until (delta: %s s",
                             user.username, delta)
                return

        if user.team == TEAM_TYPES.RED_TEAM:  # RED TEAM
            if flag.type == MARKER_TYPES.RED_FLAG:  # RED FLAG
                # User from RED TEAM captured the RED FLAG

                flag.location = self.red_base.location
                logger.debug("[PLAY]: Red flag is going back to the red base (game: %d)", self.id)
            else:  # BLUE FLAG
                # User from RED TEAM captured the BLUE FLAG

                flag.location = user.location
                logger.debug("[PLAY]: Player: '%s' take a blue flag (game: %d)", user.username, self.id)

                red_base = self.red_base
                blue_base = self.blue_base
                distance_to_base = calculate_distance(user.location, red_base.location)
                if distance_to_base <= self.action_range:
                    # User from RED TEAM brought the BLUE FLAG to the RED BASE

                    logger.debug("[PLAY]: Point captured! Blue flag is going back to the blue base (game: %d)", self.id)
                    self.red_team_points += 1
                    flag.location = blue_base.location
        else:  # BLUE TEAM
            if flag.type == MARKER_TYPES.BLUE_FLAG:  # BLUE FLAG
                # User from BLUE TEAM captured the BLUE FLAG

                flag.location = self.blue_base.location
                logger.debug("[PLAY]: Blue flag is going back to the blue base (game: %d)", self.id)
            else:  # RED FLAG
                # User from BLUE TEAM captured the RED FLAG

                flag.location = user.location
                logger.debug("[PLAY]: Player: '%s' take a red flag (game: %d)", user.username, self.id)

                red_base = self.red_base
                blue_base = self.blue_base
                distance_to_base = calculate_distance(user.location, blue_base.location)
                if distance_to_base <= self.action_range:
                    # User from BLUE TEAM brought the RED FLAG to the BLUE BASE

                    logger.debug("[PLAY]: Point captured! Red flag is going back to the red base (game: %d)", self.id)
                    self.blue_team_points += 1
                    flag.location = red_base.location

        flag.last_captured_by = user
        flag.when_captured = datetime.datetime.now()
        flag.save()

    def team_balancing(self):
        for idx, player in enumerate(self.players.all()):
            if idx % 2:
                player.team = TEAM_TYPES.RED_TEAM
            else:
                player.team = TEAM_TYPES.BLUE_TEAM
            player.save()

    def start(self):
        logger.info("Game: %s with %d players is starting...", self.id, self.name)

        if self.status == GAME_STATUSES.IN_PROGRESS:
            raise GameAlreadyStartedException()

        logger.info("Team balancing...")
        self.team_balancing()

        self.status = GAME_STATUSES.IN_PROGRESS
        self.start_time = datetime.datetime.now()
        self.save()

        # sending broadcast notification to all players
        logger.info("Sending broadcast notification to all players...")
        Notification(NOTIFICATION_TYPE.START_GAME, self.players).send()
        logger.info("Broadcast notification was sent to all players.")

    def stop(self):
        logger.info("Game: %s with %d players is stopping...", self.id, self.name)

        if self.status == GAME_STATUSES.FINISHED:
            raise GameAlreadyFinishedException()

        if self.red_team_points >= self.points_limit or self.blue_team_points >= self.points_limit:
            logger.info("Game was finished!")
            if self.red_team_points >= self.points_limit:
                logger.info("Red team win! %d : %d", self.red_team_points, self.blue_base)
            else:
                logger.info("Blue team win! %d : %d", self.blue_base, self.red_team_points)

        self.status = GAME_STATUSES.FINISHED
        self.save()
        self.players.update(team=None)

        # sending broadcast notification to all players
        logger.info("Sending broadcast notification to all players...")
        Notification(NOTIFICATION_TYPE.STOP_GAME, self.players).send()
        logger.info("Broadcast notification was sent to all players.")

    def _get_item(self, item_type):
        items = filter(lambda item: item.type == item_type, self.items.all())
        return items[0] if items else None

    def __unicode__(self):
        return "%s" % self.name

    class Meta:
        app_label = "ctf"


text:
/**
 * DownloadCampaignsByAccountIdsResponse.java
 * <p>
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.microsoft.bingads.v10.campaignmanagement;

public class DownloadCampaignsByAccountIdsResponse implements java.io.Serializable {
  // Type metadata
  private static org.apache.axis.description.TypeDesc typeDesc =
          new org.apache.axis.description.TypeDesc(DownloadCampaignsByAccountIdsResponse.class, true);

  static {
    typeDesc.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v10", ">DownloadCampaignsByAccountIdsResponse"));
    org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
    elemField.setFieldName("downloadRequestId");
    elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v10", "DownloadRequestId"));
    elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
    elemField.setMinOccurs(0);
    elemField.setNillable(true);
    typeDesc.addFieldDesc(elemField);
  }

  private java.lang.String downloadRequestId;
  private java.lang.Object __equalsCalc = null;
  private boolean __hashCodeCalc = false;

  public DownloadCampaignsByAccountIdsResponse() {
  }

  public DownloadCampaignsByAccountIdsResponse(
          java.lang.String downloadRequestId) {
    this.downloadRequestId = downloadRequestId;
  }

  /**
   * Return type metadata object
   */
  public static org.apache.axis.description.TypeDesc getTypeDesc() {
    return typeDesc;
  }

  /**
   * Get Custom Serializer
   */
  public static org.apache.axis.encoding.Serializer getSerializer(
          java.lang.String mechType,
          java.lang.Class _javaType,
          javax.xml.namespace.QName _xmlType) {
    return
            new org.apache.axis.encoding.ser.BeanSerializer(
                    _javaType, _xmlType, typeDesc);
  }

  /**
   * Get Custom Deserializer
   */
  public static org.apache.axis.encoding.Deserializer getDeserializer(
          java.lang.String mechType,
          java.lang.Class _javaType,
          javax.xml.namespace.QName _xmlType) {
    return
            new org.apache.axis.encoding.ser.BeanDeserializer(
                    _javaType, _xmlType, typeDesc);
  }

  /**
   * Gets the downloadRequestId value for this DownloadCampaignsByAccountIdsResponse.
   *
   * @return downloadRequestId
   */
  public java.lang.String getDownloadRequestId() {
    return downloadRequestId;
  }

  /**
   * Sets the downloadRequestId value for this DownloadCampaignsByAccountIdsResponse.
   *
   * @param downloadRequestId
   */
  public void setDownloadRequestId(java.lang.String downloadRequestId) {
    this.downloadRequestId = downloadRequestId;
  }

  public synchronized boolean equals(java.lang.Object obj) {
    if (!(obj instanceof DownloadCampaignsByAccountIdsResponse)) return false;
    DownloadCampaignsByAccountIdsResponse other = (DownloadCampaignsByAccountIdsResponse) obj;
    if (obj == null) return false;
    if (this == obj) return true;
    if (__equalsCalc != null) {
      return (__equalsCalc == obj);
    }
    __equalsCalc = obj;
    boolean _equals;
    _equals = true &&
            ((this.downloadRequestId == null && other.getDownloadRequestId() == null) ||
                    (this.downloadRequestId != null &&
                            this.downloadRequestId.equals(other.getDownloadRequestId())));
    __equalsCalc = null;
    return _equals;
  }

  public synchronized int hashCode() {
    if (__hashCodeCalc) {
      return 0;
    }
    __hashCodeCalc = true;
    int _hashCode = 1;
    if (getDownloadRequestId() != null) {
      _hashCode += getDownloadRequestId().hashCode();
    }
    __hashCodeCalc = false;
    return _hashCode;
  }

}


text:
namespace segmentation_platform {

// A delegate class that handles recording of the selected segmentation groups
// to metrics.
class FieldTrialRegister {
 public:
  FieldTrialRegister() = default;
  virtual ~FieldTrialRegister() = default;

  FieldTrialRegister(FieldTrialRegister&) = delete;
  FieldTrialRegister& operator=(FieldTrialRegister&) = delete;

  // Records that the current session uses `trial_name` and `group_name` as
  // segmentation groups. Calling multiple times with same `trial_name`
  // will replace the existing group with the new one, but note that the
  // previous logs already closed / staged for upload will not be changed.
  virtual void RegisterFieldTrial(base::StringPiece trial_name,
                                  base::StringPiece group_name) = 0;

  // Registers subsegments based on the `subsegment_rank` of the segment when
  // the subsegment mapping was provided by the segment. The `subsegment_rank`
  // should be computed based on the subsegment discrete mapping in the model
  // metadata.
  virtual void RegisterSubsegmentFieldTrialIfNeeded(
      base::StringPiece trial_name,
      proto::SegmentId segment_id,
      int subsegment_rank) = 0;
};

}  // namespace segmentation_platform

#endif  // COMPONENTS_SEGMENTATION_PLATFORM_PUBLIC_FIELD_TRIAL_REGISTER_H_


text:
package org.innovateuk.ifs.management.competition.setup.projectdocument.form;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.validation.constraints.Size;
import org.innovateuk.ifs.controller.BaseBindingResultTarget;

import javax.validation.constraints.NotBlank;

/**
 * Form to capture the details of the new project document
 */
public class ProjectDocumentForm extends BaseBindingResultTarget {

    private Long projectDocumentId;

    @NotBlank(message = "{validation.standard.title.required}")
    private String title;

    @Size(max = 5000, message = "{validation.field.too.many.characters}")
    @NotBlank(message = "{validation.documentform.guidance.required}")
    private String guidance;

    private boolean editable;
    private boolean enabled;
    private boolean pdf;
    private boolean spreadsheet;
    // Added for binding errors, unsaved
    private String acceptedFileTypesId;

    // for spring form binding
    public ProjectDocumentForm() {
    }

    public ProjectDocumentForm(boolean editable, boolean enabled) {
        this.editable = editable;
        this.enabled = enabled;
    }

    public ProjectDocumentForm(Long projectDocumentId, String title, String guidance, boolean editable, boolean enabled) {
        this.projectDocumentId = projectDocumentId;
        this.title = title;
        this.guidance = guidance;
        this.editable = editable;
        this.enabled = enabled;
    }

    public Long getProjectDocumentId() {
        return projectDocumentId;
    }

    public void setProjectDocumentId(Long projectDocumentId) {
        this.projectDocumentId = projectDocumentId;
    }

    public String getTitle() {
        return title;
    }

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

    public String getGuidance() {
        return guidance;
    }

    public void setGuidance(String guidance) {
        this.guidance = guidance;
    }

    public boolean isEditable() {
        return editable;
    }

    public void setEditable(boolean editable) {
        this.editable = editable;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isPdf() {
        return pdf;
    }

    public void setPdf(boolean pdf) {
        this.pdf = pdf;
    }

    public boolean isSpreadsheet() {
        return spreadsheet;
    }

    public void setSpreadsheet(boolean spreadsheet) {
        this.spreadsheet = spreadsheet;
    }

    public String getAcceptedFileTypesId() { return acceptedFileTypesId; }

    public void setAcceptedFileTypesId(String acceptedFileTypesId) {
        this.acceptedFileTypesId = acceptedFileTypesId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        ProjectDocumentForm that = (ProjectDocumentForm) o;

        return new EqualsBuilder()
                .append(editable, that.editable)
                .append(enabled, that.enabled)
                .append(pdf, that.pdf)
                .append(spreadsheet, that.spreadsheet)
                .append(projectDocumentId, that.projectDocumentId)
                .append(title, that.title)
                .append(guidance, that.guidance)
                .append(acceptedFileTypesId, that.acceptedFileTypesId)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(projectDocumentId)
                .append(title)
                .append(guidance)
                .append(editable)
                .append(enabled)
                .append(pdf)
                .append(spreadsheet)
                .append(acceptedFileTypesId)
                .toHashCode();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.deidentifier.arx.ARXLattice (ARX Developer Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.deidentifier.arx.ARXLattice

Packages that use ARXLattice

Package
Description

org.deidentifier.arx

This package provides the public API for the ARX anonymization framework.

Uses of ARXLattice in org.deidentifier.arx

Methods in org.deidentifier.arx that return ARXLattice

Modifier and Type
Method and Description

ARXLattice
ARXResult.getLattice()

Returns the lattice.

Constructors in org.deidentifier.arx with parameters of type ARXLattice

Constructor and Description

ARXLattice.Access(ARXLattice lattice)

ARXResult(DataHandle handle,
         DataDefinition definition,
         ARXLattice lattice,
         int historySize,
         double snapshotSizeSnapshot,
         double snapshotSizeDataset,
         Metric<?> metric,
         ARXConfiguration config,
         ARXLattice.ARXNode optimum,
         long time)

Internal constructor for deserialization.

ARXResult(org.deidentifier.arx.DataRegistry registry,
         DataManager manager,
         INodeChecker checker,
         DataDefinition definition,
         ARXConfiguration config,
         ARXLattice lattice,
         long duration)

Creates a new instance.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes