text:
Inverse Fast Fourier Transform
==============================
*SnFFT* support three types of inverse fast Fourier transforms.
The dense |iFFT| can take the inverse of the output of either the sparse or dense |FFT|.
The bandlimited |iFFT| can only take the inverse of the output of the bandlimited |FFT|, but benefits greatly from the restriction.
The partial |iFFT| can take the inverse of the output of either the sparse or dense |FFT|.

Dense Inverse Fast Fourier Transform
------------------------------------
.. function:: sn_ifft(N, FFT, YOR, PT)

::

# Parameters:
#	N::Int
#	- the problem size
#	FFT::Array{Array{Float64, 2}, 1}
#	- a Fast Fourier Transform of size N
#	- should be the output of sn_fft() or sn_fft_sp()
#	YOR::Array{Array{Array{SparseMatrixCSC, 1}, 1}, 1}
#	- output1 from yor()
#	PT::Array{Array{Array{Int, 1}, 1}, 1}
#	- output2 from yor()
# Return Values:
#	SNF::Array{Float64, 1}
#	- the function over Sn that corresponds to FFT

* **FFT** is the output of sn_ftt() or sn_fft_sp()
* **YOR** and **PT** are the outputs of yor(**N**)
* See the code for example4() for an example of the complete process to compute a dense |iFFT|

Bandlimited Inverse Fast Fourier Transform
------------------------------------------
.. function:: sn_ifft_bl(N, K, FFT, YOR, PT, ZFI)

::

# Parameters:
#	N::Int
#	- the problem size
#	K::Int
#	- the problem is homogenous at N-K
#	FFT::Array{Array{Float64, 2}, 1}
#	- a Fast Fourier Transform of size N
#	- should be the output of sn_fft_bl()
#	YOR::Array{Array{Array{SparseMatrixCSC, 1}, 1}, 1}
#	- output1 from yor_bl()
#	PT::Array{Array{Array{Int, 1}, 1}, 1}
#	- output2 from yor_bl()
#	ZFI::Array{Int, 1}
#	- output3 from yor_bl()
# Return Values:
#	SNF::Array{Float64, 1}
#	- the bandlimited function over Sn that corresponds to FFT

* **FFT** is the output of sn_fft_bl()
* **YOR**, **PT**, and **ZFI** are the outputs of yor_bl(**N**, **K**)
* See the code for example7() for an example of the complete process to compute a bandlimited |iFFT|

Partial Inverse Fast Fourier Transform
---------------------------------------
.. function:: sn_ifft_p(N, M, FFT, YOR, PT)

::

# Parameters:
#	N::Int
#	- the problem size
#	M::Int
#	- the number of the top components of FFT to use
#	FFT::Array{Array{Float64, 2}, 1}
#	- a Fast Fourier Transform of size N
#	- should be the output of sn_fft() or sn_fft_sp()
#	YOR::Array{Array{Array{SparseMatrixCSC, 1}, 1}, 1}
#	- output1 from yor()
#	PT::Array{Array{Array{Int, 1}, 1}, 1}
#	- output2 from yor()
# Return Values:
#	SNF::Array{Float64, 1}
#	- the function over Sn that corresponds to FFT that has been smoothed to only use the top M componenets

* **FFT** is the output of sn_ftt() or sn_fft_sp()
* **YOR** and **PT** are the outputs of yor(**N**)
* See the code for example8() for an example of the complete process to compute a partial |iFFT|

.. |FFT| replace:: fast Fourier transform
.. |iFFT| replace:: inverse fast Fourier transform


text:
miles = int(input("the number of miles driven? "))
gallons= int(input("the number of gallons used? "))

MPG = miles/gallons

#the MPG for the car
print("The MPG for the car is", MPG)

redpajama_set_name: RedPajamaGithub


text:
import logging

from app import db, Roles
from app.models.group import Group
from app.models.role_model import GroupRole
from app.models.user import User

_logger = logging.getLogger(__name__)

def load_user_roles(user_id):
    roles = db.session.query(GroupRole.role). \
        join(GroupRole.group, Group.users). \
        filter(User.id == user_id).group_by(GroupRole.role).all()
    return [Roles[role.role] for role in roles]

def find_all_roles_by_group_id(group_id):
    roles = db.session.query(GroupRole) \
        .filter(GroupRole.group_id == group_id) \
        .order_by(GroupRole.role).all()
    return [Roles[role.role] for role in roles]

def delete_roles_by_group(group_id, removed_roles):
    roles = [role.name for role in removed_roles]
    db.session.query(GroupRole).filter(
        GroupRole.group_id == group_id,
        GroupRole.role.in_(roles)
    ).delete(synchronize_session='fetch')
    db.session.commit()

def insert_roles_by_group(group_id, added_roles):
    roles = []
    for role in added_roles:
        group_role = GroupRole()
        group_role.group_id = group_id
        group_role.role = role.name
        roles.append(group_role)

    db.session.add_all(roles)
    db.session.commit()

def get_groups_with_role(role):
    return db.session.query(Group) \
        .join(GroupRole) \
        .filter(GroupRole.role == role.name) \
        .all()


text:
@interface DKCategoryCell : UICollectionViewCell
@property (nonatomic,strong) NSString *title;
@property (nonatomic) NSUInteger numberOfStories;
@end


text:
<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Istio Blog</title>
    <description>An open platform to connect, manage, and secure microservices.</description>
    <pubDate>2020-05-27T14:55:24-07:00</pubDate>
    <link>https://istio.io</link>
    <image>
      <url>https://istio.io/favicons/android-192x192.png</url>
      <link>https://istio.io</link>
    </image>

      <item>
        <title>Introducing Istio</title>
        <description>Istio 0.1 announcement</description>
        <pubDate>2017-05-24T00:00:00-07:00</pubDate>
        <link>https://istio.io/blog/2017/0.1-announcement.html</link>
        <author>The Istio Team</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/0.1-announcement.html</guid>
      </item>

      <item>
        <title>Using Istio to Improve End-to-End Security</title>
        <description>Istio Auth 0.1 announcement</description>
        <pubDate>2017-05-25T00:00:00-07:00</pubDate>
        <link>https://istio.io/blog/2017/0.1-auth.html</link>
        <author>The Istio Team</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/0.1-auth.html</guid>
      </item>

      <item>
        <title>Canary Deployments using Istio</title>
        <description>Using Istio to create autoscaled canary deployments</description>
        <pubDate>2017-06-14T00:00:00-07:00</pubDate>
        <link>https://istio.io/blog/2017/0.1-canary.html</link>
        <author>Frank Budinsky</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/0.1-canary.html</guid>
      </item>

      <item>
        <title>Using Network Policy with Istio</title>
        <description>How Kubernetes Network Policy relates to Istio policy</description>
        <pubDate>2017-08-10T00:00:00-07:00</pubDate>
        <link>https://istio.io/blog/2017/0.1-using-network-policy.html</link>
        <author>Spike Curtis</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/0.1-using-network-policy.html</guid>
      </item>

      <item>
        <title>Announcing Istio 0.2</title>
        <description>Istio 0.2 announcement</description>
        <pubDate>2017-10-10T00:00:00-07:00</pubDate>
        <link>https://istio.io/blog/2017/0.2-announcement.html</link>
        <author>The Istio Team</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/0.2-announcement.html</guid>
      </item>

      <item>
        <title>Mixer Adapter Model</title>
        <description>Provides an overview of the Mixer plug-in architecture</description>
        <pubDate>2017-11-03T00:00:00-07:00</pubDate>
        <link>https://istio.io/blog/2017/adapter-model.html</link>
        <author>Martin Taillefer</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/adapter-model.html</guid>
      </item>

      <item>
        <title>Mixer and the SPOF Myth</title>
        <description>Improving availability and reducing latency</description>
        <pubDate>2017-12-07T00:00:00-08:00</pubDate>
        <link>https://istio.io/blog/2017/mixer-spof-myth.html</link>
        <author>Martin Taillefer</author>
        <guid isPermaLink="true">https://istio.io/blog/2017/mixer-spof-myth.html</guid>
      </item>

      <item>
        <title>Consuming External Web Services</title>
        <description>Describes a simple scenario based on Istio Bookinfo sample</description>
        <pubDate>2018-01-31T00:00:00-08:00</pubDate>
        <link>https://istio.io/blog/2018/egress-https.html</link>
        <author>Vadim Eisenberg</author>
        <guid isPermaLink="true">https://istio.io/blog/2018/egress-https.html</guid>
      </item>

      <item>
        <title>Consuming External TCP Services</title>
        <description>Describes a simple scenario based on Istio Bookinfo sample</description>
        <pubDate>2018-02-06T00:00:00-08:00</pubDate>
        <link>https://istio.io/blog/2018/egress-tcp.html</link>
        <author>Vadim Eisenberg</author>
        <guid isPermaLink="true">https://istio.io/blog/2018/egress-tcp.html</guid>
      </item>

      <item>
        <title>Traffic mirroring with Istio for testing in production</title>
        <description>An introduction to safer, lower-risk deployments and release to production</description>
        <pubDate>2018-02-08T00:00:00-08:00</pubDate>
        <link>https://istio.io/blog/2018/traffic-mirroring.html</link>
        <author>Christian Posta</author>
        <guid isPermaLink="true">https://istio.io/blog/2018/traffic-mirroring.html</guid>
      </item></channel>
</rss>


text:
<?php

Route::group(['prefix' => 'purchasing/point/service', 'namespace' => 'Point\PointPurchasing\Http\Controllers\Service'], function () {
    Route::get('/', function () {
        return view('point-purchasing::app.purchasing.point.service.menu');
    });

    Route::get('/report/export', 'ServiceReportController@export');
    Route::get('/report', 'ServiceReportController@index');

    // INVOICE
    Route::group(['middleware' => 'auth'], function () {
        Route::get('/invoice/vesa-create', 'ServiceInvoiceVesaController@create');
        Route::get('/invoice/vesa-rejected', 'ServiceInvoiceVesaController@create');
        Route::get('/invoice/{id}/export', 'InvoiceController@exportPDF');
        Route::get('/invoice/{id}/archived', 'InvoiceController@archived');
        Route::get('/invoice/pdf', 'InvoiceController@indexPDF');
        Route::post('/invoice/send-email', 'InvoiceController@sendEmail');
        Route::resource('/invoice', 'InvoiceController');
    });

    // DOWNPAYMENT
    Route::get('/downpayment/reject-all', 'DownpaymentApprovalController@rejectAll');
    Route::get('/downpayment/approve-all', 'DownpaymentApprovalController@approveAll');
    Route::any('/downpayment/{id}/approve', 'DownpaymentApprovalController@approve');
    Route::any('/downpayment/{id}/reject', 'DownpaymentApprovalController@reject');
    Route::group(['middleware' => 'auth'], function () {
        Route::get('/downpayment/vesa-approval', 'DownpaymentVesaController@approval');
        Route::get('/downpayment/vesa-rejected', 'DownpaymentVesaController@rejected');

        Route::get('/downpayment/request-approval', 'DownpaymentApprovalController@requestApproval');
        Route::post('/downpayment/send-request-approval', 'DownpaymentApprovalController@sendRequestApproval');
        Route::get('/downpayment/{id}/archived', 'DownpaymentController@archived');
        Route::get('/downpayment/pdf', 'DownpaymentController@indexPDF');
        Route::get('/downpayment/create', 'DownpaymentController@create');
        Route::resource('/downpayment', 'DownpaymentController');
    });

    // PAYMENT COLLECTION
    Route::get('/payment-order/approve-all', 'PaymentOrderApprovalController@approveAll');
    Route::get('/payment-order/reject-all', 'PaymentOrderApprovalController@rejectAll');
    Route::any('/payment-order/{id}/approve', 'PaymentOrderApprovalController@approve');
    Route::any('/payment-order/{id}/reject', 'PaymentOrderApprovalController@reject');
    Route::group(['middleware' => 'auth'], function () {
        Route::get('/payment-order/vesa-rejected', 'PaymentOrderVesaController@rejected');
        Route::get('/payment-order/vesa-approval', 'PaymentOrderVesaController@approval');
        Route::get('/payment-order/vesa-create', 'PaymentOrderVesaController@create');

        Route::get('/payment-order/request-approval', 'PaymentOrderApprovalController@requestApproval');
        Route::post('/payment-order/send-request-approval', 'PaymentOrderApprovalController@sendRequestApproval');
        Route::post('/payment-order/cancel', 'PaymentOrderController@cancel');
        Route::get('/payment-order/{id}/archived', 'PaymentOrderController@archived');
        Route::get('/payment-order/create-step-1', 'PaymentOrderController@createStep1');
        Route::get('/payment-order/create-step-2/{person_person_id}', 'PaymentOrderController@createStep2');
        Route::get('/payment-order/pdf', 'PaymentOrderController@indexPDF');
        Route::post('/payment-order/create-step-3', 'PaymentOrderController@createStep3');
        Route::post('/payment-order/{id}/edit-review', 'PaymentOrderController@editReview');
        Route::post('/payment-order/{id}/store', 'PaymentOrderController@storePb');
        Route::post('/payment-order/send-email-payment', 'PaymentOrderController@sendEmailPayment');
        Route::resource('/payment-order', 'PaymentOrderController');
    });
});


text:
package org.drools.impact.analysis.parser;

import org.drools.impact.analysis.model.AnalysisModel;
import org.drools.impact.analysis.parser.domain.Person;
import org.junit.Test;

public class ParserTest {

    @Test
    public void test() {
        String str =
                "package mypkg;\n" +
                "import " + Person.class.getCanonicalName() + ";" +
                "rule R when\n" +
                "  $p : Person(name == \"Mario\")\n" +
                "then\n" +
                "  modify($p) { setAge( 18 ) };" +
                "  insert(\"Done\");\n" +
                "end";

        AnalysisModel analysisModel = new ModelBuilder().build( str );
        System.out.println(analysisModel);
    }
}


text:
// -*- C++ -*-

// Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file constructors_destructor_fn_imps.hpp
 * Contains an implementation class for bin_search_tree_.
 */

PB_DS_CLASS_T_DEC
typename PB_DS_CLASS_C_DEC::head_allocator
PB_DS_CLASS_C_DEC::s_head_allocator;

PB_DS_CLASS_T_DEC
typename PB_DS_CLASS_C_DEC::internal_node_allocator
PB_DS_CLASS_C_DEC::s_internal_node_allocator;

PB_DS_CLASS_T_DEC
typename PB_DS_CLASS_C_DEC::leaf_allocator
PB_DS_CLASS_C_DEC::s_leaf_allocator;

PB_DS_CLASS_T_DEC
PB_DS_CLASS_C_DEC::
PB_DS_CLASS_NAME() :
  m_p_head(s_head_allocator.allocate(1)),
  m_size(0)
{
  initialize();
  _GLIBCXX_DEBUG_ONLY(assert_valid();)
}

PB_DS_CLASS_T_DEC
PB_DS_CLASS_C_DEC::
PB_DS_CLASS_NAME(const e_access_traits& r_e_access_traits) :
  synth_e_access_traits(r_e_access_traits),
  m_p_head(s_head_allocator.allocate(1)),
  m_size(0)
{
  initialize();
  _GLIBCXX_DEBUG_ONLY(assert_valid();)
}

PB_DS_CLASS_T_DEC
PB_DS_CLASS_C_DEC::
PB_DS_CLASS_NAME(const PB_DS_CLASS_C_DEC& other) :
#ifdef _GLIBCXX_DEBUG
  debug_base(other),
#endif
  synth_e_access_traits(other),
  node_update(other),
  m_p_head(s_head_allocator.allocate(1)),
  m_size(0)
{
  initialize();
  m_size = other.m_size;
  _GLIBCXX_DEBUG_ONLY(other.assert_valid();)
    if (other.m_p_head->m_p_parent == 0)
      {
	_GLIBCXX_DEBUG_ONLY(assert_valid();)
	return;
      }
  __try
    {
      m_p_head->m_p_parent = recursive_copy_node(other.m_p_head->m_p_parent);
    }
  __catch(...)
    {
      s_head_allocator.deallocate(m_p_head, 1);
      __throw_exception_again;
    }

  m_p_head->m_p_min = leftmost_descendant(m_p_head->m_p_parent);
  m_p_head->m_p_max = rightmost_descendant(m_p_head->m_p_parent);
  m_p_head->m_p_parent->m_p_parent = m_p_head;
  _GLIBCXX_DEBUG_ONLY(assert_valid();)
}

PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
swap(PB_DS_CLASS_C_DEC& other)
{
  _GLIBCXX_DEBUG_ONLY(assert_valid();)
  _GLIBCXX_DEBUG_ONLY(other.assert_valid();)
  value_swap(other);
  std::swap((e_access_traits& )(*this), (e_access_traits& )other);
  _GLIBCXX_DEBUG_ONLY(assert_valid();)
  _GLIBCXX_DEBUG_ONLY(other.assert_valid();)
}

PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
value_swap(PB_DS_CLASS_C_DEC& other)
{
  _GLIBCXX_DEBUG_ONLY(debug_base::swap(other);)
  std::swap(m_p_head, other.m_p_head);
  std::swap(m_size, other.m_size);
}

PB_DS_CLASS_T_DEC
PB_DS_CLASS_C_DEC::
~PB_DS_CLASS_NAME()
{
  clear();
  s_head_allocator.deallocate(m_p_head, 1);
}

PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
initialize()
{
  new (m_p_head) head();
  m_p_head->m_p_parent = 0;
  m_p_head->m_p_min = m_p_head;
  m_p_head->m_p_max = m_p_head;
  m_size = 0;
}

PB_DS_CLASS_T_DEC
template<typename It>
void
PB_DS_CLASS_C_DEC::
copy_from_range(It first_it, It last_it)
{
  while (first_it != last_it)
    insert(*(first_it++));
}

PB_DS_CLASS_T_DEC
typename PB_DS_CLASS_C_DEC::node_pointer
PB_DS_CLASS_C_DEC::
recursive_copy_node(const_node_pointer p_other_nd)
{
  _GLIBCXX_DEBUG_ASSERT(p_other_nd != 0);
  if (p_other_nd->m_type == pat_trie_leaf_node_type)
    {
      const_leaf_pointer p_other_leaf = static_cast<const_leaf_pointer>(p_other_nd);

      leaf_pointer p_new_lf = s_leaf_allocator.allocate(1);
      cond_dealtor cond(p_new_lf);
      new (p_new_lf) leaf(p_other_leaf->value());
      apply_update(p_new_lf, (node_update* )this);
      cond.set_no_action_dtor();
      return (p_new_lf);
    }

  _GLIBCXX_DEBUG_ASSERT(p_other_nd->m_type == pat_trie_internal_node_type);
  node_pointer a_p_children[internal_node::arr_size];
  size_type child_i = 0;
  const_internal_node_pointer p_other_internal_nd =
    static_cast<const_internal_node_pointer>(p_other_nd);

  typename internal_node::const_iterator child_it =
    p_other_internal_nd->begin();

  internal_node_pointer p_ret;
  __try
    {
      while (child_it != p_other_internal_nd->end())
	a_p_children[child_i++] = recursive_copy_node(*(child_it++));
      p_ret = s_internal_node_allocator.allocate(1);
    }
  __catch(...)
    {
      while (child_i-- > 0)
	clear_imp(a_p_children[child_i]);
      __throw_exception_again;
    }

  new (p_ret) internal_node(p_other_internal_nd->get_e_ind(),
			    pref_begin(a_p_children[0]));

  --child_i;
  _GLIBCXX_DEBUG_ASSERT(child_i >= 1);
  do
    p_ret->add_child(a_p_children[child_i], pref_begin(a_p_children[child_i]),
		     pref_end(a_p_children[child_i]), this);
  while (child_i-- > 0);
  apply_update(p_ret, (node_update* )this);
  return p_ret;
}


text:
const akeliusProvider = require('../providers/akelius');
const BaseSynchronizer = require('./base');

class AkeliusSynchronizer extends BaseSynchronizer {
    constructor() {
        super();
        this.providerService = akeliusProvider;
        this.providerName = 'akelius';
    }
}

module.exports = AkeliusSynchronizer;


text:
import Hub from "../../hub/Hub";

export default class ChatEvent {
  public static get EventName() : string { return "chat_message"; }

  public static HandleEvent(userName : string, message : string) {
    Hub.logger.logSuccess(`> Chat message. ${userName}: ${message}`);
    Hub.dispatcher.dispatchEvent("chat_message_received", userName, message);
  }
}


text:
define([
    "hr/hr",
    "hr/promise",
    "utils/normalize",
    "utils/dialogs",
    "models/article",
    "core/server",
    "views/grid",
    "views/summary",
    "views/editor",
    "views/preview"
], function(hr, Q, normalize, dialogs, Article, server, Grid, Summary, Editor, Preview) {
    var generate = node.require("gitbook").generate;

    var Book = hr.View.extend({
        className: "book",
        defaults: {
            fs: null
        },

        initialize: function() {
            Book.__super__.initialize.apply(this, arguments);

            this.fs = this.options.fs;

            // Map article path -> content
            this.articles = {};
            this.currentArticle = null;

            this.grid = new Grid({
                columns: 3
            }, this);
            this.grid.appendTo(this);

            // Summary
            this.summary = new Summary({}, this);
            this.summary.update();
            this.grid.addView(this.summary, {width: 20});

            // Editor
            this.editor = new Editor({}, this);
            this.editor.update();
            this.grid.addView(this.editor);

            // Preview
            this.preview = new Preview({}, this);
            this.preview.update();
            this.grid.addView(this.preview);

            this.openReadme();
        },

        /*
         *  Build the book
         */
        buildBook: function(params, options) {
            var that = this;

            return generate.folder(_.extend(params || {}, {
                input: this.fs.options.base
            }));
        },

        /*
         *  Generate a file (pdf or ebook)
         */
        buildBookFile: function(format, params) {
            var that = this;

            var filename = format == "pdf" ? "book.pdf" : "book.epub";

            dialogs.saveAs(filename)
            .then(function(_path) {
                return generate.file(_.extend(params || {}, {
                    extension: "pdf",
                    input: that.fs.options.base,
                    output: _path,
                    generator: format
                }))
                .then(_.constant(_path));
            })
            .then(function(_path) {
                node.gui.Shell.showItemInFolder(_path);
            }, dialogs.error);
        },

        /*
         * Refresh preview
         */
        refreshPreviewServer: function() {
            var that = this;
            console.log("start server on ", this.fs.options.base);

            return server.stop()
            .then(function() {
                return that.buildBook();
            })
            .then(function(options) {
                return server.start(options.output)
            })
            .then(function() {
                server.open();
            }, function(err) {
                dialogs.alert("Error starting preview server:", err.message || err);
            });
        },

        /*
         * Show an article
         */
        openArticle: function(article) {
            var that = this;

            var doOpen = function() {
                that.currentArticle = article;
                that.trigger("article:open", article);
                that.triggerArticleState(article);

                that.toggleArticlesClass(article, "active");

                return Q();
            };

            var doSaveAndOpen = function() {
                return dialogs.saveAs(article.get("title")+".md", that.fs.options.base)
                .then(function(path) {
                    if (!that.fs.isValidPath(path)) return Q.reject(new Error("Invalid path for saving this article, need to be on the book repository."));
                    path = that.fs.virtualPath(path);
                    article.set("path", path);
                })
                // Write article
                .then(function() {
                    return that.writeArticle(article, "# "+article.get("title")+"\n")
                })
                // Save the article
                .then(function() {
                    return that.saveArticle(article);
                })
                // Save summary
                .then(function() {
                    return that.summary.save();
                })
                .then(function() {
                    return doOpen();
                })
                .fail(function(err) {
                    dialogs.alert("Error", err.message || err);
                });
            };

            if (!article.get("path")) {
                return doSaveAndOpen();
            } else {
                return that.fs.exists(article.get("path"))
                .then(function(exists) {
                    if (exists) {
                        return doOpen();
                    } else {
                        return doSaveAndOpen();
                    }
                });
            }
        },

        /*
         * Show introduction
         */
        openReadme: function() {
            return this.openArticle(new Article({}, {
                title: "Introduction",
                path: "README.md"
            }));
        },

        // Get unsaved article
        getUnsavedArticles: function() {
            return _.chain(this.articles)
            .map(function(article, _path) {
                article.path = _path;
                return article;
            })
            .filter(function(article) {
                return !article.saved;
            })
            .value();
        },

        // Save all unsaved
        saveAll: function() {
            _.each(this.getUnsavedArticles(), function(_article) {
                var article = this.summary.getArticle(_article.path);
                console.log(_article.path, article);
                if (article) this.saveArticle(article);
            }, this);
        },

        // Read/Write article in this fs
        readArticle: function(article) {
            var that = this;
            var path = article.get("path");

            if (this.articles[path]) return Q(this.articles[path].content);

            return this.fs.read(path)
            .then(function(content) {
                that.articles[path] = {
                    content: content,
                    saved: true
                };
                return content;
            });
        },
        writeArticle: function(article, content) {
            var path = article.get("path");

            this.articles[path] = this.articles[path] || {};
            this.articles[path].saved = false;
            this.articles[path].content = content;

            this.trigger("article:write", article);
            this.triggerArticleState(article);

            return Q();
        },
        saveArticle: function(article) {
            var that = this;
            var path = article.get("path");
            if (!this.articles[path]) return Q.reject(new Error("No content to save for this article"));

            // Normalize content before saving
            var content = normalize.eof(
            normalize.whitespace(
                this.articles[path].content
            ));

            return this.fs.write(article.get("path"), content)
            .then(function() {
                that.articles[path].saved = true;
                that.triggerArticleState(article);

                // Update code views
                that.trigger("article:save", article, content);

                if (server.isRunning()) {
                    dialogs.confirm("Restart Preview Server", "Do you want to restart the preview server to access your last changes?")
                    .then(function() {
                        that.refreshPreviewServer();
                    });
                }
            });
        },
        triggerArticleState: function(article) {
            var path = article.get("path");
            var st = this.articles[path]? this.articles[path].saved : true;

            this.trigger("article:state", article, st);
            this.toggleArticleClass(article, "modified", !st);
        },
        getArticleState: function(article) {
            article = article || this.currentArticle;
            var path = article.get("path");
            return this.articles[path];
        },
        toggleArticleClass: function(article, className, st) {
            this.$("*[data-article='"+article.get("path")+"']").toggleClass(className, st);
        },
        toggleArticlesClass: function(article, className) {
            this.$("*[data-article]").each(function() {
                $(this).toggleClass(className, $(this).data("article") == article.get("path"));
            });
        }
    }, {
        /*
         *  Valid that a fs is a gitbook
         */
        valid: function(fs) {
            return fs.exists("README.md")
            .then(function(exists) {
                if (!exists) {
                    return Q.reject(new Error("Invalid GitBook: need README.md and SUMMARY.md"));
                }
                return fs.exists("SUMMARY.md")
                .then(function(exists) {
                    if (!exists) {
                        return Q.reject(new Error("Invalid GitBook: need README.md and SUMMARY.md"));
                    }
                });
            });
        }
    });

    return Book;
});


text:
<?php

namespace Kali\Back\ParameterBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class KaliBackParameterBundle extends Bundle
{
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

001
018
019package org.apache.hadoop.mapreduce.lib.partition;
020
021import org.apache.hadoop.classification.InterfaceAudience;
022import org.apache.hadoop.classification.InterfaceStability;
023import org.apache.hadoop.conf.Configurable;
024import org.apache.hadoop.conf.Configuration;
025import org.apache.hadoop.io.BinaryComparable;
026import org.apache.hadoop.io.WritableComparator;
027import org.apache.hadoop.mapreduce.Partitioner;
028
029/**
030 * <p>Partition {@link BinaryComparable} keys using a configurable part of
031 * the bytes array returned by {@link BinaryComparable#getBytes()}.</p>
032 *
033 * <p>The subarray to be used for the partitioning can be defined by means
034 * of the following properties:
035 * <ul>
036 *   <li>
037 *     <i>mapreduce.partition.binarypartitioner.left.offset</i>:
038 *     left offset in array (0 by default)
039 *   </li>
040 *   <li>
041 *     <i>mapreduce.partition.binarypartitioner.right.offset</i>:
042 *     right offset in array (-1 by default)
043 *   </li>
044 * </ul>
045 * Like in Python, both negative and positive offsets are allowed, but
046 * the meaning is slightly different. In case of an array of length 5,
047 * for instance, the possible offsets are:
048 * <pre><code>
049 *  +---+---+---+---+---+
050 *  | B | B | B | B | B |
051 *  +---+---+---+---+---+
052 *    0   1   2   3   4
053 *   -5  -4  -3  -2  -1
054 * </code></pre>
055 * The first row of numbers gives the position of the offsets 0...5 in
056 * the array; the second row gives the corresponding negative offsets.
057 * Contrary to Python, the specified subarray has byte <code>i</code>
058 * and <code>j</code> as first and last element, repectively, when
059 * <code>i</code> and <code>j</code> are the left and right offset.
060 *
061 * <p>For Hadoop programs written in Java, it is advisable to use one of
062 * the following static convenience methods for setting the offsets:
063 * <ul>
064 *   <li>{@link #setOffsets}</li>
065 *   <li>{@link #setLeftOffset}</li>
066 *   <li>{@link #setRightOffset}</li>
067 * </ul>
068 */
069@InterfaceAudience.Public
070@InterfaceStability.Evolving
071public class BinaryPartitioner<V> extends Partitioner<BinaryComparable, V>
072  implements Configurable {
073
074  public static final String LEFT_OFFSET_PROPERTY_NAME =
075    "mapreduce.partition.binarypartitioner.left.offset";
076  public static final String RIGHT_OFFSET_PROPERTY_NAME =
077    "mapreduce.partition.binarypartitioner.right.offset";
078
079  /**
080   * Set the subarray to be used for partitioning to
081   * <code>bytes[left:(right+1)]</code> in Python syntax.
082   *
083   * @param conf configuration object
084   * @param left left Python-style offset
085   * @param right right Python-style offset
086   */
087  public static void setOffsets(Configuration conf, int left, int right) {
088    conf.setInt(LEFT_OFFSET_PROPERTY_NAME, left);
089    conf.setInt(RIGHT_OFFSET_PROPERTY_NAME, right);
090  }
091
092  /**
093   * Set the subarray to be used for partitioning to
094   * <code>bytes[offset:]</code> in Python syntax.
095   *
096   * @param conf configuration object
097   * @param offset left Python-style offset
098   */
099  public static void setLeftOffset(Configuration conf, int offset) {
100    conf.setInt(LEFT_OFFSET_PROPERTY_NAME, offset);
101  }
102
103  /**
104   * Set the subarray to be used for partitioning to
105   * <code>bytes[:(offset+1)]</code> in Python syntax.
106   *
107   * @param conf configuration object
108   * @param offset right Python-style offset
109   */
110  public static void setRightOffset(Configuration conf, int offset) {
111    conf.setInt(RIGHT_OFFSET_PROPERTY_NAME, offset);
112  }
113
114
115  private Configuration conf;
116  private int leftOffset, rightOffset;
117
118  public void setConf(Configuration conf) {
119    this.conf = conf;
120    leftOffset = conf.getInt(LEFT_OFFSET_PROPERTY_NAME, 0);
121    rightOffset = conf.getInt(RIGHT_OFFSET_PROPERTY_NAME, -1);
122  }
123
124  public Configuration getConf() {
125    return conf;
126  }
127
128  /**
129   * Use (the specified slice of the array returned by)
130   * {@link BinaryComparable#getBytes()} to partition.
131   */
132  @Override
133  public int getPartition(BinaryComparable key, V value, int numPartitions) {
134    int length = key.getLength();
135    int leftIndex = (leftOffset + length) % length;
136    int rightIndex = (rightOffset + length) % length;
137    int hash = WritableComparator.hashBytes(key.getBytes(),
138      leftIndex, rightIndex - leftIndex + 1);
139    return (hash & Integer.MAX_VALUE) % numPartitions;
140  }
141
142}


text:
package com.vmware.vim25;

import java.util.Calendar;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

@SuppressWarnings("all")
public class AlarmInfo extends AlarmSpec {
    public String key;
    public ManagedObjectReference alarm;
    public ManagedObjectReference entity;
    public Calendar lastModifiedTime;
    public String lastModifiedUser;
    public int creationEventId;

    public String getKey() {
        return this.key;
    }

    public ManagedObjectReference getAlarm() {
        return this.alarm;
    }

    public ManagedObjectReference getEntity() {
        return this.entity;
    }

    public Calendar getLastModifiedTime() {
        return this.lastModifiedTime;
    }

    public String getLastModifiedUser() {
        return this.lastModifiedUser;
    }

    public int getCreationEventId() {
        return this.creationEventId;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public void setAlarm(ManagedObjectReference alarm) {
        this.alarm = alarm;
    }

    public void setEntity(ManagedObjectReference entity) {
        this.entity = entity;
    }

    public void setLastModifiedTime(Calendar lastModifiedTime) {
        this.lastModifiedTime = lastModifiedTime;
    }

    public void setLastModifiedUser(String lastModifiedUser) {
        this.lastModifiedUser = lastModifiedUser;
    }

    public void setCreationEventId(int creationEventId) {
        this.creationEventId = creationEventId;
    }
}


text:
export default function ownKeys(object) {
  let keys = Object.getOwnPropertyNames(object);

  if (typeof Object.getOwnPropertySymbols === 'function') {
    keys = keys.concat(Object.getOwnPropertySymbols(object));
  }

  return keys;
}


text:
div.jimu-widget-savesession .textbox {
    width: 250px;
}

div.jimu-widget-savesession .form-control {
    padding: 5px 0 5px 0;
}

div.jimu-widget-savesession .jimu-icon {
    margin-left: 5px;
    margin-right: 5px;
}

.jimu-icon-load {
    background-position: -0px -47px;
    width: 16px;
    height: 16px;
}

.jimu-icon-load.jimu-state-disabled {
    background-position: -63px -47px;
    width: 16px;
    height: 16px;
}

.jimu-icon-load.jimu-state-hover {
    background-position: -21px -47px;
    width: 16px;
    height: 16px;
}

.jimu-icon-load:hover {
    background-position: -21px -47px;
    width: 16px;
    height: 16px;
}

.jimu-icon-download {
    background-image: url("../images/download_icon.png");
    width: 15px;
    height: 16px;
}

.jimu-icon-download.jimu-state-disabled {
    background-image: url("../images/download_icon.png");
    width: 15px;
    height: 16px;
}

.jimu-icon-download.jimu-state-hover,
.jimu-icon-download:hover {
    background-image: url("../images/download_icon_hover.png");
    width: 15px;
    height: 16px;
}

div.jimu-widget-savesession .input-text {
    display: inline;
    color: silver;
}

.jimu-widget-savesession .help-text {
    color: silver;
}

.jimu-widget-savesession a.link-btn:visited,
.jimu-widget-savesession a.link-btn {
    padding: 10px;
    color: #518dca;
}

.jimu-widget-savesession a.link-btn:hover {
    color: blue;
}

.jimu-widget-savesession a.link-btn.jimu-state-disabled:visited,
.jimu-widget-savesession a.link-btn.jimu-state-disabled:hover,
.jimu-widget-savesession a.link-btn.jimu-state-disabled {
    padding: 10px;
    color: gray;
    pointer-events: none;
    text-decoration: none;
}

#load-file-panel {
    margin-top: 10px;
    width: 200px;
    margin-left: auto;
    margin-right: auto;
}


text:
function Delete-Directory($directoryName){
    Remove-Item -Force -Recurse $directoryName -ErrorAction SilentlyContinue
}

function Create-Directory($directoryName){
    New-Item $directoryName -ItemType Directory -Force | Out-Null
}


text: A new Python bot


text:
package info.dgjones.abora.gold.cross;

import info.dgjones.abora.gold.collection.basic.Int32Array;
import info.dgjones.abora.gold.collection.basic.PrimIntArray;
import info.dgjones.abora.gold.collection.basic.PtrArray;
import info.dgjones.abora.gold.collection.steppers.Stepper;
import info.dgjones.abora.gold.cross.TupleStepper;
import info.dgjones.abora.gold.java.AboraSupport;
import info.dgjones.abora.gold.java.missing.smalltalk.Set;
import info.dgjones.abora.gold.spaces.basic.Position;
import info.dgjones.abora.gold.spaces.cross.CrossSpace;
import info.dgjones.abora.gold.spaces.cross.Tuple;
import info.dgjones.abora.gold.xcvr.Rcvr;
import info.dgjones.abora.gold.xcvr.Xmtr;
import info.dgjones.abora.gold.xpp.basic.Heaper;

/**
 * A stepper for stepping through the positions in a simple cross region in order according
 * to a lexicographic composition of OrderSpecs of each of the projections of the region.
 * See CrossOrderSpec.NOT.A.TYPE
 */
public class TupleStepper extends Stepper {

	protected CrossSpace mySpace;
	protected PtrArray myVirginSteppers;
	protected PtrArray mySteppers;
	protected PrimIntArray myLexOrder;
	protected Tuple myValue;
/*
udanax-top.st:56321:
Stepper subclass: #TupleStepper
	instanceVariableNames: '
		mySpace {CrossSpace}
		myVirginSteppers {PtrArray of: (Stepper of: Position)}
		mySteppers {PtrArray of: (Stepper of: Position)}
		myLexOrder {PrimIntArray}
		myValue {Tuple | NULL}'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'Xanadu-cross'!
*/
/*
udanax-top.st:56330:
TupleStepper comment:
'A stepper for stepping through the positions in a simple cross region in order according to a lexicographic composition of OrderSpecs of each of the projections of the region.  See CrossOrderSpec.NOT.A.TYPE '!
*/
/*
udanax-top.st:56332:
(TupleStepper getOrMakeCxxClassDescription)
	attributes: ((Set new) add: #CONCRETE; add: #COPY; yourself)!
*/
/*
udanax-top.st:56412:
TupleStepper class
	instanceVariableNames: ''!
*/
/*
udanax-top.st:56415:
(TupleStepper getOrMakeCxxClassDescription)
	attributes: ((Set new) add: #CONCRETE; add: #COPY; yourself)!
*/
public static void initializeClassAttributes() {
	AboraSupport.findAboraClass(TupleStepper.class).setAttributes( new Set().add("CONCRETE").add("COPY"));
/*

Generated during transformation: AddMethod
*/
}
public TupleStepper(CrossSpace space, PtrArray virginSteppers, PtrArray steppers, PrimIntArray lexOrder) {
	super();
	mySpace = space;
	myVirginSteppers = virginSteppers;
	mySteppers = steppers;
	myLexOrder = lexOrder;
	setValueFromSteppers();
/*
udanax-top.st:56337:TupleStepper methodsFor: 'private: creation'!
create: space {CrossSpace}
	with: virginSteppers {PtrArray of: (Stepper of: Position)}
	with: steppers {PtrArray of: (Stepper of: Position)}
	with: lexOrder {PrimIntArray}

	super create.
	mySpace := space.
	myVirginSteppers := virginSteppers.
	mySteppers := steppers.
	myLexOrder := lexOrder.
	self setValueFromSteppers!
*/
}
public void setValueFromSteppers() {
	PtrArray coords;
	coords = PtrArray.nulls(mySteppers.count());
	for (int i = 0; i < mySteppers.count(); i ++ ) {
		coords.store(i, ((Position) ((Stepper) (mySteppers.fetch(i))).get()));
	}
	myValue = mySpace.crossOfPositions(coords);
/*
udanax-top.st:56351:TupleStepper methodsFor: 'private:'!
{void} setValueFromSteppers
	| coords {PtrArray of: Position} |
	coords := PtrArray nulls: mySteppers count.
	Int32Zero almostTo: mySteppers count do: [:i {Int32} |
		coords at: i store: (((mySteppers fetch: i) cast: Stepper) get cast: Position)].
	myValue := mySpace crossOfPositions: coords!
*/
}
public Stepper copy() {
	PtrArray newSteppers;
	if ( ! (hasValue())) {
		return Stepper.emptyStepper();
	}
	newSteppers = PtrArray.nulls(mySteppers.count());
	for (int i = 0; i < mySteppers.count(); i ++ ) {
		newSteppers.store(i, ((Stepper) (mySteppers.fetch(i))).copy());
	}
	return new TupleStepper(mySpace, myVirginSteppers, newSteppers, myLexOrder);
/*
udanax-top.st:56361:TupleStepper methodsFor: 'operations'!
{Stepper} copy

	| newSteppers {PtrArray of: (Stepper of: Position)} |
	self hasValue ifFalse:
		[^Stepper emptyStepper].
	newSteppers := PtrArray nulls: mySteppers count.
	Int32Zero almostTo: mySteppers count do: [:i {Int32} |
		newSteppers at: i store: ((mySteppers fetch: i) cast: Stepper) copy].
	^TupleStepper create: mySpace with: myVirginSteppers with: newSteppers with: myLexOrder!
*/
}
public Heaper fetch() {
	return myValue;
/*
udanax-top.st:56371:TupleStepper methodsFor: 'operations'!
{Heaper wimpy} fetch
	^myValue!
*/
}
public boolean hasValue() {
	return myValue != null;
/*
udanax-top.st:56375:TupleStepper methodsFor: 'operations'!
{BooleanVar} hasValue
	^myValue ~~ NULL!
*/
}
public void step() {
	Stepper stomp;
	if (myValue == null) {
		return ;
	}
	for (int i = myLexOrder.count()-1; i >= 0; i -= 1 ) {
		int dim;
		dim = (myLexOrder.integerAt(i));
		stomp = (Stepper) (mySteppers.fetch(dim));
		stomp.step();
		if (stomp.hasValue()) {
			setValueFromSteppers();
			return ;
		}
		mySteppers.store(dim, ((Stepper) (myVirginSteppers.fetch(dim))).copy());
	}
	myValue = null;
/*
udanax-top.st:56379:TupleStepper methodsFor: 'operations'!
{void} step
	| stomp {Stepper of: Position} |
	myValue == NULL ifTrue: [^VOID].
	myLexOrder count -1 to: Int32Zero by: -1 do: [:i {Int32} |
		| dim {Int32} |
		dim := (myLexOrder integerAt: i) DOTasLong.
		stomp := (mySteppers fetch: dim) cast: Stepper.
		stomp step.
		stomp hasValue ifTrue:
			[self setValueFromSteppers.
			^VOID].
		mySteppers at: dim store: ((myVirginSteppers fetch: dim) cast: Stepper) copy].
	myValue := NULL!
*/
}
public TupleStepper(Rcvr receiver) {
	super(receiver);
	mySpace = (CrossSpace) receiver.receiveHeaper();
	myVirginSteppers = (PtrArray) receiver.receiveHeaper();
	mySteppers = (PtrArray) receiver.receiveHeaper();
	myLexOrder = (PrimIntArray) receiver.receiveHeaper();
	myValue = (Tuple) receiver.receiveHeaper();
/*
udanax-top.st:56395:TupleStepper methodsFor: 'generated:'!
create.Rcvr: receiver {Rcvr}
	super create.Rcvr: receiver.
	mySpace _ receiver receiveHeaper.
	myVirginSteppers _ receiver receiveHeaper.
	mySteppers _ receiver receiveHeaper.
	myLexOrder _ receiver receiveHeaper.
	myValue _ receiver receiveHeaper.!
*/
}
public void sendSelfTo(Xmtr xmtr) {
	super.sendSelfTo(xmtr);
	xmtr.sendHeaper(mySpace);
	xmtr.sendHeaper(myVirginSteppers);
	xmtr.sendHeaper(mySteppers);
	xmtr.sendHeaper(myLexOrder);
	xmtr.sendHeaper(myValue);
/*
udanax-top.st:56403:TupleStepper methodsFor: 'generated:'!
{void} sendSelfTo: xmtr {Xmtr}
	super sendSelfTo: xmtr.
	xmtr sendHeaper: mySpace.
	xmtr sendHeaper: myVirginSteppers.
	xmtr sendHeaper: mySteppers.
	xmtr sendHeaper: myLexOrder.
	xmtr sendHeaper: myValue.!
*/
}
public static Stepper make(CrossSpace space, PtrArray virginSteppers, PrimIntArray lexOrder) {
	PtrArray steppers;
	PrimIntArray lexO;
	if (virginSteppers.count() == 0) {
		return Stepper.itemStepper((space.crossOfPositions((PtrArray.nulls(0)))));
	}
	steppers = PtrArray.nulls(virginSteppers.count());
	for (int i = 0; i < virginSteppers.count(); i ++ ) {
		Stepper vs;
		vs = (Stepper) (virginSteppers.fetch(i));
		if ( ! (vs.hasValue())) {
			return Stepper.emptyStepper();
		}
		steppers.store(i, vs.copy());
	}
	if (lexOrder == null) {
		lexO = Int32Array.make(virginSteppers.count());
		for (int i1 = 0; i1 < virginSteppers.count(); i1 ++ ) {
			lexO.storeInteger(i1, i1);
		}
	}
	else {
		lexO = lexOrder;
	}
	return new TupleStepper(space, virginSteppers, steppers, lexO);
/*
udanax-top.st:56420:TupleStepper class methodsFor: 'pseudoconstructors'!
{Stepper} make: space {CrossSpace}
	with: virginSteppers {PtrArray of: (Stepper of: Position)}
	with: lexOrder {PrimIntArray default: NULL}

	| steppers {PtrArray of: (Stepper of: Position)} lexO {PrimIntArray} |
	virginSteppers count = Int32Zero ifTrue:
		[^Stepper itemStepper: (space crossOfPositions: (PtrArray nulls: Int32Zero))].
	steppers := PtrArray nulls: virginSteppers count.
	Int32Zero almostTo: virginSteppers count do: [:i {Int32} |
		| vs {Stepper of: Position} |
		vs := (virginSteppers fetch: i) cast: Stepper.
		vs hasValue ifFalse:
			[^Stepper emptyStepper].
		steppers at: i store: vs copy].

	lexOrder == NULL ifTrue:
		[lexO := Int32Array make: virginSteppers count.
		Int32Zero almostTo: virginSteppers count do: [:i {Int32} |
			lexO at: i storeInteger: i]]
	ifFalse:
		[lexO := lexOrder].
	^self create: space with: virginSteppers with: steppers with: lexO!
*/
}
public static TupleStepper make(CrossSpace space, PtrArray virginSteppers) {
	return (TupleStepper) make(space, virginSteppers, null);
/*
udanax-top.st:56445:TupleStepper class methodsFor: 'smalltalk: defaults'!
make: space with: virginSteppers

	^self make: space with: virginSteppers with: NULL!
*/
}
public TupleStepper() {
/*

Generated during transformation
*/
}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Vision</title>

    <link href="<?php echo base_url();?>assets/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>assets/dist/css/profiles.css" rel="stylesheet">

    <link href="<?php echo base_url();?>assets/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <link href="<?php echo base_url();?>assets/carousel.css" rel="stylesheet">

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>
              Lsm

<a href="<?php echo base_url();?>">home

<a href="<?php echo base_url();?>about_us">About

<a href="<?php echo base_url();?>click_here_to_contact_us">Contact

Vision

<a href="<?php echo base_url();?>go_to_our_goal">Goal

<a href="<?php echo base_url();?>go_to_our_mission">Mission

"

Vision

The life saver missionaries having realised the need will
            provide and give a hand to support the vulnerable, widows, orphans, street children
            and sick to their health and social wellbeing.

            <img src="<?php echo base_url(); ?>images/children-2143808__480.jpg">

Lsm Organisation Website  by junior.

                  Back to top


text:
cask 'malwarebytes-anti-malware' do
  version '1.2.4.584'
  sha256 '90e6c804e6670dc459f58418a8085f8318f63d151a801cfc946b09a2c2adfcd8'

  # data-cdn.mbamupdates.com was verified as official when first introduced to the cask
  url "https://data-cdn.mbamupdates.com/web/MBAM-Mac-#{version}.dmg"
  appcast 'https://data-cdn.mbamupdates.com/v1/mbam-mac/updates.xml',
          checkpoint: '29b2798b309c77365e7c1566daaaed0b0ccdae2eb3f59c390ff537b4846cf2cd'
  name 'Malwarebytes Anti-Malware for Mac'
  name 'AdwareMedic'
  homepage 'https://www.malwarebytes.org/antimalware/mac/'
  license :gratis

  depends_on macos: '>= :lion'

  app 'Malwarebytes Anti-Malware.app'

  zap delete: [
                '~/Library/Preferences/com.malwarebytes.antimalware.plist',
                '~/Library/Caches/com.malwarebytes.antimalware',
                '~/Library/Application Support/com.malwarebytes.antimalware',
                '~/Library/Saved Application State/com.malwarebytes.antimalware.savedState',
                '~/Library/Caches/com.malwarebytes.Malwarebytes-Anti-Malware-Service',
                '~/Library/Caches/com.malwarebytes.Malwarebytes-XPC-Service',
              ]
end


text:
<?php

namespace Plopix\R2\Core\Client;

use GuzzleHttp\Client as GuzzleHttpClient;

/**
 * Class HTTP.
 */
class HTTP
{
    /**
     * @var GuzzleHttpClient
     */
    protected $client;

    const GET    = 'GET';
    const POST   = 'POST';
    const PATCH  = 'PATCH';
    const DELETE = 'DELETE';

    /**
     * HTTP constructor.
     *
     * @param GuzzleHttpClient $client
     */
    public function __construct(GuzzleHttpClient $client = null)
    {
        if ($client === null) {
            $client = new GuzzleHttpClient();
        }
        $this->client = $client;
    }

    /**
     * Get the Client.
     *
     * @return GuzzleHttpClient
     */
    public function getClient()
    {
        return $this->client;
    }
}


text:
package org.apache.accumulo.master.tableOps;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.math.BigInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.impl.Namespaces;
import org.apache.accumulo.core.client.impl.Tables;
import org.apache.accumulo.core.client.impl.thrift.TableOperation;
import org.apache.accumulo.core.client.impl.thrift.TableOperationExceptionType;
import org.apache.accumulo.core.client.impl.thrift.ThriftTableOperationException;
import org.apache.accumulo.core.util.Base64;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.fate.zookeeper.DistributedReadWriteLock;
import org.apache.accumulo.fate.zookeeper.IZooReaderWriter;
import org.apache.accumulo.fate.zookeeper.IZooReaderWriter.Mutator;
import org.apache.accumulo.fate.zookeeper.ZooReservation;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.zookeeper.ZooQueueLock;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Utils {
  private static final byte[] ZERO_BYTE = new byte[] {'0'};
  private static final Logger log = LoggerFactory.getLogger(Utils.class);

  static void checkTableDoesNotExist(Instance instance, String tableName, String tableId, TableOperation operation) throws ThriftTableOperationException {

    String id = Tables.getNameToIdMap(instance).get(tableName);

    if (id != null && !id.equals(tableId))
      throw new ThriftTableOperationException(null, tableName, operation, TableOperationExceptionType.EXISTS, null);
  }

  static String getNextTableId(String tableName, Instance instance) throws ThriftTableOperationException {

    String tableId = null;
    try {
      IZooReaderWriter zoo = ZooReaderWriter.getInstance();
      final String ntp = ZooUtil.getRoot(instance) + Constants.ZTABLES;
      byte[] nid = zoo.mutate(ntp, ZERO_BYTE, ZooUtil.PUBLIC, new Mutator() {
        @Override
        public byte[] mutate(byte[] currentValue) throws Exception {
          BigInteger nextId = new BigInteger(new String(currentValue, UTF_8), Character.MAX_RADIX);
          nextId = nextId.add(BigInteger.ONE);
          return nextId.toString(Character.MAX_RADIX).getBytes(UTF_8);
        }
      });
      return new String(nid, UTF_8);
    } catch (Exception e1) {
      log.error("Failed to assign tableId to " + tableName, e1);
      throw new ThriftTableOperationException(tableId, tableName, TableOperation.CREATE, TableOperationExceptionType.OTHER, e1.getMessage());
    }
  }

  static final Lock tableNameLock = new ReentrantLock();
  static final Lock idLock = new ReentrantLock();

  public static long reserveTable(String tableId, long tid, boolean writeLock, boolean tableMustExist, TableOperation op) throws Exception {
    if (getLock(tableId, tid, writeLock).tryLock()) {
      if (tableMustExist) {
        Instance instance = HdfsZooInstance.getInstance();
        IZooReaderWriter zk = ZooReaderWriter.getInstance();
        if (!zk.exists(ZooUtil.getRoot(instance) + Constants.ZTABLES + "/" + tableId))
          throw new ThriftTableOperationException(tableId, "", op, TableOperationExceptionType.NOTFOUND, "Table does not exist");
      }
      log.info("table " + tableId + " (" + Long.toHexString(tid) + ") locked for " + (writeLock ? "write" : "read") + " operation: " + op);
      return 0;
    } else
      return 100;
  }

  public static void unreserveTable(String tableId, long tid, boolean writeLock) throws Exception {
    getLock(tableId, tid, writeLock).unlock();
    log.info("table " + tableId + " (" + Long.toHexString(tid) + ") unlocked for " + (writeLock ? "write" : "read"));
  }

  public static void unreserveNamespace(String namespaceId, long id, boolean writeLock) throws Exception {
    getLock(namespaceId, id, writeLock).unlock();
    log.info("namespace " + namespaceId + " (" + Long.toHexString(id) + ") unlocked for " + (writeLock ? "write" : "read"));
  }

  public static long reserveNamespace(String namespaceId, long id, boolean writeLock, boolean mustExist, TableOperation op) throws Exception {
    if (getLock(namespaceId, id, writeLock).tryLock()) {
      if (mustExist) {
        Instance instance = HdfsZooInstance.getInstance();
        IZooReaderWriter zk = ZooReaderWriter.getInstance();
        if (!zk.exists(ZooUtil.getRoot(instance) + Constants.ZNAMESPACES + "/" + namespaceId))
          throw new ThriftTableOperationException(namespaceId, "", op, TableOperationExceptionType.NAMESPACE_NOTFOUND, "Namespace does not exist");
      }
      log.info("namespace " + namespaceId + " (" + Long.toHexString(id) + ") locked for " + (writeLock ? "write" : "read") + " operation: " + op);
      return 0;
    } else
      return 100;
  }

  public static String getNamespaceId(Instance instance, String tableId, TableOperation op, String namespaceId) throws Exception {
    if (namespaceId != null) {
      return namespaceId;
    }

    // For ACCUMULO-4575 namespaceId was added in a bug fix release. Since it was added in bug fix release, we have to ensure we can properly deserialize
    // older versions. When deserializing an older version, namespaceId will be null. For this case revert to the old buggy behavior.

    try {
      return Tables.getNamespaceId(instance, tableId);
    } catch (RuntimeException e) {
      // see if this was caused because the table does not exists
      IZooReaderWriter zk = ZooReaderWriter.getInstance();
      if (!zk.exists(ZooUtil.getRoot(instance) + Constants.ZTABLES + "/" + tableId))
        throw new ThriftTableOperationException(tableId, "", op, TableOperationExceptionType.NOTFOUND, "Table does not exist");
      else
        throw e;
    }
  }

  public static long reserveHdfsDirectory(String directory, long tid) throws KeeperException, InterruptedException {
    Instance instance = HdfsZooInstance.getInstance();

    String resvPath = ZooUtil.getRoot(instance) + Constants.ZHDFS_RESERVATIONS + "/" + Base64.encodeBase64String(directory.getBytes(UTF_8));

    IZooReaderWriter zk = ZooReaderWriter.getInstance();

    if (ZooReservation.attempt(zk, resvPath, String.format("%016x", tid), "")) {
      return 0;
    } else
      return 50;
  }

  public static void unreserveHdfsDirectory(String directory, long tid) throws KeeperException, InterruptedException {
    Instance instance = HdfsZooInstance.getInstance();
    String resvPath = ZooUtil.getRoot(instance) + Constants.ZHDFS_RESERVATIONS + "/" + Base64.encodeBase64String(directory.getBytes(UTF_8));
    ZooReservation.release(ZooReaderWriter.getInstance(), resvPath, String.format("%016x", tid));
  }

  private static Lock getLock(String tableId, long tid, boolean writeLock) throws Exception {
    byte[] lockData = String.format("%016x", tid).getBytes(UTF_8);
    ZooQueueLock qlock = new ZooQueueLock(ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZTABLE_LOCKS + "/" + tableId, false);
    Lock lock = DistributedReadWriteLock.recoverLock(qlock, lockData);
    if (lock == null) {
      DistributedReadWriteLock locker = new DistributedReadWriteLock(qlock, lockData);
      if (writeLock)
        lock = locker.writeLock();
      else
        lock = locker.readLock();
    }
    return lock;
  }

  public static Lock getReadLock(String tableId, long tid) throws Exception {
    return Utils.getLock(tableId, tid, false);
  }

  static void checkNamespaceDoesNotExist(Instance instance, String namespace, String namespaceId, TableOperation operation)
      throws ThriftTableOperationException {

    String n = Namespaces.getNameToIdMap(instance).get(namespace);

    if (n != null && !n.equals(namespaceId))
      throw new ThriftTableOperationException(null, namespace, operation, TableOperationExceptionType.NAMESPACE_EXISTS, null);
  }
}


text: A simple configuration showing a GeoJSON layer in a map.


text:
<?php

namespace ConsoleHelpers\SVNBuddy\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CleanupCommand extends AbstractCommand implements IAggregatorAwareCommand
{

	/**
	 * {@inheritdoc}
	 */
	protected function configure()
	{
		$description = <<<TEXT
TODO
TEXT;

		$this
			->setName('cleanup')
			->setDescription(
				'Recursively clean up the working copy, removing locks, resuming unfinished operations, etc.'
			)
			->setHelp($description)
			->addArgument(
				'path',
				InputArgument::OPTIONAL,
				'Working copy path',
				'.'
			);

		parent::configure();
	}

	/**
	 * {@inheritdoc}
	 */
	protected function execute(InputInterface $input, OutputInterface $output)
	{
		$wc_path = $this->getWorkingCopyPath();

		$this->io->writeln('Cleaning up working copy ... ');
		$command = $this->repositoryConnector->getCommand('cleanup', '{' . $wc_path . '}');
		$command->runLive(array(
			$wc_path => '.',
		));
		$this->io->writeln('<info>Done</info>');
	}

}


text:
#include "OgreGLESFrameBufferObject.h"
#include "OgreRoot.h"
#include "OgreGLESHardwarePixelBuffer.h"
#include "OgreGLESFBORenderTexture.h"
#include "OgreGLESDepthBuffer.h"

namespace Ogre {

//-----------------------------------------------------------------------------
    GLESFrameBufferObject::GLESFrameBufferObject(GLESFBOManager *manager, uint fsaa):
        mManager(manager), mNumSamples(fsaa)
    {
        /// Generate framebuffer object
        glGenFramebuffersOES(1, &mFB);
        GL_CHECK_ERROR;

		// Check multisampling
#if GL_APPLE_framebuffer_multisample
			// Check samples supported
			glBindFramebufferOES(GL_FRAMEBUFFER_OES, mFB);
            GL_CHECK_ERROR;
			GLint maxSamples;
			glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples);
            GL_CHECK_ERROR;
			glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
            GL_CHECK_ERROR;
			mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);
#else
			mNumSamples = 0;
#endif
		// will we need a second FBO to do multisampling?
		if (mNumSamples)
		{
			glGenFramebuffersOES(1, &mMultisampleFB);
            GL_CHECK_ERROR;
		}
		else
		{
			mMultisampleFB = 0;
		}

        /// Initialise state
        mDepth.buffer=0;
        mStencil.buffer=0;
        for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
        {
            mColour[x].buffer=0;
        }
    }

    GLESFrameBufferObject::~GLESFrameBufferObject()
    {
        mManager->releaseRenderBuffer(mDepth);
        mManager->releaseRenderBuffer(mStencil);
		mManager->releaseRenderBuffer(mMultisampleColourBuffer);
        /// Delete framebuffer object
        glDeleteFramebuffersOES(1, &mFB);
        GL_CHECK_ERROR;

		if (mMultisampleFB)
			glDeleteFramebuffersOES(1, &mMultisampleFB);

        GL_CHECK_ERROR;
    }

#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
    void GLESFrameBufferObject::notifyOnContextLost()
    {
        mManager->releaseRenderBuffer(mDepth);
        mManager->releaseRenderBuffer(mStencil);
		mManager->releaseRenderBuffer(mMultisampleColourBuffer);

        glDeleteFramebuffersOES(1, &mFB);
        GL_CHECK_ERROR;

		if (mMultisampleFB)
			glDeleteFramebuffersOES(1, &mMultisampleFB);

        GL_CHECK_ERROR;
    }

    void GLESFrameBufferObject::notifyOnContextReset(const GLESSurfaceDesc &target)
    {
        /// Generate framebuffer object
        glGenFramebuffersOES(1, &mFB);
        GL_CHECK_ERROR;

        glBindFramebufferOES(GL_FRAMEBUFFER_OES, mFB);
        GL_CHECK_ERROR;

        // Bind target to surface 0 and initialise
        bindSurface(0, target);
        GL_CHECK_ERROR;
    }
#endif

    void GLESFrameBufferObject::bindSurface(size_t attachment, const GLESSurfaceDesc &target)
    {
        assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
        mColour[attachment] = target;
		// Re-initialise
		if(mColour[0].buffer)
			initialise();
    }

    void GLESFrameBufferObject::unbindSurface(size_t attachment)
    {
        assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
        mColour[attachment].buffer = 0;
		// Re-initialise if buffer 0 still bound
		if(mColour[0].buffer)
			initialise();
    }

    void GLESFrameBufferObject::initialise()
    {
		// Release depth and stencil, if they were bound
        mManager->releaseRenderBuffer(mDepth);
        mManager->releaseRenderBuffer(mStencil);
		mManager->releaseRenderBuffer(mMultisampleColourBuffer);
        /// First buffer must be bound
        if(!mColour[0].buffer)
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                "Attachment 0 must have surface attached",
                "GLESFrameBufferObject::initialise");
        }

		// If we're doing multisampling, then we need another FBO which contains a
		// renderbuffer which is set up to multisample, and we'll blit it to the final
		// FBO afterwards to perform the multisample resolve. In that case, the
		// mMultisampleFB is bound during rendering and is the one with a depth/stencil

        /// Store basic stats
        size_t width = mColour[0].buffer->getWidth();
        size_t height = mColour[0].buffer->getHeight();
        GLuint format = mColour[0].buffer->getGLFormat();

		// Bind simple buffer to add colour attachments
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, mFB);
        GL_CHECK_ERROR;

        /// Bind all attachment points to frame buffer
        for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
        {
            if(mColour[x].buffer)
            {
                if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
                {
                    StringStream ss;
                    ss << "Attachment " << x << " has incompatible size ";
                    ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
                    ss << ". It must be of the same as the size of surface 0, ";
                    ss << width << "x" << height;
                    ss << ".";
                    OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLESFrameBufferObject::initialise");
                }
                if(mColour[x].buffer->getGLFormat() != format)
                {
                    StringStream ss;
                    ss << "Attachment " << x << " has incompatible format.";
                    OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLESFrameBufferObject::initialise");
                }
	            mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_OES+x, mColour[x].zoffset);
            }
            else
            {
                // Detach
                glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES+x,
                    GL_RENDERBUFFER_OES, 0);
                GL_CHECK_ERROR;
            }
        }

		// Now deal with depth / stencil
		if (mMultisampleFB)
		{
			// Bind multisample buffer
			glBindFramebufferOES(GL_FRAMEBUFFER_OES, mMultisampleFB);
            GL_CHECK_ERROR;

			// Create AA render buffer (colour)
			// note, this can be shared too because we blit it to the final FBO
			// right after the render is finished
			mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);

			// Attach it, because we won't be attaching below and non-multisample has
			// actually been attached to other FBO
			mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_OES,
				mMultisampleColourBuffer.zoffset);

			// depth & stencil will be dealt with below
		}

        /// Depth buffer is not handled here anymore.
		/// See GLESFrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()

		/// Do glDrawBuffer calls
		GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
		for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
		{
			// Fill attached colour buffers
			if(mColour[x].buffer)
			{
				bufs[x] = GL_COLOR_ATTACHMENT0_OES + x;
			}
			else
			{
				bufs[x] = GL_NONE;
			}
		}

        /// Check status
        GLuint status;
        status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
        GL_CHECK_ERROR;

        /// Bind main buffer
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
        // The screen buffer is 1 on iOS
        glBindFramebufferOES(GL_FRAMEBUFFER_OES, 1);
#else
        glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
#endif
        GL_CHECK_ERROR;

        switch(status)
        {
        case GL_FRAMEBUFFER_COMPLETE_OES:
            // All is good
            break;
        case GL_FRAMEBUFFER_UNSUPPORTED_OES:
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                "All framebuffer formats with this texture internal format unsupported",
                "GLESFrameBufferObject::initialise");
        default:
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                "Framebuffer incomplete or other FBO status error",
                "GLESFrameBufferObject::initialise");
        }

    }

    void GLESFrameBufferObject::bind()
    {
        /// Bind it to FBO
		const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB;
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, fb);
        GL_CHECK_ERROR;
    }

	void GLESFrameBufferObject::swapBuffers()
	{
#if GL_APPLE_framebuffer_multisample
		if (mMultisampleFB)
		{
			// blit from multisample buffer to final buffer, triggers resolve
			glBindFramebufferOES(GL_READ_FRAMEBUFFER_APPLE, mMultisampleFB);
            GL_CHECK_ERROR;
			glBindFramebufferOES(GL_DRAW_FRAMEBUFFER_APPLE, mFB);
            GL_CHECK_ERROR;
            glResolveMultisampleFramebufferAPPLE();
            GL_CHECK_ERROR;
//			glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
		}
#endif
	}

	void GLESFrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer )
	{
		GLESDepthBuffer *glDepthBuffer = static_cast<GLESDepthBuffer*>(depthBuffer);

		glBindFramebufferOES(GL_FRAMEBUFFER_OES, mMultisampleFB ? mMultisampleFB : mFB );

		if( glDepthBuffer )
		{
			GLESRenderBuffer *depthBuf   = glDepthBuffer->getDepthBuffer();
			GLESRenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer();

			//Attach depth buffer, if it has one.
			if( depthBuf )
				depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT_OES, 0 );

			//Attach stencil buffer, if it has one.
			if( stencilBuf )
				stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT_OES, 0 );
		}
		else
		{
			glFramebufferRenderbufferOES( GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES,
										  GL_RENDERBUFFER_OES, 0);
			glFramebufferRenderbufferOES( GL_FRAMEBUFFER_OES, GL_STENCIL_ATTACHMENT_OES,
										  GL_RENDERBUFFER_OES, 0);
		}
	}
	//-----------------------------------------------------------------------------
	void GLESFrameBufferObject::detachDepthBuffer()
	{
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, mMultisampleFB ? mMultisampleFB : mFB );
		glFramebufferRenderbufferOES( GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, 0 );
		glFramebufferRenderbufferOES( GL_FRAMEBUFFER_OES, GL_STENCIL_ATTACHMENT_OES,
									  GL_RENDERBUFFER_OES, 0 );
	}

    size_t GLESFrameBufferObject::getWidth()
    {
        assert(mColour[0].buffer);
        return mColour[0].buffer->getWidth();
    }
    size_t GLESFrameBufferObject::getHeight()
    {
        assert(mColour[0].buffer);
        return mColour[0].buffer->getHeight();
    }
    PixelFormat GLESFrameBufferObject::getFormat()
    {
        assert(mColour[0].buffer);
        return mColour[0].buffer->getFormat();
    }
	GLsizei GLESFrameBufferObject::getFSAA()
    {
        return mNumSamples;
    }
//-----------------------------------------------------------------------------
}


text:
<?php

namespace tdc\UserBundle\Form\Type;

use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        parent::buildForm($builder, $options);

        // add your custom field
        $builder->add('name');
        $builder->add('lastname');
    }

    public function getName()
    {
        return 'tdc_user_registration';
    }
}


text:
package org.springboot.integration.common;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Convertor<C> {
    private Class<C> constructKlass;

    public Convertor(Class<C> constructKlass) {
        this.constructKlass = Objects.requireNonNull(constructKlass, "转换对象的构造类型不能为空");
    }

    public static <C> Convertor<C> of(Class<C> constructKlass) {
        return new Convertor<C>(constructKlass);
    }

    public C from(Object source, String... filedNamesToSkip) {
        if (source == null) {
            return null;
        }
        try {
            C result = constructKlass.newInstance();
            BeanUtils.copyProperties(source, result, filedNamesToSkip);
            return result;
        } catch (Exception e) {
        }
        return null;
    }

    public List<C> createFrom(Iterable<?> sources, String... filedNamesToSkip) {
        if (sources == null) {
            return null;
        }
        List<C> result = new ArrayList<C>();
        for (Object source : sources) {
            result.add(from(source, filedNamesToSkip));
        }
        return result;
    }
}


text:
Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
  # config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier

  config.assets.digest = true

  config.log_level = :debug

  config.i18n.fallbacks = true
  config.serve_static_files = true
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
  config.assets.compile = false
  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

end


text:
<?php

declare(strict_types=1);

namespace Humbug\PhpScoper;

use Humbug\PhpScoper\PhpParser\TraverserFactory;
use Humbug\PhpScoper\Scoper\Composer\InstalledPackagesScoper;
use Humbug\PhpScoper\Scoper\Composer\JsonFileScoper;
use Humbug\PhpScoper\Scoper\NullScoper;
use Humbug\PhpScoper\Scoper\PatchScoper;
use Humbug\PhpScoper\Scoper\PhpScoper;
use Humbug\PhpScoper\Scoper\SymfonyScoper;
use PhpParser\Parser;

/**
 * @final
 */
class ScoperFactory
{
    private Parser $parser;

    public function __construct(Parser $parser)
    {
        $this->parser = $parser;
    }

    public function createScoper(Configuration $configuration): Scoper
    {
        return new PatchScoper(
            new PhpScoper(
                $this->parser,
                new JsonFileScoper(
                    new InstalledPackagesScoper(
                        new SymfonyScoper(
                            new NullScoper()
                        )
                    )
                ),
                new TraverserFactory(
                    Reflector::createWithPhpStormStubs()->withSymbols(
                        $configuration->getInternalClasses(),
                        $configuration->getInternalFunctions(),
                        $configuration->getInternalConstants(),
                    ),
                )
            )
        );
    }
}


text:
<?php

namespace App\Http\Controllers\Api\V1;

use App\Radio;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Radio as RadioResource;
use App\Http\Resources\RadioCollection;

class RadiosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return new RadioCollection(Radio::all());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Mostrar los datos de una radio dada.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        return new RadioResource(Radio::findOrFail($id));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}


text:
/*!
 * Start Bootstrap - Shop Homepage HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

body {
    padding-top: 120px; /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
    /*background-image: url("../images/nettoyage-dentaire.jpg");
    background-size: cover;*/
}

#titre{
    background-image: url("../images/titre.png");
    background-position: center center;
    background-repeat: no-repeat;
    background-size: auto 100%;
    height: 20px;
    width: 220px;
}

nav{
    transition: all 0.3s ease 0s;
}

.scroll-top nav{
    background-image: url("../images/blue.jpg");
    background-size: cover;
    padding: 18px 0;
}

.navbar-inverse{
    border: none;
}

.navbar-inverse .navbar-toggle{
    border-color: white;
}

.navbar-inverse .navbar-brand,.navbar-inverse .navbar-nav > li > a {
    color: white;
}

.navbar-inverse .navbar-nav > li > a:hover {
    color: whitesmoke;
}

.navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus {
    background-color: transparent;
}

.slide-image {
    width: 100%;
}

.carousel-holder {
    margin-bottom: 30px;
}

.carousel-control,
.item {
    border-radius: 4px;
}

.caption {
    height: 130px;
    overflow: hidden;
}

.caption h4 {
    white-space: nowrap;
}

.thumbnail img {
    width: 100%;
}

.ratings {
    padding-right: 10px;
    padding-left: 10px;
    color: #d17581;
}

.thumbnail {
    padding: 0;
}

.thumbnail .caption-full {
    padding: 9px;
    color: #333;
}

footer {
    margin: 50px 0;
}


text:
package com.originate.scalypher.where

import com.originate.scalypher.ConstantString
import com.originate.scalypher.ToQuery

sealed trait NullCheck extends ToQuery
case object IsNull extends ConstantString("IS NULL") with NullCheck
case object NotNull extends ConstantString("IS NOT NULL") with NullCheck


text:
#!/bin/bash
mkdir -p /var/log/puppet
exec > >(tee -i /var/log/puppet/bootstrap_admin_node.log)
exec 2>&1

FUEL_RELEASE=$(grep release: /etc/fuel/version.yaml | cut -d: -f2 | tr -d '" ')

function countdown() {
  local i
  sleep 1
  for ((i=$1-1; i>=1; i--)); do
    printf '\b\b\b\b%04d' "$i"
    sleep 1
  done
}

function fail() {
  echo "ERROR: Fuel node deployment FAILED! Check /var/log/puppet/bootstrap_admin_node.log for details" 1>&2
  exit 1
}

function get_ethernet_interfaces() {
  # Get list of all ethernet interfaces, non-virtual, not a wireless
  for DEV in /sys/class/net/* ; do
    # Take only links into account, skip files
    if test ! -L $DEV ; then
       continue
    fi
    DEVPATH=$(readlink -f $DEV)
    # Avoid virtual devices like loopback, tunnels, bonding, vlans ...
    case $DEVPATH in
         */virtual/*)
            continue
         ;;
    esac
    IF=${DEVPATH##*/}
    # Check ethernet only
    case "`cat $DEV/type`" in
         1)
         # TYPE=1 is ethernet, may also be wireless, bond, tunnel ...
         # Virtual lo, bound, vlan, tunneling has been skipped before
         if test -d $DEV/wireless -o -L $DEV/phy80211 ;
         then
              continue
         else
         # Catch ethernet non-virtual device
              echo $IF
         fi
         ;;
         *) continue
         ;;
    esac
  done
}

# Get value of a key from ifcfg-* files
# Usage:
#   get_ifcfg_value NAME /etc/sysconfig/network-scripts/ifcfg-eth0
function get_ifcfg_value {
    local key=$1
    local path=$2
    local value=''
    if [[ -f ${path} ]]; then
        value=$(awk -F\= "\$1==\"${key}\" {print \$2}" ${path})
        value=${value//\"/}
    fi
    echo ${value}
}

# Workaround to fix dracut network configuration approach:
#   Bring down all network interfaces which have the same IP
#   address statically configured as 'primary' interface
function ifdown_ethernet_interfaces {
    local adminif_ipaddr
    local if_config
    local if_name
    local if_ipaddr

    adminif_ipaddr=$(get_ifcfg_value IPADDR /etc/sysconfig/network-scripts/ifcfg-${ADMIN_INTERFACE})
    for if_config in $(find /etc/sysconfig/network-scripts -name 'ifcfg-*' ! -name 'ifcfg-lo'); do
        if_name=$(get_ifcfg_value NAME $if_config)
        if [[ "${if_name}" == "${ADMIN_INTERFACE}" ]]; then
            continue
        fi
        if_ipaddr=$(get_ifcfg_value IPADDR $if_config)
        if [[ "${if_ipaddr}" == "${adminif_ipaddr}" ]]; then
            echo "Interface '${if_name}' uses the same ip '${if_ipaddr}' as admin interface '${ADMIN_INTERFACE}', removing ..."
            ifdown ${if_name}
            rm -f ${if_config}
        fi
    done
}

# Check if interface name is valid by checking that
# a config file with NAME equal to given name exists.
function ifname_valid {
    local adminif_name=$1
    local if_name
    local if_config
    for if_config in $(find /etc/sysconfig/network-scripts -name 'ifcfg-*' ! -name 'ifcfg-lo'); do
        if_name=$(get_ifcfg_value NAME $if_config)
        if [[ "${if_name}" == "${adminif_name}" ]]; then
            return 0
        fi
    done
    return 1
}

# LANG variable is a workaround for puppet-3.4.2 bug. See LP#1312758 for details
export LANG=en_US.UTF8
# Be sure, that network devices have been initialized
udevadm trigger --subsystem-match=net
udevadm settle

# Import bootstrap_admin_node.conf if exists
if [ -f /etc/fuel/bootstrap_admin_node.conf ]; then
    source /etc/fuel/bootstrap_admin_node.conf
fi

# Set defaults to unset / empty variables
# Although eth0 is not always valid it's a good well-known default
# If there is no such interface it will fail to pass ifname_valid
# check and will be replaced.
ADMIN_INTERFACE=${ADMIN_INTERFACE:-'eth0'}
showmenu=${showmenu:-'no'}

# Now check that ADMIN_INTERFACE points to a valid interface
# If it doesn't fallback to getting the first interface name
# from a list of all available interfaces sorted alphabetically
if ! ifname_valid $ADMIN_INTERFACE; then
    # Take the very first ethernet interface as an admin interface
    ADMIN_INTERFACE=$(get_ethernet_interfaces | sort -V | head -1)
fi

echo "Applying admin interface '$ADMIN_INTERFACE'"
export ADMIN_INTERFACE

echo "Bringing down ALL network interfaces except '${ADMIN_INTERFACE}'"
ifdown_ethernet_interfaces
systemctl restart network

echo "Applying default Fuel settings..."
set -x
fuelmenu --save-only --iface=$ADMIN_INTERFACE
set +x
echo "Done!"

if [[ "$showmenu" == "yes" || "$showmenu" == "YES" ]]; then
  fuelmenu
  else
  #Give user 15 seconds to enter fuelmenu or else continue
  echo
  echo -n "Press a key to enter Fuel Setup (or press ESC to skip)...   15"
  countdown 15 & pid=$!
  if ! read -s -n 1 -t 15 key; then
    echo -e "\nSkipping Fuel Setup..."
  else
    { kill "$pid"; wait $!; } 2>/dev/null
    case "$key" in
      $'\e')  echo "Skipping Fuel Setup.."
              ;;
      *)      echo -e "\nEntering Fuel Setup..."
              fuelmenu
              ;;
    esac
  fi
fi

# Enable sshd
systemctl enable sshd
systemctl start sshd

# Enable iptables
systemctl enable iptables.service
systemctl start iptables.service

if [ "$wait_for_external_config" == "yes" ]; then
  wait_timeout=3000
  pidfile=/var/lock/wait_for_external_config
  echo -n "Waiting for external configuration (or press ESC to skip)...
$wait_timeout"
  countdown $wait_timeout & countdown_pid=$!
  exec -a wait_for_external_config sleep $wait_timeout & wait_pid=$!
  echo $wait_pid > $pidfile
  while ps -p $countdown_pid &> /dev/null && ps -p $wait_pid &>/dev/null; do
    read -s -n 1 -t 2 key
    case "$key" in
      $'\e')   echo -e "\b\b\b\b abort on user input"
               break
               ;;
      *)       ;;
    esac
  done
  { kill $countdown_pid $wait_pid & wait $!; }
  rm -f $pidfile
fi

#Reread /etc/sysconfig/network to inform puppet of changes
. /etc/sysconfig/network
hostname "$HOSTNAME"

# XXX: ssh keys which should be included into the bootstrap image are
# generated during containers deployment. However cobbler checkfs for
# a kernel and initramfs when creating a profile, which poses chicken
# and egg problem. Fortunately cobbler is pretty happy with empty files
# so it's easy to break the loop.
make_ubuntu_bootstrap_stub () {
        local bootstrap_dir='/var/www/nailgun/bootstraps/active_bootstrap'
        local bootstrap_stub_dir='/var/www/nailgun/bootstraps/bootstrap_stub'
        mkdir -p ${bootstrap_stub_dir}
        for item in vmlinuz initrd.img; do
                touch "${bootstrap_stub_dir}/$item"
        done
        ln -s ${bootstrap_stub_dir} ${bootstrap_dir} || true
}

get_bootstrap_flavor () {
	local ASTUTE_YAML='/etc/fuel/astute.yaml'
	python <<-EOF
	from fuelmenu.fuelmenu import Settings
	conf = Settings().read("$ASTUTE_YAML").get('BOOTSTRAP', {})
	print(conf.get('flavor', 'centos').lower())
	EOF
}

get_bootstrap_skip () {
	local ASTUTE_YAML='/etc/fuel/astute.yaml'
	python <<-EOF
	from fuelmenu.fuelmenu import Settings
	conf = Settings().read("$ASTUTE_YAML").get('BOOTSTRAP', {})
	print(conf.get('skip_default_img_build', False))
	EOF
}

# Actually build the bootstrap image
build_ubuntu_bootstrap () {
	local log='/var/log/fuel-bootstrap-image-build.log'
        local ret=1
	echo "Bulding default ubuntu-bootstrap image" >&2
	if fuel-bootstrap -v --debug build --activate --notify-webui >>"$log" 2>&1; then
		ret=0
	fi
        if [ $ret -ne 0 ]; then
		# FIXME Add correct how-to url and problem description
		warning="WARNING: Failed to build the bootstrap image, see $log
for details. Perhaps your Internet connection is broken. Please fix the problem and run
\`fuel-bootstrap build --activate --notify-webui\`"
                fuel notify --topic warning --send "$warning"
        fi
        return $ret
}

# Create empty files to make cobbler happy
# (even if we don't use Ubuntu based bootstrap)
make_ubuntu_bootstrap_stub

service docker start

old_sysctl_vm_value=$(sysctl -n vm.min_free_kbytes)
if [ ${old_sysctl_vm_value} -lt 65535 ]; then
  echo "Set vm.min_free_kbytes..."
  sysctl -w vm.min_free_kbytes=65535
fi

if [ -f /root/.build_images ]; then
  #Fail on all errors
  set -e
  trap fail EXIT

  echo "Loading Fuel base image for Docker..."
  docker load -i /var/www/nailgun/docker/images/fuel-images.tar

  echo "Building Fuel Docker images..."
  WORKDIR=$(mktemp -d /tmp/docker-buildXXX)
  SOURCE=/var/www/nailgun/docker
  REPO_CONT_ID=$(docker -D run -d -p 80 -v /var/www/nailgun:/var/www/nailgun fuel/centos sh -c 'mkdir -p /var/www/html/repo/os;ln -sf /var/www/nailgun/centos/x86_64 /var/www/html/repo/os/x86_64;ln -s /var/www/nailgun/mos-centos/x86_64 /var/www/html/mos-repo;/usr/sbin/apachectl -DFOREGROUND')
  RANDOM_PORT=$(docker port $REPO_CONT_ID 80 | cut -d':' -f2)

  for imagesource in /var/www/nailgun/docker/sources/*; do
    if ! [ -f "$imagesource/Dockerfile" ]; then
      echo "Skipping ${imagesource}..."
      continue
    fi
    image=$(basename "$imagesource")
    cp -R "$imagesource" $WORKDIR/$image
    mkdir -p $WORKDIR/$image/etc
    cp -R /etc/puppet /etc/fuel $WORKDIR/$image/etc
    sed -e "s/_PORT_/${RANDOM_PORT}/" -i $WORKDIR/$image/Dockerfile
    sed -r -e 's/^"?PRODUCTION"?:.*/PRODUCTION: "docker-build"/' -i $WORKDIR/$image/etc/fuel/astute.yaml
    # FIXME(kozhukalov): Once this patch https://review.openstack.org/#/c/219581/ is merged
    # remove this line. fuel-library is to use PRODUCTION value from astute.yaml instead of
    # the same value from version.yaml. It is a part of version.yaml deprecation plan.
    sed -e 's/production:.*/production: "docker-build"/' -i $WORKDIR/$image/etc/fuel/version.yaml
    docker build -t fuel/${image}_${FUEL_RELEASE} $WORKDIR/$image
  done
  docker rm -f $REPO_CONT_ID
  rm -rf "$WORKDIR"

  #Remove trap for normal deployment
  trap - EXIT
  set +e
else
  echo "Loading docker images. (This may take a while)"
  docker load -i /var/www/nailgun/docker/images/fuel-images.tar
fi

if [ ${old_sysctl_vm_value} -lt 65535 ]; then
  echo "Restore sysctl vm.min_free_kbytes value..."
  sysctl -w vm.min_free_kbytes=${old_sysctl_vm_value}
fi

# apply puppet
puppet apply --detailed-exitcodes -d -v /etc/puppet/modules/nailgun/examples/host-only.pp
if [ $? -ge 4 ];then
  fail
fi

# Sync time
systemctl stop ntpd
systemctl start ntpdate || echo "Failed to synchronize time with 'ntpdate'"
systemctl start ntpd

rmdir /var/log/remote && ln -s /var/log/docker-logs/remote /var/log/remote

dockerctl check || fail
bash /etc/rc.local

if [ "`get_bootstrap_flavor`" = "ubuntu" ] && [ "`get_bootstrap_skip`" = "False" ]; then
	build_ubuntu_bootstrap || true
fi

# Enable updates repository
cat > /etc/yum.repos.d/mos${FUEL_RELEASE}-updates.repo << EOF
[mos${FUEL_RELEASE}-updates]
name=mos${FUEL_RELEASE}-updates
baseurl=http://mirror.fuel-infra.org/mos-repos/centos/mos${FUEL_RELEASE}-centos\$releasever-fuel/updates/x86_64/
gpgcheck=0
skip_if_unavailable=1
EOF

# Enable security repository
cat > /etc/yum.repos.d/mos${FUEL_RELEASE}-security.repo << EOF
[mos${FUEL_RELEASE}-security]
name=mos${FUEL_RELEASE}-security
baseurl=http://mirror.fuel-infra.org/mos-repos/centos/mos${FUEL_RELEASE}-centos\$releasever-fuel/security/x86_64/
gpgcheck=0
skip_if_unavailable=1
EOF

#Check if repo is accessible
echo "Checking for access to updates repository..."
repourl=$(yum repolist all -v | awk '{if ($1 ~ "baseurl" && $3 ~ "updates") print $3}' | head -1)
if urlaccesscheck check "$repourl" ; then
  UPDATE_ISSUES=0
else
  UPDATE_ISSUES=1
fi

if [ $UPDATE_ISSUES -eq 1 ]; then
  message="There is an issue connecting to the Fuel update repository. \
Please fix your connection prior to applying any updates. \
Once the connection is fixed, we recommend reviewing and applying \
Maintenance Updates for this release of Mirantis OpenStack: \
https://docs.mirantis.com/openstack/fuel/fuel-${FUEL_RELEASE}/\
release-notes.html#maintenance-updates"
  level="warning"
else
  message="We recommend reviewing and applying Maintenance Updates \
for this release of Mirantis OpenStack: \
https://docs.mirantis.com/openstack/fuel/fuel-${FUEL_RELEASE}/\
release-notes.html#maintenance-updates"
  level="done"
fi
echo
echo "*************************************************"
echo -e "${message}"
echo "*************************************************"
echo "Sending notification to Fuel UI..."
fuel notify --topic "${level}" --send $(echo "${message}" | tr '\r\n' ' ')

# TODO(kozhukalov) If building of bootstrap image fails
# and if this image was supposed to be a default bootstrap image
# we need to warn a user about this and give her
# advice how to treat this.

echo "Fuel node deployment complete!"
# Sleep for agetty autologon
sleep 3


text:
CALL "%VS90COMNTOOLS%..\..\VC\vcvarsall.bat"
msbuild %~dp0../slimdx.proj /target:Clean /v:m
exit %ERRORLEVEL%


text:
package server

import (
	"errors"
	"sync"
	"sync/atomic"
)

var (
	ERR_EXIT = errors.New("exit")
)

type Socket interface {
	Read() ([]byte, error)
	Write([]byte) error
	Close()
}
type DataHandler interface {
	Process([]byte)
}
type ErrorHandler interface {
	OnError(error)
}
type IdentityHandler interface {
	GetIdentity([]byte) uint32
	SetIdentity([]byte, uint32)
}

type Connection struct {
	conn       Socket
	wg         sync.WaitGroup
	mutex      sync.Mutex
	applicants map[uint32]chan []byte
	chexit     chan bool
	chsend     chan []byte
	chch       chan chan []byte
	dh         DataHandler
	eh         ErrorHandler
	ih         IdentityHandler
	identity   uint32
}

func NewConnection(conn Socket, maxcount int, dh DataHandler, ih IdentityHandler, eh ErrorHandler) *Connection {
	count := maxcount
	if count < 1024 {
		count = 1024
	}
	chch := make(chan chan []byte, count)
	for i := 0; i < count; i++ {
		chch <- make(chan []byte, 1)
	}
	return &Connection{
		conn:       conn,
		applicants: make(map[uint32]chan []byte, count),
		chsend:     make(chan []byte, count),
		chexit:     make(chan bool),
		chch:       chch,
		dh:         dh,
		ih:         ih,
		eh:         eh,
	}
}

func (p *Connection) Start() {
	p.wg.Add(2)
	go func() {
		defer p.wg.Done()
		p.recv()
	}()
	go func() {
		defer p.wg.Done()
		p.send()
	}()
}

func (p *Connection) Close() {
	close(p.chexit)
	p.conn.Close()
	p.wg.Wait()
}

func (p *Connection) Query(data []byte) (res []byte, err error) {
	var ch chan []byte
	select {
	case <-p.chexit:
		return nil, ERR_EXIT
	case ch = <-p.chch:
		defer func() {
			p.chch <- ch
		}()
	}
	id := p.newIdentity()
	p.ih.SetIdentity(data, id)
	p.addApplicant(id, ch)
	defer func() {
		if err != nil {
			p.popApplicant(id)
		}
	}()
	if err := p.Write(data); err != nil {
		return nil, err
	}
	select {
	case <-p.chexit:
		return nil, ERR_EXIT
	case res = <-ch:
		break
	}
	return res, nil
}

func (p *Connection) Reply(query, answer []byte) error {
	// put back the identity attached to the query
	id := p.ih.GetIdentity(query)
	p.ih.SetIdentity(answer, id)
	return p.Write(answer)
}

func (p *Connection) Write(data []byte) error {
	select {
	case <-p.chexit:
		return ERR_EXIT
	case p.chsend <- data:
		break
	}
	return nil
}

func (p *Connection) send() {
	for {
		select {
		case <-p.chexit:
			return
		case data := <-p.chsend:
			if p.conn.Write(data) != nil {
				return
			}
		}
	}
}

func (p *Connection) recv() (err error) {
	defer func() {
		if err != nil {
			select {
			case <-p.chexit:
				err = nil
			default:
				p.eh.OnError(err)
			}
		}
	}()
	for {
		select {
		case <-p.chexit:
			return nil
		default:
			break
		}
		data, err := p.conn.Read()
		if err != nil {
			return err
		}
		if id := p.ih.GetIdentity(data); id > 0 {
			ch, ok := p.popApplicant(id)
			if ok {
				ch <- data
				continue
			}
		}
		p.dh.Process(data)
	}
	return nil
}

func (p *Connection) newIdentity() uint32 {
	return atomic.AddUint32(&p.identity, 1)
}

func (p *Connection) addApplicant(identity uint32, ch chan []byte) {
	p.mutex.Lock()
	defer p.mutex.Unlock()
	p.applicants[identity] = ch
}

func (p *Connection) popApplicant(identity uint32) (chan []byte, bool) {
	p.mutex.Lock()
	defer p.mutex.Unlock()
	ch, ok := p.applicants[identity]
	if !ok {
		return nil, false
	}
	delete(p.applicants, identity)
	return ch, true
}