text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;
using Amazon.Lambda.TestUtilities;
using Kralizek.Lambda;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;

namespace Tests.Lambda.Sqs;

[TestFixture]
public class ParallelSqsEventHandlerTests
{
    private Mock<IMessageSerializer> _mockMessageSerializer;
    private Mock<IMessageHandler<TestMessage>> _mockMessageHandler;
    private Mock<IServiceScopeFactory> _mockServiceScopeFactory;
    private Mock<IServiceProvider> _mockServiceProvider;
    private Mock<ILoggerFactory> _mockLoggerFactory;
    private Mock<IServiceScope> _mockServiceScope;
    private ParallelSqsExecutionOptions _parallelExecutionOptions;

    [SetUp]
    public void Initialize()
    {
        _mockMessageSerializer = new Mock<IMessageSerializer>();

        _mockMessageSerializer
            .Setup(p => p.Deserialize<TestMessage>(It.IsAny<string>()))
            .Returns(() => new TestMessage());

        _mockMessageHandler = new Mock<IMessageHandler<TestMessage>>();
        _mockMessageHandler.Setup(p => p.HandleAsync(It.IsAny<TestMessage>(), It.IsAny<ILambdaContext>())).Returns(Task.CompletedTask);

        _mockServiceScope = new Mock<IServiceScope>();

        _mockServiceScopeFactory = new Mock<IServiceScopeFactory>();

        _mockServiceScopeFactory.Setup(p => p.CreateScope()).Returns(_mockServiceScope.Object);

        _mockServiceProvider = new Mock<IServiceProvider>();
        _mockServiceProvider.Setup(p => p.GetService(typeof(IMessageHandler<TestMessage>)))
            .Returns(_mockMessageHandler.Object);
        _mockServiceProvider.Setup(p => p.GetService(typeof(IServiceScopeFactory)))
            .Returns(_mockServiceScopeFactory.Object);

        _mockServiceProvider
            .Setup(p => p.GetService(typeof(IMessageSerializer)))
            .Returns(_mockMessageSerializer.Object);

        _mockServiceScope.Setup(p => p.ServiceProvider).Returns(_mockServiceProvider.Object);

        _mockLoggerFactory = new Mock<ILoggerFactory>();
        _mockLoggerFactory.Setup(p => p.CreateLogger(It.IsAny<string>()))
            .Returns(Mock.Of<ILogger>());

        _parallelExecutionOptions = new ParallelSqsExecutionOptions { MaxDegreeOfParallelism = 4 };
    }

    private ParallelSqsEventHandler<TestMessage> CreateSystemUnderTest()
    {
        return new ParallelSqsEventHandler<TestMessage>(_mockServiceProvider.Object, _mockLoggerFactory.Object, Options.Create(_parallelExecutionOptions));
    }

    [Test]
    public async Task HandleAsync_resolves_MessageHandler_for_each_record()
    {
        var sqsEvent = new SQSEvent
        {
            Records = new List<SQSEvent.SQSMessage>
            {
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
            }
        };

        var lambdaContext = new TestLambdaContext();

        var sut = CreateSystemUnderTest();

        await sut.HandleAsync(sqsEvent, lambdaContext);

        _mockServiceProvider.Verify(p => p.GetService(typeof(IMessageHandler<TestMessage>)), Times.Exactly(sqsEvent.Records.Count));
    }

    [Test]
    public async Task HandleAsync_creates_a_scope_for_each_record()
    {
        var sqsEvent = new SQSEvent
        {
            Records = new List<SQSEvent.SQSMessage>
            {
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
            }
        };

        var lambdaContext = new TestLambdaContext();

        var sut = CreateSystemUnderTest();

        await sut.HandleAsync(sqsEvent, lambdaContext);

        _mockServiceScopeFactory.Verify(p => p.CreateScope(), Times.Exactly(sqsEvent.Records.Count));
    }

    [Test]
    public void HandleAsync_throws_InvalidOperation_if_NotificationHandler_is_not_registered()
    {
        var sqsEvent = new SQSEvent
        {
            Records = new List<SQSEvent.SQSMessage>
            {
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
            }
        };

        var lambdaContext = new TestLambdaContext();

        _mockServiceProvider = new Mock<IServiceProvider>();
        _mockServiceProvider.Setup(p => p.GetService(typeof(IServiceScopeFactory))).Returns(_mockServiceScopeFactory.Object);

        _mockServiceScope.Setup(p => p.ServiceProvider).Returns(_mockServiceProvider.Object);

        var sut = CreateSystemUnderTest();

        Assert.ThrowsAsync<InvalidOperationException>(() => sut.HandleAsync(sqsEvent, lambdaContext));
    }

    [Test]
    public async Task MaxDegreeOfParallelism_Should_ProperlyPropagated()
    {
        var sqsEvent = new SQSEvent
        {
            Records = new List<SQSEvent.SQSMessage>
            {
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
            }
        };

        var cq = new ConcurrentQueue<Task>();

        _parallelExecutionOptions = new ParallelSqsExecutionOptions {MaxDegreeOfParallelism = 2};
        _mockMessageHandler.Setup(p => p.HandleAsync(It.IsAny<TestMessage>(), It.IsAny<ILambdaContext>()))
            .Returns(async ()=>
            {
                var t = Task.Delay(1);
                cq.Enqueue(t);
                if (cq.Count > 2)
                {
                    throw new Exception("not good");
                }
                await t;
                cq.TryDequeue(out t);
            });

        var sut = CreateSystemUnderTest();

        await sut.HandleAsync(sqsEvent, new TestLambdaContext());

        _mockMessageHandler.VerifyAll();
        _mockMessageHandler.Verify(
            handler => handler.HandleAsync(It.IsAny<TestMessage>(), It.IsAny<ILambdaContext>()),
            Times.Exactly(sqsEvent.Records.Count));
    }

    [Test]
    public void MaxDegreeOfParallelism_Should_ProperlyPropagated_And_Limited_To_Set_Max()
    {
        var sqsEvent = new SQSEvent
        {
            Records = new List<SQSEvent.SQSMessage>
            {
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
                new SQSEvent.SQSMessage
                {
                    Body = "{}"
                },
            }
        };

        var cq = new ConcurrentQueue<Task>();

        //We are checking if parallelism actually does what it's supposed to do. So we should have more then 2 concurrent processes running
        _parallelExecutionOptions = new ParallelSqsExecutionOptions { MaxDegreeOfParallelism = 4 };
        _mockMessageHandler.Setup(p => p.HandleAsync(It.IsAny<TestMessage>(), It.IsAny<ILambdaContext>()))
            .Returns(async () =>
            {
                var t = Task.Delay(1);
                cq.Enqueue(t);
                Console.WriteLine(cq.Count);
                if (cq.Count > 2)
                {
                    throw new Exception("Concurrent Tasks exceeded 2");
                }
                await t;
                cq.TryDequeue(out t);
            });

        var sut = CreateSystemUnderTest();

        Assert.ThrowsAsync<Exception>(() => sut.HandleAsync(sqsEvent, new TestLambdaContext()));
    }
}


text:
using Newtonsoft.Json.Linq;

namespace Orchard.Recipes.Models
{
    public class RecipeExecutionStepConfigurationContext : ConfigurationContext
    {
        public RecipeExecutionStepConfigurationContext(JObject configurationElement) : base(configurationElement)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Multiple Slider Widgets
~~~~~~~~~~~~~~~~~~~~~~~

Use a class based callback to track multiple slider widgets for updating a
single mesh.

In this example we simply change a few parameters for the
:func:`pyvista.Sphere` method, but this could easily be applied to any
mesh-generating/altering code.

"""
import pyvista as pv

class MyCustomRoutine():
    def __init__(self, mesh):
        self.output = mesh # Expected PyVista mesh type
        # default parameters
        self.kwargs = {
            'radius': 0.5,
            'theta_resolution': 30,
            'phi_resolution': 30,
        }

    def __call__(self, param, value):
        self.kwargs[param] = value
        self.update()

    def update(self):
        # This is where you call your simulation
        result = pv.Sphere(**self.kwargs)
        self.output.overwrite(result)
        return

###############################################################################

starting_mesh = pv.Sphere()
engine = MyCustomRoutine(starting_mesh)

###############################################################################

p = pv.Plotter()
p.add_mesh(starting_mesh, show_edges=True)
p.add_slider_widget(
    callback=lambda value: engine('phi_resolution', int(value)),
    rng=[3, 60],
    value=30,
    title="Phi Resolution",
    pointa=(.025, .1), pointb=(.31, .1),
    style='modern',
)
p.add_slider_widget(
    callback=lambda value: engine('theta_resolution', int(value)),
    rng=[3, 60],
    value=30,
    title="Theta Resolution",
    pointa=(.35, .1), pointb=(.64, .1),
    style='modern',
)
p.add_slider_widget(
    callback=lambda value: engine('radius', value),
    rng=[0.1, 1.5],
    value=0.5,
    title="Radius",
    pointa=(.67, .1), pointb=(.98, .1),
    style='modern',
)
p.show()


text:
#pragma once
#ifndef GWEN_TOOLTIP_H
#define GWEN_TOOLTIP_H

#include <Gwen/Controls/Base.h>
#include <Gwen/Gwen.h>
#include <Gwen/Skin.h>

using namespace Gwen;
using namespace Gwen::Controls;

namespace ToolTip {
GWEN_EXPORT bool TooltipActive();

GWEN_EXPORT void Enable(Controls::Base *pControl);
GWEN_EXPORT void Disable(Controls::Base *pControl);

GWEN_EXPORT void ControlDeleted(Controls::Base *pControl);

GWEN_EXPORT void RenderToolTip(Skin::Base *skin);
}

#endif


text:
package com.fly.firefly.ui.module;

import com.fly.firefly.AppModule;
import com.fly.firefly.ui.activity.BookingFlight.ItinenaryFragment;
import com.fly.firefly.ui.activity.Login.LoginFragment;
import com.fly.firefly.ui.presenter.BookingPresenter;
import com.fly.firefly.ui.presenter.LoginPresenter;
import com.squareup.otto.Bus;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module(
        injects = ItinenaryFragment.class,
        addsTo = AppModule.class,
        complete = false
)
public class ItinenaryModule {

    private final BookingPresenter.ItinenaryView loginView;

    public ItinenaryModule(BookingPresenter.ItinenaryView loginView) {
        this.loginView = loginView;
    }

    @Provides
    @Singleton
    BookingPresenter provideLoginPresenter(Bus bus) {
        return new BookingPresenter(loginView, bus);
    }
}


text:
/**
 * @file vga_commands.h VGA library commands definitions
 */

#ifndef _VGA_COMMANDS_H_
#define _VGA_COMMANDS_H_

#ifdef __cplusplus
extern "C" {
#endif

/** VGA driver commands */
enum EVgaCommands
{
    /**
     * VGA_SET_BLOCK command sets rectangle in VGA ram to send pixels to.
     * The command needs 4 byte-arguments:
     *    left boundary in pixels,
     *    right boundary in pixels,
     *    top boundary in pixels,
     *    bottom boundary in pixels, (last arg in not implemented yet)
     */
    VGA_SET_BLOCK       = 0x01,

    /**
     * VGA_SET_MODE command sets memory addressing mode: there are 2 modes
     * available: 0 - normal addressing mode, 1 - ssd1306 compatible mode.
     * After sending each pixel in normal addressing mode, x position shifts
     * right by 1 pixel until end of block is reached, then y position shifts
     * down by 1 pixel, and x position move to the start of block.
     * After sending each pixel in ssd1306 compatible mode, y position shifts
     * down by 1 pixel until 8 vertical pixels are printed, then y position changes
     * to top of block, and x position shifts right by 1 pixel.
     */
    VGA_SET_MODE        = 0x02,

    VGA_SET_RESOLUTION  = 0x03,

    VGA_DISPLAY_ON      = 0x04,
};

#ifdef __cplusplus
}
#endif

// ----------------------------------------------------------------------------
#endif


text:
package com.github.britter.bootifytestpyramid.web;

import com.github.britter.bootifytestpyramid.domain.OrderGateway;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Optional;

import static com.github.britter.bootifytestpyramid.domain.OrderTemplates.bigOrder;
import static com.github.britter.bootifytestpyramid.domain.OrderTemplates.completeKitchen;
import static com.github.britter.bootifytestpyramid.domain.OrderTemplates.smallOrder;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.endsWith;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(SpringExtension.class)
@WebMvcTest(OrderController.class)
class OrderControllerIT {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private OrderGateway orderGateway;

    @Nested
    class GetAll {

        @Test
        void should_return_all_orders() throws Exception {
            given(orderGateway.findAll()).willReturn(
                    asList(smallOrder(), completeKitchen())
            );

            mvc.perform(get("/orders"))
                    .andExpect(status().isOk())
                    .andExpect(OrderResponseMatchers.smallOrderFieldsAtIndex(0))
                    .andExpect(OrderResponseMatchers.completeKitchenFieldsAtIndex(1));
        }
    }

    @Nested
    class GetByCity {

        @Test
        void should_return_all_orders() throws Exception {
            given(orderGateway.findByCity(anyString())).willReturn(
                    asList(smallOrder(), completeKitchen())
            );

            mvc.perform(get("/orders?city=Newton"))
                    .andExpect(status().isOk())
                    .andExpect(OrderResponseMatchers.smallOrderFieldsAtIndex(0))
                    .andExpect(OrderResponseMatchers.completeKitchenFieldsAtIndex(1));
        }

        @Test
        void should_return_query_for_city() throws Exception {
            mvc.perform(get("/orders?city=Newton"));

            verify(orderGateway).findByCity("Newton");
        }
    }

    @Nested
    class GetOne {

        @Test
        void should_return_order_by_id() throws Exception {
            given(orderGateway.findById(anyLong())).willReturn(Optional.of(bigOrder()));

            mvc.perform(get("/orders/15"))
                    .andExpect(status().isOk())
                    .andExpect(OrderResponseMatchers.bigOrderFields());
        }

        @Test
        void should_return_not_found_when_order_is_not_found() throws Exception {
            given(orderGateway.findById(anyLong())).willReturn(Optional.empty());

            mvc.perform(get("/orders/15"))
                    .andExpect(status().isNotFound());
        }
    }

    @Nested
    class Create {

        @Nested
        class Creation {

            @Autowired
            @Value("classpath:com/github/britter/bootifytestpyramid/web/create-order-request.json")
            private Resource createOrderRequest;

            @Test
            void should_return_location() throws Exception {
                given(orderGateway.createOrder(any())).willReturn(smallOrder());

                mvc.perform(post("/orders")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(IOUtils.toByteArray(createOrderRequest.getURI())))
                        .andExpect(status().isCreated())
                        .andExpect(header().string("location", endsWith("/orders/1")));
            }

        }

        @Nested
        class Validation {

            @Test
            void should_reject_create_order_request_when_address_is_missing() throws Exception {
                mvc.perform(post("/orders")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(
                                "{\n" +
                                        "  \"items\": [\n" +
                                        "    {\n" +
                                        "      \"name\": \"Couch\",\n" +
                                        "      \"description\": \"A cozzy couch\",\n" +
                                        "      \"weight\": 20.0,\n" +
                                        "      \"price\": 19.99,\n" +
                                        "      \"quantity\": 1\n" +
                                        "    }\n" +
                                        "  ]\n" +
                                        "}"
                        ))
                        .andExpect(status().isBadRequest());
            }

            @Test
            void should_reject_create_order_request_when_weight_is_negative() throws Exception {
                mvc.perform(post("/orders")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(
                                "{\n" +
                                        "  \"deliveryAddress\": {\n" +
                                        "    \"firstName\": \"John\",\n" +
                                        "    \"lastName\": \"Doe\",\n" +
                                        "    \"street\": \"Mainstreet 15\",\n" +
                                        "    \"zip\": \"64782\",\n" +
                                        "    \"city\": \"Newton\"\n" +
                                        "  },\n" +
                                        "  \"items\": [\n" +
                                        "    {\n" +
                                        "      \"name\": \"Couch\",\n" +
                                        "      \"description\": \"A cozzy couch\",\n" +
                                        "      \"weight\": -20.0,\n" +
                                        "      \"price\": 19.99,\n" +
                                        "      \"quantity\": 1\n" +
                                        "    }\n" +
                                        "  ]\n" +
                                        "}"
                        ))
                        .andExpect(status().isBadRequest());
            }

            @Test
            void should_reject_create_order_request_when_price_is_negative() throws Exception {
                mvc.perform(post("/orders")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(
                                "{\n" +
                                        "  \"deliveryAddress\": {\n" +
                                        "    \"firstName\": \"John\",\n" +
                                        "    \"lastName\": \"Doe\",\n" +
                                        "    \"street\": \"Mainstreet 15\",\n" +
                                        "    \"zip\": \"64782\",\n" +
                                        "    \"city\": \"Newton\"\n" +
                                        "  },\n" +
                                        "  \"items\": [\n" +
                                        "    {\n" +
                                        "      \"name\": \"Couch\",\n" +
                                        "      \"description\": \"A cozzy couch\",\n" +
                                        "      \"weight\": 20.0,\n" +
                                        "      \"price\": -19.99,\n" +
                                        "      \"quantity\": 1\n" +
                                        "    }\n" +
                                        "  ]\n" +
                                        "}"
                        ))
                        .andExpect(status().isBadRequest());
            }

            @Test
            void should_reject_create_order_request_when_quantity_is_negative() throws Exception {
                mvc.perform(post("/orders")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(
                                "{\n" +
                                        "  \"deliveryAddress\": {\n" +
                                        "    \"firstName\": \"John\",\n" +
                                        "    \"lastName\": \"Doe\",\n" +
                                        "    \"street\": \"Mainstreet 15\",\n" +
                                        "    \"zip\": \"64782\",\n" +
                                        "    \"city\": \"Newton\"\n" +
                                        "  },\n" +
                                        "  \"items\": [\n" +
                                        "    {\n" +
                                        "      \"name\": \"Couch\",\n" +
                                        "      \"description\": \"A cozzy couch\",\n" +
                                        "      \"weight\": 20.0,\n" +
                                        "      \"price\": 19.99,\n" +
                                        "      \"quantity\": -1\n" +
                                        "    }\n" +
                                        "  ]\n" +
                                        "}"
                        ))
                        .andExpect(status().isBadRequest());
            }
        }
    }
}


text:
<?php

namespace frontend\controllers;

use frontend\models\Author;
use frontend\models\BookSearch;
use traits\Access;
use Yii;
use frontend\models\Book;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use yii\helpers\Utils;

/**
 * BookController implements the CRUD actions for Book model.
 */
class BookController extends Controller
{
    public function behaviors()
    {
       return Access::onlyAuthUsers();
    }

    /**
     * Lists all Book models.
     * @return mixed
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->queryParams;
        $params = Utils::rememberSearchModel($params, 'BookSearch');

        $searchModel = new BookSearch();
        $dataProvider = $searchModel->search($params);
        $authors = $this->getAuthors();

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel'  => $searchModel,
            'authors' => $authors,
        ]);
    }

    /**
     * Displays a single Book model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Book model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Book();
        $image = UploadedFile::getInstance($model, 'preview');
        $request = Yii::$app->request;

        if ($model->load($request->post()) && $model->save()) {
            $model->upload($image);
            return $this->redirect('index');
        } else {
            $data = [
                'model' => $model,
                'authors' => $this->getAuthors(),
            ];

            if ($request->isAjax) {
                return $this->renderAjax('create', $data );
            }

            return $this->render('create', $data);
        }
    }

    /**
     * Updates an existing Book model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $image = UploadedFile::getInstance($model, 'preview');

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->upload($image);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'authors' => $this->getAuthors(),
            ]);
        }
    }

    /**
     * Deletes an existing Book model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Book model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Book the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Book::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Метод получения всех авторов
     * @return array
     */
    protected function getAuthors() {
        /** @var Author[] $models */
        $models = Author::find()->all();
        $records = [];

        if ($models) {
            foreach ($models as $model) {
               $records[$model->id] = $model->getFullName();
            }
        }
        return $records;

    }
}


text:
package org.hoteia.cas.security;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

public class SpringSecurityPasswordEncoder implements org.jasig.cas.authentication.handler.PasswordEncoder {
    private final PasswordEncoder encoder;

    public SpringSecurityPasswordEncoder() {
        encoder = new StandardPasswordEncoder();
    }

    @Override
    public String encode(String password) {
        return encoder.encode(password);
    }

    public PasswordEncoder getEncoder() {
        return encoder;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WatchOnlyBitcoinWallet.Views
{
    /// <summary>
    /// Interaction logic for ForkBalanceWindow.xaml
    /// </summary>
    public partial class ForkBalanceWindow : Window
    {
        public ForkBalanceWindow()
        {
            InitializeComponent();
        }
    }
}


text:
package io.sweetheart.examples.pis.classesAndObjects

import ChecksumAccumulator.calculate

object Summer {

  def main(args: Array[String]) = {
    for (arg <- args)
      println(arg + ": " + calculate(arg))
  }
}


text:
package br.gov.siscomex.portalunico.edocex.model;

import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "RetornoAnexarDocumento", propOrder =
    { "idDocumento"
})

@XmlRootElement(name="RetornoAnexarDocumento")
/**
  * Retorno do serviço de anexar documento.
 **/
@ApiModel(description="Retorno do serviço de anexar documento.")
public class RetornoAnexarDocumento  {

  @XmlElement(name="idDocumento", required = true)
  @ApiModelProperty(example = "4456487453", required = true, value = "Id do documento.
Valor mínimo: 1
Valor máximo: 9223372036854775807")
 /**
   * Id do documento.
Valor mínimo: 1
Valor máximo: 9223372036854775807
  **/
  private Long idDocumento = null;
 /**
   * Id do documento.<br/>Valor mínimo: 1<br/>Valor máximo: 9223372036854775807
   * @return idDocumento
  **/
  @JsonProperty("idDocumento")
  @NotNull
  public Long getIdDocumento() {
    return idDocumento;
  }

  public void setIdDocumento(Long idDocumento) {
    this.idDocumento = idDocumento;
  }

  public RetornoAnexarDocumento idDocumento(Long idDocumento) {
    this.idDocumento = idDocumento;
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class RetornoAnexarDocumento {\n");

    sb.append("    idDocumento: ").append(toIndentedString(idDocumento)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
import _ from "lodash"
import toastr from "toastr";
import {Book, CacheableResource, Entity, HadithTag, Person, User} from "resources/resources";
import {ILocationService, IScope} from "angular";
import angular from "angular"
import { getApp } from "../app-def";

declare function getHtmlBasePath(): string;

export class SelectorCtrl {
  public addingEntitiesEnabled:string;
  public ids:number|number[];
  public entities:any;
  public type:string;
  public singleSelect:string;
  public textOnly:string;
  public clickable:string;
  public clickCallback:any;
  public firstLoad = true;
  public query:string;
  private EntityResource:CacheableResource<Entity<number>, number>;

  constructor(private $scope:IScope,
              private $location:ILocationService,
              private PersonResource:CacheableResource<Person, number>,
              private BookResource:CacheableResource<Book, number>,
              private HadithTagResource:CacheableResource<HadithTag, number>,
              private UserResource:CacheableResource<User, number>) {

    if (!this.ids) {
      if (this.singleSelect) {
        this.ids = null;
      } else {
        this.ids = [];
      }
    }

    if (!this.entities) {
      this.entities = [];
    }

    if (!this.textOnly) {
      this.textOnly = 'false';
    }

    if (!this.clickable) {
      this.clickable = 'false';
    }

    if (!this.addingEntitiesEnabled) {
      this.addingEntitiesEnabled = 'false';
    }

    if (!this.type || typeof(this.type) !== 'string') {
      throw 'Selector must have its type attribute set to a string.';
    }

    switch (this.type.toLowerCase()) {
      case 'person':
        this.EntityResource = PersonResource;
        break;

      case 'book':
        this.EntityResource = BookResource;
        break;

      case 'hadithtag':
        this.EntityResource = HadithTagResource;
        break;

      case 'user':
        this.EntityResource = UserResource;
        break;

      default:
        throw 'Invalid type for selector.';
    }

    $scope.$watchCollection('ctrl.ids', this.onIdsChanged);
    $scope.$watchCollection('ctrl.entities', this.onEntitiesChanged);
  }

  public onClick(entity) {
    if (this.clickCallback) {
      this.clickCallback({entity: entity});
    } else {
      this.$location.path(`${this.type}/${entity.id}`);
    }
  }

  public findEntities(query) {
    return this.EntityResource.query({search: query});
  }

  public createEntity(query) {
    switch (this.type.toLowerCase()) {
      case 'hadithtag':
        let entity = this.HadithTagResource.create();
        entity.name = query;
        entity.save().then(() => {
          this.entities.push(entity);
          this.query = '';
        }, (result) => {
          // TODO: This code is duplicated. Once we work on issue 86, we can create a helper function in
          // ToastService and use it here. Issue link:
          // https://github.com/hadithhouse/hadithhouse/issues/86
          if (result.data && result.data.detail) {
            toastr.error('Failed to delete entity. Error was: ' + result.data.detail);
          } else if (result.data) {
            toastr.error('Failed to delete entity. Error was: ' + result.data);
          } else {
            toastr.error('Failed to delete entity. Please try again!');
          }
        });
        break;

      case 'person':
      case 'book':
      case 'user':
        throw 'Not implemented yet.';

      default:
        throw 'Unreachable code.';
    }
  }

  public entityToString(entity) {
    return entity.toString();
  }

  private onIdsChanged = (newValue, oldValue) => {
    if (newValue && this.firstLoad) {
      // An ID(s) was(were) passed to the selector and this.entities have not
      // been set yet, so we set it.
      this.firstLoad = false;
    } else {
      // The selector has already been loaded, so we just check whether we have
      // changes in the ID that we need to refresh
      if (angular.equals(newValue, oldValue)) {
        return;
      }
    }
    if (this.singleSelect === 'true') {
      if (this.ids !== null) {
        this.entities = [<number>this.ids].map((id) => {
          // See if we already have the entity loaded, otherwise make a request to load it.
          return _.find<Entity<number>>(this.entities, (e) => {
              return e.id === id;
            }) || this.EntityResource.get(id);
        });
      } else {
        this.entities = [];
      }
    } else {
      this.entities = (<number[]>this.ids).map((id) => {
        // See if we already have the entity loaded, otherwise make a request to load it.
        return _.find<Entity<number>>(this.entities, (e) => {
            return e.id === id;
          }) || this.EntityResource.get(id);
      });
    }
  };

  private onEntitiesChanged = (newValue, oldValue) => {
    if (newValue && oldValue && angular.equals(newValue, oldValue)) {
      return;
    }
    if (this.entities) {
      // If the control only allows single select, we remove every elements
      // before the last.
      if (this.singleSelect === 'true') {
        // Single select mode, so only allow one entity to be selected and delete previous ones.
        if (this.entities.length > 1) {
          this.entities.splice(0, this.entities.length - 1);
        }
        if (this.entities.length === 1) {
          // Ensure that the resource has been resolved before updating the scope's ID
          if (typeof(this.entities[0].id) === 'number') {
            this.ids = this.entities[0].id;
          }
        } else {
          this.ids = null;
        }
      } else {
        if (_.every(this.entities, (e:any) => {
            return typeof(e.id) === 'number';
          })) {
          this.ids = this.entities.map((entity) => {
            return entity.id;
          });
        }
      }
    }
  };
}

getApp().controller('SelectorCtrl',
  ['$scope', '$location', 'PersonResource', 'BookResource', 'HadithTagResource', 'UserResource',
    SelectorCtrl]);

// TODO: Consider creating a class for this.
getApp().directive('hhSelector', function () {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: getHtmlBasePath() + 'directives/selector.directive.html',
    controller: 'SelectorCtrl',
    controllerAs: 'ctrl',
    bindToController: true,
    scope: {
      addingEntitiesEnabled: '@',
      clickCallback: '&?',
      clickable: '@',
      ids: '=',
      readOnly: '=',
      singleSelect: '@',
      textOnly: '@',
      type: '@'
    }
  };
});


text:
pylearning
==========

A python machine learning lib. Currently for practice only.


text:
{% load static %}
{#Example Framework Header#}
{%  if SETTINGS.DEBUG %}
    {%  for sheet in SETTINGS.STYLE_SHEETS %}
    <link rel="stylesheet" href="{% get_static_prefix %}css/{{ sheet }}" type="text/css" media="all" />
    {%  endfor %}
    {%  for less in SETTINGS.LESS_SHEETS %}
    <link rel="stylesheet" href="{% get_static_prefix %}less/{{ less }}" type="text/less" media="all" />
    {%  endfor %}
    <script src="{% get_static_prefix %}js/less-1.0.41.min.js" charset="utf-8" type="text/javascript"></script>
{%  else %}
    <link rel='stylesheet' href="Fail.css"/>
    <link rel="stylesheet" href="{% get_static_prefix %}css/limbo.min.css" type="text/css" media="all" />
    <link rel="stylesheet" href="{% get_static_prefix %}css/style.css" type="text/css" media="all" />
{%  endif %}

<script src="{% get_static_prefix %}js/jquery.js" charset="utf-8" type="text/javascript"></script>
<script src="{% get_static_prefix %}js/jquery-ui.min.js" charset="utf-8" type="text/javascript"></script>


text:
static const CGFloat kAnimationDuration = 0.3f;
static const CGFloat kVisibleWidth = 260.0f;

@interface TheSidebarController()

@property (assign, nonatomic) SidebarTransitionStyle selectedTransitionStyle;
@property (assign, nonatomic) Side selectedSide;
@property (strong, nonatomic) UIViewController *selectedSidebarViewController;
@property (strong, nonatomic) NSArray *sidebarAnimations;
@property (strong, nonatomic) UIViewController *contentContainerViewController;
@property (strong, nonatomic) UIViewController *leftSidebarContainerViewController;
@property (strong, nonatomic) UIViewController *rightSidebarContainerViewController;
@property (assign, nonatomic) CATransform3D contentTransform;

- (void)showSidebarViewControllerFromSide:(Side)side withTransitionStyle:(SidebarTransitionStyle)transitionStyle;
- (void)hideSidebarViewController;
- (void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view;

@end

@implementation TheSidebarController

#pragma mark - Designated Initializer
- (id)init
{
    return [self initWithContentViewController:nil leftSidebarViewController:nil rightSidebarViewController:nil];
}

- (id)initWithContentViewController:(UIViewController *)contentViewController leftSidebarViewController:(UIViewController *)leftSidebarViewController
{
    return [self initWithContentViewController:contentViewController leftSidebarViewController:leftSidebarViewController rightSidebarViewController:nil];
}

- (id)initWithContentViewController:(UIViewController *)contentViewController rightSidebarViewController:(UIViewController *)rightSidebarViewController
{
    return [self initWithContentViewController:contentViewController leftSidebarViewController:nil rightSidebarViewController:rightSidebarViewController];
}

- (id)initWithContentViewController:(UIViewController *)contentViewController leftSidebarViewController:(UIViewController *)leftSidebarViewController rightSidebarViewController:(UIViewController *)rightSidebarViewController
{
    self = [super init];

    if(self)
    {
        _contentContainerViewController = [[UIViewController alloc] init];
        _leftSidebarContainerViewController = [[UIViewController alloc] init];
        _rightSidebarContainerViewController = [[UIViewController alloc] init];

        _contentViewController = contentViewController;
        _leftSidebarViewController = leftSidebarViewController;
        _rightSidebarViewController = rightSidebarViewController;

        _animationDuration = kAnimationDuration;
        _visibleWidth = kVisibleWidth;
        _sidebarAnimations = @[SIDEBAR_ANIMATIONS];
        _sidebarIsPresenting = NO;
    }

    return self;
}

#pragma mark - UIViewController Lifecycle
- (void)viewDidLoad
{
    NSAssert(self.contentViewController != nil, @"contentViewController was not set");

    [super viewDidLoad];
    self.view.translatesAutoresizingMaskIntoConstraints = YES;
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    if(self.leftSidebarViewController)
    {
        // Parent View Controller
        [self addChildViewController:self.leftSidebarContainerViewController];
        [self.view addSubview:self.leftSidebarContainerViewController.view];
        [self.leftSidebarContainerViewController didMoveToParentViewController:self];
        self.leftSidebarContainerViewController.view.translatesAutoresizingMaskIntoConstraints = YES;
        self.leftSidebarContainerViewController.view.hidden = YES;

        // Child View Controller
        [self.leftSidebarContainerViewController addChildViewController:self.leftSidebarViewController];
        [self.leftSidebarContainerViewController.view addSubview:self.leftSidebarViewController.view];
        [self.leftSidebarViewController didMoveToParentViewController:self.leftSidebarContainerViewController];
    }

    if(self.rightSidebarViewController)
    {
        // Parent View Controller
        [self addChildViewController:self.rightSidebarContainerViewController];
        [self.view addSubview:self.rightSidebarContainerViewController.view];
        [self.rightSidebarContainerViewController didMoveToParentViewController:self];
        self.rightSidebarContainerViewController.view.translatesAutoresizingMaskIntoConstraints = YES;
        self.rightSidebarContainerViewController.view.hidden = YES;

        // Child View Controller
        [self.rightSidebarContainerViewController addChildViewController:self.rightSidebarViewController];
        [self.rightSidebarContainerViewController.view addSubview:self.rightSidebarViewController.view];
        [self.rightSidebarViewController didMoveToParentViewController:self.rightSidebarContainerViewController];
    }

    // Parent View Controller
    [self addChildViewController:self.contentContainerViewController];
    [self.view addSubview:self.contentContainerViewController.view];
    [self.contentContainerViewController didMoveToParentViewController:self];

    // Child View Controller
    [self.contentContainerViewController addChildViewController:self.contentViewController];
    [self.contentContainerViewController.view addSubview:self.contentViewController.view];
    [self.contentViewController didMoveToParentViewController:self.contentContainerViewController];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - TheSidebarController Presentation Methods
- (void)dismissSidebarViewController
{
    [self hideSidebarViewController];
}

- (void)presentLeftSidebarViewController
{
    [self presentLeftSidebarViewControllerWithStyle:SidebarTransitionStyleFacebook];
}

- (void)presentLeftSidebarViewControllerWithStyle:(SidebarTransitionStyle)transitionStyle
{
    NSAssert(self.leftSidebarViewController != nil, @"leftSidebarViewController was not set");
    [self showSidebarViewControllerFromSide:LeftSide withTransitionStyle:transitionStyle];
}

- (void)presentRightSidebarViewController
{
    [self presentRightSidebarViewControllerWithStyle:SidebarTransitionStyleFacebook];
}

- (void)presentRightSidebarViewControllerWithStyle:(SidebarTransitionStyle)transitionStyle
{
    NSAssert(self.rightSidebarViewController != nil, @"rightSidebarViewController was not set");
    [self showSidebarViewControllerFromSide:RightSide withTransitionStyle:transitionStyle];
}

#pragma mark - TheSidebarController Private Methods
- (void)showSidebarViewControllerFromSide:(Side)side withTransitionStyle:(SidebarTransitionStyle)transitionStyle
{
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    self.view.autoresizingMask = UIViewAutoresizingNone;

    if(side == LeftSide)
    {
        self.leftSidebarContainerViewController.view.hidden = NO;
        self.rightSidebarContainerViewController.view.hidden = YES;
        self.selectedSidebarViewController = self.leftSidebarViewController;
        self.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
    }
    else if(side == RightSide)
    {
        self.rightSidebarContainerViewController.view.hidden = NO;
        self.leftSidebarContainerViewController.view.hidden = YES;
        self.selectedSidebarViewController = self.rightSidebarViewController;
        self.view.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
    }

    self.selectedSide = side;
    self.selectedTransitionStyle = transitionStyle;

    if([self.delegate conformsToProtocol:@protocol(TheSidebarControllerDelegate)] && [self.delegate respondsToSelector:@selector(sidebarController:willShowViewController:)])
    {
        [self.delegate sidebarController:self willShowViewController:self.selectedSidebarViewController];
    }

    NSString *animationClassName = self.sidebarAnimations[transitionStyle];
    Class animationClass = NSClassFromString(animationClassName);
    [animationClass animateContentView:self.contentContainerViewController.view
                           sidebarView:self.selectedSidebarViewController.parentViewController.view
                              fromSide:self.selectedSide
                          visibleWidth:self.visibleWidth
                              duration:self.animationDuration
                            completion:^(BOOL finished) {
                                [[UIApplication sharedApplication] endIgnoringInteractionEvents];
                                self.sidebarIsPresenting = YES;

                                if([self.delegate conformsToProtocol:@protocol(TheSidebarControllerDelegate)] && [self.delegate respondsToSelector:@selector(sidebarController:didShowViewController:)])
                                {
                                    [self.delegate sidebarController:self didShowViewController:self.selectedSidebarViewController];
                                }
                            }
     ];
}

- (void)hideSidebarViewController
{
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];

    if([self.delegate conformsToProtocol:@protocol(TheSidebarControllerDelegate)] && [self.delegate respondsToSelector:@selector(sidebarController:willHideViewController:)])
    {
        [self.delegate sidebarController:self willHideViewController:self.selectedSidebarViewController];
    }

    NSString *animationClassName = self.sidebarAnimations[self.selectedTransitionStyle];
    Class animationClass = NSClassFromString(animationClassName);
    [animationClass reverseAnimateContentView:self.contentContainerViewController.view
                                  sidebarView:self.selectedSidebarViewController.parentViewController.view
                                     fromSide:self.selectedSide
                                 visibleWidth:self.visibleWidth
                                     duration:self.animationDuration
                                   completion:^(BOOL finished) {
                                       [[UIApplication sharedApplication] endIgnoringInteractionEvents];
                                       self.sidebarIsPresenting = NO;

                                       if([self.delegate conformsToProtocol:@protocol(TheSidebarControllerDelegate)] && [self.delegate respondsToSelector:@selector(sidebarController:didHideViewController:)])
                                       {
                                           [self.delegate sidebarController:self didHideViewController:self.selectedSidebarViewController];
                                       }
                                   }
     ];
}

#pragma mark - UIViewController Setters
- (void)setContentViewController:(UIViewController *)contentViewController
{
    // Old View Controller
    UIViewController *oldViewController = self.contentViewController;
    [oldViewController willMoveToParentViewController:nil];
    [oldViewController.view removeFromSuperview];
    [oldViewController removeFromParentViewController];

    // New View Controller
    UIViewController *newViewController = contentViewController;
    [self.contentContainerViewController addChildViewController:newViewController];
    [self.contentContainerViewController.view addSubview:newViewController.view];
    [newViewController didMoveToParentViewController:self.contentContainerViewController];

    _contentViewController = newViewController;
}

- (void)setLeftSidebarViewController:(UIViewController *)leftSidebarViewController
{
    // Old View Controller
    UIViewController *oldViewController = self.leftSidebarViewController;
    [oldViewController willMoveToParentViewController:nil];
    [oldViewController.view removeFromSuperview];
    [oldViewController removeFromParentViewController];

    // New View Controller
    UIViewController *newViewController = leftSidebarViewController;
    [self.leftSidebarContainerViewController addChildViewController:newViewController];
    [self.leftSidebarContainerViewController.view addSubview:newViewController.view];
    [newViewController didMoveToParentViewController:self.leftSidebarContainerViewController];

    _leftSidebarViewController = newViewController;
}

- (void)setRightSidebarViewController:(UIViewController *)rightSidebarViewController
{
    // Old View Controller
    UIViewController *oldViewController = self.leftSidebarViewController;
    [oldViewController willMoveToParentViewController:nil];
    [oldViewController.view removeFromSuperview];
    [oldViewController removeFromParentViewController];

    // New View Controller
    UIViewController *newViewController = rightSidebarViewController;
    [self.rightSidebarContainerViewController addChildViewController:newViewController];
    [self.rightSidebarContainerViewController.view addSubview:newViewController.view];
    [newViewController didMoveToParentViewController:self.rightSidebarContainerViewController];

    _rightSidebarViewController = newViewController;
}

#pragma mark - Autorotation Delegates
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

    if((toInterfaceOrientation == UIInterfaceOrientationPortrait) ||
       (toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))
    {
        NSLog(@"Portrait");
    }
    else if((toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
            (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {
        NSLog(@"Landscape");
    }

}

#pragma mark - Helpers
- (void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view
{
    CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y);
    CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y);

    newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
    oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);

    CGPoint position = view.layer.position;

    position.x -= oldPoint.x;
    position.x += newPoint.x;

    position.y -= oldPoint.y;
    position.y += newPoint.y;

    view.layer.position = position;
    view.layer.anchorPoint = anchorPoint;
}

@end

#pragma mark - TheSidebarController Category
@implementation UIViewController(TheSidebarController)

- (TheSidebarController *)sidebarController
{
    if([self.parentViewController.parentViewController isKindOfClass:[TheSidebarController class]])
    {
        return (TheSidebarController *)self.parentViewController.parentViewController;
    }
    else if([self.parentViewController isKindOfClass:[UINavigationController class]] &&
            [self.parentViewController.parentViewController.parentViewController isKindOfClass:[TheSidebarController class]])
    {
        return (TheSidebarController *)self.parentViewController.parentViewController.parentViewController;
    }

    return nil;
}

@end


text:
Use [Git Cop](https://github.com/bkuhlmann/git-cop) to enforce styles via a Git Hook, continuous
integration server, and/or both.


text:
{#
    ikhaya/article_delete.html
    ~~~~~~~~~~~~~~~~~~~~~~~~~~

    This template is flashed to ensure that the user wants to delete the selected article.

    :copyright: (c) 2013-2017 by the Inyoka Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
#}

{% import 'macros.html' as macros %}

{% call macros.outer_form(csrf_token(), action=article|url('delete')|e, submit_label=_('Delete')) %}

    {% trans link=article|url('show')|e, article=article.subject %}
      Are you sure you want to delete the article "{{ article }}"?
    {% endtrans %}

  <input type="submit" name="cancel" value="{% trans %}Cancel{% endtrans %}" />
  {% if article.public %}
    <input type="submit" name="unpublish" value="{% trans %}Unpublish{% endtrans %}" />
  {% endif %}
{% endcall %}


text:
There is a BVN menu located on the right-hand side of the menu bar.

### Change letterhead fields
This button opens the dialogue box for editing the address, date, office etc.

### Refresh all fields
This button refreshes all fields filled in the dialogue box.

### Toggle print graphics
This button hides the BVN header and footer. Use this when printing on pre-printed letterhead stock.

### Apply BVN table format
Use this button to apply the BVN table style.

![]({{site.baseurl}}/assets/templates-bvn-menu.jpg)


text:
import React from 'react';
import { StyleSheet } from 'react-native';

const ROW_HEIGHT = 70;

const styles = StyleSheet.create({
  row: {
    backgroundColor: '#313842',
    paddingLeft: 15,
    paddingRight: 15,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    height: ROW_HEIGHT,
  },
  timeline: {
    height: ROW_HEIGHT,
    width: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  timelineVerticalLink: {
    height: ROW_HEIGHT,
    width: 1,
    backgroundColor: '#526373',
    justifyContent: 'center'
  },
  icon: {
    color: '#e7d629',
    backgroundColor: 'transparent',
    position: 'absolute',
    alignItems: 'center'
  },
  content: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'flex-start',
    paddingRight: 10,
    paddingLeft: 10,
    paddingTop: 10,
  },
  text: {
    fontSize: 17,
    fontWeight: '500',
    color: 'white',
  },
  time: {
    fontSize: 10,
    fontWeight: '400',
    color: '#828B7B',
  }
});

export default styles;


text:
function paths = setPaths()
% SETPATHS Setup paths based on default directory structure.
%
%   paths = setPaths()
%
%   Stavros Tsogkas, <tsogkas@cs.toronto.edu>
%   Last update: February 2017

paths.spbmil.root      = fileparts(mfilename('fullpath'));

% data
paths.data             = fullfile(paths.root, 'data');
paths.bsds500          = fullfile(paths.data,'BSDS500');
paths.bsds500gt        = fullfile(paths.bsds500, 'groundtruth');
paths.bsds500im        = fullfile(paths.bsds500, 'images');
paths.symmax500        = fullfile(paths.data,'SYMMAX500');

% output/results
paths.spbmil.output    = fullfile(paths.spbmil.root, 'output');
psths.spbmil.plots     = fullfile(paths.spbmil.output, 'plots');
paths.spbmil.models    = fullfile(paths.spbmil.output,'models');
paths.spbmil.spectral  = fullfile(paths.spbmil.output, 'spectral');


text:
from bst.node import Node
from bst.binary_search_tree import BinarySearchTree

t = BinarySearchTree()
five = t.add(5)
three = t.add(3)
seven = t.add(7)
two = t.add(2)
four = t.add(4)
six = t.add(6)
nine = t.add(9)
eight = t.add(8)
one = t.add(1)

min_of_all_tree = t.min()
print min_of_all_tree.value
max_of_all_tree = t.max()
print max_of_all_tree.value

min_from_node_seven = t.min(seven)
print min_from_node_seven.value
max_from_node_seven = t.max(seven)
print max_from_node_seven.value


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

import * as _ from 'lodash';
import {isNullOrUndefined, isUndefined} from 'util';
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  Injector,
  OnDestroy,
  OnInit,
  Output,
  ViewChild,
} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {DeriveRule} from '@domain/data-preparation/prep-rules';
import {RuleSuggestInputComponent} from './rule-suggest-input.component';
import {EditRuleComponent} from './edit-rule.component';

@Component({
  selector: 'edit-rule-derive',
  templateUrl: './edit-rule-derive.component.html'
})
export class EditRuleDeriveComponent extends EditRuleComponent implements OnInit, AfterViewInit, OnDestroy {

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Private Variables
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  @ViewChild('derive_value_input')
  private valueInput: RuleSuggestInputComponent;

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Protected Variables
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Public Variables
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
  public deriveVal: string;
  public deriveAs: string;
  public isTooltipShow: boolean = false;

  @Output()
  public advancedEditorClickEvent = new EventEmitter();

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Constructor
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  // 생성자
  constructor(
    protected elementRef: ElementRef,
    protected injector: Injector) {
    super(elementRef, injector);
  }

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Override Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /**
   * 컴포넌트 초기 실행
   */
  public ngOnInit() {
    super.ngOnInit();
  } // function - ngOnInit

  /**
   * 화면 초기화
   */
  public ngAfterViewInit() {
    super.ngAfterViewInit();
  } // function - ngAfterViewInit

  /**
   * 컴포넌트 제거
   */
  public ngOnDestroy() {
    super.ngOnDestroy();

  } // function - ngOnDestroy

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Public Method - API
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /**
   * Rule 형식 정의 및 반환
   * @return
   */
  public getRuleData(): { command: string, ruleString: string, uiRuleString: DeriveRule } {

    this.deriveVal = this.valueInput.getFormula();
    const val = _.cloneDeep(this.deriveVal);

    if (isUndefined(val) || '' === val || '\'\'' === val) {
      Alert.warning(this.translateService.instant('msg.dp.alert.insert.expression'));
      return undefined
    }

    if (isUndefined(this.deriveAs) || '' === this.deriveAs) {
      Alert.warning(this.translateService.instant('msg.dp.alert.insert.new.col'));
      return undefined
    }

    let deriveAs: string;
    if (this.deriveAs.indexOf(' ') === -1) {
      deriveAs = `'${this.deriveAs}'`;
    } else {
      deriveAs = '`' + this.deriveAs + '`';
    }

    return {
      command: 'derive',
      ruleString: 'derive value: ' + val + ' as: ' + deriveAs,
      uiRuleString: {
        name: 'derive',
        expression: this.deriveVal,
        newCol: this.deriveAs,
        isBuilder: true
      }
    }

  } // function - getRuleData

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Public Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
  /**
   * Open advanced editor popup
   */
  public openPopupFormulaInput() {
    this.deriveVal = this.valueInput.getFormula();
    this.advancedEditorClickEvent.emit({command: 'derive', val: 'deriveVal'});
  } // function - openPopupFormulaInput

  /**
   * Apply formula using Advanced formula popup
   * @param {{command: string, formula: string}} data
   */
  public doneInputFormula(data: { command: string, formula: string }) {
    this.deriveVal = data.formula;
    this.valueInput.setFormula(this.deriveVal);
  }

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Protected Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

  /**
   * 컴포넌트 표시 전 실행
   * @protected
   */
  protected beforeShowComp() {
  } // function - beforeShowComp

  /**
   * 컴포넌트 표시 후 실행
   * @protected
   */
  protected afterShowComp() {

    if (this.deriveAs === '' || isNullOrUndefined(this.deriveAs)) {
      this.deriveAs = 'col_1';
    }
  } // function - afterShowComp

  /**
   * parse rule string
   * @param data ({jsonRuleString : DeriveRule})
   */
  protected parsingRuleString(data: { jsonRuleString: DeriveRule }) {

    this.deriveVal = data.jsonRuleString.expression;
    this.deriveAs = data.jsonRuleString.newCol;

  } // function - parsingRuleString

  /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  | Private Method
  |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

}


text: Test on russian rules. University lab. Nostalgie...


text:
namespace cpplinq
{
    namespace detail
    {
        struct default_select_many_selector
        {
            template <class T1, class T2>
            auto operator()(T1&& t1, T2&& t2) const
                -> decltype(std::forward<T2>(t2))
            {
                return std::forward<T2>(t2);
            }
        };
    }

    namespace detail
    {
        template <typename Fn, typename Arg>
        struct resolve_select_many_fn_return_type
        {
            typedef decltype(std::declval<Fn>()(std::declval<Arg>())) value;
        };

        template <typename TCol>
        struct value_collection_adapter
        {
            value_collection_adapter(const TCol& col)
                : _collection(col){}

            value_collection_adapter(const value_collection_adapter& src)
                : _collection(src._collection) {}

            value_collection_adapter(value_collection_adapter && src)
                : _collection(std::move(src._collection)) {}

            const TCol& get() const
            {
                return _collection;
            }

            TCol& get()
            {
                return _collection;
            }

        private:
            TCol _collection;
        };

        template<typename TCol>
        struct collection_store_type
        {
            typedef typename std::remove_reference<TCol>::type                         collection_type;
            typedef std::reference_wrapper<collection_type>                            reference_store_type;
            typedef value_collection_adapter<collection_type>                          value_store_type;

            typedef typename std::conditional<std::is_reference<TCol>::value, reference_store_type, value_store_type>::type    store;
        };
    }

    // cur<T> -> (T -> cur<element_type>) -> cur<element_type>
    template <class Container1, class Fn, class Fn2>
    class linq_select_many
    {
        template <class T> static T instance(); // for type inference

        Container1      c1;
        Fn              fn;
        Fn2             fn2;

        typedef typename Container1::cursor Cur1;
        typedef decltype(from(instance<Fn>()(instance<Cur1>().get()))) Container2;
        typedef typename Container2::cursor Cur2;

        typedef typename detail::resolve_select_many_fn_return_type<Fn, typename Cur1::element_type>::value inner_collection;

    public:
        class cursor
        {
        public:
            typedef typename util::min_cursor_category<typename Cur1::cursor_category,
                                                       typename Cur2::cursor_category,
                                                       forward_cursor_tag>::type
                cursor_category;
            typedef typename Cur2::reference_type reference_type;
            typedef typename Cur2::element_type element_type;

            typedef detail::collection_store_type<inner_collection>     collection_store_type;
            typedef typename collection_store_type::store               collection_store;
            typedef std::shared_ptr<collection_store>                   collection_store_ptr;

        private:
            // TODO: we need to lazy eval somehow, but this feels wrong.
            Cur1                                cur1;
            dynamic_cursor<reference_type>      cur2;
            Fn                                  fn;
            Fn2                                 fn2;
            collection_store_ptr                store;

        public:
            cursor(Cur1 cur1, const Fn& fn, const Fn2& fn2)
                : cur1(std::move(cur1)), fn(fn), fn2(fn2)
            {
                if (!cur1.empty())
                {
                    store = std::make_shared<collection_store>(fn(cur1.get()));
                    cur2 = from(store->get()).get_cursor();
                }

                thunk();
            }

            bool empty() const
            {
                return cur2.empty();
            }

            void inc()
            {
                cur2.inc();
                thunk();
            }

            reference_type get() const
            {
                return fn2(cur1.get(), cur2.get());
            }

        private:
            void thunk()
            {
                // refill cur2
                while (cur2.empty() && !cur1.empty()) {
                    cur1.inc();
                    if (cur1.empty())
                        break;

                    store = std::make_shared<collection_store>(fn(cur1.get()));
                    cur2 = from(store->get()).get_cursor();
                }
            }
        };

        linq_select_many(Container1 c1, Fn fn, Fn2 fn2)
        : c1(std::move(c1)), fn(std::move(fn)), fn2(std::move(fn2))
        {
        }

        cursor get_cursor() const
        {
            return cursor(c1.get_cursor(), fn, fn2);
        }
    };
}


text:
links
=====

This is an example of object oriented design using type composition rather than inheritance to implement polymorphic reuse of code.


text:
extern "C" {
#endif  // defined(__cplusplus)

// Opaque reference to a plugin registrar.
typedef struct FlutterDesktopPluginRegistrar* FlutterDesktopPluginRegistrarRef;

// Function pointer type for registrar destruction callback.
typedef void (*FlutterDesktopOnPluginRegistrarDestroyed)(
    FlutterDesktopPluginRegistrarRef);

// Returns the engine messenger associated with this registrar.
FLUTTER_EXPORT FlutterDesktopMessengerRef
FlutterDesktopPluginRegistrarGetMessenger(
    FlutterDesktopPluginRegistrarRef registrar);

// Returns the texture registrar associated with this registrar.
FLUTTER_EXPORT FlutterDesktopTextureRegistrarRef
FlutterDesktopRegistrarGetTextureRegistrar(
    FlutterDesktopPluginRegistrarRef registrar);

// Registers a callback to be called when the plugin registrar is destroyed.
FLUTTER_EXPORT void FlutterDesktopPluginRegistrarSetDestructionHandler(
    FlutterDesktopPluginRegistrarRef registrar,
    FlutterDesktopOnPluginRegistrarDestroyed callback);

#if defined(__cplusplus)
}  // extern "C"
#endif

#endif  // FLUTTER_SHELL_PLATFORM_COMMON_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_


text:
#ifndef __GSL_SORT_SHORT_H__
#define __GSL_SORT_SHORT_H__

#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_permutation.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif

__BEGIN_DECLS

void gsl_sort_short (short * data, const size_t stride, const size_t n);
void gsl_sort_short_index (size_t * p, const short * data, const size_t stride, const size_t n);

int gsl_sort_short_smallest (short * dest, const size_t k, const short * src, const size_t stride, const size_t n);
int gsl_sort_short_smallest_index (size_t * p, const size_t k, const short * src, const size_t stride, const size_t n);

int gsl_sort_short_largest (short * dest, const size_t k, const short * src, const size_t stride, const size_t n);
int gsl_sort_short_largest_index (size_t * p, const size_t k, const short * src, const size_t stride, const size_t n);

__END_DECLS

#endif /* __GSL_SORT_SHORT_H__ */


text:
package nl.esciencecenter.e3dchem.sstea;

import java.io.File;
import java.io.IOException;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.workflow.UnsupportedWorkflowVersionException;
import org.knime.core.util.LockFailedException;
import org.knime.testing.core.TestrunConfiguration;

import nl.esciencecenter.e3dchem.knime.testing.TestFlowRunner;

public class WorkflowsTest {
    @Rule
    public ErrorCollector collector = new ErrorCollector();
    private TestFlowRunner runner;

    @Before
    public void setUp() {
        TestrunConfiguration runConfiguration = new TestrunConfiguration();
        runConfiguration.setTestDialogs(true);
        runConfiguration.setReportDeprecatedNodes(true);
        runConfiguration.setCheckMemoryLeaks(true);
        runConfiguration.setLoadSaveLoad(false);
        runConfiguration.setAllowedMemoryIncrease(2097152);
        runner = new TestFlowRunner(collector, runConfiguration);
    }

    @Test
    public void test_simple() throws IOException, InvalidSettingsException, CanceledExecutionException,
            UnsupportedWorkflowVersionException, LockFailedException, InterruptedException {
        File workflowDir = new File("src/knime/sstea-simple-test");
        runner.runTestWorkflow(workflowDir);
    }

    @Test
    public void test_inputs() throws IOException, InvalidSettingsException, CanceledExecutionException,
            UnsupportedWorkflowVersionException, LockFailedException, InterruptedException {
        File workflowDir = new File("src/knime/sstea-test-inputs");
        runner.runTestWorkflow(workflowDir);
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bol. Soc. venez. Cienc. nat. 5(no. 40): 459 (1939)

#### Original name
Leptosporina Chardón

### Remarks
null


text:
<!doctype html>

  <title>Socket.IO chat</title>
  <link rel="stylesheet" href="../css/index.css">

  <form action="">
    <input id="m" autocomplete="off" /><button>Send</button>
  </form>


text:
'''
Plot the visualization of the standard resting state network on the
connectivity circle plot showing the Freesurfer aparc annotation map.

This provides a quick visualization of the primary connections of the standard
resting state network.

Uses the standard RSNs provided by [1]
[1] P. Garcés, M. C. Martín-Buro, and F. Maestú,
"Quantifying the Test-Retest Reliability of Magnetoencephalography
Resting-State Functional Connectivity," Brain Connect., vol. 6, no. 6,
pp. 448–460, 2016.

Author: Praveen Sripad <pravsripad@gmail.com>
'''

import os.path as op
import numpy as np
import mne

from mne.datasets import sample
from jumeg.jumeg_utils import get_jumeg_path
from jumeg.connectivity import make_annot_from_csv
from jumeg.connectivity import plot_grouped_connectivity_circle

data_path = sample.data_path()
subject = 'sample'
subjects_dir = data_path + '/subjects'
parc_fname = 'standard_garces_2016'
csv_fname = op.join(get_jumeg_path(), 'data', 'standard_rsns.csv')

# set make_annot to True to save the annotation to disk
labels, coords, foci = make_annot_from_csv(subject, subjects_dir, csv_fname,
                                           parc_fname=parc_fname,
                                           make_annot=False,
                                           return_label_coords=True)

aparc = mne.read_labels_from_annot('sample', subjects_dir=subjects_dir)
aparc_names = [apa.name for apa in aparc]
lh_aparc = [mylab for mylab in aparc if mylab.hemi == 'lh']
rh_aparc = [mylab for mylab in aparc if mylab.hemi == 'rh']

# get the appropriate resting state labels
rst_aparc = []
for i, rst_label in enumerate(labels):
    myfoci = foci[i]  # get the vertex
    if rst_label.hemi == 'lh':  # vertex hemi is stored in the rst_label
        for mylab in lh_aparc:
            if myfoci in mylab.vertices:
                print('Left: ', rst_label.name, myfoci, mylab, aparc.index(mylab))
                rst_aparc.append(mylab)
    elif rst_label.hemi == 'rh':
        for mylab in rh_aparc:
            if myfoci in mylab.vertices:
                print('Right: ', rst_label.name, myfoci, mylab, aparc.index(mylab))
                rst_aparc.append(mylab)
    else:
        print('ERROR: ', rst_label)

# only 16 labels in aparc show up, there are no vertices in the left hemi for
# Frontoinsular_Median cingulate-lh
rst_indices = [aparc.index(rst) for rst in rst_aparc]

networks = {'Visual': ['lateraloccipital-lh', 'lateraloccipital-rh'],
            'Sensorimotor': ['supramarginal-lh', 'supramarginal-rh'],
            'Auditory': ['inferiortemporal-lh', 'middletemporal-rh'],
            'DMN': ['precuneus-lh', 'inferiorparietal-lh',
                    'inferiorparietal-rh', 'medialorbitofrontal-lh'],
            'Left_FP': ['inferiorparietal-lh', 'superiortemporal-lh'],
            'Right_FP': ['inferiorparietal-rh', 'superiortemporal-rh'],
            'Frontoinsular': ['inferiortemporal-lh', 'inferiortemporal-rh']}

# make a temporary connectivity matrix
n_nodes = 68
con = np.zeros((n_nodes, n_nodes))

rst_combindices = [[16, 31], [50, 14], [50, 15], [50, 28], [14, 15],
                   [14, 28], [15, 28], [22, 23], [14, 60], [62, 63],
                   [15, 61],
                   [16, 17]]

# assign different values to different networks manually
con[16, 31] = 0.4  # Auditory
con[50, 14] = con[50, 15] = con[50, 28] = con[14, 15] = con[14, 28] = con[15, 28] = 0.5  # DMN
con[22, 23] = 0.6  # Visual
con[14, 60] = 0.7  # Left FP
con[62, 63] = 0.8  # Sensorimotor
con[15, 61] = 0.9  # Right FP
con[16, 17] = 1  # Frontoinsular

con += con.T  # since we only add the combinations

# plot the connectivity circle showing standard RSNs
from matplotlib.colors import ListedColormap
cmap = ListedColormap(['m', 'k', 'b', 'y', 'r', 'c', 'g'])
yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml'
plot_grouped_connectivity_circle(yaml_fname, con, aparc_names, n_lines=12,
                                 labels_mode=None, node_order_size=68,
                                 colormap=cmap, colorbar=True, replacer_dict=None,
                                 indices=None, out_fname='rsn_circle_plot.png')


text:
<title>dlib C++ Library - sockets_kernel_1.h</title>

// Copyright (C) 2003  Davis E. King (davis@dlib.net), Miguel Grinberg
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SOCKETS_KERNEl_1_
#define DLIB_SOCKETS_KERNEl_1_

#ifdef DLIB_ISO_CPP_ONLY
#error "DLIB_ISO_CPP_ONLY is defined so you can't use this OS dependent code.  Turn DLIB_ISO_CPP_ONLY off if you want to use it."
#endif

#include "sockets_kernel_abstract.h"

#include "../algs.h"
#include <string>
#include "../threads.h"
#include "../smart_pointers.h"
#include "../uintn.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    // forward declarations
    class socket_factory;
    class listener;
    class SOCKET_container;

// ----------------------------------------------------------------------------------------

    // lookup functions

    int
    get_local_hostname (
        std::string& hostname
    );

// -----------------

    int
    hostname_to_ip (
        const std::string& hostname,
        std::string& ip,
        int n = 0
    );

// -----------------

    int
    ip_to_hostname (
        const std::string& ip,
        std::string& hostname
    );

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // connection object
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    class connection
    {
        /*!
            INITIAL_VALUE
                - sd                      == false
                - sdo                     == false
                - sdr                     == 0

            CONVENTION
                - connection_socket       == the socket handle for this connection.
                - connection_foreign_port == the port that foreign host is using for
                  this connection.
                - connection_foreign_ip   == a string containing the IP address of the
                  foreign host.
                - connection_local_port   == the port that the local host is using for
                  this connection.
                - connection_local_ip     == a string containing the IP address of the
                  local interface being used by this connection.

                - sd == if shutdown() has been called then true else false.
                - sdo == if shutdown_outgoing() has been called then true else false.
                - sdr == the return value of shutdown() if it has been called.  if it
                  hasn't been called then 0.

        !*/

        friend class listener;                // make listener a friend of connection
        // make create_connection a friend of connection
        friend int create_connection (
            connection*& new_connection,
            unsigned short foreign_port,
            const std::string& foreign_ip,
            unsigned short local_port = 0,
            const std::string& local_ip = ""
        );

    public:

        ~connection (
        );

        void* user_data;

        long write (
            const char* buf,
            long num
        );

        long read (
            char* buf,
            long num
        );

        long read (
            char* buf,
            long num,
            unsigned long timeout
        );

        unsigned short get_local_port (
        ) const {  return connection_local_port; }

        unsigned short get_foreign_port (
        ) const { return connection_foreign_port; }

        const std::string& get_local_ip (
        ) const { return connection_local_ip; }

        const std::string& get_foreign_ip (
        ) const { return connection_foreign_ip; }

        int shutdown_outgoing (
        );

        int shutdown (
        );

        // I would use SOCKET here but I don't want to include the windows
        // header files since they bring in a bunch of unpleasantness.  So
        // I'm doing this instead which should ultimately be the same type
        // as the SOCKET win the windows API.
        typedef unsigned_type<void*>::type socket_descriptor_type;

        int disable_nagle(
        );

        socket_descriptor_type get_socket_descriptor (
        ) const;

    private:

        bool readable (
            unsigned long timeout
        ) const;
        /*!
            requires
                - timeout < 2000000
            ensures
                - returns true if a read call on this connection will not block.
                - returns false if a read call on this connection will block or if
                  there was an error.
        !*/

        bool sd_called (
        )const
        /*!
            ensures
                - returns true if shutdown() has been called else
                  returns false
        !*/
        {
            sd_mutex.lock();
            bool temp = sd;
            sd_mutex.unlock();
            return temp;
        }

        bool sdo_called (
        )const
        /*!
            ensures
                - returns true if shutdown_outgoing() or shutdown() has been called
                  else returns false
        !*/
        {
            sd_mutex.lock();
            bool temp = false;
            if (sdo || sd)
                temp = true;
            sd_mutex.unlock();
            return temp;
        }

        // data members
        SOCKET_container& connection_socket;
        const unsigned short connection_foreign_port;
        const std::string connection_foreign_ip;
        const unsigned short connection_local_port;
        const std::string connection_local_ip;

        bool sd;  // called shutdown
        bool sdo; // called shutdown_outgoing
        int sdr; // return value for shutdown
        mutex sd_mutex; // a lock for the three above vars

        connection(
            SOCKET_container sock,
            unsigned short foreign_port,
            const std::string& foreign_ip,
            unsigned short local_port,
            const std::string& local_ip
        );
        /*!
            requires
                sock is a socket handle and
                sock is the handle for the connection between foreign_ip:foreign_port
                and local_ip:local_port
            ensures
                *this is initialized correctly with the above parameters
        !*/

        // restricted functions
        connection(connection&);        // copy constructor
        connection& operator=(connection&);    // assignment operator
    };

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // listener object
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    class listener
    {
        /*!
            CONVENTION
                if (inaddr_any == false)
                {
                    listening_ip == a string containing the address the listener is
                                    listening on
                }
                else
                {
                    the listener is listening on all interfaces
                }

                listening_port == the port the listener is listening on
                listening_socket == the listening socket handle for this object
        !*/

        // make the create_listener a friend of listener
        friend int create_listener (
            listener*& new_listener,
            unsigned short port,
            const std::string& ip = ""
        );

    public:

        ~listener (
        );

        int accept (
            connection*& new_connection,
            unsigned long timeout = 0
        );

        int accept (
            scoped_ptr<connection>& new_connection,
            unsigned long timeout = 0
        );

        unsigned short get_listening_port (
        ) { return listening_port; }

        const std::string& get_listening_ip (
        ) { return listening_ip; }

    private:

        // data members
        SOCKET_container& listening_socket;
        const unsigned short listening_port;
        const std::string listening_ip;
        const bool inaddr_any;

        listener(
            SOCKET_container sock,
            unsigned short port,
            const std::string& ip
        );
        /*!
            requires
                sock is a socket handle                                             and
                sock is listening on the port and ip(may be "") indicated in the
                above parameters
            ensures
                *this is initialized correctly with the above parameters
        !*/

        // restricted functions
        listener(listener&);        // copy constructor
        listener& operator=(listener&);    // assignment operator
    };

// ----------------------------------------------------------------------------------------

    int create_listener (
        listener*& new_listener,
        unsigned short port,
        const std::string& ip
    );

    int create_connection (
        connection*& new_connection,
        unsigned short foreign_port,
        const std::string& foreign_ip,
        unsigned short local_port,
        const std::string& local_ip
    );

    int create_listener (
        scoped_ptr<listener>& new_listener,
        unsigned short port,
        const std::string& ip = ""
    );

    int create_connection (
        scoped_ptr<connection>& new_connection,
        unsigned short foreign_port,
        const std::string& foreign_ip,
        unsigned short local_port = 0,
        const std::string& local_ip = ""
    );

// ----------------------------------------------------------------------------------------

}

#ifdef NO_MAKEFILE
#include "sockets_kernel_1.cpp"
#endif

#endif // DLIB_SOCKETS_KERNEl_1_


text:
var x, y = null;
var d = document;
var b = $('body')[0];

function getCookie() {
  return d.cookie;
}

function isHasAcceptedPolicy() {
  return (null != getCookie().match(/acceptedPolicy=true/));
}

async function acceptPolicy() {
  var banner = $('#policy-banner')[0];
  banner.style.opacity = 0;
  writeCookie("acceptedPolicy", true);
  await sleep(1000);
  banner.style.display = "none";
}

function writeCookie(cookieName, cookieValue, ttl = 14) {
  var date = new Date();
  date.setTime(date.getTime() + ttl * 24 * 3600 * 1000);
  d.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toUTCString() + "; " + "domain=" + window.location.hostname
+ "; path=/";
}

function toggleTheme() {
  if (!isHasAcceptedPolicy()) {
    return;
  }

  $('body').toggleClass('dark-theme').toggleClass('light-theme');
  writeCookie("darkTheme", $('body').hasClass('dark-theme'));
}

function toggleDyslexicFont() {
  if (!isHasAcceptedPolicy()) {
    return;
  }

  $('body').toggleClass('dyslexic');
  writeCookie("dyslexic", $('body').hasClass('dyslexic'));
}

function loadYouTube() {
  var videos = d.getElementsByClassName('youtube');
  for (var i = 0; i < videos.length; i++) {
    videos[i].innerHTML = d.getElementById(videos[i].getAttribute('data-videoid')).innerHTML;
  }
}

function restoreSettingsFromCookie() {
  if (!isHasAcceptedPolicy()) {
    var bannerClass = $('.policy-banner');
    for(var i = 0; i < bannerClass.length; i++)
      bannerClass[i].style.display = "block";
    return;
  }

  if (null != getCookie().match(/darkTheme=false/)) {
    $('#dark-mode').prop('checked', true);
    toggleTheme();
  }
  if (null != getCookie().match(/dyslexic=true/)) {
    $('#dyslexic').prop('checked', true);
    toggleDyslexicFont();
  }
  if (null != getCookie().match(/fontSize/)) zoom((getCookie().match(/(^| )fontSize=([^;]+)/))[2] - 12);
  acceptPolicy();
}

function g(evt) {
  return evt.touches;
}

function touchStart(evt) {
  const firstTouch = g(evt)[0];
  x = firstTouch.clientX;
  y = firstTouch.clientY;
};

function touchMove(evt) {
  if (null == x || null == y) {
    return;
  }

  var xu = evt.touches[0].clientX;
  var yu = evt.touches[0].clientY;

  var xd = x - xu;
  var yd = y - yu;

  if (Math.abs(xd) > 11 && Math.abs(xd) > 2 * Math.abs(yd)) {
    if (xd > 0) {
      loadPage("next");
    } else {
      loadPage("previous");
    }
  }

  x = null;
  y = null;
};

function loadPage(partId) {
  var href = $('#' + partId)[0].href;
  if ("" == href) return;

  window.location.href = href;
}

function zoom(points) {
  if (!isHasAcceptedPolicy()) {
    return;
  }

  var fontSize = (parseInt(b.style.fontSize, 10) || 12) + points;
  if (fontSize > 20) fontSize = 22;
  if (fontSize < 12) fontSize = 10;
  b.style.fontSize = fontSize + 'pt';
  writeCookie("fontSize", fontSize);
}

function clearCookies() {
  writeCookie("acceptedPolicy", '', -1);
  writeCookie("activateGoogleAnalytics", '', -1);
  writeCookie("fontSize", '', -1);
  writeCookie("darkTheme", '', -1);
  writeCookie("condensed", '', -1);
  writeCookie("dyslexic", '', -1);
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function setUpPageForUsers() {
  await sleep(200);
  var isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

  if (isMobile) {
    d.addEventListener('touchstart', touchStart, false);
    d.addEventListener('touchmove', touchMove, false);
    document.getElementById('mobile-top').scrollIntoView(true);
    toggleAllAccordions();
  }

  d.getElementsByTagName("html")[0].className = "animated";

  $('#dark-mode').change(toggleTheme);
  $('#dyslexic').change(toggleDyslexicFont);
}

function toggleAccordion(e) {
  e.classList.toggle("inactive");
  e.classList.toggle("active");
}

function toggleAllAccordions() {
  document
    .querySelectorAll('.inactive')
    .forEach(e => {
      toggleAccordion(e);
    });
}

restoreSettingsFromCookie();
setUpPageForUsers();


text:
class ActiveRecord::Base
  class << self
    def construct_finder_sql_with_included_associations_with_selectable_includes(options, join_dependency)
      scope = scope(:find)
      select_options = options[:select] || (scope && scope[:select])
      sql = construct_finder_sql_with_included_associations_without_selectable_includes(options, join_dependency)
      unless select_options.blank?
        sql.sub!(/\ASELECT /, "SELECT #{select_options}, ")
      end
      sql
    end
    alias_method_chain :construct_finder_sql_with_included_associations, :selectable_includes
  end
end

class ActiveRecord::Associations::ClassMethods::JoinDependency
  def instantiate_with_selectable_includes(rows)
    unless rows.empty?
      keys_from_select = rows.first.keys.reject {|k| k =~ /\At\d+_r\d+/}
      join_base.extra_columns = keys_from_select
    end
    instantiate_without_selectable_includes(rows)
  end
  alias_method_chain :instantiate, :selectable_includes
end

class ActiveRecord::Associations::ClassMethods::JoinDependency::JoinBase
  attr_accessor :extra_columns

  def extract_record_with_selectable_includes(row)
    record = extract_record_without_selectable_includes(row)
    extra_columns.inject(record){|record, an| record[an] = row[an]; record} if extra_columns
    record
  end

  alias_method_chain :extract_record, :selectable_includes
end