text:
/**
 * @provides phortune-invoice-css
 */

.phortune-invoice-view {
  max-width: 800px;
  margin: 16px auto;
  background: #fff;
}

.phortune-invoice-view .phabricator-main-menu {
  display: none;
}

.phortune-invoice-view .phabricator-standard-page-footer {
  display: none;
}

.device-desktop .phortune-invoice-view .phui-property-list-key {
  width: 16%;
}

.device-desktop .phortune-invoice-view .phui-property-list-value {
  width: 80%;
}

.phortune-invoice-logo {
  margin-bottom: 24px;
}

.phortune-invoice-logo img {
  margin: 0 auto;
}

.phortune-invoice-contact {
  margin-bottom: 32px;
}

.phortune-invoice-contact td {
  padding: 4px 16px;
}

.phortune-invoice-to {
  border-right: 1px solid {$lightblueborder};
}

.phortune-mini-header {
  color: {$lightbluetext};
  font-weight: bold;
  text-transform: uppercase;
  margin-bottom: 4px;
  letter-spacing: 0.25em;
}

.phortune-invoice-status {
  margin-bottom: 24px;
}

.phortune-invoice-status .phui-info-view {
  margin: 0;
}

.phortune-invoice-view .phui-box.phui-object-box {
  margin-bottom: 24px;
}

.phortune-invoice-footer {
  color: {$lightgreytext};
  margin: 48px 0 64px;
  text-align: center;
}

.phortune-invoice-footer strong {
  color: #000;
}


text:
<?php

namespace AppBundle\Form;

use JMS\DiExtraBundle\Annotation\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * @FormType
 */
class MatchType extends AbstractType
{
    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @InjectParams({
     *     "translator" = @Inject("translator")
     * })
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email_to_user', 'textarea', [
                'label' => 'match.email.to',
                'attr'  => [
                    'rows' => 25
                ]
            ])
            ->add('email_to_match_user', 'textarea', [
                'label' => 'match.email.to',
                'attr'  => [
                    'rows' => 25
                ]
            ])
            ->add('user_id', 'hidden', [
                'label' => false,
                'data'  => $options['user']->getId()
            ])
            ->add('match_user_id', 'hidden', [
                'label' => false
            ])
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'mapped' => false
        ]);

        $resolver->setRequired([
            'user'
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'match';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package facebody

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

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// LiquifyFace invokes the facebody.LiquifyFace API synchronously
func (client *Client) LiquifyFace(request *LiquifyFaceRequest) (response *LiquifyFaceResponse, err error) {
	response = CreateLiquifyFaceResponse()
	err = client.DoAction(request, response)
	return
}

// LiquifyFaceWithChan invokes the facebody.LiquifyFace API asynchronously
func (client *Client) LiquifyFaceWithChan(request *LiquifyFaceRequest) (<-chan *LiquifyFaceResponse, <-chan error) {
	responseChan := make(chan *LiquifyFaceResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.LiquifyFace(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// LiquifyFaceWithCallback invokes the facebody.LiquifyFace API asynchronously
func (client *Client) LiquifyFaceWithCallback(request *LiquifyFaceRequest, callback func(response *LiquifyFaceResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *LiquifyFaceResponse
		var err error
		defer close(result)
		response, err = client.LiquifyFace(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// LiquifyFaceRequest is the request struct for api LiquifyFace
type LiquifyFaceRequest struct {
	*requests.RpcRequest
	FormatResultToJson requests.Boolean `position:"Query" name:"FormatResultToJson"`
	OssFile            string           `position:"Query" name:"OssFile"`
	SlimDegree         requests.Float   `position:"Body" name:"SlimDegree"`
	RequestProxyBy     string           `position:"Query" name:"RequestProxyBy"`
	ImageURL           string           `position:"Body" name:"ImageURL"`
}

// LiquifyFaceResponse is the response struct for api LiquifyFace
type LiquifyFaceResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Code      string `json:"Code" xml:"Code"`
	Message   string `json:"Message" xml:"Message"`
	Data      Data   `json:"Data" xml:"Data"`
}

// CreateLiquifyFaceRequest creates a request to invoke LiquifyFace API
func CreateLiquifyFaceRequest() (request *LiquifyFaceRequest) {
	request = &LiquifyFaceRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("facebody", "2019-12-30", "LiquifyFace", "facebody", "openAPI")
	request.Method = requests.POST
	return
}

// CreateLiquifyFaceResponse creates a response to parse from LiquifyFace response
func CreateLiquifyFaceResponse() (response *LiquifyFaceResponse) {
	response = &LiquifyFaceResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?php

namespace MartinBean\Database\Eloquent;

use Illuminate\Support\Str;

trait SingularTableName
{
    /**
     * Get the table associated with the model.
     *
     * @return string
     */
    public function getTable()
    {
        if (isset($this->table)) {
            return $this->table;
        }
        return str_replace('\\', '', Str::snake(Str::singular(class_basename($this))));
    }
}


text:
<?php

BLoader::import('boot.application.view');

class BApplicationView extends BObject
{

    public function prepare()
 {
        return null;
    }

    public function cleanup()
    {
        return null;
    }

}


text:
namespace media {

class DecoderBuffer;

// Maintains a queue of DecoderBuffers in increasing timestamp order.
//
// Individual buffer durations are ignored when calculating the duration of the
// queue i.e., the queue must have at least 2 in-order buffers to calculate
// duration.
//
// Not thread safe: access must be externally synchronized.
class MEDIA_EXPORT DecoderBufferQueue {
 public:
  DecoderBufferQueue();
  ~DecoderBufferQueue();

  // Push |buffer| to the end of the queue. If |buffer| is queued out of order
  // it will be excluded from duration calculations.
  //
  // It is invalid to push an end-of-stream |buffer|.
  void Push(const scoped_refptr<DecoderBuffer>& buffer);

  // Pops a DecoderBuffer from the front of the queue.
  //
  // It is invalid to call Pop() on an empty queue.
  scoped_refptr<DecoderBuffer> Pop();

  // Removes all queued buffers.
  void Clear();

  // Returns true if this queue is empty.
  bool IsEmpty();

  // Returns the duration of encoded data stored in this queue as measured by
  // the timestamps of the earliest and latest buffers, ignoring out of order
  // buffers.
  //
  // Returns zero if the queue is empty.
  base::TimeDelta Duration();

  // Returns the total size of buffers inside the queue.
  size_t data_size() const { return data_size_; }

 private:
  typedef std::deque<scoped_refptr<DecoderBuffer> > Queue;
  Queue queue_;

  // A subset of |queue_| that contains buffers that are in strictly
  // increasing timestamp order. Used to calculate Duration() while ignoring
  // out-of-order buffers.
  Queue in_order_queue_;

  base::TimeDelta earliest_valid_timestamp_;

  // Total size in bytes of buffers in the queue.
  size_t data_size_;

  DISALLOW_COPY_AND_ASSIGN(DecoderBufferQueue);
};

}  // namespace media

#endif  // MEDIA_BASE_DECODER_BUFFER_QUEUE_H_


text:
Yay, we can program with confidence that our work is backed up and history is saved!

There is *so much more* to Git, but this is 99% of what you'll be doing most of the time. It's a very powerful system that's used in a lot of different ways.

In general though, the average person just tracks their project history, commits their progress, and shares that history with a remote repository like GitLab or GitHub. Easy peasy.

I hope this was a fun introduction for you! Feel free to ask any questions you have on the Hello Web App discussion forum: https://discuss.hellowebapp.com

If you're looking for the next step, I invite you to check out Hello Web App, my book and course teaching web app development with Django. Even if you're new to programming and the command line, the book is pretty easy to just follow along, try things out, and learn more by doing. Check it out here: https://hellowebbooks.com/learn-django

Thanks friends, and good luck on your programming journey!

-Tracy


text:
ALTER TABLE Runtimeparameter ADD COLUMN name_ VARCHAR(255);
UPDATE Runtimeparameter SET name_ = REGEXP_SUBSTRING(key_,'[^:]*$');

SET DATABASE TRANSACTION CONTROL MVCC;

COMMIT;


text:
require 'spec_helper'

describe 'varnish::service' do
  describe 'varnish::service class on Debian' do
    let(:facts) {{
      :osfamily => 'Debian',
      :lsbdistid => 'Ubuntu',
    }}

    it { should contain_service('varnish').with({
        :ensure => 'stopped',
        :enable => false,
      })
    }
  end
end


text:
@implementation BMAttributedStringDescriptor

+ (instancetype)attributedStringDescriptorWithColor:(UIColor *)textColor font:(UIFont *)textFont {
    BMAttributedStringDescriptor *descriptor = [self new];
    descriptor.color = textColor;
    descriptor.font = textFont;
    return descriptor;
}

+ (instancetype)attributedStringDescriptorWithColor:(UIColor *)textColor font:(UIFont *)textFont range:(NSRange)range {
    BMAttributedStringDescriptor *descriptor = [self attributedStringDescriptorWithColor:textColor font:textFont];
    descriptor.range = range;
    return descriptor;
}

+ (instancetype)attributedStringDescriptorWithColor:(UIColor *)textColor font:(UIFont *)textFont paragraphStyle:(NSParagraphStyle *)paragraphStyle range:(NSRange)range {
    BMAttributedStringDescriptor *descriptor = [self attributedStringDescriptorWithColor:textColor font:textFont];
    descriptor.range = range;
    descriptor.paragraphStyle = paragraphStyle;
    return descriptor;
}

- (id)init {
    if ((self = [super init])) {
        self.range = NSMakeRange(0, NSUIntegerMax);
    }
    return self;
}

- (NSDictionary *)attributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    [attributes bmSafeSetObject:self.paragraphStyle forKey:NSParagraphStyleAttributeName];
    [attributes bmSafeSetObject:self.font forKey:NSFontAttributeName];
    [attributes bmSafeSetObject:self.color forKey:NSForegroundColorAttributeName];
    return attributes;
}

- (void)applyToString:(NSMutableAttributedString *)string {
    NSRange effectiveRange = self.range;

    effectiveRange.location = MIN(effectiveRange.location, string.length);
    effectiveRange.length = MIN(effectiveRange.length, string.length - effectiveRange.location);
    [string setAttributes:self.attributes range:effectiveRange];
}

@end


text:
package de.passau.uni.sec.compose.id.core.service;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import de.passau.uni.sec.compose.id.common.exception.IdManagementException;
import de.passau.uni.sec.compose.id.common.exception.IdManagementException.Level;
import de.passau.uni.sec.compose.id.core.domain.IPrincipal;
import de.passau.uni.sec.compose.id.core.event.Event;
import de.passau.uni.sec.compose.id.core.event.ListEntitiesInGroupEvent;
import de.passau.uni.sec.compose.id.core.event.ListUsersInGroupEvent;
import de.passau.uni.sec.compose.id.core.persistence.entities.EntityGroupMembership;
import de.passau.uni.sec.compose.id.core.persistence.entities.Group;
import de.passau.uni.sec.compose.id.core.persistence.entities.Membership;
import de.passau.uni.sec.compose.id.core.persistence.repository.EntityGroupMembershipRepository;
import de.passau.uni.sec.compose.id.core.persistence.repository.GroupRepository;
import de.passau.uni.sec.compose.id.core.persistence.repository.MembershipRepository;
import de.passau.uni.sec.compose.id.core.service.security.Authorization;
import de.passau.uni.sec.compose.id.rest.messages.EntityGroupMembershipResponseMessage;
import de.passau.uni.sec.compose.id.rest.messages.MembershipResponseMessage;
import de.passau.uni.sec.compose.id.rest.messages.UsersInGroupMessage;

@Service
public class ListEntitiesGroupService extends AbstractListEntityService
{

	private static Logger LOG = LoggerFactory.getLogger(ListEntitiesGroupService.class);

	@Autowired
    GroupRepository groupRepository;

	@Autowired
    EntityGroupMembershipRepository membershipRepository;

	@Autowired
	Authorization authz;

	@Override
	public Object postACListAllEntities(Event event)
			throws IdManagementException {

		ListEntitiesInGroupEvent lsitEvent = ((ListEntitiesInGroupEvent)event);
		Group group = groupRepository.getOne(lsitEvent.getId());
		List<EntityGroupMembership> membs = membershipRepository.findByGroup(group);
		List<EntityGroupMembershipResponseMessage> response = new LinkedList<EntityGroupMembershipResponseMessage>();
		for(EntityGroupMembership memb: membs)
		{
			if(memb.isApprovedByGroupOwner() && memb.isApprovedBySelfOwner())
				response.add(new EntityGroupMembershipResponseMessage(memb));
		}
		UsersInGroupMessage ret = new UsersInGroupMessage();
		ret.setApprovedMemberships(response);
		return ret;
	}

	@Override
	public void verifyACListAllEntities(Event event)
			throws IdManagementException {

		Collection<IPrincipal> p = event.getPrincipals();
		if(p == null || p.size()==0)
			throw new IdManagementException("Authentication required.",null, LOG," Attempt to access GET without providing credentials",Level.DEBUG, 401);

	}

}


text:
package com.angkorteam.framework.wicket.resource;

import com.angkorteam.framework.ResourceScope;
import org.apache.wicket.Application;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.request.resource.PackageResourceReference;

import java.util.LinkedList;
import java.util.List;

public class BootstrapResourceReference {

    public static final Javascript JAVASCRIPT = new Javascript();

    public static final Style STYLE = new Style();

    private static class Style extends PackageResourceReference {
        /**
         *
         */
        private static final long serialVersionUID = -6051027241848636445L;

        public Style() {
            super(ResourceScope.class, "AdminLTE/bootstrap/css/bootstrap.min.css");
        }
    }

    private static class Javascript extends PackageResourceReference {

        /**
         *
         */
        private static final long serialVersionUID = 4037301510391116867L;

        public Javascript() {
            super(ResourceScope.class, "AdminLTE/bootstrap/js/bootstrap.min.js");
        }

        @Override
        public List<HeaderItem> getDependencies() {
            List<HeaderItem> items = new LinkedList<>();
            items.add(JavaScriptHeaderItem.forReference(Application.get().getJavaScriptLibrarySettings().getJQueryReference()));
            return items;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;
using SampleBase;

namespace CStyleSamplesCS
{
    /// <summary>
    /// Image moment
    /// </summary>
    /// <remarks>http://opencv.jp/sample/moment.html</remarks>
    class Moments
    {
        public Moments()
        {
            using (IplImage srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.AnyColor | LoadMode.AnyDepth))
            {
                if (srcImg.NChannels == 3 && srcImg.COI == 0)
                {
                    srcImg.COI = 1;
                }

                CvMoments moments = new CvMoments(srcImg, false);
                srcImg.COI = 0;

                double spatialMoment = moments.GetSpatialMoment(0, 0);
                double centralMoment = moments.GetCentralMoment(0, 0);
                double normCMoment = moments.GetNormalizedCentralMoment(0, 0);
                CvHuMoments huMoments = new CvHuMoments(moments);

                // drawing
                using (CvFont font = new CvFont(FontFace.HersheySimplex, 1.0, 1.0, 0, 2, LineType.Link8))
                {
                    string[] text = new string[10];
                    text[0] = string.Format("spatial={0:F3}", spatialMoment);
                    text[1] = string.Format("central={0:F3}", centralMoment);
                    text[2] = string.Format("norm={0:F3}", spatialMoment);
                    text[3] = string.Format("hu1={0:F10}", huMoments.Hu1);
                    text[4] = string.Format("hu2={0:F10}", huMoments.Hu2);
                    text[5] = string.Format("hu3={0:F10}", huMoments.Hu3);
                    text[6] = string.Format("hu4={0:F10}", huMoments.Hu4);
                    text[7] = string.Format("hu5={0:F10}", huMoments.Hu5);
                    text[8] = string.Format("hu6={0:F10}", huMoments.Hu6);
                    text[9] = string.Format("hu7={0:F10}", huMoments.Hu7);

                    CvSize textSize = font.GetTextSize(text[0]);
                    for (int i = 0; i < 10; i++)
                    {
                        srcImg.PutText(text[i], new CvPoint(10, (textSize.Height + 3) * (i + 1)), font, CvColor.Black);
                    }
                }

                using (var window = new CvWindow("Image", WindowMode.AutoSize))
                {
                    window.ShowImage(srcImg);
                    Cv.WaitKey(0);
                }
            }

        }
    }
}


text:
js-calc is a client-side calculator developed in JavaScript and CSS that is
compatible with [Bootstrap][] and [jQuery][].

## Usage

In order to use js-calc add a HTML container element, e. g.

```html
<div class="calculator"></div>
```

Then load the CSS file (optionally use the minified version):

```html
<link rel="stylesheet" href="css/js-calc.min.css" />
```

Alternatively, you can import the LESS files in your LESS code.

Add `<script></script>` tags to load jQuery and js-calc (optionally use the
minified versions):

```html
<script src="jquery.min.js"></script>
<script src="js/js-calc.min.js"></script>
```

Then call the following code in JavaScript:

```javascript
$(".calculator").jscalc();
```

### Options

You can specify the following options when calling `jscalc()`:

* `point` (String). Specifies the locale-dependent character for the
  decimal point (default is ".").

### Examples

```javascript
$(".calculator").jscalc();      // use default options
$(".calculator").jscalc({
    point: ","
});                             // use German notation
```

## Build

To build js-calc perform the following steps:

1.  Prepare the `npm` environment using

    ```shell
    $ npm install
    ```

2.  Then execute

    ```shell
    $ grunt
    ```

3.  Afterwards, you find the built js-calc files in ``target/build`` as well
    as a documentation in ``target/docs``.

## Demo

To build and view a demo perform the following steps:

1.  Install needed `npm` modules using

    ```shell
    $ npm install
    ```

2.  Build the demo page using

    ```shell
    $ grunt demo
    ```

3.  View `demo.html` in folder `target/demo` using your favorite browser.

## Customization

If you wish to customize the calculator, feel free to change the LESS variables
in ``less/variables.less`` and re-build the software as described under
[Build](#Build).

## License

This piece of software was released under the [MIT License][MIT].

[Bootstrap]: http://getbootstrap.com
[jQuery]: http://jquery.com
[MIT]: http://opensource.org/licenses/MIT


text:
package edu.javacourse.hibernate;

/**
 * @author Demo
 */
//@Entity
//@Table(name = "jc_city")
public class City {

    //    @Id
//    @GeneratedValue(strategy = GenerationType.IDENTITY)
//    @Column(name = "city_id")
    private Integer cityId;

    //@Column(name = "city_name")
    private String cityName;

    // targetEntity используется в случае, если вместо класса интерфейс или суперкласс
    //@ManyToOne(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY, targetEntity = Region.class)
    //@JoinColumn(name = "region_id")  //
    private Region region;

    public City() {
    }

    public City(Integer cityId, String name, Region region) {
        this.cityId = cityId;
        this.cityName = name;
        this.region = region;
    }

    public Integer getCityId() {
        return cityId;
    }

    public void setCityId(Integer cityId) {
        this.cityId = cityId;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public Region getRegion() {
        return region;
    }

    public void setRegion(Region region) {
        this.region = region;
    }

    @Override
    public String toString() {
        return "City{" + "cityId=" + cityId + ", name=" + cityName + '}';
    }
}


text:
var rp = require('request-promise');
// var bodyParser = require('body-parser');

module.exports = {
	remoteCall : function(options){
		return rp(options);
	}
}


text:
export const dbConfig = {
    mongoDb : {
        //fill this out with your provider (or local)
        username: 'shane.arthur',
        'password':'Dallas4mavs8',
        'url' : 'ds011261.mlab.com:11261',
        'dbName' : 'shanewebsite'
    }
};

export const serverConfig = {
    webpackDevServerPort : 8080,
    expressPort : 3000
};

export const endpoints = {
    debug : 'http://localhost:3000',
    prod: 'production'
};


text:
..
   This file is part of Logtalk <https://logtalk.org/>
   Copyright 1998-2022 Paulo Moura <pmoura@logtalk.org>
   SPDX-License-Identifier: Apache-2.0

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

.. rst-class:: align-right

**built-in method**

.. index:: pair: catch/3; Built-in method
.. _methods_catch_3:

``catch/3``
===========

Description
-----------

::

   catch(Goal, Catcher, Recovery)

Catches exceptions thrown by a goal. See also the ISO Prolog standard
definition. This built-in meta-predicate is declared as a private method
and thus cannot be used as a message to an object.

Modes and number of proofs
--------------------------

::

   catch(?callable, ?term, ?callable) - zero_or_more

Errors
------

(none)

Examples
--------

(none)

.. seealso::

   :ref:`methods_throw_1`,
   :ref:`methods_context_1`,
   :ref:`methods_instantiation_error_0`,
   :ref:`methods_uninstantiation_error_1`,
   :ref:`methods_type_error_2`,
   :ref:`methods_domain_error_2`,
   :ref:`methods_existence_error_2`,
   :ref:`methods_permission_error_3`,
   :ref:`methods_evaluation_error_1`,
   :ref:`methods_representation_error_1`
   :ref:`methods_resource_error_1`,
   :ref:`methods_syntax_error_1`,
   :ref:`methods_system_error_0`


text:
var assert = require('assert'),
    _ = require('lodash')

// Assertions based on a single response
exports.statusCode = function(response, expected) {
  assert(_.isNumber(response.statusCode), "Response does not have a valid statusCode:\n" + JSON.stringify(response))
  if(_.isArray(expected)) {
    var allowed = _.map(expected, function(v) { return parseInt(v) })
    assert(_.includes(allowed, response.statusCode), "Expected in: " + allowed + "\nReceived: " + response.statusCode)
  } else {
    assert.strictEqual(response.statusCode, parseInt(expected), "Expected: " + expected + "\nReceived: " + response.statusCode)
  }
}

exports.responseBody = function(response, expected) {
  assert(_.isString(response.body), "Response does not have a body:\n" + JSON.stringify(response))
  assert.strictEqual(response.body, expected, "Expected: " + expected + "\nReceived: " + response.body)
}

exports.responseHeader = function(response, expected) {
  var expectedParts = expected.split(": ")
  var actual = response.headers[expectedParts[0].toLowerCase()]
  assert(_.isString(actual), "Response does not have '" + expectedParts[0] + "' header")
  if(expectedParts[1]) {
    assert.strictEqual(actual, expectedParts[1], "Expected: " + expectedParts[1] + "\nReceived: " + actual)
  }
}

exports.jsonResultCount = function(response, expected) {
  assert(_.isString(response.body), "Response does not have a body:\n" + JSON.stringify(response))

  var expectedCount = parseInt(expected)
  //console.log("checking for " + expectedCount + " rows")
  var results = JSON.parse(response.body)

  assert(_.isArray(results), "Expected JSON Array. Received: " + response.body)
  assert.strictEqual(results.length, expectedCount, "received " + results.length + " rows, expected " + expectedCount)
}

exports.jsonResult = function(response, expected) {
  assert(_.isString(response.body), "Response does not have a body:\n" + JSON.stringify(response))

  // console.log("deep comparison of parsed JSON")
  var expectedObj = (_.isArray(expected) || _.isObject(expected)) ? expected : JSON.parse(expected)
  var responseObj = JSON.parse(response.body)
  assert.deepEqual(responseObj, expectedObj, "\nExpected: " + JSON.stringify(expectedObj) + "\nReceived: " + response.body)
}

exports.jsonSubset = function(response, expected) {
  var expectedObj = (_.isArray(expected) || _.isObject(expected)) ? expected : JSON.parse(expected)
  var responseObj = JSON.parse(response.body)
  assertSubset(responseObj, expectedObj, "Expected subset: " + JSON.stringify(expectedObj) + "\nReceived: " + response.body)
}

var assertSubset = function(haystack, needle, message) {
  message = message || ""
  // Currently arrays must be same length and order... I *think* this is the right behavior
  if(_.isArray(haystack) && _.isArray(needle) && haystack.length == needle.length) {
    _.each(_.zip(haystack, needle), function(pair) { assertSubset(pair[0], pair[1], message) })
  } else if(_.isObject(haystack) && _.isObject(needle)) {
    _.forOwn(needle, function(value, key) {
      assert(_.has(haystack, key), message + "\nMissing key: " + key + " in " + JSON.stringify(haystack))
      assertSubset(haystack[key], value, message)
    })
  } else {
    assert.strictEqual(haystack, needle, message + "\nExpected: " + needle + "\nFound: " + haystack)
  }
}

exports.jsonUnorderedArray = function(response, expected) {
  assert(_.isString(response.body), "Response does not have a body:\n" + JSON.stringify(response))

  // console.log("deep comparison of parsed JSON ignoring order (slow)")
  var expectedArr = _.isArray(expected) ? expected : JSON.parse(expected)
  var responseArr = JSON.parse(response.body)
  assert(_.isArray(responseArr), "Expected JSON Array. Received: " + response.body)

  var alreadyFound = []
  _.each(responseArr, function(obj) {
    for(var j=0; j<expectedArr.length; j++) {
      if(_.isEqual(obj, expectedArr[j]) && !alreadyFound[j]) {
        alreadyFound[j] = true
        return
      }
    }
    assert.fail(responseArr, expectedArr,
      "Failed to find object in JSON array. Missing [at least one instance of]:\n" + JSON.stringify(obj))
  })
}

exports.jsonKeys = function(response, expected) {
  assert(_.isString(response.body), "Response does not have a body:\n" + JSON.stringify(response))

  //console.log("Checking for keys: " + expected)
  var results = JSON.parse(response.body)

  // Wrap non-array objects in array for sake of iterator
  if(!_.isArray(results)) { results = [results] }
  assert.ok(results.length > 0, "No results to compare")

  _.each(results, function(result){
    expectedKeys = (_.isObject(expected)) ? expected : JSON.parse(expected)
    resultKeys = _.keys(result)
    _.each(expectedKeys, function(key) {
      assert.ok( result.hasOwnProperty(key), "Missing key " + key + " in result: \n" + JSON.stringify(result))
    })
    assert.strictEqual(expectedKeys.length, resultKeys.length, "Expected keys: " + JSON.stringify(expectedKeys) + " but found extra keys in: " + JSON.stringify(result))
  })
}

// A bit experimental, but seems to simplify definining one-off assertions directly in a test
// YAML example:
// assert:
// - callback: !!js/function >
//     function handle(response) {
//       this.assert(response.statusCode < 500, 'Expected <500\nReceived '+response.statusCode)
//     }
exports.callback = function(response, callback) {
  var callbackFn = callback
  if(_.isString(callback)) {
    callbackFn = eval(callback)
  }
  assert(_.isFunction(callbackFn), "Expected: function \nReceived: " + callback)

  // Put _, assert, and require on the 'this' object of the callback
  callbackFn.call({ assert: assert, require: require, _: _ }, response)
}


text:
@interface NSString (Utils)

+ (NSString *)uuidString;

@end


text:
package org.jivesoftware.util.cache;

/**
 * Interface that defines the necessary behavior for objects added to a Cache.
 * Objects only need to know how big they are (in bytes). That size
 * should be considered to be a best estimate of how much memory the Object
 * occupies and may be based on empirical trials or dynamic calculations.

 *
 * While the accuracy of the size calculation is important, care should be
 * taken to minimize the computation time so that cache operations are
 * speedy.
 *
 * @author Jive Software
 * @see org.jivesoftware.util.cache.Cache
 */
public interface Cacheable extends java.io.Serializable {

    /**
     * Returns the approximate size of the Object in bytes. The size should be
     * considered to be a best estimate of how much memory the Object occupies
     * and may be based on empirical trials or dynamic calculations.

     *
     * @return the size of the Object in bytes.
     */
    public int getCachedSize() throws CannotCalculateSizeException;
}


text:
title: Documentation
layout: two-columns
---

## So You Want to Build Your Own Internet?!

There are three main components needed to build a minimal People's Open Network:
* __Home Nodes__
* __Exit Nodes__
* and a __Meshnode Database__

### Home Nodes
Typically, we use Western Digital MyNet N600 home routers as our Home Nodes. These need to be "flashed" with a custom version of OpenWrt, which includes Babel (routing protocol) and Tunneldigger (L2TP tunnelling, i.e. VPN). You can build your own version of this firmware here:  https://github.com/sudomesh/sudowrt-firmware

or you can download a pre-built version and follow our walkthrough: https://peoplesopen.net/walkthrough

### Exit Node
This will be your network's gateway to the larger internet. To learn how to build your own, check out https://github.com/sudomesh/exitnode

Once built, you may also want to test that you can connect to your Exit Node. Here are exercises to learn more about tunneling over your Exit Node: https://github.com/sudomesh/tunneldigger-lab

### Meshnode Database
This is a centralized server hosted somewhere, either on the internet or on a local network where you do all configuration of Home Nodes. To avoid IP address conflicts, this database keeps track of all IP addresses ever given out on your People's Open Network. To build your own meshnode database, follow the instructions here: https://github.com/sudomesh/meshnode-database

## Additional Components

### Extender Nodes
This is what we call roof-mounted tranceivers, which make point-to-point links over longer distances. Currently, the official recommendation is to leave the default firmware on Extender Nodes, though we do have an unmaintained version of our firmware for Extender Nodes. You can learn more about the Extender Nodes we use via the following links:
* https://sudoroom.org/wiki/Mesh/Flashing_extender_nodes
* https://github.com/sudomesh/node-whisperer-program/tree/master/extension

### Ethernet Crimping
Learn how to make your own internet tubes, so you can connect your extender nodes to your Home Node: https://github.com/sudomesh/propaganda/blob/master/handouts/how-to-make-straight-through-network-cables.pdf

### Admin Dashboard
A web dashboard for Home Nodes: https://github.com/sudomesh/peoplesopen-dash

### Admin Shell
A work-in-progress shell interface for Home Nodes: https://github.com/sudomesh/peoplesopen-shell


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using FluentAssertions;
using IdentityModel;
using IdentityServer4.Configuration;
using IdentityServer4.UnitTests.Common;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Xunit;

namespace IdentityServer4.UnitTests.Validation.AuthorizeRequest
{
    public class Authorize_ClientValidation_Invalid
    {
        private const string Category = "AuthorizeRequest Client Validation - Invalid";

        private IdentityServerOptions _options = TestIdentityServerOptions.Create();

        [Fact]
        [Trait("Category", Category)]
        public async Task Invalid_Protocol_Client()
        {
            var parameters = new NameValueCollection();
            parameters.Add(OidcConstants.AuthorizeRequest.ClientId, "wsfed");
            parameters.Add(OidcConstants.AuthorizeRequest.Scope, "openid");
            parameters.Add(OidcConstants.AuthorizeRequest.RedirectUri, "https://wsfed/callback");
            parameters.Add(OidcConstants.AuthorizeRequest.ResponseType, OidcConstants.ResponseTypes.IdToken);

            var validator = Factory.CreateAuthorizeRequestValidator();
            var result = await validator.ValidateAsync(parameters);

            result.IsError.Should().BeTrue();
            result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient);
        }
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.8.3928.0.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
[System.Xml.Serialization.XmlRootAttribute("Hypermedia", Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd", IsNullable=false)]
public partial class HypermediaType {

    private ParameterType[] transferParametersField;

    private DocumentType[] documentsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Parameters", IsNullable=false)]
    public ParameterType[] TransferParameters {
        get {
            return this.transferParametersField;
        }
        set {
            this.transferParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Document", IsNullable=false)]
    public DocumentType[] Documents {
        get {
            return this.documentsField;
        }
        set {
            this.documentsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class ParameterType {

    private PropertyType[] propertyField;

    private string typeNameField;

    private bool usedForQueriesField;

    private bool usedForActionsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Property")]
    public PropertyType[] Property {
        get {
            return this.propertyField;
        }
        set {
            this.propertyField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string typeName {
        get {
            return this.typeNameField;
        }
        set {
            this.typeNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool usedForQueries {
        get {
            return this.usedForQueriesField;
        }
        set {
            this.usedForQueriesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool usedForActions {
        get {
            return this.usedForActionsField;
        }
        set {
            this.usedForActionsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class PropertyType {

    private string nameField;

    private string typeField;

    private bool mandatoryField;

    private bool mandatoryFieldSpecified;

    private bool isKeyField;

    private bool isKeyFieldSpecified;

    private bool hiddenField;

    private bool hiddenFieldSpecified;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string type {
        get {
            return this.typeField;
        }
        set {
            this.typeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool mandatory {
        get {
            return this.mandatoryField;
        }
        set {
            this.mandatoryField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool mandatorySpecified {
        get {
            return this.mandatoryFieldSpecified;
        }
        set {
            this.mandatoryFieldSpecified = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool isKey {
        get {
            return this.isKeyField;
        }
        set {
            this.isKeyField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool isKeySpecified {
        get {
            return this.isKeyFieldSpecified;
        }
        set {
            this.isKeyFieldSpecified = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool hidden {
        get {
            return this.hiddenField;
        }
        set {
            this.hiddenField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool hiddenSpecified {
        get {
            return this.hiddenFieldSpecified;
        }
        set {
            this.hiddenFieldSpecified = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class ResultDocumentType {

    private string documentField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string document {
        get {
            return this.documentField;
        }
        set {
            this.documentField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class QueryParameterType {

    private string parameterNameField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string parameterName {
        get {
            return this.parameterNameField;
        }
        set {
            this.parameterNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class LinkType {

    private QueryParameterType[] queryParametersField;

    private ResultDocumentType[] resultDocumentsField;

    private string relField;

    private string documentField;

    private string queryField;

    private string contentTypeField;

    private string parameterTypeNameField;

    private bool mandatoryField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("QueryParameter", IsNullable=false)]
    public QueryParameterType[] QueryParameters {
        get {
            return this.queryParametersField;
        }
        set {
            this.queryParametersField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("ResultDocument", IsNullable=false)]
    public ResultDocumentType[] ResultDocuments {
        get {
            return this.resultDocumentsField;
        }
        set {
            this.resultDocumentsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string rel {
        get {
            return this.relField;
        }
        set {
            this.relField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string document {
        get {
            return this.documentField;
        }
        set {
            this.documentField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string query {
        get {
            return this.queryField;
        }
        set {
            this.queryField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string contentType {
        get {
            return this.contentTypeField;
        }
        set {
            this.contentTypeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string parameterTypeName {
        get {
            return this.parameterTypeNameField;
        }
        set {
            this.parameterTypeNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool mandatory {
        get {
            return this.mandatoryField;
        }
        set {
            this.mandatoryField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class PermissionType {

    private string scopeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string scope {
        get {
            return this.scopeField;
        }
        set {
            this.scopeField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class PermissionsType {

    private PermissionType[] permissionField;

    private bool authorizeField;

    public PermissionsType() {
        this.authorizeField = true;
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Permission")]
    public PermissionType[] Permission {
        get {
            return this.permissionField;
        }
        set {
            this.permissionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    [System.ComponentModel.DefaultValueAttribute(true)]
    public bool authorize {
        get {
            return this.authorizeField;
        }
        set {
            this.authorizeField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class PoliciesType {

    private PermissionsType permissionsField;

    /// <remarks/>
    public PermissionsType Permissions {
        get {
            return this.permissionsField;
        }
        set {
            this.permissionsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class OperationType {

    private PoliciesType policiesField;

    private string nameField;

    private method methodField;

    private string titleField;

    private string parameterTypeNameField;

    private string resultDocumentField;

    /// <remarks/>
    public PoliciesType Policies {
        get {
            return this.policiesField;
        }
        set {
            this.policiesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public method method {
        get {
            return this.methodField;
        }
        set {
            this.methodField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string title {
        get {
            return this.titleField;
        }
        set {
            this.titleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string parameterTypeName {
        get {
            return this.parameterTypeNameField;
        }
        set {
            this.parameterTypeNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string resultDocument {
        get {
            return this.resultDocumentField;
        }
        set {
            this.resultDocumentField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public enum method {

    /// <remarks/>
    Post,

    /// <remarks/>
    Delete,

    /// <remarks/>
    Patch,
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class EntityType {

    private string collectionNameField;

    private string documentField;

    private string referencedDocumentField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string collectionName {
        get {
            return this.collectionNameField;
        }
        set {
            this.collectionNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string document {
        get {
            return this.documentField;
        }
        set {
            this.documentField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string referencedDocument {
        get {
            return this.referencedDocumentField;
        }
        set {
            this.referencedDocumentField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class ClassificationType {

    private string classField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string @class {
        get {
            return this.classField;
        }
        set {
            this.classField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schema.bluehands.de/2022/Hypermedia.xsd")]
public partial class DocumentType {

    private ClassificationType[] classificationsField;

    private PropertyType[] propertiesField;

    private EntityType[] entitiesField;

    private OperationType[] operationsField;

    private LinkType[] linksField;

    private PoliciesType policiesField;

    private string nameField;

    private string titleField;

    private bool isQueryResultField;

    private bool isQueryResultFieldSpecified;

    private bool hasSelfLinkField;

    public DocumentType() {
        this.hasSelfLinkField = true;
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Classification", IsNullable=false)]
    public ClassificationType[] Classifications {
        get {
            return this.classificationsField;
        }
        set {
            this.classificationsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable=false)]
    public PropertyType[] Properties {
        get {
            return this.propertiesField;
        }
        set {
            this.propertiesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Entity", IsNullable=false)]
    public EntityType[] Entities {
        get {
            return this.entitiesField;
        }
        set {
            this.entitiesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Operation", IsNullable=false)]
    public OperationType[] Operations {
        get {
            return this.operationsField;
        }
        set {
            this.operationsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Link", IsNullable=false)]
    public LinkType[] Links {
        get {
            return this.linksField;
        }
        set {
            this.linksField = value;
        }
    }

    /// <remarks/>
    public PoliciesType Policies {
        get {
            return this.policiesField;
        }
        set {
            this.policiesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string title {
        get {
            return this.titleField;
        }
        set {
            this.titleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public bool isQueryResult {
        get {
            return this.isQueryResultField;
        }
        set {
            this.isQueryResultField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool isQueryResultSpecified {
        get {
            return this.isQueryResultFieldSpecified;
        }
        set {
            this.isQueryResultFieldSpecified = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    [System.ComponentModel.DefaultValueAttribute(true)]
    public bool hasSelfLink {
        get {
            return this.hasSelfLinkField;
        }
        set {
            this.hasSelfLinkField = value;
        }
    }
}


text:
#pragma once

#include <string>
#include <vector>
#include "ui/element.h"
#include "ui/elementdelegate.h"

namespace aft {
namespace ui {
// Forward reference
class UI;
class UIFacet;

/**
 *  Interface of basic Element interactions
 */
class UIDelegate
{
public:
    using ElementList = std::vector<Element *>;
public:
    /** Add the element to the user interface, if possible. */
    virtual bool add(const Element& element) = 0;
    virtual void flush(const Element& element) = 0;
    /** Set focus to element, if possible. */
    virtual bool focus(const Element& element) = 0;
    /** Get an element by ElementHandle.
     *  TODO These 2 get() methods are likely to go away.
     */
    virtual const Element* get(const ElementHandle& handle) = 0;
    /** Get an element by name */
    virtual const Element* get(const std::string& name) = 0;
    /** Hide user element from display */
    virtual bool hide(const Element& element) = 0;
    /** Get user input from element */
    virtual bool input(Element& element, std::string& value) = 0;
    /** Output the element to the user interface */
    virtual bool output(const Element& element, bool showValue = false) const = 0;
    /** Remove or hide element from the user interface, if possible. */
    virtual bool remove(const Element& element) = 0;
    /** Show user element */
    virtual bool show(const Element& element) = 0;
};

/**
 *  This class implements a UI Delegate and Element Delegate that is memory only,
 *  thus does not perform actual UI.
 */
class BaseUIDelegate : public UIDelegate {
public:
    BaseUIDelegate(UI* ui);
    virtual ~BaseUIDelegate() = default;
public:
    virtual bool add(const Element& element) override;
    virtual void flush(const Element& element) override;
    virtual bool focus(const Element& element) override;
    virtual const Element* get(const ElementHandle& handle) override;
    virtual const Element* get(const std::string& name) override;
    virtual bool hide(const Element& element) override;
    virtual bool input(Element& element, std::string& value) override;
    virtual bool output(const Element& element, bool showValue = false) const override;
    virtual bool remove(const Element& element) override;
    virtual bool show(const Element& element) override;

protected:
    UI* ui_;
    std::unique_ptr<ElementDelegate> delegate_;
    ElementList& elements_;
};

} // namespace ui
} // namespace aft


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

	<changeSet id="extend-code-list-item-description" author="ricci" dbms="postgresql">

		<comment>Extend code list item description column size to 500 characters</comment>

		<modifyDataType
		    schemaName="collect"
		    tableName="ofc_code_list"
		    columnName="description1"
			newDataType="VARCHAR(500)" />

		<modifyDataType
		    schemaName="collect"
		    tableName="ofc_code_list"
			columnName="description2"
			newDataType="VARCHAR(500)" />

		<modifyDataType
			schemaName="collect"
		    tableName="ofc_code_list"
		    columnName="description3"
			newDataType="VARCHAR(500)" />

	</changeSet>

</databaseChangeLog>


text:
package iot

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

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// QueryConsumerGroupList invokes the iot.QueryConsumerGroupList API synchronously
func (client *Client) QueryConsumerGroupList(request *QueryConsumerGroupListRequest) (response *QueryConsumerGroupListResponse, err error) {
	response = CreateQueryConsumerGroupListResponse()
	err = client.DoAction(request, response)
	return
}

// QueryConsumerGroupListWithChan invokes the iot.QueryConsumerGroupList API asynchronously
func (client *Client) QueryConsumerGroupListWithChan(request *QueryConsumerGroupListRequest) (<-chan *QueryConsumerGroupListResponse, <-chan error) {
	responseChan := make(chan *QueryConsumerGroupListResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.QueryConsumerGroupList(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// QueryConsumerGroupListWithCallback invokes the iot.QueryConsumerGroupList API asynchronously
func (client *Client) QueryConsumerGroupListWithCallback(request *QueryConsumerGroupListRequest, callback func(response *QueryConsumerGroupListResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *QueryConsumerGroupListResponse
		var err error
		defer close(result)
		response, err = client.QueryConsumerGroupList(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// QueryConsumerGroupListRequest is the request struct for api QueryConsumerGroupList
type QueryConsumerGroupListRequest struct {
	*requests.RpcRequest
	RealTenantId      string           `position:"Query" name:"RealTenantId"`
	RealTripartiteKey string           `position:"Query" name:"RealTripartiteKey"`
	IotInstanceId     string           `position:"Query" name:"IotInstanceId"`
	PageSize          requests.Integer `position:"Query" name:"PageSize"`
	Fuzzy             requests.Boolean `position:"Query" name:"Fuzzy"`
	CurrentPage       requests.Integer `position:"Query" name:"CurrentPage"`
	GroupName         string           `position:"Query" name:"GroupName"`
	ApiProduct        string           `position:"Body" name:"ApiProduct"`
	ApiRevision       string           `position:"Body" name:"ApiRevision"`
}

// QueryConsumerGroupListResponse is the response struct for api QueryConsumerGroupList
type QueryConsumerGroupListResponse struct {
	*responses.BaseResponse
	RequestId    string                       `json:"RequestId" xml:"RequestId"`
	Success      bool                         `json:"Success" xml:"Success"`
	ErrorMessage string                       `json:"ErrorMessage" xml:"ErrorMessage"`
	PageSize     int                          `json:"PageSize" xml:"PageSize"`
	PageCount    int                          `json:"PageCount" xml:"PageCount"`
	Total        int                          `json:"Total" xml:"Total"`
	CurrentPage  int                          `json:"CurrentPage" xml:"CurrentPage"`
	Code         string                       `json:"Code" xml:"Code"`
	Data         DataInQueryConsumerGroupList `json:"Data" xml:"Data"`
}

// CreateQueryConsumerGroupListRequest creates a request to invoke QueryConsumerGroupList API
func CreateQueryConsumerGroupListRequest() (request *QueryConsumerGroupListRequest) {
	request = &QueryConsumerGroupListRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Iot", "2018-01-20", "QueryConsumerGroupList", "", "")
	request.Method = requests.POST
	return
}

// CreateQueryConsumerGroupListResponse creates a response to parse from QueryConsumerGroupList response
func CreateQueryConsumerGroupListResponse() (response *QueryConsumerGroupListResponse) {
	response = &QueryConsumerGroupListResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
QUnit.module('debounce');

function getReq(reloadTimeout, saveTimeout) {
    var req = {session: {}};

    req.session.reload = function(cb) {
        setTimeout(cb, reloadTimeout);
    };

    req.session.save = function(cb) {
        setTimeout(cb, saveTimeout);
    };

    return req;
}

function noop() {}

test('setup', function() {
    var opts = {};
    equal(typeof debounce, 'function', 'debounce defined');
    equal(typeof debounce(), 'function', 'returned function');
    debounce(opts);
    equal(opts.wait, 1000, 'default wait');
    opts.wait = 2000;
    debounce(opts);
    equal(opts.wait, 2000, 'setup wait');
});

test('middleware function', function() {
    var middleware = debounce(),
        req = getReq();

    middleware(req, null, function() {
        ok(true, 'next called');
    });

    equal(typeof req.debounce, 'function', 'debounce attached to request');
});

test('debounce arguments validation', function() {
    var middleware = debounce(),
        req = getReq();

    middleware(req, null, noop);

    throws(function() {
        req.debounce();
    }, 'Function required.');
});

test('debounce once', function() {
    var middleware = debounce(),
        req = getReq(),
        dcounter = 0,
        scounter = 0,
        rcounter = 0,
        id;

    expect(8);
    stop();

    middleware(req, null, noop);

    req.session.save = function(cb) {
        scounter++;
        cb();
    };

    req.session.reload = function(cb) {
        rcounter++;
        equal(typeof req.session._debounce, 'object', 'debounce store attached');
        equal(typeof req.session._debounce[id], 'number', 'timestamp attached');
        cb();
    };
    id = req.debounce(function() {
        dcounter++;
    });

    setTimeout(function() {
        equal(dcounter, 1, 'debounced function called only once');
        equal(scounter, 3, 'session saved amount');
        equal(rcounter, 2, 'session reload amount');
        equal(req.session._debounce, null, 'debounce map removed from session');
        start();
    }, 2050);
});

test('debounce with immediate=true', function() {
    var middleware = debounce(),
        req = getReq(),
        dcounter = 0,
        scounter = 0,
        rcounter = 0,
        id;

    expect(7);
    stop();

    middleware(req, null, noop);

    req.session.save = function(cb) {
        scounter++;
        cb();
    };

    req.session.reload = function(cb) {
        rcounter++;
        equal(typeof req.session._debounce, 'object', 'debounce store attached');
        equal(typeof req.session._debounce[id], 'number', 'timestamp attached');
        cb();
    };

    id = req.debounce(function() {
        dcounter++;
    }, true);

    equal(dcounter, 1, 'debounced function called immediately');

    setTimeout(function() {
        equal(dcounter, 1, 'debounced function called only once');
        equal(scounter, 2, 'session saved amount');
        equal(rcounter, 1, 'session reload amount');
        equal(req.session._debounce, null, 'debounce map removed from session');
        start();
    }, 1020);
});

test('debounce multiple times', function() {
    var middleware = debounce(),
        req = getReq(),
        counter = 0;

    expect(1);
    stop();

    middleware(req, null, noop);

    function fn() {
        counter++;
    }

    req.debounce(fn, 2000);

    setTimeout(function() {
        req.debounce(fn, 2000);
    }, 1000);

    setTimeout(function() {
        req.debounce(fn, 2000);
    }, 2000);

    setTimeout(function() {
        equal(counter, 1, 'debounced function called once');
        start();
    }, 5000);
});

test('debounce multiple times with immediate=true', function() {
    var middleware = debounce(),
        req = getReq(),
        counter = 0;

    expect(1);
    stop();

    middleware(req, null, noop);

    function fn() {
        counter++;
    }

    req.debounce(fn, 2000, true);

    setTimeout(function() {
        req.debounce(fn, 2000, true);
    }, 1000);

    setTimeout(function() {
        req.debounce(fn, 2000, true);
    }, 2000);

    setTimeout(function() {
        equal(counter, 2, 'debounced function called only once');
        start();
    }, 5000);
});

test('double call with immediate=true, second call faster than session store roundtrip', function() {
    var middleware = debounce(),
        reloadTimeout = 500,
        req = getReq(reloadTimeout, 0),
        counter = 0;

    expect(1);
    stop();

    middleware(req, null, noop);

    function fn() {
        counter++;
    }

    req.debounce(fn, 500, true);

    setTimeout(function () {
        req.debounce(fn, 500, true);
    }, reloadTimeout / 2);

    setTimeout(function() {
        equal(counter, 1, 'debounced function called only once');
        start();
    }, 5000);
});


text:
[clappr](../../../index.md) / [io.clappr.player.bitrate](../../index.md) / [BitrateHistory](../index.md) / [BitrateLog](index.md) / [endTime](./end-time.md)

# endTime

`var endTime: `[`Long`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-long/index.html)


text:
package org.apache.cassandra.service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.lifecycle.Tracker;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.format.SSTableFormat;
import org.apache.cassandra.io.sstable.format.VersionAndType;
import org.apache.cassandra.notifications.INotification;
import org.apache.cassandra.notifications.INotificationConsumer;
import org.apache.cassandra.notifications.InitialSSTableAddedNotification;
import org.apache.cassandra.notifications.SSTableAddedNotification;
import org.apache.cassandra.notifications.SSTableDeletingNotification;
import org.apache.cassandra.notifications.SSTableListChangedNotification;
import org.apache.cassandra.utils.NoSpamLogger;

/**
 * Tracks all sstables in use on the local node.
 *
 * <p>Each table tracks its own SSTables in {@link ColumnFamilyStore} (through {@link Tracker}) for most purposes, but
 * this class groups information we need on all the sstables the node has.
 */
public class SSTablesGlobalTracker implements INotificationConsumer
{
    private static final Logger logger = LoggerFactory.getLogger(SSTablesGlobalTracker.class);
    private static final NoSpamLogger noSpamLogger = NoSpamLogger.getLogger(logger, 5L, TimeUnit.MINUTES);

    /*
     * As of CASSANDRA-15897, the only thing we track here is the set of sstable versions in use.
     *
     * That set is maintained in `versionsInUse`, an immutable set replaced when changed (so that it can be read safely
     * and cheaply). To track when that set changes and needs to be re-computed, we essentially maintain a map of
     * sstables versions in use to the number of sstables for that version. But as we know that sstables will
     * overwhelmingly be on the "current" version, we special case said current version (makes things cheaper without
     * too much complexity here). Those are `sstablesForCurrentVersion` and `sstablesForOtherVersions`.
     *
     * This would be sufficient if we could guarantee that for any sstable, we only ever have 1 addition notification
     * and 1 corresponding remove notification. But sstables can have complex lifecycles and relying on this property
     * could be fragile. As a matter of fact, at the time of this writing, the removal notification is sometimes fired
     * twice for the same sstable. To keep this component more resilient, we also maintain the set of all sstables for
     * which we've received an addition, which allows us to ignore removals for sstables we don't know.
     *
     * Concurrency handling: the 'allSSTables' set handles concurrency directly as it is updated in all cases. The rest
     * of the data structures of this class are only updated together within a synchronized block when handling new
     * sstables additions/removals.
     */

    private final Set<Descriptor> allSSTables = ConcurrentHashMap.newKeySet();

    private final VersionAndType currentVersion;
    private int sstablesForCurrentVersion;
    private final Map<VersionAndType, Integer> sstablesForOtherVersions = new HashMap<>();

    private volatile ImmutableSet<VersionAndType> versionsInUse = ImmutableSet.of();

    private final Set<INotificationConsumer> subscribers = new CopyOnWriteArraySet<>();

    public SSTablesGlobalTracker(SSTableFormat.Type currentSSTableFormat)
    {
        this.currentVersion = new VersionAndType(currentSSTableFormat.info.getLatestVersion(), currentSSTableFormat);
    }

    /**
     * The set of all sstable versions currently in use on this node.
     */
    public Set<VersionAndType> versionsInUse()
    {
        return versionsInUse;
    }

    /**
     * Register a new subscriber to this tracker.
     *
     * Registered subscribers are currently notified when the set of sstable versions in use changes, using a
     * {@link SSTablesVersionsInUseChangeNotification}.
     *
     * @param subscriber the new subscriber to register. If this subscriber is already registered, this method does
     * nothing (meaning that even if a subscriber is registered multiple times, it will only be notified once on every
     * change).
     * @return whether the subscriber was register (so whether it was not already registered).
     */
    public boolean register(INotificationConsumer subscriber)
    {
        return subscribers.add(subscriber);
    }

    /**
     * Unregister a subscriber from this tracker.
     *
     * @param subscriber the subscriber to unregister. If this subscriber is not registered, this method does nothing.
     * @return whether the subscriber was unregistered (so whether it was registered subscriber of this tracker).
     */
    public boolean unregister(INotificationConsumer subscriber)
    {
        return subscribers.remove(subscriber);
    }

    @Override
    public void handleNotification(INotification notification, Object sender)
    {
        Iterable<Descriptor> removed = removedSSTables(notification);
        Iterable<Descriptor> added = addedSSTables(notification);
        if (Iterables.isEmpty(removed) && Iterables.isEmpty(added))
            return;

        boolean triggerUpdate = handleSSTablesChange(removed, added);
        if (triggerUpdate)
        {
            SSTablesVersionsInUseChangeNotification changeNotification = new SSTablesVersionsInUseChangeNotification(versionsInUse);
            subscribers.forEach(s -> s.handleNotification(changeNotification, this));
        }
    }

    @VisibleForTesting
    boolean handleSSTablesChange(Iterable<Descriptor> removed, Iterable<Descriptor> added)
    {
        /*
         We collect changes to 'sstablesForCurrentVersion' and 'sstablesForOtherVersions' as delta first, and then
         apply those delta within a synchronized block below. The goal being to reduce the work done in that
         synchronized block.
        */
        int currentDelta = 0;
        Map<VersionAndType, Integer> othersDelta = null;
        /*
         Note: we deal with removes first as if a notification both removes and adds, it's a compaction and while
         it should never remove and add the same descriptor in practice, doing the remove first is more logical.
        */
        for (Descriptor desc  : removed)
        {
            if (!allSSTables.remove(desc))
                continue;

            VersionAndType version = version(desc);
            if (currentVersion.equals(version))
                --currentDelta;
            else
                othersDelta = update(othersDelta, version, -1);
        }
        for (Descriptor desc : added)
        {
            if (!allSSTables.add(desc))
                continue;

            VersionAndType version = version(desc);
            if (currentVersion.equals(version))
                ++currentDelta;
            else
                othersDelta = update(othersDelta, version, +1);
        }

        if (currentDelta == 0 && (othersDelta == null))
            return false;

        /*
         Set to true if the set of versions in use is changed by this update. That is, if a version having no
         version prior now has some, or if the count for some version reaches 0.
        */
        boolean triggerUpdate;
        synchronized (this)
        {
            triggerUpdate = (currentDelta > 0 && sstablesForCurrentVersion == 0)
                            || (currentDelta < 0 && sstablesForCurrentVersion <= -currentDelta);
            sstablesForCurrentVersion += currentDelta;
            sstablesForCurrentVersion = sanitizeSSTablesCount(sstablesForCurrentVersion, currentVersion);

            if (othersDelta != null)
            {
                for (Map.Entry<VersionAndType, Integer> entry : othersDelta.entrySet())
                {
                    VersionAndType version = entry.getKey();
                    int delta = entry.getValue();
                    /*
                     Updates the count, removing the version if it reaches 0 (note: we could use Map#compute for this,
                     but we wouldn't be able to modify `triggerUpdate` without making it an Object, so we don't bother).
                    */
                    Integer oldValue = sstablesForOtherVersions.get(version);
                    int newValue = oldValue == null ? delta : oldValue + delta;
                    newValue = sanitizeSSTablesCount(newValue, version);
                    triggerUpdate |= oldValue == null || newValue == 0;
                    if (newValue == 0)
                        sstablesForOtherVersions.remove(version);
                    else
                        sstablesForOtherVersions.put(version, newValue);
                }
            }

            if (triggerUpdate)
                versionsInUse = computeVersionsInUse(sstablesForCurrentVersion, currentVersion, sstablesForOtherVersions);
        }
        return triggerUpdate;
    }

    private static ImmutableSet<VersionAndType> computeVersionsInUse(int sstablesForCurrentVersion, VersionAndType currentVersion, Map<VersionAndType, Integer> sstablesForOtherVersions)
    {
        ImmutableSet.Builder<VersionAndType> builder = ImmutableSet.builder();
        if (sstablesForCurrentVersion > 0)
            builder.add(currentVersion);
        builder.addAll(sstablesForOtherVersions.keySet());
        return builder.build();
    }

    private static int sanitizeSSTablesCount(int sstableCount, VersionAndType version)
    {
        if (sstableCount >= 0)
            return sstableCount;

        /*
         This shouldn't happen and indicate a bug either in the tracking of this class, or on the passed notification.
         That said, it's not worth bringing the node down, so we log the problem but otherwise "correct" it.
        */
        noSpamLogger.error("Invalid state while handling sstables change notification: the number of sstables for " +
                           "version {} was computed to {}. This indicate a bug and please report it, but it should " +
                           "not have adverse consequences.", version, sstableCount, new RuntimeException());
        return 0;
    }

    private static Iterable<Descriptor> addedSSTables(INotification notification)
    {
        if (notification instanceof SSTableAddedNotification)
            return Iterables.transform(((SSTableAddedNotification)notification).added, s -> s.descriptor);
        if (notification instanceof SSTableListChangedNotification)
            return Iterables.transform(((SSTableListChangedNotification)notification).added, s -> s.descriptor);
        if (notification instanceof InitialSSTableAddedNotification)
            return Iterables.transform(((InitialSSTableAddedNotification)notification).added, s -> s.descriptor);
        else
            return Collections.emptyList();
    }

    private static Iterable<Descriptor> removedSSTables(INotification notification)
    {
        if (notification instanceof SSTableDeletingNotification)
            return Collections.singletonList(((SSTableDeletingNotification)notification).deleting.descriptor);
        if (notification instanceof SSTableListChangedNotification)
            return Iterables.transform(((SSTableListChangedNotification)notification).removed, s -> s.descriptor);
        else
            return Collections.emptyList();
    }

    private static Map<VersionAndType, Integer> update(Map<VersionAndType, Integer> counts,
                                                       VersionAndType toUpdate,
                                                       int delta)
    {
        Map<VersionAndType, Integer> m = counts == null ? new HashMap<>() : counts;
        m.merge(toUpdate, delta, (a, b) -> (a + b == 0) ? null : (a + b));
        return m;
    }

    @VisibleForTesting
    static VersionAndType version(Descriptor sstable)
    {
        return new VersionAndType(sstable.version, sstable.formatType);
    }
}


text:
"""
test_bag
----------------------------------

Tests for `python_algorithms.bag` module.
"""

import unittest

from python_algorithms.basic.bag import Bag

class TestBag(unittest.TestCase):

    def setUp(self):
        self.empty_bag = Bag()
        self.bag = Bag()
        self.seq = [1, 2, 2, 3, 3, 3]
        for x in self.seq:
            self.bag.add(x)

    def test_add_to_empty_bag(self):
        self.empty_bag.add(0)
        seq_iter = [x for x in self.empty_bag]
        self.assertEqual(len(seq_iter), 1)
        self.assertEqual(seq_iter[0], 0)

    def test_add_to_bag(self):
        self.bag.add(0)
        seq_iter = [x for x in self.bag]
        self.assertEqual(len(seq_iter), len(self.seq) + 1)
        self.assertEqual(sorted(seq_iter), [0] + self.seq)

    def test_size_of_empty_bag(self):
        self.assertEqual(self.empty_bag.size, 0)

    def test_size_of_bag(self):
        self.assertEqual(self.bag.size, len(self.seq))

    def test_iterate_empty_bag(self):
        for curr in self.empty_bag:
            self.assertEqual(False, True)

    def test_iterate_bag(self):
        iter_seq = []
        for curr in self.bag:
            iter_seq.append(curr)
        iter_seq.sort()
        self.assertEqual(iter_seq, self.seq)

    def test_str_empty_bag(self):
        self.assertEqual(str(self.empty_bag), "")

    def test_str_bag(self):
        bag_str = str(self.bag)
        bag_seq = sorted([int(x) for x in bag_str.split()])
        self.assertEqual(bag_seq, self.seq)

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
source ~/.profile

if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
    echo "[error] Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be defined." >&2
    exit 1
fi

function handle_error () {
  echo "[error] Encountered a return code of $? on line $1." >&2
  echo "[error] The build did not complete successfully." >&2
  exit 1
}

trap 'handle_error $LINENO' ERR

set -o pipefail

build_start_time="$(date +'%s')"

pushd "$(dirname "$0")" > /dev/null

# Ensure we're up-to-date
sudo apt-get -y update

# Options:
# --force-confdef: Force to keep default option without prompting.
# --force-confold: Force to keep old conf files.
sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confnew" --force-yes upgrade

# Download and decompress our custom Spark build.
cd $HOME
spark_version="${X_SPARK_VERSION:-1.6.1}"
wget --no-check-certificate http://resources.sixafter.com/spark-${spark_version}-bin-custom.tgz
mkdir spark
tar -xf spark-${spark_version}-bin-custom.tgz -C ./spark --strip-components=1

# Move the slave information in place.
if [ -a /tmp/slaves ]; then
  sudo mv /tmp/slaves spark/conf/
fi

popd > /dev/null

build_end_time="$(date +'%s')"

diff_secs="$(($build_end_time-$build_start_time))"
build_mins="$(($diff_secs / 60))"
build_secs="$(($diff_secs - $build_mins * 60))"

echo ""
echo "Build completed successfully in: ${build_mins}m ${build_secs}s"


text:
/**
 * Created by apps-libX on November 8th 2015, 4:26:41 pm.
 *
 * @module test.appsLibX.appbase
 * @name appbase
 *
 * @description
 * Tests for appbase under appsLibX.appbase
 * _Test description._
 */

describe('Service: appsLibX.appbase.appbase', function () {

    'use strict';

    // load the service's module
    beforeEach(module('appsLibX.appbase'));

    // instantiate service
    var service;

    //update the injection
    beforeEach(inject(function (appbase) {
        service = appbase;
    }));

    /**
     * @description
     * Sample test case to check if the service is injected properly
     * */
    it('should be injected and defined', function () {
        expect(service).toBeDefined();
    });
});


text:
process.stdout.on("error", function(error) {
  if (error.code === "EPIPE" || error.errno === "EPIPE") {
    process.exit(0);
  }
});

module.exports = function(value) {
  process.stdout.write(value == null ? "null\n" : JSON.stringify(value) + "\n");
};


text:
- Updated the Docker image to: *demisto/python3:3.9.8.24399*.
##### DeleteIndicatorRelationships
- Updated the Docker image to: *demisto/python3:3.9.8.24399*.
##### SearchIndicatorRelationships
- Updated the Docker image to: *demisto/python3:3.9.8.24399*.


text:
package loyalty.service;

import org.chtijbug.drools.platform.core.callback.SpecificMessageCallback;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

/**
 * Created by nheron on 20/01/2016.
 */
public class LoyaltyGenericCallbackMessage implements SpecificMessageCallback {
    @Override
    public void handleMessage(String messageId, String messageContent) {
        System.out.println("MessageID= "+messageId+" MessagContent= "+messageContent);
    }
}


text:
title: LibDocument
subtitle: Document processing with JSON and Python API support for Linux, OS X, and iOS.
layout: default
modal-id: 1
date: 2015-11-29
img: LibDocument-600.png
thumbnail: LibDocument-thumbnail.png
alt: image-alt
category: Software Development
tags:
- opensource
relative: /libdocument
---


text:
const path = require('path')
const webpack = require('webpack')
const babelOptions = require('./client.babel.js')
const getUglify = env => (
  env === 'production' ? new webpack.optimize.UglifyJsPlugin() : () => null
)

module.exports = env => ({
  entry: './src/client/index.js',
  output: {
    path: path.resolve(__dirname, '../static'),
    filename: 'main.js',
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude:  /node_modules/,
        loader: 'babel-loader',
        query: babelOptions,
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(env),
      },
    }),
    getUglify(env),
  ]
})


text:
Docker-compatible Vagrant base boxes

## Requirement

   1. [VirtualBox](https://www.virtualbox.org/)
   2. [Vagrant](https://www.vagrantup.com/)

## Features

- Ubuntu 14.04.x LTS
- Docker daemon
- Docker Compose

## Usage

```bash
cd /path/to/project
vagrant up
```


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

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Dev Center (dev.cyc.com) – Ontology Development Resources</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />

    <link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
    <meta name="Date-Revision-yyyymmdd" content="20180124" />
    <meta http-equiv="Content-Language" content="en" />

                Cyc Developer Center

        Last Published: 2018-01-24
                          |                           Cyc Dev Center
        >
    Ontology Development Resources

                    Cycorp
            |
                        Developer Center
            |
                        Java APIs
            |
                        Ontologies
            |
                        Cyc Administration
            |
                        Downloads
            |
                        Issues
            |
                        GitHub

Cyc Developer Center

                          Introduction

                          Issues

                          Downloads

                          Cyc XSDs

                          Cyc XSL

Java APIs

                          Overview

                          Core API Suite

                          KB API

                          Query API

                          Session API

                          README

                          CHANGELOG

                          Download

                          FAQs & HOWTOs

                          License

Javadocs

                          Core API Spec

                          Core Client Impl

Examples

                          API Usage

                          Basic Core API Usage

                          Advanced Querying

                          Query Justification

                          XML Marshalling

Ontology Development

            Overview

                          Tutorials

                          Ontologist's Handbook

                          Cyc Basics

                          Efficient CycL

                          Tools

                          CycL Queries

                          References

                          Cyc Vocabulary

                          Glossary

                          Common Cyc Abbreviations

                          KB Hierarchy diagram

Cyc Administration

                          Cyc Admin Handbook

                          Cyc Admin FAQ

Ontology Development Resources

Diagram of the Cyc KB Hierarchy.
  (Learn more)

New to Cyc? Read some ontology development tutorials to get started!

The Ontologist’s Handbook explores the principles of ontology development and knowledge editing:

Ontologist’s Handbook

Cyc Basics

Writing Efficient CycL

Tools for Knowledge Editing and Ontology Development

CycL Queries

Useful references for ontology development:

Cyc Vocabulary

Glossary

Common Cyc Abbreviations

KB Hierarchy diagram

For additional information, refer to the documentation page on the Cycorp homepage.

              Copyright ©                    2015–2018
                        Cycorp, Inc.
            All rights reserved.


text:
layout: post
title: New site - visualizing election results
---

I have [a new site up which graphically displays information about the results of the 2009 South African elections](http://afrith.github.io/election-web/). This project was an exercise in learning to use [the D3.js framework](http://d3js.org/). All the code and data is available in [a github repository](https://github.com/afrith/election-web).


text:
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using Serilog;
using Thinktecture.IdentityServer.Core.Configuration;
using Thinktecture.IdentityServer.Core.Models;
using Thinktecture.IdentityServer.Core.Services;
using Thinktecture.IdentityServer.Core.Services.InMemory;
using AuthenticationOptions = Thinktecture.IdentityServer.Core.Configuration.AuthenticationOptions;

namespace AzureAdOffice365Authentication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Trace()
                .CreateLogger();

            X509Certificate2 certificate = new X509Certificate2(
                $@"{AppDomain.CurrentDomain.BaseDirectory}\bin\Configuration\idsrv3test.pfx", "idsrv3test");

            List<InMemoryUser> users = new List<InMemoryUser>();
            List<Client> clients = new List<Client>
            {
                new Client
                {
                    Enabled = true,
                    ClientName = "MVC Client",
                    ClientId = "mvc",
                    Flow = Flows.Implicit,
                    EnableLocalLogin = false,
                    RequireConsent = false,

                    RedirectUris = new List<string>
                    {
                        "https://localhost:44300/"
                    }
                }
            };

            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    Factory = new IdentityServerServiceFactory
                    {
                        ClientStore = new Registration<IClientStore>(r => new InMemoryClientStore(clients)),
                        UserService = new Registration<IUserService>(r => new InMemoryUserService(users)),
                        ScopeStore = new Registration<IScopeStore>(r => new InMemoryScopeStore(StandardScopes.All))
                    },
                    SiteName = "AccidentalFish Office365 Sample",
                    SigningCertificate = certificate,
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        CookieOptions = new CookieOptions
                        {
                            SlidingExpiration = true
                        },
                        EnableLocalLogin = false,
                        EnablePostSignOutAutoRedirect = true,
                        IdentityProviders = ConfigureIdentityProviders
                    }
                });
            });

            // Configure MVC to use the above token endpoint
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44300/identity",
                ClientId = "mvc",
                RedirectUri = "https://localhost:44300/",
                ResponseType = "id_token",

                SignInAsAuthenticationType = "Cookies"
            });
        }

        private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            string clientId = Constants.ClientId; // your client ID as configured in Azure
            string redirectUri = "https://localhost:44300/identity/signin-azuread"; // the reply URL as configured in Azure
            string postLogoutRedirectUri = "https://localhost:44300"; // an appropriate page for your project

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "AzureAd",
                Caption = "Sign in with Azure AD",
                Scope = "openid email",
                ClientId = clientId,
                Authority = "https://login.windows.net/common/",
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = redirectUri,
                AuthenticationMode = AuthenticationMode.Passive,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false
                },
                SignInAsAuthenticationType = signInAsType // this MUST come after TokenValidationParameters
            };
            app.UseOpenIdConnectAuthentication(options);
        }
    }
}


text:
package com.cmput301f16t11.a2b;

import com.google.android.gms.maps.model.LatLng;

import org.junit.Before;
import org.junit.Test;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class StatusUnitTest {

    /*
    This test currently has no tests that are not tested elsewhere. Once we have gui testing it
    may make more sense to test if the list is displaying the correct data
     */

    private LatLng startLocation = new LatLng(50,50);
    private LatLng endLocation = new LatLng(50,50);
    private int fare = 10;
    private User user = new User();
    private UserRequest req;
    /**
     *US 02.01.01
     As a rider or driver, I want to see the status of a request that I am involved in
     */
    @Before
    public void setUp(){
        req = new UserRequest(startLocation, endLocation,fare,user.getId());
    }

    @Test
    public void checkAcceptedTrue(){
        req.setAcceptedStatus(true);
        assertTrue(req.getAcceptedStatus());

    }
    @Test
    public void checkCompletedTrue(){
        req.setCompletedStatus(true);
        assertTrue(req.isCompleted());
    }
    @Test
    public void checkAcceptedFalse(){
        req.setAcceptedStatus(false);
        assertFalse(req.getAcceptedStatus());
    }
    @Test
    public void checkCompletedFalse(){
        req.setCompletedStatus(false);
        assertFalse(req.isCompleted());
    }
}