text:
import json
import logging

from couchdbkit.exceptions import ResourceNotFound
from django.core.management import BaseCommand, CommandError
from gevent.pool import Pool

import corehq.apps.accounting.models as acct
import corehq.apps.app_manager.models as apps
import corehq.apps.hqmedia.models as hqmedia
from corehq.apps.export import models as exports
from corehq.blobs import get_blob_db, CODES
from corehq.blobs.migratingdb import MigratingBlobDB
from corehq.blobs.mixin import BlobMetaRef
from corehq.blobs.util import set_max_connections
from corehq.util.decorators import change_log_level

USAGE = "Usage: ./manage.py check_blob_logs [options] FILE [FILE [FILE]]"

BLOB_MIXIN_MODELS = {
    CODES.application: apps.Application,
    CODES.data_export: exports.CaseExportInstance,
    # TODO adapt to SQL forms if its ever needed
    #CODES.form_xml: xform.XFormInstance,
    #CODES.form_attachment: xform.XFormInstance,
    CODES.multimedia: hqmedia.CommCareMultimedia,
    CODES.invoice: acct.InvoicePdf,
}

class Command(BaseCommand):
    """Verify missing blobs in blob db backend migration log files.

    Example: ./manage.py check_blob_logs [options] migration-log.txt
    """
    help = USAGE

    def add_arguments(self, parser):
        parser.add_argument(
            'files',
            nargs="+",
            help="Log files with blobs to check. Each line of the log file "
                 "should be a JSON record with blobmeta_id, domain, "
                 "type_code, parent_id, blob_key, and error fields",
        )
        parser.add_argument(
            '--migrate',
            action="store_true",
            default=False,
            help="Copy blobs found in old db to new db.",
        )
        parser.add_argument(
            '--num-workers',
            type=int,
            default=10,
            help="Worker pool size for concurrent processing.",
        )

    @change_log_level('boto3', logging.WARNING)
    @change_log_level('botocore', logging.WARNING)
    def handle(self, files, migrate=False, num_workers=10, **options):
        set_max_connections(num_workers)
        blob_db = get_blob_db()
        if not isinstance(blob_db, MigratingBlobDB):
            raise CommandError(
                "Expected to find migrating blob db backend (got %r)" % blob_db)
        old_db = blob_db.old_db
        new_db = blob_db.new_db
        ignored = 0

        try:
            pool = Pool(size=num_workers)
            for filepath in files:
                print("Processing {}".format(filepath))
                with open(filepath, encoding='utf-8') as fh:
                    for line in fh:
                        if not line:
                            continue
                        try:
                            rec = json.loads(line)
                        except ValueError:
                            ignored += 1
                            print(("Ignore {}", line))
                            continue
                        pool.spawn(process, rec, old_db, new_db, migrate)

            print("CTRL+C to abort")
            while not pool.join(timeout=10):
                print("waiting for {} workers to finish...".format(len(pool)))
        except KeyboardInterrupt:
            pass

        if ignored:
            print("Ignored {} malformed records".format(ignored))
        for type_code, stats in sorted(Stats.items.items()):
            try:
                group = BLOB_MIXIN_MODELS[type_code].__name__
            except KeyError:
                group = CODES.name_of(type_code, "type_code %s" % type_code)
            total = stats.new + stats.old + stats.noref + stats.lost
            print("{}: checked {} records".format(group, total))
            print("  Found in new db: {}".format(stats.new))
            print("  Found in old db: {}".format(stats.old))
            print("  Not referenced: {}".format(stats.noref))
            print("  Not found: {}".format(stats.lost))

def process(rec, old_db, new_db, migrate):
    category = check_blob(rec, old_db, new_db, migrate)
    stats = Stats.get(rec["type_code"])
    setattr(stats, category, getattr(stats, category) + 1)

def check_blob(rec, old_db, new_db, migrate=False):
    key = rec["blob_key"]

    if new_db.exists(key=key):
        return "new"

    if old_db.exists(key=key):
        if migrate:
            with old_db.get(key=key, type_code=CODES.maybe_compressed) as content:
                new_db.copy_blob(content, key=key)
            action = "Migrated from"
        else:
            action = "Found in"
        print("{} old db: {}".format(action, key))
        return "old"

    doc_type = BLOB_MIXIN_MODELS.get(rec["type_code"])
    if doc_type is not None:
        couchdb = doc_type.get_db()
        doc_id = rec["parent_id"]
        try:
            doc = couchdb.get(doc_id)
        except ResourceNotFound:
            print("Not referenced: {} doc not found".format(json.dumps(rec)))
            return "noref"

        for name, info in doc.get("external_blobs", {}).items():
            data = BlobMetaRef._normalize_json(couchdb.dbname, doc_id, info)
            if data["key"] == key:
                print("Missing: {} blob info: {}: {}".format(
                    json.dumps(rec),
                    repr(name),
                    info,
                ))
                return "lost"

        print("Not referenced: {}".format(json.dumps(rec)))
        return "noref"

    print("Missing: {}".format(json.dumps(rec)))
    return "lost"

class Stats(object):

    items = {}

    @classmethod
    def get(cls, type_code):
        item = cls.items.get(type_code)
        if item is None:
            item = cls.items[type_code] = cls()
        return item

    def __init__(self):
        self.new = 0
        self.old = 0
        self.lost = 0
        self.noref = 0


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace SolarSystem.Backend.Classes
{
    public class Station
    {
        public event Action<OrderBox> OnOrderBoxFinishedAtStation;
        public event Action<OrderBox> OnOrderBoxReceivedAtStation;
        public event Action<Station, List<Article>> OnShelfBoxNeededRequest;

        public string Name { get; }

        public List<ShelfBox> ShelfBoxes;

        private readonly AreaCode _areaCode;

        public List<OrderBox> OrderBoxes;

        public int MaxShelfBoxes { get; }
        public int MaxOrderBoxes { get; }

        public bool StationIsFull => OrderBoxes.Capacity == OrderBoxes.Count;

        private OrderBoxPickingContainer _orderBoxBeingPacked = null;

        private readonly Storage _storage;

        private int _shelfBoxWaitCount;

        public Station(string name, int maxShelfBoxes,int maxOrderBoxes, AreaCode areaCode)
        {
            ShelfBoxes = new List<ShelfBox>(maxShelfBoxes);
            OrderBoxes = new List<OrderBox>(maxOrderBoxes);
            Name = name ?? throw new ArgumentNullException(nameof(name));
            MaxShelfBoxes = maxShelfBoxes;
            MaxOrderBoxes = maxOrderBoxes;
            _areaCode = areaCode;
            _shelfBoxWaitCount = 0;

            TimeKeeper.Tick += TickLoop;

        }

        public void ReceiveOrderBox(OrderBox orderBox)
        {
            // If the station is full but still received an orderBox -> throw error
            if (OrderBoxes.Count >= MaxOrderBoxes)
            {
                throw new AccessViolationException($"Station {this} in should not have received an orderBox.");
            }
            // Add orderBox to orderBoxes
            OrderBoxes.Add(orderBox);

            // Maybe request more shelfboxes - depends on if there is more space left for shelfBoxes
            MaybeRequestShelfBoxes();

            // Invoke event stating this happened
            OnOrderBoxReceivedAtStation?.Invoke(orderBox);
        }

        private void TickLoop()
        {
            // If no orderBoxes -> skip
            if (!OrderBoxes.Any()) return;
            // Else call ChooseOrderBoxToPack
            if (_orderBoxBeingPacked == null)
            {
                ChooseOrderBoxToPack();
            }
        }

        private void MaybeRequestShelfBoxes()
        {
            // If waiting for shelfboxes already then skip
            if (_shelfBoxWaitCount > 0) return;

            // Find needed articles
            var neededArticles = FindNeededArticlesInOrderBoxes();
            // If any articles are needed then
            if (neededArticles.Any())
            {
                // Set StorageReceiveWatingTime to articlesNeeded.length
                _shelfBoxWaitCount = neededArticles.Count;
                // invoke NeedTheseArticles(articlesNeeded, Station)
                OnShelfBoxNeededRequest?.Invoke(this, neededArticles);
            }
        }

        private List<Article> FindNeededArticlesInOrderBoxes()
        {
            // Calculate spaces left for shelfBoxes, call it spacesLeft
            var spacesLeft = ShelfBoxes.Capacity - ShelfBoxes.Count;
            // Create neededArticlesList with size spacesLeft
            var neededArticlesList = new List<Article>(spacesLeft);

            // Loop through orderBoxes in FIFO.
            foreach (var orderBox in OrderBoxes)
            {
                // Loop through unpicked lines in orderbox
                foreach (var unpickedLine in orderBox.LinesNotPicked())
                {
                    // If neededArticlesList is full then return neededArticlesList
                    if (neededArticlesList.Count == neededArticlesList.Capacity)
                    {
                        return neededArticlesList;
                    }

                    // Else if this line does not have a corresponding shelfbox then
                    if (!ShelfBoxes.Select(s => s.Line.Article).Contains(unpickedLine.Article))
                    {
                        // then add its article to neededArticlesList
                        neededArticlesList.Add(unpickedLine.Article);
                    }
                }
            }

            return neededArticlesList;
        }

        private void EvictOrderBox(OrderBox orderBox)
        {
            // Remove orderBox from orderBoxes
            OrderBoxes.Remove(orderBox);
            // Invoke OnOrderBoxFinishedAtStation with orderBox
            OnOrderBoxFinishedAtStation?.Invoke(orderBox);
        }

        public void MaybeEvictShelfBoxes()
        {
            // Create evictionList
            var evictionList = new List<ShelfBox>();
            // Loop through all shelfBoxes
            foreach (var shelfBox in ShelfBoxes)
            {
                // Check if any unpacked lines of this type exist
                bool shelfBoxIsNeeded = OrderBoxes.SelectMany(o => o.LinesNotPickedIn(_areaCode)).Any(l => Equals(l.Article, shelfBox.Line.Article));
                // if not, add to evictionList
                if ( ! shelfBoxIsNeeded)
                {
                    evictionList.Add(shelfBox);
                }
            }

            // Evict all shelfBoxes in evictionList by sending them back to Storage
            evictionList.ForEach(SendShelfBoxToStorage);

            // If any shelfBoxes were evicted, call MaybeRequestShelfBoxes
            if (evictionList.Any())
            {
                MaybeRequestShelfBoxes();
            }
        }

        private void SendShelfBoxToStorage(ShelfBox shelfBox)
        {
            // Remove shelfBox from ShelfBoxes
            ShelfBoxes.Remove(shelfBox);
            // faked sending: beep, beep
        }

        private void OrderBoxLineFinishedPacking(OrderBox orderBox)
        {
            // Check if any shelfBoxes can be evicted
            MaybeEvictShelfBoxes();

            // Set orderBoxLineBeingPicked to null
            _orderBoxBeingPacked = null;

            // If orderBox is fully packed then
            if (!orderBox.LinesNotPickedIn(_areaCode).Any())
            {
                // Evict orderBox
                EvictOrderBox(orderBox);
            }

        }

        private void ChooseOrderBoxToPack()
        {
            // If orderBoxBeingPacked != null -> throw error
            if (_orderBoxBeingPacked != null)
            {
                throw new InvalidDataException($"{nameof(_orderBoxBeingPacked)} should be null when this is called.");
            }

            // Loop through orderBoxes
            foreach (var orderBox in OrderBoxes)
            {
                // Loop through unpacked lines
                foreach (var line in orderBox.LinesNotPickedIn(_areaCode))
                {
                    // If line matches shelfbox then
                    if (ShelfBoxes.Any(s => Equals(s.Line.Article, line.Article)))
                    {
                        // Create new OrderBoxLineBeingPicked with orderBox and line to be picked
                        _orderBoxBeingPacked = new OrderBoxPickingContainer(orderBox, line);
                        // Listen to orderBoxLineBeingPicked's finishedEvent
                        _orderBoxBeingPacked.OnLinePickedForOrderBox += OrderBoxLineFinishedPacking;

                        // Return, since we have found a pickable line
                        return;
                    }
                }
            }
        }

        public void ReceiveShelfBoxFromStorage(ShelfBox shelfBox)
        {
            // Decrement StorageReceiveWaitingTime by one
            _shelfBoxWaitCount -= 1;
            // Add received shelfbox to shelfboxes
            ShelfBoxes.Add(shelfBox);
        }

        public override string ToString()
        {
            return $"{Name}";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from "@angular/core";
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { User } from './models/user';
import { ServiceBase } from '../shared/service-base';
import { OperationResult } from '../shared/operation-result';
import { ApiService, ApiRoutes } from '../shared/api-service';
import { DataService } from '../shared/data-service';
import { SelectListItem } from '../shared/select-list-item';

@Injectable()
export class UserService extends ApiService<User>{
    protected static routes:ApiRoutes =
    {
        getUrl:"/api/users",
        getOneUrl:"/api/users/",
        addUrl:"api/users/add",
        updateUrl:"/api/users/update/",
        deleteUrl:"/api/users/delete/"
    }

    constructor(http: DataService)
    {
        super(UserService.routes,http);
    }

    public getPositions():Observable<SelectListItem[]>
    {
        return this.http.get("/api/users/positions").map(this.extractData);
    }
    public getDepartments():Observable<SelectListItem[]>
    {
        return this.http.get("/api/departments/select-list").map(this.extractData);
    }
}


text:
import React from 'react'
import { Image } from 'stardust'

const src = 'http://semantic-ui.com/images/wireframe/image.png'

const ImageImageExample = () => (
  <Image src={src} size='small' />
)

export default ImageImageExample


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

namespace LASI.Core
{
    static class SubordinateClauseIdentifier
    {
        public static void Identify(params Sentence[] sentences)
        {
            foreach (var s in sentences)
            {
                var remainder = RemainderofSentenceIncludingSubordinator(s.Words);
            }
        }
        private static IEnumerable<Word> RemainderofSentenceIncludingSubordinator(IEnumerable<Word> words) =>
            words.SkipWhile(IsRelativePronounOrSubordinatingConjunction);
        /// <summary>
        /// This is the most common beginning of a subordinating clause. It begins with either a subordinating conjunction or a relative (wh) pronoun.
        /// Example, "Dennis, who was a huge dick, ate at Wendy's and harassed the management.
        /// "who was a huge dick," is the subordinate clause.
        /// </summary>
        /// <param name="word">Word</param>
        /// <returns> <c>true</c> or false</returns>
        private static bool IsRelativePronounOrSubordinatingConjunction(Word word)
        {
            if (word is Preposition prep)
                return !(word is RelativePronoun) || !(prep.PrepositionRole == PrepositionRole.SubordinatingConjunction);
            return false;
        }

    }
}


text:
'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './components/AppRoutes';

window.onload = () => {
  ReactDOM.render(<AppRoutes/>, document.getElementById('app'));
};


text:
package org.axonframework.disruptor.commandhandling;

import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.CommandMessage;
import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.eventsourcing.GenericAggregateFactory;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.messaging.unitofwork.DefaultUnitOfWork;
import org.axonframework.messaging.unitofwork.UnitOfWork;
import org.axonframework.modelling.command.AggregateAnnotationCommandHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.Repository;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import org.junit.jupiter.api.*;

import static org.axonframework.modelling.command.AggregateLifecycle.apply;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class DisruptorRepositoryTest {

    private final EventStore eventStore = mock(EventStore.class);

    @Test
    void disruptorCommandBusRepositoryNotAvailableOutsideOfInvokerThread() {
        DisruptorCommandBus commandBus = DisruptorCommandBus.builder().build();
        Repository<TestAggregate> repository = commandBus
                .createRepository(eventStore, new GenericAggregateFactory<>(TestAggregate.class));

        AggregateAnnotationCommandHandler<TestAggregate> handler =
                AggregateAnnotationCommandHandler.<TestAggregate>builder()
                                                 .aggregateType(TestAggregate.class)
                                                 .repository(repository)
                                                 .build();

        handler.subscribe(commandBus);
        DefaultCommandGateway gateway = DefaultCommandGateway.builder().commandBus(commandBus).build();

        // Create the aggregate
        String aggregateId = "" + System.currentTimeMillis();
        gateway.sendAndWait(new CreateCommandAndEvent(aggregateId));

        // Load the aggregate from the repository -- from "worker" thread
        UnitOfWork<CommandMessage<?>> uow = DefaultUnitOfWork.startAndGet(null);
        try {
            repository.load(aggregateId);
            fail("Expected IllegalStateException");
        } catch (IllegalStateException e) {
            assertTrue(e.getMessage().contains("DisruptorCommandBus"));
        } finally {
            uow.rollback();
        }
    }

    public static class CreateCommandAndEvent {

        @TargetAggregateIdentifier
        private final String id;

        public CreateCommandAndEvent(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }
    }

    @SuppressWarnings("unused")
    public static class TestAggregate {

        @SuppressWarnings("FieldCanBeLocal")
        @AggregateIdentifier
        private String id;

        private TestAggregate() {
        }

        @CommandHandler
        public TestAggregate(CreateCommandAndEvent command) {
            apply(command);
        }

        @EventSourcingHandler
        private void on(CreateCommandAndEvent event) {
            this.id = event.getId();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_write"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="@string/reset_counter" />

        <Button
            android:id="@+id/button_write_no_response"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="@string/reset_counter_no_response" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_read_counter"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="@string/read" />

        <Button
            android:id="@+id/button_toggle_notify"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="@string/notify" />

        <Button
            android:id="@+id/button_toggle_indicate"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="@string/indicate" />

    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/textview_console"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textIsSelectable="true"
            android:typeface="monospace" />
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/button_clear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/clear" />

        <Button
            android:id="@+id/button_connect"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/connect" />

    </LinearLayout>

</LinearLayout>


text:
package org.ripple.bouncycastle.jce;

import java.util.Enumeration;

import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.ripple.bouncycastle.asn1.x9.X9ECParameters;
import org.ripple.bouncycastle.jce.spec.ECNamedCurveParameterSpec;

/**
 * a table of locally supported named curves.
 */
public class ECNamedCurveTable
{
    /**
     * return a parameter spec representing the passed in named
     * curve. The routine returns null if the curve is not present.
     *
     * @param name the name of the curve requested
     * @return a parameter spec for the curve, null if it is not available.
     */
    public static ECNamedCurveParameterSpec getParameterSpec(
        String  name)
    {
        X9ECParameters  ecP = org.ripple.bouncycastle.crypto.ec.CustomNamedCurves.getByName(name);
        if (ecP == null)
        {
            try
            {
                ecP = org.ripple.bouncycastle.crypto.ec.CustomNamedCurves.getByOID(new ASN1ObjectIdentifier(name));
            }
            catch (IllegalArgumentException e)
            {
                // ignore - not an oid
            }

            if (ecP == null)
            {
                ecP = org.ripple.bouncycastle.asn1.x9.ECNamedCurveTable.getByName(name);
                if (ecP == null)
                {
                    try
                    {
                        ecP = org.ripple.bouncycastle.asn1.x9.ECNamedCurveTable.getByOID(new ASN1ObjectIdentifier(name));
                    }
                    catch (IllegalArgumentException e)
                    {
                        // ignore - not an oid
                    }
                }
            }
        }

        if (ecP == null)
        {
            return null;
        }

        return new ECNamedCurveParameterSpec(
                                        name,
                                        ecP.getCurve(),
                                        ecP.getG(),
                                        ecP.getN(),
                                        ecP.getH(),
                                        ecP.getSeed());
    }

    /**
     * return an enumeration of the names of the available curves.
     *
     * @return an enumeration of the names of the available curves.
     */
    public static Enumeration getNames()
    {
        return org.ripple.bouncycastle.asn1.x9.ECNamedCurveTable.getNames();
    }
}


text:
Title: Tie skaitļi ir abrīnojami.
Date: 2008-02-11 06:38
Category: Sākums
Tags: 2008
Lang: lv

Mazliet atkal par inflāciju, bet sāksim par ko citu. Vakar braucu no Valmieras, apturēja policija. Ātrums pārsniegts nebija, gaismas ieslēgtas bija un visas dega, tiesības un tehniskā arī bija līdzi un tad viņš paprasīja par apdrošināšanu. Iedodu polisi, viņš tā skatās un saka: "Te kaut kas nav kārtībā.", paskatos .. hmz, tiešām nav. Izrādās 8 dienas beigusies apdrošināšana. "Būs jāmaksā sods, 30 - 50 latu apmērā un būs jāuzgaida 10 minūtes." Tiek sastādīts protokols, par kuru mazliet vēlāk.

Aizbraucam uz alfu, lai uzreiz nopirktu jaunu polisi. Iepriekšējo reizi pirku ergo, jo bija tikai ~17ls. Aizeju apsēžos, saku, ka vajadzētu apdrošināt automašīnu. Džekiņš tur visu datorā sabaksta un saka, ka 15,...(neatceros precīzi). Es jau sapriecājies, saku, ka jā, jā, ņemu, bet viņš kaut ko palabo un saka: "Jūsu automašīnai tomēr 44,...". wtf? Viņš ieteica aiziet tur pat uz baltu, jo viņiem vēl nav cēlušās cenas.

Tagad jautājums. Cēlušās cenas? no 17 uz 45 latiem? Inflācija? Es teiktu - wtf? Tas vai tad nesanāk 164%? Kā ir ar apdrošināšanu Igaunijā? :D

Es protams saprotu, ka cenas pieaug, utt, bet tas ir neprāts par tādiem procentiem, vienk. 3 mēnešu laikā.

Par to protokolu. Nez kāpēc viņi uzreiz neuzliek sodu, bet man tagad jākavē laiks, jādomā kā tikt no darba un jāiet kaut kur skaidroties. Es jau iedomājos sarunu:

Viņš: "Kāpēc nebija polises?"

Es: "Domāju, ka polise ir derīga līdz martam! Uzreiz pēc tam aizbraucu un nopirku jaunu."

Viņš: "Sods 40ls"

Es: "Paldies!"

Domās: "Sasodīts, paldies .. par to, ka uzliekat man sodu! Tikai 40ls? Tiešām nebūs 120ls? Inflācija! Vajadzēja būt vismaz 100ls."

Tas varētu prasīt kādas 5 minūtes. Un pēc 30 minūtes, lai viņš uzrakstītu vēlvienu protokolu, kur norādīta maksājamā summa, utt(bet es jau nezinu, nekad neesmu bijis). Un vēlviena sačakarēta diena. Mums tā visa sistēma ir kaut kāda nepareiza.


text:
using System;

class Lines
{
	static readonly byte[] linesBySize = { 0, 0, 0, 0, 0, 0, 0, 0 };
	static readonly byte[] transposedNumbers = { 0, 0, 0, 0, 0, 0, 0, 0 };

	static void Main()
	{
			byte[] numbers = new byte[8];

			for (byte i = 0; i < 8; i++)
			{
				numbers[i] = byte.Parse(Console.ReadLine());
				CountLinesInNumber(numbers[i]);
				TransposeBits(i, numbers[i]);
			}
			foreach (byte j in transposedNumbers)
			{
				CountLinesInNumber(j);
			}
			RemoveDoubleCountingInSingles();
			byte maxCount = 0;
			byte maxCountLength = 0;
			for (byte c = 8; c >= 1; c--)
			{
				if (linesBySize[c - 1] > maxCount)
				{
					maxCountLength = c;
					maxCount = linesBySize[c - 1];
					break;
				}
			}
			Console.WriteLine(maxCountLength);
			Console.WriteLine(maxCount);
	}

	static void CountLinesInNumber(byte currentNumber)
	{
		byte currentBitCount = 0;
		byte currentBit = 0;
		byte previousBit = 0;
		while (currentNumber > 0)
			{
				currentBit = (byte)(1 & currentNumber);
				if (currentBit == 1)
				{
					currentBitCount++;
					if (currentNumber == 1)
					{
						linesBySize[currentBitCount - 1]++;
					}
				}
				else if (currentBit == 0 && previousBit == 1)
				{
					linesBySize[currentBitCount - 1]++;
					currentBitCount = 0;
				}

				previousBit = currentBit;
				currentNumber >>= 1;
			}
	}
	static void TransposeBits(byte numberIndex, byte currentNumber)
	{
		byte currentBit = 0;
		byte currentPosition = 0;
		while (currentNumber > 0)
		{
			currentBit = (byte)(1 & currentNumber);
			if (currentBit == 1)
			{
				transposedNumbers[currentPosition] |= (byte)(1 << numberIndex);
			}
			currentNumber >>= 1;
			currentPosition++;
		}
	}
	static void RemoveDoubleCountingInSingles()
	{
		if (linesBySize[0] != 0)
			linesBySize[0] /= 2;
	}
}


text:
package org.tp23.antinstaller.renderer.text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ResourceBundle;

import org.tp23.antinstaller.InstallerContext;
import org.tp23.antinstaller.input.DateInput;
import org.tp23.antinstaller.input.OutputField;

public class DateInputRenderer
	implements TextOutputFieldRenderer {

	private static final ResourceBundle res = ResourceBundle.getBundle("org.tp23.antinstaller.renderer.text.Res");

	protected InstallerContext ctx;
	public DateInputRenderer() {
	}

	public void setContext(InstallerContext ctx) {
		this.ctx = ctx;
	}

	public void renderOutput(OutputField field, BufferedReader reader, PrintStream out) throws IOException {
		DateInput iField = (DateInput) field;
		out.print(field.getDisplayText());

		out.print("   [");
		out.print(res.getString("_default_"));
		out.print(":");
		out.print(iField.getDefaultValue());
		out.println("]");

// @TODO check this from the patch submitted for bug 1469254
		String input = reader.readLine();

		out.println();
		if(input==null || input.equals(""))input = iField.getDefaultValue();
		iField.setInputResult(input);
	}
	public void renderError(OutputField field, BufferedReader reader, PrintStream out) throws IOException{
		DateInput iField = (DateInput) field;
		out.println("The input is not in the correct format:"+iField.getDateFormat());
		renderOutput(field, reader, out);
	}
	public boolean isAbort(){
		return false;
	}
}


text:
using Microsoft.Owin;
using Owin;
using Phobos.Api.App_Start;

[assembly: OwinStartup(typeof(Phobos.Api.Startup))]

namespace Phobos.Api
{
	public class Startup
	{
		public void Configuration(IAppBuilder app)
		{
			SimpleInjector.Container container = new SimpleInjector.Container();

			CompositionRoot.CompositionRoot.Register(container, app);

			OAuthConfig.Register(container, app);

			WebApiConfig.Register(container, app);
		}
	}
}


text:
<!DOCTYPE html>

    <title>savvit</title>

savvit

        quick start

        {{ link }} to authenticate with reddit and download your file.

        what

        savvit backs up the pages you have saved on reddit. it exports them
        to a bookmarks file that you can import in to your web browser
        or view as a regular html file.

        how

        savvit is a tiny python script that uses praw, flask, twisted, and a
        few other packages. you can find the source
        here.

        limitations

        chrome has a bug that prevents it from loading the bookmarks file,
        but a bug report has been filed and it's being fixed. only
        firefox has been tested to work for importing bookmarks, but you
        can use any browser to view the file as regular html.

        feedback

        i plan on developing savvit a bit further if enough people like it.
        if you have any questions, comments, or suggestions, please feel free to
        comment on github or send a message to /u/1npo on reddit.


text:
from datadog_checks.base.utils.models.fields import get_default_field_value

def shared_service(field, value):
    return get_default_field_value(field, value)

def instance_collect_client_metrics(field, value):
    return False

def instance_command_stats(field, value):
    return False

def instance_db(field, value):
    return 0

def instance_disable_connection_cache(field, value):
    return False

def instance_disable_generic_tags(field, value):
    return False

def instance_empty_default_hostname(field, value):
    return False

def instance_keys(field, value):
    return get_default_field_value(field, value)

def instance_metric_patterns(field, value):
    return get_default_field_value(field, value)

def instance_min_collection_interval(field, value):
    return 15

def instance_password(field, value):
    return get_default_field_value(field, value)

def instance_service(field, value):
    return get_default_field_value(field, value)

def instance_slowlog_max_len(field, value):
    return 128

def instance_socket_timeout(field, value):
    return 5

def instance_ssl(field, value):
    return False

def instance_ssl_ca_certs(field, value):
    return get_default_field_value(field, value)

def instance_ssl_cert_reqs(field, value):
    return 2

def instance_ssl_certfile(field, value):
    return get_default_field_value(field, value)

def instance_ssl_keyfile(field, value):
    return get_default_field_value(field, value)

def instance_tags(field, value):
    return get_default_field_value(field, value)

def instance_unix_socket_path(field, value):
    return get_default_field_value(field, value)

def instance_username(field, value):
    return get_default_field_value(field, value)

def instance_warn_on_missing_keys(field, value):
    return True


text:
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Core.Services;
using NadekoBot.Core.Services.Database;
using NadekoBot.Core.Services.Database.Models;
using NadekoBot.Extensions;

namespace NadekoBot.Core.Modules.Gambling.Services
{
    public class ShopService : IShopService
    {
        private readonly DbService _db;

        public ShopService(DbService db)
        {
            _db = db;
        }

        private IndexedCollection<ShopEntry> GetEntriesInternal(IUnitOfWork uow, ulong guildId) =>
            uow.GuildConfigs.ForId(
                    guildId,
                    set => set.Include(x => x.ShopEntries).ThenInclude(x => x.Items)
                )
                .ShopEntries
                .ToIndexed();

        public async Task<bool> ChangeEntryPriceAsync(ulong guildId, int index, int newPrice)
        {
            if (index < 0)
                throw new ArgumentOutOfRangeException(nameof(index));
            if (newPrice <= 0)
                throw new ArgumentOutOfRangeException(nameof(newPrice));

            using var uow = _db.GetDbContext();
            var entries = GetEntriesInternal(uow, guildId);

            if (index >= entries.Count)
                return false;

            entries[index].Price = newPrice;
            await uow.SaveChangesAsync();
            return true;
        }

        public async Task<bool> ChangeEntryNameAsync(ulong guildId, int index, string newName)
        {
            if (index < 0)
                throw new ArgumentOutOfRangeException(nameof(index));
            if (string.IsNullOrWhiteSpace(newName))
                throw new ArgumentNullException(nameof(newName));

            using var uow = _db.GetDbContext();
            var entries = GetEntriesInternal(uow, guildId);

            if (index >= entries.Count)
                return false;

            entries[index].Name = newName.TrimTo(100);
            await uow.SaveChangesAsync();
            return true;
        }

        public async Task<bool> SwapEntriesAsync(ulong guildId, int index1, int index2)
        {
            if (index1 < 0)
                throw new ArgumentOutOfRangeException(nameof(index1));
            if (index2 < 0)
                throw new ArgumentOutOfRangeException(nameof(index2));

            using var uow = _db.GetDbContext();
            var entries = GetEntriesInternal(uow, guildId);

            if (index1 >= entries.Count || index2 >= entries.Count || index1 == index2)
                return false;

            entries[index1].Index = index2;
            entries[index2].Index = index1;

            await uow.SaveChangesAsync();
            return true;
        }

        public async Task<bool> MoveEntryAsync(ulong guildId, int fromIndex, int toIndex)
        {
            if (fromIndex < 0)
                throw new ArgumentOutOfRangeException(nameof(fromIndex));
            if (toIndex < 0)
                throw new ArgumentOutOfRangeException(nameof(toIndex));

            using var uow = _db.GetDbContext();
            var entries = GetEntriesInternal(uow, guildId);

            if (fromIndex >= entries.Count || toIndex >= entries.Count || fromIndex == toIndex)
                return false;

            var entry = entries[fromIndex];
            entries.RemoveAt(fromIndex);
            entries.Insert(toIndex, entry);

            await uow.SaveChangesAsync();
            return true;
        }
    }
}


text:
<?php

namespace Bkwld\Decoy\Controllers;

use Auth;
use Decoy;
use Former;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Bkwld\Decoy\Models\Admin;
use Illuminate\Foundation\Auth\ResetsPasswords;

/**
 * Handle logging in of users.  This is based on the AuthController.php and
 * PasswordController that Laravel's `php artisan make:auth` generates.
 */
class ResetPassword extends Base
{
    use ResetsPasswords;

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null               $token
     * @return \Illuminate\Http\Response
     */
    public function showResetForm(Request $request, $token = null)
    {
        // Pass validation rules
        Former::withRules([
            'email'                 => 'required|email',
            'password'              => 'required',
            'password_confirmation' => 'required|same:password',
        ]);

        // Set the breadcrumbs
        app('decoy.breadcrumbs')->set([
            route('decoy::account@login') => 'Login',
            route('decoy::account@forgot') => 'Forgot Password',
            url()->current() => 'Reset Password',
        ]);

        // Show the page
        $this->title = 'Reset Password';
        $this->description = 'Almost done.';

        return $this->populateView('decoy::account.reset', [
            'token' => $token,
        ]);
    }

    /**
     * Get the post register / login redirect path. This is set to the login route
     * so that the guest middleware can pick it up and redirect to the proper
     * start page.
     *
     * @return string
     */
    public function redirectPath()
    {
        return route('decoy::account@login');
    }

    /**
     * Subclass the resetPassword method so that it doesn't `bcrypt()` the
     * password.  We're trusting to the model's onSaving callback for this.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword $user
     * @param  string                                      $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $user->forceFill([
            'password' => $password,
            'remember_token' => Str::random(60),
        ])->save();

        Auth::login($user);
    }
}


text:
import $ from "@/jlib2";
import api from "@/pg-api";
import flashMessage from "@/flash";

function login() {
    const data = {
        username: $("[name=username]").value(),
        password: $("[name=password]").value()
    };

    if (data.username === "" || data.password === "") {
        return;
    }

    $("#login-btn").prop("disabled", "true");
    $("#login-btn").text("Logging in...");

    api.login(
        data,
        () => (location.href = "/"),
        (req: any) => {
            $("#login-btn").text("Login");
            $("#login-btn").prop("disabled", "false");
            if (req.status === 401) {
                flashMessage("Incorrect username or password");
            } else {
                flashMessage("Unknown error");
            }
        }
    );
}

function checkKeyAndLogin(e: Event) {
    if ((e as KeyboardEvent).keyCode === 13) {
        login();
    }
}

$("#login-btn").click(login);
$("[name=username]").keyup(checkKeyAndLogin);
$("[name=password]").keyup(checkKeyAndLogin);


text:
#ifndef AMGCL_IO_MM_HPP
#define AMGCL_IO_MM_HPP

/**
 * \file   amgcl/io/mm.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Readers for Matrix Market sparse matrices and dense vectors.
 */

#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <numeric>

#include <type_traits>
#include <tuple>

#include <amgcl/util.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/value_type/interface.hpp>
#include <amgcl/detail/sort_row.hpp>

namespace amgcl {
namespace io {

/// Matrix market reader.
class mm_reader {
    public:
        /// Open the file by name
        mm_reader(const std::string &fname) : f(fname) {
            precondition(f, "Failed to open file \"" + fname + "\"");

            // Read banner.
            precondition(std::getline(f, line), format_error());

            std::istringstream is(line);
            std::string banner, mtx, coord, dtype, storage;

            precondition(
                    is >> banner >> mtx >> coord >> dtype >> storage,
                    format_error());

            precondition(banner  == "%%MatrixMarket", format_error("no banner"));
            precondition(mtx     == "matrix",         format_error("not a matrix"));

            if (storage == "general") {
                _symmetric = false;
            } else if (storage == "symmetric") {
                _symmetric = true;
            } else {
                precondition(false, "unsupported storage type");
            }

            if (coord == "coordinate") {
                _sparse = true;
            } else if (coord == "array") {
                _sparse = false;
            } else {
                precondition(false, format_error("unsupported coordinate type"));
            }

            if (dtype == "real") {
                _complex = false;
                _integer = false;
            } else if (dtype == "complex") {
                _complex = true;
                _integer = false;
            } else if (dtype == "integer") {
                _complex = false;
                _integer = true;
            } else {
                precondition(false, format_error("unsupported data type"));
            }

            // Skip comments.
            do {
                precondition(std::getline(f, line), format_error("unexpected eof"));
            } while (line[0] == '%');

            // The last line is comment-free and holds the matrix sizes
            is.clear(); is.str(line);
            precondition(is >> nrows >> ncols, format_error());
        }

        /// Matrix in the file is symmetric.
        bool is_symmetric()  const { return _symmetric; }

        /// Matrix in the file is sparse.
        bool is_sparse()  const { return _sparse; }

        /// Matrix in the file is complex-valued.
        bool is_complex() const { return _complex; }

        /// Matrix in the file is integer-valued.
        bool is_integer() const { return _integer; }

        /// Number of rows.
        size_t rows() const { return nrows; }

        /// Number of rows.
        size_t cols() const { return ncols; }

        /// Read sparse matrix from the file.
        template <typename Idx, typename Val>
        std::tuple<size_t, size_t> operator()(
                std::vector<Idx> &ptr,
                std::vector<Idx> &col,
                std::vector<Val> &val,
                ptrdiff_t row_beg = -1,
                ptrdiff_t row_end = -1
                )
        {
            precondition(_sparse, format_error("not a sparse matrix"));
            precondition(amgcl::is_complex<Val>::value == _complex,
                    _complex ?
                        "attempt to read complex values into real vector" :
                        "attempt to read real values into complex vector"
                        );
            precondition(std::is_integral<Val>::value == _integer,
                    _integer ?
                        "attempt to read integer values into real vector" :
                        "attempt to read real values into integer vector"
                        );

            // Read sizes
            ptrdiff_t n, m;
            size_t nnz;
            std::istringstream is;
            {
                // line already holds the matrix sizes
                is.clear(); is.str(line);
                precondition(is >> n >> m >> nnz, format_error());
            }

            if (row_beg < 0) row_beg = 0;
            if (row_end < 0) row_end = n;

            precondition(row_beg >= 0 && row_end <= n,
                    "Wrong subset of rows is requested");

            ptrdiff_t _nnz = _symmetric ? 2 * nnz : nnz;

            if (row_beg != 0 || row_end != n)
                _nnz *= 1.2 * (row_end - row_beg) / n;

            std::vector<Idx> _row; _row.reserve(_nnz);
            std::vector<Idx> _col; _col.reserve(_nnz);
            std::vector<Val> _val; _val.reserve(_nnz);

            ptrdiff_t chunk = row_end - row_beg;

            ptr.resize(chunk + 1); std::fill(ptr.begin(), ptr.end(), 0);

            for(size_t k = 0; k < nnz; ++k) {
                precondition(std::getline(f, line), format_error("unexpected eof"));
                is.clear(); is.str(line);

                Idx i, j;
                Val v;

                precondition(is >> i >> j, format_error());

                i -= 1;
                j -= 1;

                v = read_value<Val>(is);

                if (row_beg <= i && i < row_end) {
                    ++ptr[i - row_beg + 1];

                    _row.push_back(i - row_beg);
                    _col.push_back(j);
                    _val.push_back(v);
                }

                if (_symmetric && i != j && row_beg <= j && j < row_end) {
                    ++ptr[j - row_beg + 1];

                    _row.push_back(j - row_beg);
                    _col.push_back(i);
                    _val.push_back(v);
                }
            }

            std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());

            col.resize(ptr.back());
            val.resize(ptr.back());

            for(size_t k = 0, e = val.size(); k < e; ++k) {
                Idx i = _row[k];
                Idx j = _col[k];
                Val v = _val[k];

                Idx head = ptr[i]++;
                col[head] = j;
                val[head] = v;
            }

            std::rotate(ptr.begin(), ptr.end() - 1, ptr.end());
            ptr.front() = 0;

#pragma omp parallel for
            for(ptrdiff_t i = 0; i < chunk; ++i) {
                Idx beg = ptr[i];
                Idx end = ptr[i+1];

                amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg);
            }

            return std::make_tuple(chunk, m);
        }

        /// Read dense array from the file.
        template <typename Val>
        std::tuple<size_t, size_t> operator()(
                std::vector<Val> &val,
                ptrdiff_t row_beg = -1,
                ptrdiff_t row_end = -1
                )
        {
            precondition(!_sparse, format_error("not a dense array"));
            precondition(amgcl::is_complex<Val>::value == _complex,
                    _complex ?
                        "attempt to read complex values into real vector" :
                        "attempt to read real values into complex vector"
                        );
            precondition(std::is_integral<Val>::value == _integer,
                    _integer ?
                        "attempt to read integer values into real vector" :
                        "attempt to read real values into integer vector"
                        );

            // Read sizes
            ptrdiff_t n, m;
            std::istringstream is;
            {
                // line already holds the matrix sizes
                is.clear(); is.str(line);
                precondition(is >> n >> m, format_error());
            }

            if (row_beg < 0) row_beg = 0;
            if (row_end < 0) row_end = n;

            precondition(row_beg >= 0 && row_end <= n,
                    "Wrong subset of rows is requested");

            val.resize((row_end - row_beg) * m);

            for(ptrdiff_t j = 0; j < m; ++j) {
                for(ptrdiff_t i = 0; i < n; ++i) {
                    precondition(std::getline(f, line), format_error("unexpected eof"));
                    if (row_beg <= i && i < row_end) {
                        is.clear(); is.str(line);
                        val[(i - row_beg) * m + j] = read_value<Val>(is);
                    }
                }
            }

            return std::make_tuple(row_end - row_beg, m);
        }
    private:
        std::ifstream f;
        std::string line;

        bool _sparse;
        bool _symmetric;
        bool _complex;
        bool _integer;

        size_t nrows, ncols;

        std::string format_error(const std::string &msg = "") const {
            std::string err_string = "MatrixMarket format error";
            if (!msg.empty())
                err_string += " (" + msg + ")";
            return err_string;
        }

        template <typename T>
        typename std::enable_if<amgcl::is_complex<T>::value, T>::type
        read_value(std::istream &s) {
            typename math::scalar_of<T>::type x,y;
            precondition(s >> x >> y, format_error());
            return T(x,y);
        }

        template <typename T>
        typename std::enable_if<!amgcl::is_complex<T>::value, T>::type
        read_value(std::istream &s) {
            T x;
            if (std::is_same<T, char>::value) {
                // Special case:
                // We want to read 8bit integers from MatrixMarket, not chars.
                int i;
                precondition(s >> i, format_error());
                x = static_cast<char>(i);
            } else {
                precondition(s >> x, format_error());
            }
            return x;
        }

};

namespace detail {
template <typename Val>
typename std::enable_if<is_complex<Val>::value, std::ostream&>::type
write_value(std::ostream &s, Val v) {
    return s << std::scientific << std::setprecision(20) << std::real(v) << " " << std::imag(v);
}

template <typename Val>
typename std::enable_if<!is_complex<Val>::value, std::ostream&>::type
write_value(std::ostream &s, Val v) {
    return s << std::scientific << std::setprecision(20) << v;
}

} // namespace detail

/// Write dense array in Matrix Market format.
template <typename Val>
void mm_write(
        const std::string &fname,
        const Val *data,
        size_t rows,
        size_t cols = 1
        )
{
    std::ofstream f(fname.c_str());
    precondition(f, "Failed to open file \"" + fname + "\" for writing");

    // Banner
    f << "%%MatrixMarket matrix array ";
    if (is_complex<Val>::value) {
        f << "complex ";
    } else if(std::is_integral<Val>::value) {
        f << "integer ";
    } else {
        f << "real ";
    }
    f << "general\n";

    // Sizes
    f << rows << " " << cols << "\n";

    // Data
    for(size_t j = 0; j < cols; ++j) {
        for(size_t i = 0; i < rows; ++i) {
            detail::write_value(f, data[i * cols + j]) << "\n";
        }
    }
}

/// Write sparse matrix in Matrix Market format.
template <class Matrix>
void mm_write(const std::string &fname, const Matrix &A) {
    typedef typename backend::value_type<Matrix>::type Val;

    const size_t rows = backend::rows(A);
    const size_t cols = backend::cols(A);
    const size_t nnz  = backend::nonzeros(A);

    std::ofstream f(fname.c_str());
    precondition(f, "Failed to open file \"" + fname + "\" for writing");

    // Banner
    f << "%%MatrixMarket matrix coordinate ";
    if (is_complex<Val>::value) {
        f << "complex ";
    } else if(std::is_integral<Val>::value) {
        f << "integer ";
    } else {
        f << "real ";
    }
    f << "general\n";

    // Sizes
    f << rows << " " << cols << " " << nnz << "\n";

    // Data
    for(size_t i = 0; i < rows; ++i) {
        for(auto a = backend::row_begin(A, i); a; ++a) {
            f << i + 1 << " " << a.col() + 1 << " ";
            detail::write_value(f, a.value()) << "\n";
        }
    }
}

} // namespace io
} // namespace amgcl

#endif


text:
recife
======

simple compositor

requirements to build
======
* Qt
* OpenCV

TODO
======
* bug - app crash on timeline change without layer (or without selected layer)
* feature - add video source
* feature - add js validation to inputs
* feature - add resolution support
* feature - render to video/image file
* feature - save session to disk
* feature - change scale of render viewport (100%, 50%, etc.)


text:
@implementation CCLCellDayTranslation

+ (instancetype)cellDayTranslationFor:(CCLCalendarData *)calendarData
{
    return [[self alloc] initWithCalendarData:calendarData];
}

- (instancetype)init
{
    return [self initWithCalendarData:nil];
}

- (instancetype)initWithCalendarData:(CCLCalendarData *)calendarData
{
    NSParameterAssert(calendarData);

    self = [super init];

    if (self)
    {
        _calendarData = calendarData;
    }

    return self;
}

- (NSCalendar *)calendar
{
    return [[CTKCalendarSupplier calendarSupplier] autoupdatingCalendar];
}

#pragma mark -
#pragma mark Day Locator

- (CCLDayLocator *)dayLocatorForColumn:(NSUInteger)column row:(NSUInteger)row
{
    CCLCalendarData *calendarData = self.calendarData;

    if ([calendarData rowViewTypeForRow:row] == CCLRowViewTypeMonth)
    {
        @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"row must not be a month's title row" userInfo:nil];
    }

    // TODO violates LoD, pull this out of CalendarData
    CCLMonth *month = [calendarData monthForRow:row];
    NSUInteger monthTitleRow = [calendarData.titleRows previousMonthRowOfRow:row];
    NSUInteger firstWeekRow = monthTitleRow + 1;
    NSUInteger week = row - firstWeekRow + 1; // weeks are 1-based
    NSUInteger weekday = [self weekdayForColumn:column];
    CCLDayLocator *dayLocator = [CCLDayLocator dayLocatorInMonth:month week:week weekday:weekday];

    return dayLocator;
}

- (NSUInteger)weekdayForColumn:(NSUInteger)column
{
    NSUInteger weekday = column + 1;
    NSUInteger firstWeekdayRollover = [self firstWeekdayRollover];

    return weekday + firstWeekdayRollover;
}

/// Returns the distance in days from the beginning of week to the weekday ordinal.
/// If @p firstWeekday is 2 (Monday), this method returns @p 1.
- (NSUInteger)firstWeekdayRollover
{
    NSCalendar *calendar = [self calendar];
    NSUInteger firstWeekday = calendar.firstWeekday;
    NSUInteger weekdayRollover = firstWeekday - 1;

    return weekdayRollover;
}

#pragma mark Week Locator

- (CCLDayLocator *)weekLocatorForRow:(NSUInteger)row
{
#warning stub: add locator for Week Total
    NSUInteger column = 0;
    return [self dayLocatorForColumn:column row:row];
}
@end


text:
SYNONYM

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

#### Published in
Hedwigia 34: 319 (1895)

#### Original name
Sirentyloma salaciae Henn., 1895

### Remarks
null


text:
/**
 *
 */
package de.unikoblenz.west.koldfish.dam.cli;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.jms.JMSException;

import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIException;
import org.apache.jena.iri.IRIFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.google.common.primitives.Longs;

import de.unikoblenz.west.koldfish.dam.DataAccessModule;
import de.unikoblenz.west.koldfish.dam.DataAccessModuleException;
import de.unikoblenz.west.koldfish.dam.DataAccessModuleListener;
import de.unikoblenz.west.koldfish.dam.ErrorResponse;
import de.unikoblenz.west.koldfish.dam.impl.JmsDataAccessModule;
import de.unikoblenz.west.koldfish.dictionary.Dictionary;
import de.unikoblenz.west.koldfish.messages.DerefResponse;

/**
 * @author lkastler
 *
 */
public class DataAccessModuleMain {

  private static final Logger log = LogManager.getLogger(DataAccessModuleMain.class);

  public static void main(String[] args) throws Exception {
    List<IRI> iris = new LinkedList<IRI>();

    for (String iri : args) {
      try {
        iris.add(IRIFactory.iriImplementation().construct(iri));
      } catch (IRIException e) {
        log.warn("{} is not a proper IRI", iri);
      }
    }

    DataAccessModuleMain main = new DataAccessModuleMain();

    main.handle(iris);

  }

  private volatile AtomicInteger uris = new AtomicInteger();

  private DataAccessModule dam;

  private DataAccessModuleMain() throws Exception {
    dam = new JmsDataAccessModule();

    dam.addListener(new DataAccessModuleListener() {

      Dictionary dict = new Dictionary();

      @Override
      public void onDerefResponse(DerefResponse response) {
        for (long[] items : response) {
          try {
            log.debug(dict.convertIds(Longs.asList(items)));
          } catch (JMSException e) {
            log.error(e);
          }
        }
      }

      @Override
      public void onErrorResponse(ErrorResponse response) {
        log.error(response.getException());
      }

    });

    dam.start();
  }

  private void handle(List<IRI> iris) {
    uris.addAndGet(iris.size());

    for (IRI iri : iris) {
      log.info("trying to deref IRI {}", iri);
      try {
        dam.deref(iri);
      } catch (DataAccessModuleException e) {
        log.error(e);
        uris.decrementAndGet();
      }
    }
  }

}


text:
package msgraph

import "context"

//
type WorkbookFunctionsSkew_pRequestBuilder struct{ BaseRequestBuilder }

// Skew_p action undocumented
func (b *WorkbookFunctionsRequestBuilder) Skew_p(reqObj *WorkbookFunctionsSkew_pRequestParameter) *WorkbookFunctionsSkew_pRequestBuilder {
	bb := &WorkbookFunctionsSkew_pRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
	bb.BaseRequestBuilder.baseURL += "/skew_p"
	bb.BaseRequestBuilder.requestObject = reqObj
	return bb
}

//
type WorkbookFunctionsSkew_pRequest struct{ BaseRequest }

//
func (b *WorkbookFunctionsSkew_pRequestBuilder) Request() *WorkbookFunctionsSkew_pRequest {
	return &WorkbookFunctionsSkew_pRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
	}
}

//
func (r *WorkbookFunctionsSkew_pRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {
	err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj)
	return
}


text:
require File.join(File.dirname(__FILE__), '../../test_helper')

class RemoteWirecardTest < Test::Unit::TestCase

  def setup
    test_account = fixtures(:wirecard)
    test_account[:signature] = test_account[:login]
    @gateway = WirecardGateway.new(test_account)

    @amount = 100
    @credit_card = credit_card('4200000000000000')
    @declined_card = credit_card('4000300011112220')

    @options = {
      :order_id => 1,
      :billing_address => address,
      :description => 'Wirecard remote test purchase',
      :email => 'soleone@example.com'
    }
  end

  # Success tested
  def test_successful_authorization
    assert response = @gateway.authorize(@amount, @credit_card, @options)
    assert_success response
    assert response.test?
    assert response.message[/THIS IS A DEMO/]
    assert response.authorization
  end

  def test_successful_authorize_and_capture
    amount = @amount
    assert auth = @gateway.authorize(amount, @credit_card, @options)
    assert_success auth
    assert auth.message[/THIS IS A DEMO/]
    assert auth.authorization
    assert capture = @gateway.capture(amount, auth.authorization, @options)
    assert_success capture
  end

  def test_successful_purchase
    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_success response
    assert response.message[/THIS IS A DEMO/]
  end

  # Failure tested

  def test_wrong_creditcard_authorization
    assert response = @gateway.authorize(@amount, @declined_card, @options)
    assert_failure response
    assert response.test?
    assert response.message[/credit card number not allowed in demo mode/i]
  end

  def test_wrong_creditcard_purchase
    assert response = @gateway.purchase(@amount, @declined_card, @options)
    assert_failure response
    assert response.message[ /Credit card number not allowed in demo mode/ ]
  end

  def test_unauthorized_capture
    assert response = @gateway.capture(@amount, "1234567890123456789012")
    assert_failure response
    assert response.message == "Could not find referenced transaction for GuWID 1234567890123456789012."
  end

  def test_invalid_login
    gateway = WirecardGateway.new(:login => '', :password => '', :signature => '')
    assert response = gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert response.message[ /wrong credentials/ ]
  end

end


text:
require_relative "../base"

describe SfnParameters::Safe::Ssl do
  let(:key) { "TEST_KEY" }
  let(:salt) { "TEST_SALT" }
  let(:subject) { described_class.new(key: key, salt: salt) }

  it "should have key set" do
    expect(subject.arguments[:key]).to eq(key)
  end

  it "should have salt set" do
    expect(subject.arguments[:salt]).to eq(salt)
  end

  describe "#new" do
    context "when key is unset" do
      let(:key) { nil }

      it "should raise an ArgumentError" do
        expect { subject }.to raise_error(ArgumentError)
      end
    end

    context "when salt is unset" do
      let(:salt) { nil }

      it "should generate a random salt" do
        expect(subject.arguments[:salt]).to be_a(String)
      end
    end
  end

  describe "#lock" do
    let(:data) { "TEST_DATA" }
    let(:lock) { subject.lock(data) }

    it "should return a Hash result" do
      expect(lock).to be_a(Hash)
    end

    it "should include base64 encoded salt" do
      expect(lock[:salt]).to eq(
        Base64.urlsafe_encode64(salt)
      )
    end

    it "should set type of safe used" do
      expect(lock[:sfn_parameters_lock]).to eq("ssl")
    end

    it "should include cipher used" do
      expect(lock[:cipher]).to eq(described_class.const_get(:DEFAULT_CIPHER))
    end

    it "should base64 encode locked value" do
      expect(Base64.urlsafe_decode64(lock[:content])).to be_a(String)
    end

    it "should encrypt locked value" do
      expect(Base64.urlsafe_decode64(lock[:content])).not_to eq(data)
    end
  end

  describe "#unlock" do
    let(:data) { "TEST_DATA" }

    it "should properly unlock locked data" do
      locked = subject.lock(data)
      expect(Base64.urlsafe_decode64(locked[:content])).not_to eq(data)
      expect(subject.unlock(locked)).to eq(data)
    end

    context "with missing content" do
      it "should raise an ArgumentError" do
        locked = subject.lock(data)
        locked.delete(:content)
        expect { subject.unlock(locked) }.to raise_error(ArgumentError)
      end
    end

    context "with missing iv" do
      it "should raise an ArgumentError" do
        locked = subject.lock(data)
        locked.delete(:iv)
        expect { subject.unlock(locked) }.to raise_error(ArgumentError)
      end
    end

    context "with missing salt" do
      it "should raise an ArgumentError" do
        locked = subject.lock(data)
        locked.delete(:salt)
        expect { subject.unlock(locked) }.to raise_error(ArgumentError)
      end
    end
  end
end


text:
from msrest.serialization import Model

class SentimentBatchResultItem(Model):
    """SentimentBatchResultItem.

    :param id: Unique, non-empty document identifier.
    :type id: str
    :param score: A decimal number between 0 and 1 denoting the sentiment of
     the document. A score above 0.7 usually refers to a positive document
     while a score below 0.3 normally has a negative connotation. Mid values
     refer to neutral text.
    :type score: float
    :param statistics: (Optional) if showStats=true was specified in the
     request this field will contain information about the document payload.
    :type statistics:
     ~azure.cognitiveservices.language.textanalytics.models.DocumentStatistics
    """

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'score': {'key': 'score', 'type': 'float'},
        'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'},
    }

    def __init__(self, *, id: str=None, score: float=None, statistics=None, **kwargs) -> None:
        super(SentimentBatchResultItem, self).__init__(**kwargs)
        self.id = id
        self.score = score
        self.statistics = statistics


text:
<Weapon>
	<Category>Cannon</Category>
	<AmmoCost>0.4</AmmoCost>
	<Arc>90</Arc>
	<Delay>5</Delay>
	<SalvoSize>2</SalvoSize>
	<SalvoDelay>0.45</SalvoDelay>
	<FirePowerRating>2</FirePowerRating>
	<ProjectileLife>2.0</ProjectileLife>
	<ProjectileSpeed>8.0</ProjectileSpeed>
	<WeaponEffect>flakbolt</WeaponEffect>
	<FireSound>BasicCannon</FireSound>
	<HitEffect>explosionflak</HitEffect>
	<HitEffectTime>1.4</HitEffectTime>
	<HitEffectScale>0.1</HitEffectScale>
	<Scale>0.16</Scale>
	<Spread>8</Spread>
	<FighterDamageModifier>1.5</FighterDamageModifier>
	<ProjectileDamageModifier>2</ProjectileDamageModifier>
	<PointDefense>true</PointDefense>
	<dieOnProjectileCollision>true</dieOnProjectileCollision>
	<DamageGraph>
		<DamageNode>
			<Range>0</Range>
			<Damage>230</Damage>
		</DamageNode>
		<DamageNode>
			<Range>205</Range>
			<Damage>103</Damage>
		</DamageNode>
	</DamageGraph>
</Weapon>


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Mapping;

/**
 * @property MappedSuperClassMetadata $parent
 */
class RootClassMetadata extends EntityClassMetadata
{
    public function getRootClass() : RootClassMetadata
    {
        return $this;
    }
}


text:
package com.google.moviestvsentiments.assetSentiment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * A controller that handles requests related to Assets and UserSentiments.
 */
@RestController
public class AssetSentimentController {

    @Autowired
    private AssetSentimentRepository assetSentimentRepository;

    @Autowired
    private UserSentimentRepository userSentimentRepository;

    /**
     * Returns a list of AssetSentiments that match the given AssetType, account name and SentimentType.
     * @param assetType The type of Asset to match.
     * @param accountName The name of the account to use when checking for user sentiments.
     * @param sentimentType The type of user sentiment to match.
     * @return A list of matching AssetSentiments.
     */
    @GetMapping("/assets")
    public List<AssetSentiment> getAssets(@RequestParam("assetType") AssetType assetType,
                                          @RequestParam("accountName") String accountName,
                                          @RequestParam("sentimentType") SentimentType sentimentType) {
        List<AssetSentiment> withReaction = assetSentimentRepository.getAssetsWithSentiment(assetType, accountName,
                sentimentType);
        if (sentimentType != SentimentType.UNSPECIFIED) {
            return withReaction;
        }

        List<AssetSentiment> withoutReaction = assetSentimentRepository.getAssetsWithoutSentiment(assetType, accountName);
        withReaction.addAll(withoutReaction);
        return withReaction;
    }

    /**
     * Inserts or replaces the UserSentiment with the given fields into the user sentiments table. If the UserSentiment
     * is saved successfully, the saved version is returned. If the user sentiment cannot be saved, an error message is
     * returned.
     * @param accountName The name of the account associated with the UserSentiment.
     * @param assetId The id of the asset associated with the UserSentiment.
     * @param assetType The type of the asset associated with the UserSentiment.
     * @param sentimentType The type of the UserSentiment.
     * @param timestamp The timestamp of the UserSentiment.
     * @return A ResponseEntity with either the saved UserSentiment or the error message.
     */
    @PutMapping("/sentiment")
    public ResponseEntity updateSentiment(@RequestParam String accountName, @RequestParam String assetId,
                                          @RequestParam AssetType assetType, @RequestParam SentimentType sentimentType,
                                          @RequestParam Instant timestamp) {
        try {
            UserSentiment userSentiment = UserSentiment.create(accountName, assetId, assetType, sentimentType, timestamp);
            userSentiment = userSentimentRepository.save(userSentiment);
            return ResponseEntity.ok().body(userSentiment);
        } catch (JpaSystemException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    /**
     * Updates the given list of UserSentiments in the database and returns the list of successfully updated
     * UserSentiments. If a UserSentiment does not already exist in the database, then it will be added. If the
     * UserSentiments can not be saved, then an error message is returned.
     * @param sentiments The list of UserSentiments to update.
     * @return A ResponseEntity with either the updated UserSentiments or the error message.
     */
    @PutMapping("/sentiments")
    public ResponseEntity updateSentiments(@RequestBody List<UserSentiment> sentiments) {
        try {
            Iterable<UserSentiment> iterable = userSentimentRepository.saveAll(sentiments);
            List<UserSentiment> savedSentiments = StreamSupport.stream(iterable.spliterator(), false)
                    .collect(Collectors.toList());
            return ResponseEntity.ok().body(savedSentiments);
        } catch (JpaSystemException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
}


text:
title: Restrict Possible Usernames
---
## Restrict Possible Usernames

## Solution:
```javascript
let username = "JackOfAllTrades";
let userCheck = /^[a-z]{2,}\d*$/i;
let result = userCheck.test(username);
```
## Explain:
1. The only numbers in the username have to be at the end. `\d$`
   There can be zero or more of them at the end. `*`
```javascript
/\d*$/;
```
2. Username letters can be lowercase and uppercase. `i`
```javascript
/\d*$/i;
```
3. Usernames have to be at least two characters long. `{2,}`
   A two-letter username can only use alphabet letter characters. `^[a-z]`
```javascript
/^[a-z]{2,}\d*$/i;
```


text:
#ifndef OCTREE_POINTCLOUD_HPP_
#define OCTREE_POINTCLOUD_HPP_

#include <vector>
#include <assert.h>

#include <pcl/common/common.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT>
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::OctreePointCloud (const double resolution) :
    OctreeT (), input_ (PointCloudConstPtr ()), indices_ (IndicesConstPtr ()),
    epsilon_ (0), resolution_ (resolution), minX_ (0.0f), maxX_ (resolution), minY_ (0.0f),
    maxY_ (resolution), minZ_ (0.0f), maxZ_ (resolution), boundingBoxDefined_ (false)
{
  assert (resolution > 0.0f);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT>
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::~OctreePointCloud ()
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::addPointsFromInputCloud ()
{
  size_t i;

  assert (this->leafCount_==0);
  if (indices_)
  {
    for (std::vector<int>::const_iterator current = indices_->begin (); current != indices_->end (); ++current)
    {
      if (isFinite (input_->points[*current]))
      {
        assert( (*current>=0) && (*current < static_cast<int> (input_->points.size ())));

        // add points to octree
        this->addPointIdx (*current);
      }
    }
  }
  else
  {
    for (i = 0; i < input_->points.size (); i++)
    {
      if (isFinite (input_->points[i]))
      {
        // add points to octree
        this->addPointIdx (static_cast<unsigned int> (i));
      }
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::addPointFromCloud (const int pointIdx_arg, IndicesPtr indices_arg)
{
  this->addPointIdx (pointIdx_arg);
  if (indices_arg)
    indices_arg->push_back (pointIdx_arg);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::addPointToCloud (const PointT& point_arg, PointCloudPtr cloud_arg)
{
  assert (cloud_arg==input_);

  cloud_arg->points.push_back (point_arg);

  this->addPointIdx (static_cast<const int> (cloud_arg->points.size ()) - 1);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::addPointToCloud (const PointT& point_arg, PointCloudPtr cloud_arg,
                                                           IndicesPtr indices_arg)
{
  assert (cloud_arg==input_);
  assert (indices_arg==indices_);

  cloud_arg->points.push_back (point_arg);

  this->addPointFromCloud (static_cast<const int> (cloud_arg->points.size ()) - 1, indices_arg);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> bool
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::isVoxelOccupiedAtPoint (const PointT& point_arg) const
{
  OctreeKey key;

  // generate key for point
  this->genOctreeKeyforPoint (point_arg, key);

  // search for key in octree
  return (isPointWithinBoundingBox (point_arg) && this->existLeaf (key));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> bool
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::isVoxelOccupiedAtPoint (const int& pointIdx_arg) const
{
  // retrieve point from input cloud
  const PointT& point = this->input_->points[pointIdx_arg];

  // search for voxel at point in octree
  return (this->isVoxelOccupiedAtPoint (point));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> bool
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::isVoxelOccupiedAtPoint (
    const double pointX_arg, const double pointY_arg, const double pointZ_arg) const
{
  OctreeKey key;

  // generate key for point
  this->genOctreeKeyforPoint (pointX_arg, pointY_arg, pointZ_arg, key);

  return (this->existLeaf (key));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::deleteVoxelAtPoint (const PointT& point_arg)
{
  OctreeKey key;

  // generate key for point
  this->genOctreeKeyforPoint (point_arg, key);

  this->removeLeaf (key);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::deleteVoxelAtPoint (const int& pointIdx_arg)
{
  // retrieve point from input cloud
  const PointT& point = this->input_->points[pointIdx_arg];

  // delete leaf at point
  this->deleteVoxelAtPoint (point);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> int
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getOccupiedVoxelCenters (
    AlignedPointTVector &voxelCenterList_arg) const
{
  OctreeKey key;
  key.x = key.y = key.z = 0;

  voxelCenterList_arg.clear ();

  return getOccupiedVoxelCentersRecursive (this->rootNode_, key, voxelCenterList_arg);

}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> int
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getApproxIntersectedVoxelCentersBySegment (
    const Eigen::Vector3f& origin,
    const Eigen::Vector3f& end,
    AlignedPointTVector &voxel_center_list,
    float precision)
{
  Eigen::Vector3f direction = end - origin;
  float norm = direction.norm ();
  direction.normalize ();

  const float step_size = static_cast<const float> (resolution_) * precision;
  // Ensure we get at least one step for the first voxel.
  const int nsteps = std::max (1, static_cast<int> (norm / step_size));

  OctreeKey prev_key;

  bool bkeyDefined = false;

  // Walk along the line segment with small steps.
  for (int i = 0; i < nsteps; ++i)
  {
    Eigen::Vector3f p = origin + (direction * step_size * static_cast<const float> (i));

    PointT octree_p;
    octree_p.x = p.x ();
    octree_p.y = p.y ();
    octree_p.z = p.z ();

    OctreeKey key;
    this->genOctreeKeyforPoint (octree_p, key);

    // Not a new key, still the same voxel.
    if ((key == prev_key) && (bkeyDefined) )
      continue;

    prev_key = key;
    bkeyDefined = true;

    PointT center;
    genLeafNodeCenterFromOctreeKey (key, center);
    voxel_center_list.push_back (center);
  }

  OctreeKey end_key;
  PointT end_p;
  end_p.x = end.x ();
  end_p.y = end.y ();
  end_p.z = end.z ();
  this->genOctreeKeyforPoint (end_p, end_key);
  if (!(end_key == prev_key))
  {
    PointT center;
    genLeafNodeCenterFromOctreeKey (end_key, center);
    voxel_center_list.push_back (center);
  }

  return (static_cast<int> (voxel_center_list.size ()));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::defineBoundingBox ()
{

  double minX, minY, minZ, maxX, maxY, maxZ;

  PointT min_pt;
  PointT max_pt;

  // bounding box cannot be changed once the octree contains elements
  assert (this->leafCount_ == 0);

  pcl::getMinMax3D (*input_, min_pt, max_pt);

  float minValue = std::numeric_limits<float>::epsilon () * 512.0f;

  minX = min_pt.x;
  minY = min_pt.y;
  minZ = min_pt.z;

  maxX = max_pt.x + minValue;
  maxY = max_pt.y + minValue;
  maxZ = max_pt.z + minValue;

  // generate bit masks for octree
  defineBoundingBox (minX, minY, minZ, maxX, maxY, maxZ);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::defineBoundingBox (const double minX_arg,
                                                                          const double minY_arg,
                                                                          const double minZ_arg,
                                                                          const double maxX_arg,
                                                                          const double maxY_arg,
                                                                          const double maxZ_arg)
{
  // bounding box cannot be changed once the octree contains elements
  assert (this->leafCount_ == 0);

  assert (maxX_arg >= minX_arg);
  assert (maxY_arg >= minY_arg);
  assert (maxZ_arg >= minZ_arg);

  minX_ = minX_arg;
  maxX_ = maxX_arg;

  minY_ = minY_arg;
  maxY_ = maxY_arg;

  minZ_ = minZ_arg;
  maxZ_ = maxZ_arg;

  minX_ = min (minX_, maxX_);
  minY_ = min (minY_, maxY_);
  minZ_ = min (minZ_, maxZ_);

  maxX_ = max (minX_, maxX_);
  maxY_ = max (minY_, maxY_);
  maxZ_ = max (minZ_, maxZ_);

  // generate bit masks for octree
  getKeyBitSize ();

  boundingBoxDefined_ = true;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::defineBoundingBox (
    const double maxX_arg, const double maxY_arg, const double maxZ_arg)
{
  // bounding box cannot be changed once the octree contains elements
  assert (this->leafCount_ == 0);

  assert (maxX_arg >= 0.0f);
  assert (maxY_arg >= 0.0f);
  assert (maxZ_arg >= 0.0f);

  minX_ = 0.0f;
  maxX_ = maxX_arg;

  minY_ = 0.0f;
  maxY_ = maxY_arg;

  minZ_ = 0.0f;
  maxZ_ = maxZ_arg;

  minX_ = min (minX_, maxX_);
  minY_ = min (minY_, maxY_);
  minZ_ = min (minZ_, maxZ_);

  maxX_ = max (minX_, maxX_);
  maxY_ = max (minY_, maxY_);
  maxZ_ = max (minZ_, maxZ_);

  // generate bit masks for octree
  getKeyBitSize ();

  boundingBoxDefined_ = true;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::defineBoundingBox (const double cubeLen_arg)
{
  // bounding box cannot be changed once the octree contains elements
  assert (this->leafCount_ == 0);

  assert (cubeLen_arg >= 0.0f);

  minX_ = 0.0f;
  maxX_ = cubeLen_arg;

  minY_ = 0.0f;
  maxY_ = cubeLen_arg;

  minZ_ = 0.0f;
  maxZ_ = cubeLen_arg;

  minX_ = min (minX_, maxX_);
  minY_ = min (minY_, maxY_);
  minZ_ = min (minZ_, maxZ_);

  maxX_ = max (minX_, maxX_);
  maxY_ = max (minY_, maxY_);
  maxZ_ = max (minZ_, maxZ_);

  // generate bit masks for octree
  getKeyBitSize ();

  boundingBoxDefined_ = true;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getBoundingBox (
    double& minX_arg, double& minY_arg, double& minZ_arg,
    double& maxX_arg, double& maxY_arg, double& maxZ_arg) const
{
  minX_arg = minX_;
  minY_arg = minY_;
  minZ_arg = minZ_;

  maxX_arg = maxX_;
  maxY_arg = maxY_;
  maxZ_arg = maxZ_;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT>
void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::adoptBoundingBoxToPoint (const PointT& pointIdx_arg)
{

  const float minValue = std::numeric_limits<float>::epsilon ();

  // increase octree size until point fits into bounding box
  while (true)
  {
    bool bLowerBoundViolationX = (pointIdx_arg.x < minX_);
    bool bLowerBoundViolationY = (pointIdx_arg.y < minY_);
    bool bLowerBoundViolationZ = (pointIdx_arg.z < minZ_);

    bool bUpperBoundViolationX = (pointIdx_arg.x >= maxX_);
    bool bUpperBoundViolationY = (pointIdx_arg.y >= maxY_);
    bool bUpperBoundViolationZ = (pointIdx_arg.z >= maxZ_);

    // do we violate any bounds?
    if (bLowerBoundViolationX || bLowerBoundViolationY || bLowerBoundViolationZ || bUpperBoundViolationX
        || bUpperBoundViolationY || bUpperBoundViolationZ )
    {

      if (boundingBoxDefined_)
      {

        double octreeSideLen;
        unsigned char childIdx;

        // octree not empty - we add another tree level and thus increase its size by a factor of 2*2*2
        childIdx = static_cast<unsigned char> (((!bUpperBoundViolationX) << 2) | ((!bUpperBoundViolationY) << 1)
            | ((!bUpperBoundViolationZ)));

        OctreeBranch* newRootBranch;

        this->createBranch (newRootBranch);
        this->branchCount_++;

        this->setBranchChild (*newRootBranch, childIdx, this->rootNode_);

        this->rootNode_ = newRootBranch;

        octreeSideLen = static_cast<double> (1 << this->octreeDepth_) * resolution_;

        if (!bUpperBoundViolationX)
          minX_ -= octreeSideLen;

        if (!bUpperBoundViolationY)
          minY_ -= octreeSideLen;

        if (!bUpperBoundViolationZ)
          minZ_ -= octreeSideLen;

        // configure tree depth of octree
        this->octreeDepth_++;
        this->setTreeDepth (this->octreeDepth_);

        // recalculate bounding box width
        octreeSideLen = static_cast<double> (1 << this->octreeDepth_) * resolution_ - minValue;

        // increase octree bounding box
        maxX_ = minX_ + octreeSideLen;
        maxY_ = minY_ + octreeSideLen;
        maxZ_ = minZ_ + octreeSideLen;

      }
      // bounding box is not defined - set it to point position
      else
      {
        // octree is empty - we set the center of the bounding box to our first pixel
        this->minX_ = pointIdx_arg.x - this->resolution_ / 2;
        this->minY_ = pointIdx_arg.y - this->resolution_ / 2;
        this->minZ_ = pointIdx_arg.z - this->resolution_ / 2;

        this->maxX_ = pointIdx_arg.x + this->resolution_ / 2;
        this->maxY_ = pointIdx_arg.y + this->resolution_ / 2;
        this->maxZ_ = pointIdx_arg.z + this->resolution_ / 2;

        getKeyBitSize ();

        boundingBoxDefined_ = true;
      }

    }
    else
      // no bound violations anymore - leave while loop
      break;
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::addPointIdx (const int pointIdx_arg)
{
  OctreeKey key;

  assert (pointIdx_arg < static_cast<int> (input_->points.size ()));

  const PointT& point = input_->points[pointIdx_arg];

  // make sure bounding box is big enough
  adoptBoundingBoxToPoint (point);

  // generate key
  genOctreeKeyforPoint (point, key);

  // add point to octree at key
  this->add (key, pointIdx_arg);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> const PointT&
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getPointByIndex (const unsigned int index_arg) const
{
  // retrieve point from input cloud
  assert (index_arg < static_cast<unsigned int> (input_->points.size ()));
  return (this->input_->points[index_arg]);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> LeafT*
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::findLeafAtPoint (const PointT& point) const
{
  OctreeKey key;

  // generate key for point
  this->genOctreeKeyforPoint (point, key);

  return (this->findLeaf (key));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getKeyBitSize ()
{
  unsigned int maxVoxels;

  unsigned int maxKeyX;
  unsigned int maxKeyY;
  unsigned int maxKeyZ;

  double octreeSideLen;

  const float minValue = std::numeric_limits<float>::epsilon();

  // find maximum key values for x, y, z
  maxKeyX = static_cast<unsigned int> ((maxX_ - minX_) / resolution_);
  maxKeyY = static_cast<unsigned int> ((maxY_ - minY_) / resolution_);
  maxKeyZ = static_cast<unsigned int> ((maxZ_ - minZ_) / resolution_);

  // find maximum amount of keys
  maxVoxels = max (max (max (maxKeyX, maxKeyY), maxKeyZ), static_cast<unsigned int> (2));

  // tree depth == amount of bits of maxVoxels
  this->octreeDepth_ = max ((min (static_cast<unsigned int> (OCT_MAXTREEDEPTH), static_cast<unsigned int> (ceil (this->Log2 (maxVoxels)-minValue)))),
                                  static_cast<unsigned int> (0));

  octreeSideLen = static_cast<double> (1 << this->octreeDepth_) * resolution_-minValue;

  if (this->leafCount_ == 0)
  {
    double octreeOversizeX;
    double octreeOversizeY;
    double octreeOversizeZ;

    octreeOversizeX = (octreeSideLen - (maxX_ - minX_)) / 2.0;
    octreeOversizeY = (octreeSideLen - (maxY_ - minY_)) / 2.0;
    octreeOversizeZ = (octreeSideLen - (maxZ_ - minZ_)) / 2.0;

    minX_ -= octreeOversizeX;
    minY_ -= octreeOversizeY;
    minZ_ -= octreeOversizeZ;

    maxX_ += octreeOversizeX;
    maxY_ += octreeOversizeY;
    maxZ_ += octreeOversizeZ;
  }
  else
  {
    maxX_ = minX_ + octreeSideLen;
    maxY_ = minY_ + octreeSideLen;
    maxZ_ = minZ_ + octreeSideLen;
  }

 // configure tree depth of octree
  this->setTreeDepth (this->octreeDepth_);

}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::genOctreeKeyforPoint (const PointT& point_arg,
                                                                             OctreeKey & key_arg) const
  {
    // calculate integer key for point coordinates
    key_arg.x = static_cast<unsigned int> ((point_arg.x - this->minX_) / this->resolution_);
    key_arg.y = static_cast<unsigned int> ((point_arg.y - this->minY_) / this->resolution_);
    key_arg.z = static_cast<unsigned int> ((point_arg.z - this->minZ_) / this->resolution_);
  }

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::genOctreeKeyforPoint (
    const double pointX_arg, const double pointY_arg,
    const double pointZ_arg, OctreeKey & key_arg) const
{
  PointT tempPoint;

  tempPoint.x = static_cast<float> (pointX_arg);
  tempPoint.y = static_cast<float> (pointY_arg);
  tempPoint.z = static_cast<float> (pointZ_arg);

  // generate key for point
  genOctreeKeyforPoint (tempPoint, key_arg);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> bool
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::genOctreeKeyForDataT (const int& data_arg, OctreeKey & key_arg) const
{
  const PointT tempPoint = getPointByIndex (data_arg);

  // generate key for point
  genOctreeKeyforPoint (tempPoint, key_arg);

  return (true);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::genLeafNodeCenterFromOctreeKey (const OctreeKey & key, PointT & point) const
{
  // define point to leaf node voxel center
  point.x = static_cast<float> ((static_cast<double> (key.x) + 0.5f) * this->resolution_ + this->minX_);
  point.y = static_cast<float> ((static_cast<double> (key.y) + 0.5f) * this->resolution_ + this->minY_);
  point.z = static_cast<float> ((static_cast<double> (key.z) + 0.5f) * this->resolution_ + this->minZ_);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::genVoxelCenterFromOctreeKey (
    const OctreeKey & key_arg,
    unsigned int treeDepth_arg,
    PointT& point_arg) const
{
  // generate point for voxel center defined by treedepth (bitLen) and key
  point_arg.x = static_cast<float> ((static_cast <double> (key_arg.x) + 0.5f) * (this->resolution_ * static_cast<double> (1 << (this->octreeDepth_ - treeDepth_arg))) + this->minX_);
  point_arg.y = static_cast<float> ((static_cast <double> (key_arg.y) + 0.5f) * (this->resolution_ * static_cast<double> (1 << (this->octreeDepth_ - treeDepth_arg))) + this->minY_);
  point_arg.z = static_cast<float> ((static_cast <double> (key_arg.z) + 0.5f) * (this->resolution_ * static_cast<double> (1 << (this->octreeDepth_ - treeDepth_arg))) + this->minZ_);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::genVoxelBoundsFromOctreeKey (
    const OctreeKey & key_arg,
    unsigned int treeDepth_arg,
    Eigen::Vector3f &min_pt,
    Eigen::Vector3f &max_pt) const
{
  // calculate voxel size of current tree depth
  double voxel_side_len = this->resolution_ * static_cast<double> (1 << (this->octreeDepth_ - treeDepth_arg));

  // calculate voxel bounds
  min_pt (0) = static_cast<float> (static_cast<double> (key_arg.x) * voxel_side_len + this->minX_);
  min_pt (1) = static_cast<float> (static_cast<double> (key_arg.y) * voxel_side_len + this->minY_);
  min_pt (2) = static_cast<float> (static_cast<double> (key_arg.z) * voxel_side_len + this->minZ_);

  max_pt (0) = static_cast<float> (static_cast<double> (key_arg.x + 1) * voxel_side_len + this->minX_);
  max_pt (1) = static_cast<float> (static_cast<double> (key_arg.y + 1) * voxel_side_len + this->minY_);
  max_pt (2) = static_cast<float> (static_cast<double> (key_arg.z + 1) * voxel_side_len + this->minZ_);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> double
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getVoxelSquaredSideLen (unsigned int treeDepth_arg) const
{
  double sideLen;

  // side length of the voxel cube increases exponentially with the octree depth
  sideLen = this->resolution_ * static_cast<double>(1 << (this->octreeDepth_ - treeDepth_arg));

  // squared voxel side length
  sideLen *= sideLen;

  return (sideLen);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> double
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getVoxelSquaredDiameter (unsigned int treeDepth_arg) const
{
  // return the squared side length of the voxel cube as a function of the octree depth
  return (getVoxelSquaredSideLen (treeDepth_arg) * 3);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafT, typename OctreeT> int
pcl::octree::OctreePointCloud<PointT, LeafT, OctreeT>::getOccupiedVoxelCentersRecursive (
    const OctreeBranch* node_arg,
    const OctreeKey& key_arg,
    AlignedPointTVector &voxelCenterList_arg) const
{
  // child iterator
  unsigned char childIdx;

  int voxelCount = 0;

  // iterate over all children
  for (childIdx = 0; childIdx < 8; childIdx++)
  {
    if (!this->branchHasChild (*node_arg, childIdx))
      continue;

    const OctreeNode * childNode;
    childNode = this->getBranchChild (*node_arg, childIdx);

    // generate new key for current branch voxel
    OctreeKey newKey;
    newKey.x = (key_arg.x << 1) | (!!(childIdx & (1 << 2)));
    newKey.y = (key_arg.y << 1) | (!!(childIdx & (1 << 1)));
    newKey.z = (key_arg.z << 1) | (!!(childIdx & (1 << 0)));

    switch (childNode->getNodeType ())
    {
      case BRANCH_NODE:
      {
        // recursively proceed with indexed child branch
        voxelCount += getOccupiedVoxelCentersRecursive (static_cast<const OctreeBranch*> (childNode), newKey, voxelCenterList_arg);
        break;
      }
      case LEAF_NODE:
      {
        PointT newPoint;

        genLeafNodeCenterFromOctreeKey (newKey, newPoint);
        voxelCenterList_arg.push_back (newPoint);

        voxelCount++;
        break;
      }
      default:
        break;
    }
  }
  return (voxelCount);
}

#define PCL_INSTANTIATE_OctreePointCloudSingleBufferWithLeafDataTVector(T) template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafDataTVector<int> , pcl::octree::OctreeBase<int, pcl::octree::OctreeLeafDataTVector<int> > >;
#define PCL_INSTANTIATE_OctreePointCloudDoubleBufferWithLeafDataTVector(T) template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafDataTVector<int> , pcl::octree::Octree2BufBase<int, pcl::octree::OctreeLeafDataTVector<int> > >;
#define PCL_INSTANTIATE_OctreePointCloudLowMemWithLeafDataTVector(T)       template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafDataTVector<int> , pcl::octree::OctreeLowMemBase<int, pcl::octree::OctreeLeafDataTVector<int> > >;

#define PCL_INSTANTIATE_OctreePointCloudSingleBufferWithLeafDataT(T) template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafDataT<int> , pcl::octree::OctreeBase<int, pcl::octree::OctreeLeafDataT<int> > >;
#define PCL_INSTANTIATE_OctreePointCloudDoubleBufferWithLeafDataT(T) template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafDataT<int> , pcl::octree::Octree2BufBase<int, pcl::octree::OctreeLeafDataT<int> > >;
#define PCL_INSTANTIATE_OctreePointCloudLowMemWithLeafDataT(T)       template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafDataT<int> , pcl::octree::OctreeLowMemBase<int, pcl::octree::OctreeLeafDataT<int> > >;

#define PCL_INSTANTIATE_OctreePointCloudSingleBufferWithEmptyLeaf(T) template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafEmpty<int> , pcl::octree::OctreeBase<int, pcl::octree::OctreeLeafEmpty<int> > >;
#define PCL_INSTANTIATE_OctreePointCloudDoubleBufferWithEmptyLeaf(T) template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafEmpty<int> , pcl::octree::Octree2BufBase<int, pcl::octree::OctreeLeafEmpty<int> > >;
#define PCL_INSTANTIATE_OctreePointCloudLowMemWithEmptyLeaf(T)       template class PCL_EXPORTS pcl::octree::OctreePointCloud<T, pcl::octree::OctreeLeafEmpty<int> , pcl::octree::OctreeLowMemBase<int, pcl::octree::OctreeLeafEmpty<int> > >;

#endif /* OCTREE_POINTCLOUD_HPP_ */