text:
===============
django-markitup
===============

.. image:: https://img.shields.io/pypi/v/django-markitup.svg
    :target: https://pypi.python.org/pypi/django-markitup/
    :alt: Latest PyPI version

.. image:: https://img.shields.io/pypi/dm/django-markitup.svg
    :target: https://pypi.python.org/pypi/django-markitup/
    :alt: Number of PyPI downloads

.. image:: https://img.shields.io/pypi/pyversions/django-markitup.svg
    :target: https://pypi.python.org/pypi/django-markitup/
    :alt: Supported Python versions

.. image:: https://travis-ci.org/zsiciarz/django-markitup.svg
    :target: https://travis-ci.org/zsiciarz/django-markitup

A Django reusable application for end-to-end markup handling. Includes:

* Easy integration of the `MarkItUp!`_ markup editor widget (by Jay
  Salvat) in Django projects, with server-side support for MarkItUp!'s
  AJAX preview. Plug in MarkItUp! via form widget or template tags.

* ``MarkupField``, a ``TextField`` that automatically renders and
  stores both its raw and rendered values in the database, on the
  assumption that disk space is cheaper than CPU cycles in a web
  application.

.. _MarkItUp!: http://markitup.jaysalvat.com/

Installation
============

Install from PyPI with ``easy_install`` or ``pip``::

    pip install django-markitup

To use ``django-markitup`` in your Django project:

    1. Add ``'markitup'`` to your ``INSTALLED_APPS`` setting.

    2. Make the contents of the ``markitup/static/markitup`` directory
       available at ``STATIC_URL/markitup``; the simplest way is via
       `django.contrib.staticfiles`_.

    3. Set `the MARKITUP_FILTER setting`_.

    4. If you want to use AJAX-based preview, add
          ``url(r'^markitup/', include('markitup.urls'))`` in your root URLconf.

.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/howto/static-files/

Dependencies
------------

``django-markitup`` 3.x requires `Django`_ 1.8 or later and Python 2.7+ or 3.4+.

``django-markitup`` 2.x requires `Django`_ 1.4 or later and Python 2.6+ or 3.3+.

``django-markitup`` 1.x requires `Django`_ 1.3 or later and Python 2.5 or later.

`MarkItUp!`_ is not an external dependency; it is bundled with
``django-markitup``.

.. _Django: http://www.djangoproject.com/

Using the MarkItUp! widget
==========================

The MarkItUp! widget lives at ``markitup.widgets.MarkItUpWidget``, and
can be used like any other Django custom widget.

To assign it to a form field::

    from markitup.widgets import MarkItUpWidget

    class MyForm(forms.Form):
        content = forms.CharField(widget=MarkItUpWidget())

When this form is displayed on your site, you must include the form media
somewhere on the page using ``{{ form.media }}``, or the MarkItUpWidget will
have no effect. By default ``{{ form.media }}`` also includes the jQuery
library based on your `JQUERY_URL`_ setting. To prevent including jQuery, set
the `JQUERY_URL`_ setting to ``None``.

MarkItUpWidget accepts three optional keyword arguments:
``markitup_set`` and ``markitup_skin`` (see `Choosing a MarkItUp!
button set and skin`_) and ``auto_preview`` (to override the value of
the `MARKITUP_AUTO_PREVIEW`_ setting).

To use the widget in the Django admin::

    from markitup.widgets import AdminMarkItUpWidget

    class MyModelAdmin(admin.ModelAdmin):
    ...
    def formfield_for_dbfield(self, db_field, request, **kwargs):
        if db_field.name == 'content':
            kwargs['widget'] = AdminMarkItUpWidget()
        return super(MyModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)

You can also use the formfield_overrides attribute of the ModelAdmin, which
is simpler but only allows setting the widget per field type (so it isn't
possible to use the MarkItUpWidget on one TextField in a model and not
another)::

    from markitup.widgets import AdminMarkItUpWidget

    class MyModelAdmin(admin.ModelAdmin):
        formfield_overrides = {models.TextField: {'widget': AdminMarkItUpWidget}}

If you use `MarkupField`_ in your model, it is rendered in the admin
  with an ``AdminMarkItUpWidget`` by default.

Using MarkItUp! via templatetags
================================

In some cases it may be inconvenient to use ``MarkItUpWidget`` (for
instance, if the form in question is defined in third-party code). For
these cases, django-markitup provides template tags to achieve the
same effect purely in templates.

First, load the django-markitup template tag library::

    {% load markitup_tags %}

Then include the MarkItUp! CSS and Javascript in the  of your page::

    {% markitup_media %}

By default the ``markitup_media`` tag also includes jQuery, based on the value
of your `JQUERY_URL`_ setting, with a fallback to the version hosted at Google
Ajax APIs. To suppress the inclusion of jQuery (if you are already including it
yourself), set the `JQUERY_URL`_ setting to ``None``.

If you prefer to link CSS and Javascript from different locations, the
``markitup_media`` tag can be replaced with two separate tags,
``markitup_css`` and ``markitup_js``. ``markitup_js`` accepts a
parameter to suppress jQuery inclusion, just like
``markitup_media``. (Note that jQuery must be included in your
template before the ``markitup_editor`` tag is used).

Last, use the ``markitup_editor`` template tag to apply the MarkItUp!
editor to a textarea in your page. It accepts one argument, the HTML
id of the textarea. If you are rendering the textarea in the usual way
via a Django form object, that id value is available as
``form.fieldname.auto_id``::

    {{ form.fieldname }}

    {% markitup_editor form.fieldname.auto_id %}

You can use ``markitup_editor`` on as many different textareas as you
like.

``markitup_editor`` accepts an optional second parameter, which can be
either ``"auto_preview"`` or ``"no_auto_preview"`` to override the
value of the `MARKITUP_AUTO_PREVIEW`_ setting.

The actual HTML included by these templatetags is defined by the
contents of the templates ``markitup/include_css.html``,
``markitup/include_js.html``, and ``markitup/editor.html``. You can
override these templates in your project and customize them however
you wish.

MarkupField
===========

You can apply the MarkItUp! editor control to any textarea using the
above techniques, and handle the markup on the server side however you
prefer.

For a seamless markup-handling solution, django-markitup also provides
a ``MarkupField`` model field that automatically renders and stores
both its raw and rendered values in the database, using the value of
`the MARKITUP_FILTER setting`_ to parse the markup into HTML.

A ``MarkupField`` is easy to add to any model definition::

    from django.db import models
    from markitup.fields import MarkupField

    class Article(models.Model):
        title = models.CharField(max_length=100)
        body = MarkupField()

``MarkupField`` automatically creates an extra non-editable field
``_body_rendered`` to store the rendered markup. This field doesn't
need to be accessed directly; see below.

Accessing a MarkupField on a model
----------------------------------

When accessing an attribute of a model that was declared as a
``MarkupField``, a ``Markup`` object is returned.  The ``Markup``
object has two attributes:

``raw``:
    The unrendered markup.
``rendered``:
    The rendered HTML version of ``raw`` (read-only).

This object also has a ``__unicode__`` method that calls
``django.utils.safestring.mark_safe`` on ``rendered``, allowing
``MarkupField`` attributes to appear in templates as rendered HTML
without any special template tag or having to access ``rendered``
directly.

Assuming the ``Article`` model above::

    >>> a = Article.objects.all()[0]
    >>> a.body.raw
    '*fancy*'
    >>> a.body.rendered
    '
fancy
'
    >>> print(unicode(a.body))

fancy

    >>> a.body.render_with('markitup.renderers.render_rest')
    >>> print(unicode(a.body))
    '
\n
fancy
\n
\n'

Assignment to ``a.body`` is equivalent to assignment to
``a.body.raw``.

.. note::
    a.body.rendered is only updated when a.save() or a.body.render_with()
    is called

Editing a MarkupField in a form
-------------------------------

When editing a ``MarkupField`` model attribute in a ``ModelForm``
(i.e. in the Django admin), you'll generally want to edit the original
markup and not the rendered HTML.  Because the ``Markup`` object
returns rendered HTML from its __unicode__ method, it's necessary to
use the ``MarkupTextarea`` widget from the ``markupfield.widgets``
module, which knows to return the raw markup instead.

By default, a ``MarkupField`` uses the MarkItUp! editor control in the
admin (via the provided ``AdminMarkItUpWidget``), but a plain
``MarkupTextarea`` in other forms. If you wish to use the MarkItUp!
editor with this ``MarkupField`` in your own form, you'll need to use
the provided ``MarkItUpWidget`` rather than ``MarkupTextarea``.

If you apply your own custom widget to the form field representing a
``MarkupField``, your widget must either inherit from
``MarkupTextarea`` or its ``render`` method must convert its ``value``
argument to ``value.raw``.

Choosing a MarkItUp! button set and skin
========================================

MarkItUp! allows the toolbar button-set to be customized in a
Javascript settings file.  By default, django-markitup uses the
"default" set (meant for HTML editing).  Django-markitup also includes
basic "markdown" and "textile" sets (these are available from `the
MarkItUp site <http://markitup.jaysalvat.com>`_), as well as a
"restructuredtext" set.

To use an alternate set, assign the ``MARKITUP_SET`` setting a URL path
(absolute or relative to ``STATIC_URL``) to the set directory.  For
instance, to use the "markdown" set included with django-markitup::

    MARKITUP_SET = 'markitup/sets/markdown/'

MarkItUp! skins can be specified in a similar manner.  Both "simple"
and "markitup" skins are included, by default "simple" is used.  To
use the "markitup" skin instead::

    MARKITUP_SKIN = 'markitup/skins/markitup/'

Neither of these settings has to refer to a location inside
django-markitup's media.  You can define your own sets and skins and
store them anywhere, as long as you set the MARKITUP_SET and
MARKITUP_SKIN settings to the appropriate URLs.

Set and skin may also be chosen on a per-widget basis by passing the
``markitup_set`` and ``markitup_skin`` keyword arguments to
MarkItUpWidget.

Using AJAX preview
==================

If you've included ``markitup.urls`` in your root URLconf (as
demonstrated above under `Installation`_), all you need to enable
server-side AJAX preview is `the MARKITUP_FILTER setting`_.

The rendered HTML content is displayed in the Ajax preview wrapped by
an HTML page generated by the ``markitup/preview.html`` template; you
can override this template in your project and customize the preview
output.

.. note::

    Using the MarkItUpWidget or ``markitup_editor`` template tag will
    automatically set the ``previewParserPath`` in your MarkItUp! set
    to ``reverse('markitup_preview')``, if ``markitup.urls`` is
    included in your URLconf.

The MARKITUP_FILTER setting
===========================

The ``MARKITUP_FILTER`` setting defines how markup is transformed into
HTML on your site. This setting is only required if you are using
``MarkupField`` or MarkItUp! AJAX preview.

``MARKITUP_FILTER`` must be a two-tuple. The first element must be a
string, the Python dotted path to a markup filter function.  This
function should accept markup as its first argument and return HTML.
It may accept other keyword arguments as well.  You may parse your
markup using any method you choose, as long as you can wrap it in a
function that meets these criteria.

The second element must be a dictionary of keyword arguments to pass
to the filter function.  The dictionary may be empty.

For example, if you have python-markdown installed, you could use it
like this::

    MARKITUP_FILTER = ('markdown.markdown', {'safe_mode': True})

Alternatively, you could use the "textile" filter provided by Django
like this::

    MARKITUP_FILTER = ('django.contrib.markup.templatetags.markup.textile', {})

(The textile filter function doesn't accept keyword arguments, so the
kwargs dictionary must be empty in this case.)

``django-markitup`` provides one sample rendering function,
``render_rest`` in the ``markitup.renderers`` module.

render_markup template filter
=============================

If you have set `the MARKITUP_FILTER setting`_ and use the MarkItUp!
AJAX preview, but don't wish to store rendered markup in the database
with `MarkupField`_ (or are using third-party models that don't use
`MarkupField`_), you may want a convenient way to render content in
your templates using your MARKITUP_FILTER function. For this you can
use the ``render_markup`` template filter::

    {% load markitup_tags %}

    {{ post.content|render_markup }}

Other settings
==============

MARKITUP_PREVIEW_FILTER
-----------------------

This optional setting can be used to override the markup filter used
for the Ajax preview view, if for some reason you need it to be
different from the filter used for rendering markup in a
``MarkupField``. It has the same format as ``MARKITUP_FILTER``; by
default it is set equal to ``MARKITUP_FILTER``.

MARKITUP_AUTO_PREVIEW
---------------------

If set to ``True``, the preview window will be activated by
default. Defaults to ``False``.

JQUERY_URL
----------

MarkItUp! requires the jQuery Javascript library.  By default, django-markitup
links to jQuery 2.0.3 at ajax.googleapis.com (via the URL
``http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js``).  If you
wish to use a different version of jQuery, or host it yourself, set the
JQUERY_URL setting.  For example::

    JQUERY_URL = 'jquery.min.js'

This will use the jQuery available at STATIC_URL/jquery.min.js. A relative
``JQUERY_URL`` is relative to ``STATIC_URL``.

If you include the jQuery library manually in your templates and don't want
``django-markitup`` to include it, set ``JQUERY_URL`` to ``None``.


text:
//==============================================================================
//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_SDK_TIMING_CTIC_HPP_INCLUDED
#define NT2_SDK_TIMING_CTIC_HPP_INCLUDED

/**
* @file
* @brief Defines and implements the ctic() and ctoc() timing functions.
**/

#include <nt2/sdk/timing/config.hpp>
#include <nt2/sdk/timing/now.hpp>
#include <nt2/sdk/timing/details/timer.hpp>

namespace nt2 { namespace details
{
  // INTERNAL ONLY
  // cycle_based_timer is a timing helper class to be used in the stack counter
  // It use read_cycles() to retrieves cycles based timestamps.
  struct cycle_based_timer
  {
    NT2_SDK_TIMING_DECL static void             Print(const cycles_t& val);
                        static inline cycles_t  Time() { return read_cycles(); }
  };

  // INTERNAL ONLY
  // Static const instance of a cycles_t based counter
  counter<cycles_t,cycle_based_timer>  const cycle_timer = {};
} }

namespace nt2
{
  /**
  * @brief Starts a cycle-based timing section
  *
  * ctic starts a nestable timing section. Timestamp at call point is stored
  * into a stack of timing and pops up at the next call to ctoc()
  *
  * @see toc()
  **/
  inline void ctic()
  {
    details::cycle_timer.tic();
  }

  /**
  * @brief Ends a cycle-based timing section
  *
  * ctoc ends a timing section started by a call to ctic(). Those sections
  * could be nested as long as each toc has a matching ctic().
  *
  * @warning  If ctoc is called without a matching call to ctic(), a runtime
  *           assertion will be triggered.
  *
  * @param display  If true, force the timing result to be displayed on the
  *                 standard output.
  *
  * @return the number of cycles (as a cycles_t) since last call to ctic()
  *
  * @see ctic()
  **/
  inline cycles_t  ctoc( bool display = true )
  {
    return details::cycle_timer.toc(display);
  }
}

#endif

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var ReactControlledComponent = require('./ReactControlledComponent');

// Used as a way to call batchedUpdates when we don't have a reference to
// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.

// Defaults
var fiberBatchedUpdates = function(fn, bookkeeping) {
  return fn(bookkeeping);
};

function batchedUpdates(fn, bookkeeping) {
  // If we have Fiber loaded, we need to wrap this in a batching call so that
  // Fiber can apply its default priority for this call.
  return fiberBatchedUpdates(fn, bookkeeping);
}

var isNestingBatched = false;
function batchedUpdatesWithControlledComponents(fn, bookkeeping) {
  if (isNestingBatched) {
    // If we are currently inside another batch, we need to wait until it
    // fully completes before restoring state. Therefore, we add the target to
    // a queue of work.
    return batchedUpdates(fn, bookkeeping);
  }
  isNestingBatched = true;
  try {
    return batchedUpdates(fn, bookkeeping);
  } finally {
    // Here we wait until all updates have propagated, which is important
    // when using controlled components within layers:
    // https://github.com/facebook/react/issues/1698
    // Then we restore state of any controlled component.
    isNestingBatched = false;
    ReactControlledComponent.restoreStateIfNeeded();
  }
}

var ReactGenericBatchingInjection = {
  injectFiberBatchedUpdates: function(_batchedUpdates) {
    fiberBatchedUpdates = _batchedUpdates;
  },
};

var ReactGenericBatching = {
  batchedUpdates: batchedUpdatesWithControlledComponents,
  injection: ReactGenericBatchingInjection,
};

module.exports = ReactGenericBatching;


text:
package com.google.cloud.datafusion.v1beta1.samples;

// [START datafusion_v1beta1_generated_datafusionclient_listnamespaces_instancename_sync]
import com.google.cloud.datafusion.v1beta1.DataFusionClient;
import com.google.cloud.datafusion.v1beta1.InstanceName;
import com.google.cloud.datafusion.v1beta1.Namespace;

public class SyncListNamespacesInstancename {

  public static void main(String[] args) throws Exception {
    syncListNamespacesInstancename();
  }

  public static void syncListNamespacesInstancename() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
      InstanceName parent = InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]");
      for (Namespace element : dataFusionClient.listNamespaces(parent).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END datafusion_v1beta1_generated_datafusionclient_listnamespaces_instancename_sync]


text:
#ifndef __ZDIGEST_H_INCLUDED__
#define __ZDIGEST_H_INCLUDED__

#ifdef __cplusplus
extern "C" {
#endif

//  Opaque class structure
typedef struct _zdigest_t zdigest_t;

//  @interface
//  Constructor - creates new digest object, which you use to build up a
//  digest by repeatedly calling zdigest_update() on chunks of data.
CZMQ_EXPORT zdigest_t *
    zdigest_new (void);

//  Destroy a digest object
CZMQ_EXPORT void
    zdigest_destroy (zdigest_t **self_p);

//  Add buffer into digest calculation
CZMQ_EXPORT void
    zdigest_update (zdigest_t *self, byte *buffer, size_t length);

//  Return final digest hash data. If built without crypto support, returns
//  NULL.
CZMQ_EXPORT byte *
    zdigest_data (zdigest_t *self);

//  Return final digest hash size
CZMQ_EXPORT size_t
    zdigest_size (zdigest_t *self);

//  Return digest as printable hex string; caller should not modify nor
//  free this string. After calling this, you may not use zdigest_update()
//  on the same digest. If built without crypto support, returns NULL.
CZMQ_EXPORT char *
    zdigest_string (zdigest_t *self);

//  Self test of this class
CZMQ_EXPORT int
    zdigest_test (bool verbose);
//  @end

#ifdef __cplusplus
}
#endif

#endif


text:
using System;
using Gibraltar.Monitor;
using Loupe.Extensibility.Data;

namespace Gibraltar.Server.Client
{
    /// <summary>
    /// Client logger implementation for our core Loupe logging interface
    /// </summary>
    internal class ClientLogger : IClientLogger
    {
        public bool SilentMode { get { return Log.SilentMode; } }

        public void Write(LogMessageSeverity severity, string category, string caption, string description, params object[] args)
        {
            Log.Write(severity, category, caption, description, args);
        }

        public void Write(LogMessageSeverity severity, Exception exception, bool attributeToException, string category, string caption,
            string description, params object[] args)
        {
            Log.Write(severity, LogWriteMode.Queued, exception, attributeToException, category, caption, description, args);
        }
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/registration.dir/src/registration.cpp.o"
  "/home/mike/catkin_ws/devel/lib/wrock/registration.pdb"
  "/home/mike/catkin_ws/devel/lib/wrock/registration"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/registration.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
namespace Compote {
namespace Component {

    using Compote::Entity::AbstractComponentFactory;
    using Compote::Script::LuaAccessor;

    class CRigidBody : public IComponent {
    public:
        const static ComponentType sk_componentType;
        static constexpr const char* LUA_METATABLE_NAME = "CRigidBody";

        glm::vec2 m_velocity;
        glm::vec2 m_acceleration;
        glm::vec2 m_forceAccum;

        bool m_bApplyGravity;

        float m_damping;

        CRigidBody() :
                m_velocity(glm::vec2()),
                m_acceleration(glm::vec2()),
                m_damping(0.70f),
                m_forceAccum(glm::vec2()),
                m_bApplyGravity(true) { }

        CRigidBody(bool applyGravity) :
                m_velocity(glm::vec2()),
                m_acceleration(glm::vec2()),
                m_damping(0.70f),
                m_forceAccum(glm::vec2()),
                m_bApplyGravity(applyGravity) { }

        CRigidBody(bool applyGravity, float damping) :
                m_velocity(glm::vec2()),
                m_acceleration(glm::vec2()),
                m_damping(damping),
                m_forceAccum(glm::vec2()),
                m_bApplyGravity(applyGravity) { }

        virtual ~CRigidBody() { }

        inline const ComponentType getComponentType(void) const {
            return CRigidBody::sk_componentType;
        }

        static const char *getName(void) {
            return "CRigidBody";
        }

        void addForce(glm::vec2 forceToAdd) {
            m_forceAccum += forceToAdd;
        }

        void clearForce(void) {
            m_forceAccum.x = 0.0f;
            m_forceAccum.y = 0.0f;
        }

        IComponent *clone(void) const {
            return nullptr;
        }
    };

    class CRigidBodyFactory : public AbstractComponentFactory<CRigidBody> {
    public:
        CRigidBodyFactory() {}
        ~CRigidBodyFactory() {}

        IComponent* createWithLuaDatas(LuaAccessor& accessor) const {
            CRigidBody *component = new CRigidBody();
            component->m_bApplyGravity = accessor["applyingGravity"];
            component->m_damping = accessor["damping"];
            return component;
        }
    };
}
}
#endif


text:
![Verification](pictures/verification.gif)

**A proof editor for first order logic made for students learning first order logic.**

## Short overview

![Conan](pictures/conan01.png)

Conan offers a design that is akin to text editors, which allows the user to familiarise themselves with the program faster from their common use of the former. The user is allowed to jump to any row of the proof and is able to insert new rows or delete and edit old rows to correct mistakes or even introduce new ones.

![Conan](pictures/conan02.png)

A row consists of a formula field, a rule field and up to three reference fields. The formula field is where the user inputs the desired formula and the rule field should contain the rule that justifies it. References fields are only shown when the rule requires them and are used in conjunction with that specific rule.

![Conan](pictures/conan03.png)

The user is free to input any type of formula, including formulas that are not well-formed. However, while the formula is not well-formed, the formula field turns pink, instantly alerting the user of the mistake they introduced.

![Conan](pictures/conan04.png)

At the top of the proof we have the sequent, which will be updated automatically, adding all the premises of the proof. The consequent of the sequent is used to indicate when the goal has been reached in a valid way. This is indicated with a green colour.

![Conan](pictures/conan05.png)

There are collapsible panes of buttons showcasing the rules of natural deduction, a few derived rules and the symbols which are used in the program. The user may press these buttons to input the rule or symbol to the active field or row. Collapsing the pane allows the user to hide the buttons and work on their recall at will.

![Conan](pictures/conan06.png)

In the short proof, we have that the first two rows are verified since both of them are well-formed formulas that are justified by being premises. The third row is verified since implication elimination takes one implication as a reference and the left hand side of the implication as the other reference. A final check makes sure that the right hand side of the implication matches the row in question.

![Conan](pictures/conan07.png)

Erasing the formula in row two makes the row unverified and affects the third row. Red frames appear, surrounding the rules, alerting the user of the error.

For this proof, we may also generate the formula of the third row by first inputting two verified rows and then inputting both the rule and the correct references in the third row, generating the formula automatically resulting in the same proof as before.

![Conan](pictures/conan08.png)

The status bars are located at the bottom of the program. The left status field is used to indicate errors and the right status field shows how the formula is interpreted in the program. The errors in the status bar are minimal and only indicate basic slips, instead of indicating errors in proof strategy or faulty reasoning.

## Videos

Wellformedness

![Wellformed](pictures/wellformed.gif)

Export to LaTeX

![Export to LaTeX](pictures/exportlatex.gif)


text:
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav3" aria-controls="navbarNav3" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home (current)

              Features

              Pricing

              Team

              About

          Button


text:
export const environment = {
  production: false,
  apiUrl: 'https://api.nytimes.com/svc/archive/v1/',
  apiKey: '',
  localStorage: 0,
  localStorageLocation: '/assets/data/',
};


text:
require "secretly/version"

module Secretly

  def self.fetch( where, lookup )
    send "fetch_from_#{where}", lookup
  end

  def self.fetch_from_file( filepath )
    filepath = File.expand_path( filepath )
    raise "Secret file '#{filepath} does not exist" unless File.exists?( filepath )
    File.read( filepath ).strip
  end

end


text:
using System;
using System.Text;

public static partial class Extensions
{
    /// <summary>
    ///     A string extension method that extracts the Int16 from the string.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>The extracted Int16.</returns>
    public static short ExtractInt16(this string @this)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < @this.Length; i++)
        {
            if (Char.IsDigit(@this[i]))
            {
                if (sb.Length == 0 && i > 0 && @this[i - 1] == '-')
                {
                    sb.Append('-');
                }
                sb.Append(@this[i]);
            }
        }

        return Convert.ToInt16(sb.ToString());
    }
}


text:
import Generator from 'yeoman-generator';

class ReadmeGenerator extends Generator {
  constructor(args, opts) {
    super(args, opts);

    this.option('pluginname', {
      type: String,
      required: true,
    });
    this.option('name', {
      type: String,
      required: false,
      defaults: null,
    });
    this.option('description', {
      type: String,
      required: false,
      defaults: '',
    });
    this.option('license', {
      type: String,
      required: false,
      defaults: 'LICENSE'
    });
  }

  writing() {
    const pkg = this.fs.readJSON(this.destinationPath('package.json'), {});
    if (pkg.license) {
      this.options.license = pkg.license;
    }
    this.fs.copyTpl(
      this.templatePath('README.md'),
      this.destinationPath('README.md'),
      this.options
    );
  }

  install() {
    this.npmInstall();
  }
}

module.exports = ReadmeGenerator


text:
package org.apache.activemq.test.rollback;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.EmbeddedBrokerTestSupport;
import org.apache.activemq.RedeliveryPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.MessageCreator;

/**
 *
 */
public class RollbacksWhileConsumingLargeQueueTest extends EmbeddedBrokerTestSupport implements MessageListener {

   private static final transient Logger LOG = LoggerFactory.getLogger(RollbacksWhileConsumingLargeQueueTest.class);

   protected int numberOfMessagesOnQueue = 650;
   private Connection connection;
   private AtomicInteger deliveryCounter = new AtomicInteger(0);
   private AtomicInteger ackCounter = new AtomicInteger(0);
   private CountDownLatch latch;
   private Throwable failure;

   public void testWithReciever() throws Throwable {
      latch = new CountDownLatch(numberOfMessagesOnQueue);
      Session session = connection.createSession(true, 0);
      MessageConsumer consumer = session.createConsumer(destination);

      long start = System.currentTimeMillis();
      while ((System.currentTimeMillis() - start) < 1000 * 1000) {
         if (getFailure() != null) {
            throw getFailure();
         }

         // Are we done receiving all the messages.
         if (ackCounter.get() == numberOfMessagesOnQueue) {
            return;
         }

         Message message = consumer.receive(1000);
         if (message == null) {
            continue;
         }

         try {
            onMessage(message);
            session.commit();
         }
         catch (Throwable e) {
            session.rollback();
         }
      }

      fail("Did not receive all the messages.");
   }

   public void testWithMessageListener() throws Throwable {
      latch = new CountDownLatch(numberOfMessagesOnQueue);
      new DelegatingTransactionalMessageListener(this, connection, destination);

      long start = System.currentTimeMillis();
      while ((System.currentTimeMillis() - start) < 1000 * 1000) {

         if (getFailure() != null) {
            throw getFailure();
         }

         if (latch.await(1, TimeUnit.SECONDS)) {
            LOG.debug("Received: " + deliveryCounter.get() + "  message(s)");
            return;
         }

      }

      fail("Did not receive all the messages.");
   }

   @Override
   protected ConnectionFactory createConnectionFactory() throws Exception {
      ActiveMQConnectionFactory answer = (ActiveMQConnectionFactory) super.createConnectionFactory();
      RedeliveryPolicy policy = new RedeliveryPolicy();
      policy.setMaximumRedeliveries(3);
      policy.setRedeliveryDelay(0);
      policy.setInitialRedeliveryDelay(0);
      policy.setUseExponentialBackOff(false);
      answer.setRedeliveryPolicy(policy);
      return answer;
   }

   @Override
   protected void setUp() throws Exception {
      super.setUp();

      connection = createConnection();
      connection.start();

      // lets fill the queue up
      for (int i = 0; i < numberOfMessagesOnQueue; i++) {
         template.send(createMessageCreator(i));
      }

   }

   @Override
   protected void tearDown() throws Exception {
      if (connection != null) {
         connection.close();
      }
      super.tearDown();
   }

   protected MessageCreator createMessageCreator(final int i) {
      return new MessageCreator() {
         @Override
         public Message createMessage(Session session) throws JMSException {
            TextMessage answer = session.createTextMessage("Message: " + i);
            answer.setIntProperty("Counter", i);
            return answer;
         }
      };
   }

   @Override
   public void onMessage(Message message) {
      String msgId = null;
      String msgText = null;

      try {
         msgId = message.getJMSMessageID();
         msgText = ((TextMessage) message).getText();
      }
      catch (JMSException e) {
         setFailure(e);
      }

      try {
         assertEquals("Message: " + ackCounter.get(), msgText);
      }
      catch (Throwable e) {
         setFailure(e);
      }

      int value = deliveryCounter.incrementAndGet();
      if (value % 2 == 0) {
         LOG.info("Rolling Back message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText);
         throw new RuntimeException("Dummy exception on message: " + value);
      }

      LOG.info("Received message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText);
      ackCounter.incrementAndGet();
      latch.countDown();
   }

   public synchronized Throwable getFailure() {
      return failure;
   }

   public synchronized void setFailure(Throwable failure) {
      this.failure = failure;
   }
}


text:
import React from 'react';
import { QueryRenderer } from 'react-relay';
import { Spinner, LargeMessage } from 'giu';
import _t from '../../translate';
import { getEnvironment } from '../gral/relay';

type Props = {
  relayEnvironment?: Object,
  query: Object,
  vars?: Object,
  Component: ReactClass<*>,
  renderDuringLoad?: boolean,
};

const QueryRendererWrapper = ({
  relayEnvironment,
  query,
  vars,
  Component,
  renderDuringLoad,
  ...props
}: Props) => (
  <QueryRenderer
    environment={relayEnvironment || getEnvironment()}
    query={query}
    variables={vars}
    render={({ error, props: relayData }) => {
      if (error) {
        console.error(error); // eslint-disable-line
        return (
          <LargeMessage>{_t('error_Oops, an error occurred!')}</LargeMessage>
        );
      }
      if (relayData) {
        return <Component {...props} {...relayData} />;
      }
      if (renderDuringLoad) return <Component {...props} />;
      return <Spinner />;
    }}
  />
);

export default QueryRendererWrapper;


text:
<content-type name="/component/testimonial-carousel" is-wcm-type="true">
	<label>Component - Testimonial Carousel</label>
	<form>/component/testimonial-carousel</form>
	<form-path>simple</form-path>
	<model-instance-path>NOT-USED-BY-SIMPLE-FORM-ENGINE</model-instance-path>
	<file-extension>xml</file-extension>
	<content-as-folder>false</content-as-folder>
	<previewable>false</previewable>
	<noThumbnail>true</noThumbnail>
	<image-thumbnail></image-thumbnail>
	<paths>
			<excludes>
				<pattern>^/site/website/.*</pattern>
				<pattern>^/site/components/sections/.*</pattern>
				<pattern>^/site/components/section-headers/.*</pattern>
				<pattern>^/site/components/services/.*</pattern>
				<pattern>^/site/components/teammates/.*</pattern>
			</excludes>
	</paths>
</content-type>


text:
def connectEcs(region)
    Aws::ECS::Client.new(region: region)
end

def awsBucket(region, bucketName)
    # connect to s3
    s3 = Aws::S3::Client.new(
        region: region
    )
    buckets = s3.list_buckets.to_h
    buckets.extend(Hashie::Extensions::DeepLocate)
    bucket = buckets.deep_locate -> (key, value, _object) { key == :name && value.include?(bucketName) }
    if bucket.empty?
        Kinglog.log.info "Creating bucket #{bucketName}!"
        s3.create_bucket(bucket: bucketName)
        Kinglog.log.info "Enabling bucket versioning!"
        s3.put_bucket_versioning(bucket: bucketName, versioning_configuration: { mfa_delete: 'Disabled', status: 'Enabled' })
    else
        Kinglog.log.info "Bucket allready exists"
    end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white" >

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

    <FrameLayout
        android:id="@+id/left_container"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="left" />

</android.support.v4.widget.DrawerLayout>


text:
import csv
import os
from typing import List, Set
import unittest

from file_reading import read_actions_file
from file_reading import read_platform_supported_actions
from file_reading import read_unprocessed_coverage_tests_file
from models import Action
from models import ActionsByName
from models import ActionType
from models import CoverageTest
from models import CoverageTestsByPlatform
from models import TestPlatform
from test_analysis import expand_parameterized_tests
from test_analysis import partition_framework_tests_per_platform_combination

TEST_DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "test_data")

def CreateDummyAction(id: str):
    return Action(id, id, id, id, ActionType.STATE_CHANGE, TestPlatform,
                  TestPlatform)

def CreateCoverageTest(id: str, platforms: Set[TestPlatform]):
    return CoverageTest([CreateDummyAction(id)], platforms)

class TestAnalysisTest(unittest.TestCase):
    def test_partition_framework_tests_per_platform_combination(self):
        tests_by_platform: CoverageTestsByPlatform = {}
        windows_tests = []
        windows_tests.append(CreateCoverageTest("a", {TestPlatform.WINDOWS}))
        windows_tests.append(CreateCoverageTest("b", {TestPlatform.WINDOWS}))
        windows_tests.append(CreateCoverageTest("c", {TestPlatform.WINDOWS}))
        tests_by_platform[TestPlatform.WINDOWS] = windows_tests
        mac_tests = []
        mac_tests.append(CreateCoverageTest("a", {TestPlatform.MAC}))
        mac_tests.append(CreateCoverageTest("c", {TestPlatform.MAC}))
        tests_by_platform[TestPlatform.MAC] = mac_tests
        linux_tests = []
        linux_tests.append(CreateCoverageTest("a", {TestPlatform.LINUX}))
        tests_by_platform[TestPlatform.LINUX] = linux_tests

        partitions = partition_framework_tests_per_platform_combination(
            tests_by_platform)
        self.assertEqual(len(partitions), 3)

        self.assertTrue(frozenset({TestPlatform.WINDOWS}) in partitions)
        windows_tests = partitions[frozenset({TestPlatform.WINDOWS})]
        self.assertEqual(len(windows_tests), 1)
        self.assertEqual(windows_tests[0].id, "b")

        self.assertTrue(
            frozenset({TestPlatform.MAC, TestPlatform.WINDOWS}) in partitions)
        mac_win_tests = partitions[frozenset(
            {TestPlatform.MAC, TestPlatform.WINDOWS})]
        self.assertEqual(len(mac_win_tests), 1)
        self.assertEqual(mac_win_tests[0].id, "c")

        mac_win_linux_key = frozenset(
            {TestPlatform.MAC, TestPlatform.WINDOWS, TestPlatform.LINUX})
        self.assertTrue(mac_win_linux_key in partitions)
        mac_win_linux_tests = partitions[mac_win_linux_key]
        self.assertEqual(len(mac_win_linux_tests), 1)
        self.assertEqual(mac_win_linux_tests[0].id, "a")

    def test_processed_coverage(self):
        actions_filename = os.path.join(TEST_DATA_DIR, "test_actions.csv")
        supported_actions_filename = os.path.join(
            TEST_DATA_DIR, "framework_supported_actions.csv")
        actions: ActionsByName = {}
        action_base_name_to_default_param = {}
        with open(actions_filename, "r", encoding="utf-8") as f, \
                open(supported_actions_filename, "r", encoding="utf-8") \
                    as supported_actions_file:
            supported_actions = read_platform_supported_actions(
                csv.reader(supported_actions_file))
            actions_csv = csv.reader(f, delimiter=',')
            (actions, action_base_name_to_default_param) = read_actions_file(
                actions_csv, supported_actions)

        coverage_filename = os.path.join(TEST_DATA_DIR,
                                         "test_unprocessed_coverage.csv")
        coverage_tests: List[CoverageTest] = []
        with open(coverage_filename, "r", encoding="utf-8") as f:
            coverage_csv = csv.reader(f, delimiter=',')
            coverage_tests = read_unprocessed_coverage_tests_file(
                coverage_csv, actions, action_base_name_to_default_param)
        coverage_tests = expand_parameterized_tests(coverage_tests)

        # Compare with expected
        expected_processed_tests = []
        processed_filename = os.path.join(TEST_DATA_DIR,
                                          "expected_processed_coverage.csv")
        with open(processed_filename, "r", encoding="utf-8") as f:
            coverage_csv = csv.reader(f, delimiter=',')
            expected_processed_tests = read_unprocessed_coverage_tests_file(
                coverage_csv, actions, action_base_name_to_default_param)

        # Hack for easy comparison and printing: transform coverage tests into
        # a Tuple[List[str], Set[TestPlatform]].
        self.assertCountEqual([([action.name
                                 for action in test.actions], test.platforms)
                               for test in coverage_tests],
                              [([action.name
                                 for action in test.actions], test.platforms)
                               for test in expected_processed_tests])

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


text:
import {ArraySchemaType, SchemaType} from '@sanity/types'
import {resolveTypeName} from '@sanity/util/content'
import {IGNORE_KEYS} from './constants'

// eslint-disable-next-line @typescript-eslint/ban-types
export function isEmpty(value: Record<string, unknown>): value is Record<never, never> {
  return Object.keys(value).every((key) => IGNORE_KEYS.includes(key))
}

export function getItemType(arrayType: ArraySchemaType, item: any): SchemaType | undefined {
  const itemTypeName = resolveTypeName(item)

  return itemTypeName === 'object' && arrayType.of.length === 1
    ? arrayType.of[0]
    : arrayType.of.find((memberType) => memberType.name === itemTypeName)
}


text:
const router = require('express').Router();
const bcrypt = require('bcrypt');
const jwt = require("jwt-simple");
const co = require('co');
const ObjectID = require('mongodb').ObjectID;
const MongoError = require('mongodb').MongoError;

const toMongodb = require('jsonpatch-to-mongodb');

const myAcl = require('../../my-acl');

const dbX = require('../../db');
const collectionName = 'users';

const saltRounds = 10;

const postSearch = (req, res) => {

  if (!req.body) {
    return res.status(400).json({
      message: 'No search params provided.'
    });
  }
  const searchParams = JSON.parse(JSON.stringify(req.body));
  const isFindOne = !!searchParams._id;

  co(function*() {
    const db = yield dbX.dbPromise;
    let project, searchResult;
    if (isFindOne) {
      searchParams._id = new ObjectID(searchParams._id);
      projection = {password: 0};
      searchResult = yield db.collection(collectionName).find(searchParams, projection).toArray();
      if (searchResult.length) {
        // get userRoles
        const aclInstance = yield myAcl.aclInstancePromise;
        const userRoles = yield aclInstance.userRoles(req.body._id);
        searchResult[0]['roles'] = userRoles;
      }
    } else {
      projection = {password: 0, settings: 0};
      searchResult = yield db.collection(collectionName).find(searchParams, projection).toArray();
    }
    return res.json(searchResult);
  }).catch(error => {
    if (error instanceof MongoError) {
      // front end will check if error contains error code like 'E11000' using error.indexOf
      return res.status(500).json(error.toString());
    } else {
      return res.status(500).json(error.stack);
    }
  })

}

router.post('/search', postSearch);

/*
  GET /
  return only users of the same facility as for req.user
  if req.user.facility === 'f000', return all the users
*/
router.get('/', (req, res) => {
  // co(function*() {
  //   const db = yield dbX.dbPromise;
  //   const userList = yield db.collection('users').find({}, {password: 0}).toArray();
  //   res.json(userList);
  // }).catch(function(err) {
  //   return res.status(500).json(err.stack);
  // });

  co(function*() {
    const db = yield dbX.dbPromise;
    const query = req.user.facility === 'f000' ?
      {} :
      {facility: {$in: [req.user.facility, 'f000']}};
    const users = yield db.collection('users').find(query, {username: 1, displayName: 1}).toArray();
    res.json(users);
  }).catch(function(err) {
    return res.status(500).json(err.stack);
  });
  // res.json(req.user);

})

router.patch('/', (req, res) => {
  // a user can edit its own record
  // a admin can edit all the records
  const editorUserId = req.user._id; // this is an ObjectID instance
  const targetUserId = req.query._id; // this is a string
  if (!targetUserId) {
    return res.status(400).json({
      message: "insufficient parameters."
    })
  }
  if (!req.body || !req.body.patches) {
    return res.status(400).json({
      message: 'no data provided.'
    })
  }

  const sameUser = JSON.stringify(editorUserId) === JSON.stringify(targetUserId);
  co(function*() {
    const db = yield dbX.dbPromise;

    let canPatch = sameUser;
    if (!canPatch) { // check if editor is admin
      const aclInstance = yield myAcl.aclInstancePromise;
      canPatch = yield aclInstance.hasRole(JSON.parse(JSON.stringify(editorUserId)), 'admin');
    }
    if (!canPatch) {
      return res.status(401).json({error: 'not authorized'});
    } else {
      console.log('patches', req.body.patches);
      const rolesToAdd = [];
      const rolesIndexToRemove = [];
      const patchesX = [];
      req.body.patches.forEach(p => {
        switch (true) {
          case p.path.indexOf('roles') > -1 && (p.op === 'replace' || p.op === 'add'):
            rolesToAdd.push(p.value);
            break;
          case p.path.indexOf('roles') > -1 && (p.op === 'remove'):
            rolesIndexToRemove.push(+p.path.split('/')[2]);
            break;
          case p.path.indexOf('password') > -1:
            // hash pasword
            const pX = JSON.parse(JSON.stringify(p));
            patchesX.push(p);
            break;
          default:
            patchesX.push(p);
        }
      })
      let patchResultR = {};
      let patchResultX;
      // deal with roles changes
      if (rolesToAdd.length || rolesIndexToRemove.length) {
        const aclInstance = yield myAcl.aclInstancePromise;
        const userRolesBefore = yield aclInstance.userRoles(targetUserId);
        // deal with removed roles
        let userRolesAfter = rolesIndexToRemove.length ? userRolesBefore.reduce((acc, curr, index) => {
          if (rolesIndexToRemove.indexOf(index) === -1) {
            acc.push(curr);
          }
          return acc;
        }, []) : JSON.parse(JSON.stringify(userRolesBefore));
        userRolesAfter = [...userRolesAfter, ...rolesToAdd]; // not caring the duplicated ones, acl.addUserRoles will ignore them
        // console.log(userRolesBefore);
        // console.log(rolesToAdd);
        // console.log(rolesIndexToRemove);
        // console.log(userRolesAfter);
        // reset roles by remove all and adding userRolesAfter
        yield aclInstance.removeUserRoles(targetUserId, userRolesBefore);
        yield aclInstance.addUserRoles(targetUserId, userRolesAfter);
        patchResultR.roles = 'done';
      }

      // deal with the rest
      if (patchesX.length) {
        const patchesToApply = toMongodb(req.body.patches);
        console.log('patchesToApply', patchesToApply);
        // todo: deal with password
        patchResultX = yield db.collection('users').updateOne(
          {_id: new ObjectID(targetUserId)},
          patchesToApply
        );
      }

      res.json(Object.assign({}, patchResultX, patchResultR));
    }
  }).catch(err => {
    return res.status(500).json(err.stack);
  })

  // res.json({editorUserId, targetUserId, sameUser})
})

router.get('/one', (req, res) => {
  if (!req.query.userId && !req.query.username) {
    return res.status(400).json({
      message: "insufficient parameters."
    })
  }

  switch (true) {
    case !!req.query.userId:

      const userId = new ObjectID(req.query.userId);
      co(function*() {
        const db = yield dbX.dbPromise;
        const docs = yield db.collection('users').find({_id: userId}, {password: 0}).toArray();
        if (!docs.length) {return res.status(400).json({
          message: `no user whose id is ${userId}`
        })}
        const user = docs[0];
        const userRecordsInACL =
          yield db.collection('acl_users').find({key: req.query.userId}, {_id: 0, key: 0}).toArray();
        const userRolesObj = userRecordsInACL[0];
        user.roles = userRolesObj ? Object.keys(userRolesObj) : [];
        return res.send(user);
      }).catch((err) => {
        return res.status(500).json(err.stack);
      })

      break;
    case !!req.query.username:
      const username = req.query.username;
      co(function*() {
        const db = yield dbX.dbPromise;
        const docs = yield db.collection('users').find({username}, {password: 0}).toArray();
        if (!docs.length) {return res.status(400).json({
          message: `no user whose name is ${username}`
        })}
        const user = docs[0];
        // console.log(user._id.toHexString());
        const userRecordsInACL =
          yield db.collection('acl_users').find({key: user._id.toHexString()}, {_id: 0, key: 0}).toArray();
        const userRolesObj = userRecordsInACL[0];
        user.roles = userRolesObj ? Object.keys(userRolesObj) : [];
        return res.send(user);
        // res.send('ok');
      }).catch((err) => {
        return res.status(500).json(err.stack);
      })

      break;
  }

  // res.send('ok');
})

/* return staffs of the facility which current user belongs to */
router.get('/staffs', (req, res) => {
  co(function*() {
    const db = yield dbX.dbPromise;
    const staffs = yield db.collection('users').find({
      facility: req.user.facility,
    }, {username: 1, displayName: 1}).toArray();
    res.json(staffs);
  }).catch(function(err) {
    return res.status(500).json(err.stack);
  });
  // res.json(req.user);
})

router.post('/', (req, res) => {
  if (!req.body.username ||!req.body.password || !req.body.displayName) return res.status(400).json({
    message: 'Usernme or password or display name is missing.'
  });
  /* consider adding verification for username and password */

  const username = req.body.username;
  const displayName = req.body.displayName;
  const password = req.body.password;
  const roles = req.body.roles || ['guest'];
  co(function*() {
    const hash = yield bcrypt.hash(password, saltRounds);
    const db = yield dbX.dbPromise;
    // const db = dbX.db;
    const itemToInsert = {
      username,
      password: hash,
      displayName,
      createdBy: req.user._id,
      createdAt: (new Date()).toISOString(),
      isActive: true,
      facility: req.body.facility,
      department: req.body.department
    }
    const insertResult = yield db.collection('users').insertOne(itemToInsert);
    const updateVersionResult = yield db.collection('versions').updateOne({
      collection: 'users'
    }, {
      '$set': {version: `${(new Date()).toISOString().substring(0, 10)}:${Math.random()}`}
    }, {
      upsert: true
    });
    // mongodb driver will add _id to itemToInsert after above ops
    const aclInstance = yield myAcl.aclInstancePromise;
    const aclResult = yield aclInstance.addUserRoles(itemToInsert._id.toHexString(), roles)
    // db.close();
    delete itemToInsert.password;
    res.json(itemToInsert);
  }).catch(function(err) {
    const errStr = JSON.stringify(err.stack);
    // if duplicate username ...
    if (errStr.indexOf('E11000')) return res.status(400).json({
      message: 'Duplicate username.'
    });
    return res.status(500).json(err.stack);
  });
});

module.exports = router;


text:
namespace SciHub.Data
{
    using System;
    using System.Data.Entity;
    using System.Linq;
    using Common.Models;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Models;
    using Models.Book;
    using Models.Common;
    using Models.Movie;
    using Models.ShortStory;
    using Models.TvShow;

    public class SciHubDbContext : IdentityDbContext<User>, ISciHubDbContext
    {
        public SciHubDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public virtual IDbSet<Actor> Actors { get; set; }

        public virtual IDbSet<BookAuthor> BookAuthors { get; set; }

        public virtual IDbSet<BookComment> BookComments { get; set; }

        public virtual IDbSet<BookCover> BookCovers { get; set; }

        public virtual IDbSet<BookRating> BookRatings { get; set; }

        public virtual IDbSet<Book> Books { get; set; }

        public virtual IDbSet<Director> Directors { get; set; }

        public virtual IDbSet<MovieComment> MovieComments { get; set; }

        public virtual IDbSet<MoviePoster> MoviePosters { get; set; }

        public virtual IDbSet<MovieRating> MovieRatings { get; set; }

        public virtual IDbSet<Movie> Movies { get; set; }

        public virtual IDbSet<MovieStudio> MovieStudios { get; set; }

        public virtual IDbSet<ShortStory> ShortStories { get; set; }

        public virtual IDbSet<ShortStoryComment> ShortStoryComments { get; set; }

        public virtual IDbSet<ShortStoryRating> ShortStoryRatings { get; set; }

        public virtual IDbSet<Tag> Tags { get; set; }

        public virtual IDbSet<TvShowChannel> TvShowChannels { get; set; }

        public virtual IDbSet<TvShowComment> TvShowComments { get; set; }

        public virtual IDbSet<TvShowPoster> TvShowPosters { get; set; }

        public virtual IDbSet<TvShowRating> TvShowRatings { get; set; }

        public virtual IDbSet<TvShow> TvShows { get; set; }

        public static SciHubDbContext Create()
        {
            return new SciHubDbContext();
        }

        public override int SaveChanges()
        {
            this.ApplyAuditInfoRules();
            return base.SaveChanges();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder
                .Entity<Movie>()
                .HasMany(x => x.Comments)
                .WithRequired(x => x.Movie)
                .WillCascadeOnDelete(true);

            modelBuilder
                .Entity<Book>()
                .HasMany(x => x.Comments)
               .WithRequired(x => x.Book)
                .WillCascadeOnDelete(true);

            modelBuilder
                .Entity<TvShow>()
                .HasMany(x => x.Comments)
                .WithRequired(x => x.TvShow)
                .WillCascadeOnDelete(true);

            modelBuilder
                .Entity<ShortStory>()
                .HasMany(x => x.Comments)
                .WithRequired(x => x.ShortStory)
                .WillCascadeOnDelete(true);

            base.OnModelCreating(modelBuilder);
        }

        private void ApplyAuditInfoRules()
        {
            // Approach via @julielerman: http://bit.ly/123661P
            foreach (var entry in
                this.ChangeTracker.Entries()
                    .Where(
                        e =>
                        e.Entity is IAuditInfo && ((e.State == EntityState.Added) || (e.State == EntityState.Modified))))
            {
                var entity = (IAuditInfo)entry.Entity;
                if (entry.State == EntityState.Added && entity.CreatedOn == default(DateTime))
                {
                    entity.CreatedOn = DateTime.Now;
                }
                else
                {
                    entity.ModifiedOn = DateTime.Now;
                }
            }
        }
    }
}


text:
package ru.job4j.h7testtask.t3stock;

/**
 * The StubInput class.
 */
public class StubInput implements SimpleInput {
    /**
     * The array of string elements.
     */
    private String[] array;
    /**
     * The position.
     */
    private int pos;

    /**
     * @param array to be assigned.
     */
    public StubInput(String[] array) {
        this.array = array;
    }

    /**
     * @param s is the string to be printed out.
     * @return the User's choice.
     */
    @Override
    public int ask(String s) {
        System.out.print(s);
        return Integer.parseInt(array[pos++]);
    }

    /**
     * @param s is the string to be printed out.
     * @return the User's choice.
     */
    @Override
    public double askD(String s) {
        System.out.print(s);
        return Double.parseDouble(array[pos++]);
    }

    /**
     * @return the User's choice.
     */
    @Override
    public int ask() {
        return Integer.parseInt(array[pos++]);
    }
}


text:
FROM nginx:alpine

# Use /etc/hostname as index.html so you can distinguish the servers
RUN rm /usr/share/nginx/html/index.html \
  && ln -s /etc/hostname /usr/share/nginx/html/index.html


text:
package org.gradle.model.internal.inspect;

import org.gradle.model.Finalize;

public class FinalizeRuleDefinitionHandler extends AbstractMutationRuleDefinitionHandler<Finalize> {
    @Override
    protected boolean isFinalize() {
        return true;
    }
}


text:
- __Google Chronicle Backstory__
Integration name has been updated


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

public class SquareNumbers
{
    public static void Main()
    {
        List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
        List<int> squareNumbers = new List<int>();

        foreach (var number in numbers)
        {
            double result = Math.Sqrt(number);
            bool isSquare = result % 1 == 0;

            if (isSquare)
            {
                squareNumbers.Add(number);
            }
        }

        squareNumbers.Sort((a, b) => b.CompareTo(a));

        Console.WriteLine(string.Join(" ", squareNumbers));
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePasswordResetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username')->unique();
            $table->string('password');
            $table->string('email')->unique();
            $table->rememberToken();
            $table->string('photo')->default('default.jpg');
            $table->string('auth')->default('1');
            $table->string('status')->default('1');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('password_resets');
    }
}


text:
namespace
{
    using namespace OIC::Service;

    ResourceState convertBrokerState(BROKER_STATE state)
    {
        SCOPE_LOG_F(DEBUG, TAG);

        switch (state)
        {
            case BROKER_STATE::ALIVE:
                return ResourceState::ALIVE;

            case BROKER_STATE::REQUESTED:
                return ResourceState::REQUESTED;

            case BROKER_STATE::LOST_SIGNAL:
                return ResourceState::LOST_SIGNAL;

            case BROKER_STATE::DESTROYED:
                return ResourceState::DESTROYED;

            case BROKER_STATE::NONE:
                return ResourceState::NONE;
        }

        return ResourceState::NONE;
    }

    CacheState convertCacheState(CACHE_STATE state)
    {
        SCOPE_LOG_F(DEBUG, TAG);

        switch (state)
        {
            case CACHE_STATE::READY:
                return CacheState::READY;

            case CACHE_STATE::READY_YET:
            case CACHE_STATE::UPDATING:
                return CacheState::UNREADY;

            case CACHE_STATE::LOST_SIGNAL:
                return CacheState::LOST_SIGNAL;

            case CACHE_STATE::DESTROYED:
            case CACHE_STATE::NONE:
                return CacheState::NONE;
        }

        return CacheState::NONE;
    }

    OCStackResult hostingCallback(BROKER_STATE state,
            RCSRemoteResourceObject::StateChangedCallback onResourceStateChanged)
    {
        SCOPE_LOG_F(DEBUG, TAG);

        onResourceStateChanged(convertBrokerState(state));
        return OC_STACK_OK;
    }

    OCStackResult cachingCallback(std::shared_ptr< PrimitiveResource >,
            const RCSResourceAttributes& data, int eCode,
            RCSRemoteResourceObject::CacheUpdatedCallback onCacheUpdated)
    {
        SCOPE_LOG_F(DEBUG, TAG);

        onCacheUpdated(data, eCode);
        return OC_STACK_OK;
    }

    void setRemoteAttributesCb(const HeaderOptions&, const ResponseStatement& response, int eCode,
            RCSRemoteResourceObject::RemoteAttributesSetCallback onRemoteAttributesSet)
    {
        SCOPE_LOG_F(DEBUG, TAG);

        onRemoteAttributesSet(response.getAttributes(), eCode);
    }

    void getRemoteAttributesCb(const HeaderOptions&, const ResponseStatement& response, int eCode,
            RCSRemoteResourceObject::RemoteAttributesGetCallback onRemoteAttributesReceived)
    {
        SCOPE_LOG_F(DEBUG, TAG);

        onRemoteAttributesReceived(response.getAttributes(), eCode);
    }
}

namespace OIC
{
    namespace Service
    {

        RCSQueryParams& RCSQueryParams::setResourceInterface(std::string resourceInterface)
        {
            m_resourceInterface = std::move(resourceInterface);
            return *this;
        }

        RCSQueryParams& RCSQueryParams::setResourceType(std::string resourceType)
        {
            m_resourceType = std::move(resourceType);
            return *this;
        }

        RCSQueryParams& RCSQueryParams::put(std::string key, std::string value)
        {
            m_map[std::move(key)] = std::move(value);
            return *this;
        }

        std::string RCSQueryParams::getResourceInterface() const
        {
            return m_resourceInterface;
        }

        std::string RCSQueryParams::getResourceType() const
        {
            return m_resourceType;
        }

        std::string RCSQueryParams::get(const std::string& key) const
        {
            try
            {
                return m_map.at(key);
            }
            catch (const std::out_of_range&)
            {
                throw RCSInvalidKeyException(key + " is an invalid key");
            }
        }

        const RCSQueryParams::Map& RCSQueryParams::getAll() const
        {
            return m_map;
        }

        RCSRemoteResourceObject::RCSRemoteResourceObject(
                std::shared_ptr< PrimitiveResource > primtiveResource) :
                m_primitiveResource{ primtiveResource },
                m_cacheId{ },
                m_brokerId{ }
        {
        }

        RCSRemoteResourceObject::~RCSRemoteResourceObject()
        {
            SCOPE_LOG_F(DEBUG, TAG);
            try
            {
                stopCaching();
                stopMonitoring();
            }
            catch(std::exception &e)
            {
                OIC_LOG_V(ERROR, TAG, "%s", e.what());
            }
        }

        RCSRemoteResourceObject::Ptr RCSRemoteResourceObject::fromOCResource(
                std::shared_ptr< OC::OCResource > ocResource)
        {
            if (!ocResource)
            {
                throw RCSInvalidParameterException("the oc resource must not be nullptr.");
            }

            return std::make_shared< RCSRemoteResourceObject >(
                    PrimitiveResource::create(ocResource));
        }

        std::shared_ptr< OC::OCResource > RCSRemoteResourceObject::toOCResource(
        RCSRemoteResourceObject::Ptr rcsResource)
        {
            if (!rcsResource)
            {
                throw RCSInvalidParameterException("the rcs resource must not be nullptr.");
            }

            OC::OCResource::Ptr ocResource = OC::OCPlatform::constructResourceObject(rcsResource->getAddress(),
                rcsResource->getUri(),
                rcsResource->m_primitiveResource->getConnectivityType(),
                rcsResource->isObservable(),
                rcsResource->getTypes(),
                rcsResource->getInterfaces());

            return ocResource;
        }

        bool RCSRemoteResourceObject::isMonitoring() const
        {
            return m_brokerId != 0;
        }

        bool RCSRemoteResourceObject::isCaching() const
        {
            return m_cacheId != 0;
        }

        bool RCSRemoteResourceObject::isObservable() const
        {
            return m_primitiveResource->isObservable();
        }

        void RCSRemoteResourceObject::startMonitoring(StateChangedCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "startMonitoring : Callback is NULL" };
            }

            if (isMonitoring())
            {
                OIC_LOG(DEBUG, TAG, "startMonitoring : already started");
                throw RCSBadRequestException{ "Monitoring already started." };
            }

            m_brokerId = ResourceBroker::getInstance()->hostResource(m_primitiveResource,
                    std::bind(hostingCallback, std::placeholders::_1, std::move(cb)));
        }

        void RCSRemoteResourceObject::stopMonitoring()
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!isMonitoring())
            {
                OIC_LOG(DEBUG, TAG, "stopMonitoring : Not started");
                return;
            }

            ResourceBroker::getInstance()->cancelHostResource(m_brokerId);
            m_brokerId = 0;
        }

        ResourceState RCSRemoteResourceObject::getState() const
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!isMonitoring())
            {
                return ResourceState::NONE;
            }

            return convertBrokerState(
                    ResourceBroker::getInstance()->getResourceState(m_primitiveResource));
        }

        void RCSRemoteResourceObject::startCaching()
        {
            startCaching({ });
        }

        void RCSRemoteResourceObject::startCaching(CacheUpdatedCallback cb, CacheMode mode)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (isCaching())
            {
                OIC_LOG(DEBUG, TAG, "startCaching : already Started");
                throw RCSBadRequestException{ "Caching already started." };
            }

            if (mode == CacheMode::OBSERVE_ONLY)
            {
                m_cacheId = ResourceCacheManager::getInstance()->requestResourceCache(
                        m_primitiveResource,
                        std::bind(cachingCallback, std::placeholders::_1,
                                  std::placeholders::_2, std::placeholders::_3,
                                  std::move(cb)), CACHE_METHOD::OBSERVE_ONLY,
                                  REPORT_FREQUENCY::UPTODATE, 0);
            }

            else if (cb)
            {
                m_cacheId = ResourceCacheManager::getInstance()->requestResourceCache(
                        m_primitiveResource,
                        std::bind(cachingCallback, std::placeholders::_1,
                                std::placeholders::_2, std::placeholders::_3,
                                std::move(cb)), CACHE_METHOD::ITERATED_GET,
                                REPORT_FREQUENCY::UPTODATE, 0);
            }
            else
            {
                m_cacheId = ResourceCacheManager::getInstance()->requestResourceCache(
                        m_primitiveResource, { }, CACHE_METHOD::ITERATED_GET,
                        REPORT_FREQUENCY::NONE, 0);
            }

            OIC_LOG_V(DEBUG, TAG, "startCaching CACHE ID %d", m_cacheId);
        }

        void RCSRemoteResourceObject::stopCaching()
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!isCaching())
            {
                OIC_LOG(DEBUG, TAG, "Caching already terminated");
                return;
            }

            try
            {
                ResourceCacheManager::getInstance()->cancelResourceCache(m_cacheId);
            }
            catch (const RCSInvalidParameterException &)
            {
                throw;
            }
            catch (...)
            {
                m_cacheId = 0;
                throw;
            }
            m_cacheId = 0;
        }

        CacheState RCSRemoteResourceObject::getCacheState() const
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!isCaching())
            {
                return CacheState::NONE;
            }

            return convertCacheState(
                    ResourceCacheManager::getInstance()->getResourceCacheState(m_cacheId));
        }

        bool RCSRemoteResourceObject::isCachedAvailable() const
        {
            if (!isCaching())
            {
                return false;
            }

            return ResourceCacheManager::getInstance()->isCachedData(m_cacheId);
        }

        RCSResourceAttributes RCSRemoteResourceObject::getCachedAttributes() const
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!isCaching())
            {
                throw RCSBadRequestException{ "Caching not started." };
            }

            if (!isCachedAvailable())
            {
                throw RCSBadRequestException{ "Cache data is not available." };
            }

            return ResourceCacheManager::getInstance()->getCachedData(m_cacheId);
        }

        RCSResourceAttributes::Value RCSRemoteResourceObject::getCachedAttribute(
                const std::string& key) const
        {
            SCOPE_LOG_F(DEBUG, TAG);

            return getCachedAttributes().at(key);
        }

        std::string RCSRemoteResourceObject::getUri() const
        {
            return m_primitiveResource->getUri();
        }

        std::string RCSRemoteResourceObject::getAddress() const
        {
            return m_primitiveResource->getHost();
        }

        std::vector< std::string > RCSRemoteResourceObject::getTypes() const
        {
            return m_primitiveResource->getTypes();
        }

        std::vector< std::string > RCSRemoteResourceObject::getInterfaces() const
        {
            return m_primitiveResource->getInterfaces();
        }

        void RCSRemoteResourceObject::getRemoteAttributes(RemoteAttributesGetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "getRemoteAttributes : Callback is empty" };
            }

            m_primitiveResource->requestGet(
                    std::bind(getRemoteAttributesCb, std::placeholders::_1, std::placeholders::_2,
                            std::placeholders::_3, std::move(cb)));
        }

        void RCSRemoteResourceObject::get(GetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "get : Callback is empty" };
            }

            m_primitiveResource->requestGet(std::move(cb));
        }

        void RCSRemoteResourceObject::get(const RCSQueryParams& queryParams, GetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "get : Callback is empty" };
            }

            const auto& paramMap = queryParams.getAll();

            m_primitiveResource->requestGetWith(
                    queryParams.getResourceType(), queryParams.getResourceInterface(),
                    OC::QueryParamsMap{ paramMap.begin(), paramMap.end() },
                    std::move(cb));
        }

        void RCSRemoteResourceObject::setRemoteAttributes(const RCSResourceAttributes& attribute,
                RemoteAttributesSetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "setRemoteAttributes : Callback is empty" };
            }

            m_primitiveResource->requestSet(attribute,
                    std::bind(setRemoteAttributesCb, std::placeholders::_1, std::placeholders::_2,
                            std::placeholders::_3, cb));
        }

        void RCSRemoteResourceObject::set(const RCSResourceAttributes& attributes, SetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "set : Callback is empty" };
            }

            m_primitiveResource->requestSet(attributes, std::move(cb));
        }

        void RCSRemoteResourceObject::set(const RCSQueryParams& queryParams,
                const RCSResourceAttributes& attributes, SetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "set : Callback is empty" };
            }

            const auto& paramMap = queryParams.getAll();

            m_primitiveResource->requestSetWith(
                    queryParams.getResourceType(), queryParams.getResourceInterface(),
                    OC::QueryParamsMap{ paramMap.begin(), paramMap.end() }, attributes,
                    std::move(cb));
        }

        void RCSRemoteResourceObject::set(const RCSQueryParams& queryParams,
                const RCSRepresentation& rep, SetCallback cb)
        {
            SCOPE_LOG_F(DEBUG, TAG);

            if (!cb)
            {
                throw RCSInvalidParameterException{ "set : Callback is empty" };
            }

            const auto& paramMap = queryParams.getAll();

            m_primitiveResource->requestSetWith(
                    queryParams.getResourceType(), queryParams.getResourceInterface(),
                    OC::QueryParamsMap{ paramMap.begin(), paramMap.end() }, rep,
                    std::move(cb));
        }

    }
}


text:
#ifndef SPARROW_NDDOINITIALIZER_H
#define SPARROW_NDDOINITIALIZER_H

#include <Sparrow/Implementations/Nddo/Parameters.h>
#include <Sparrow/Implementations/Nddo/Utils/IntegralsEvaluationUtils/oneCenterIntegralContainer.h>
#include <Sparrow/Implementations/Nddo/Utils/ParameterUtils/ElementPairParameters.h>
#include <Sparrow/Implementations/Nddo/Utils/ParameterUtils/ElementParameters.h>
#include <Utils/DataStructures/AtomsOrbitalsIndexes.h>
#include <Utils/Scf/MethodInterfaces/StructureDependentInitializer.h>
#include <string>
#include <vector>

namespace Scine {
namespace Sparrow {

namespace nddo {

/**
 * @brief Settings for generic NDDO methods.
 * Reads the parameters and applies them to the system of interest.
 * Depending on the method, the basis functions used can either be BasisFunction::sp (MNDO, AM1) of BasisFunction::spd
 * (i.e. PM6, AM1*, MNDO/d) and it can have just atomic parameters (i.e. AM1, MNDO) or also diatomic parameters (i.e.
 * PM6)
 */
class NDDOInitializer : public Utils::StructureDependentInitializer {
 public:
  explicit NDDOInitializer(BasisFunctions basisFunctions = BasisFunctions::spd, bool hasDiatomicParameters = true)
    : basisFunctions_(basisFunctions), hasDiatomicParameters_(hasDiatomicParameters){};

  /**
   * @brief (Re)generate values and run-time parameters from the current raw parameters.
   *         Only needed if the parameters are modified manually.
   * @param elements a vector containing the elements constituting the molecule.
   * @param basisFunctions Whether the method just accomodate s and p basis functions (i.e. AM1, MNDO), or if it can
   *        also activate d basis functions.
   * @param hasDiatomicParameters Whether the method also has diatomic parameters (i.e. PM6).
   */
  void applyRawParameters(const Utils::ElementTypeCollection& elements);
  /*! Load the parameters from a file. */
  void readParameters(const std::string& parameterPath);
  /*! Save the parameters to a file. */
  void saveParameters(const std::string& fileName);
  /*! Initialize the method <b>after</b> the parameters have been set or loaded. */
  void initialize(const Utils::ElementTypeCollection& elements) override;

  Utils::AtomsOrbitalsIndexes getAtomsOrbitalsIndexes() const override;
  unsigned getNumberElectronsForUnchargedSpecies() const override;
  std::vector<double> getCoreCharges() const override;
  bool unrestrictedCalculationPossible() const override;

  /*! Get reference to the class for raw NDDO parameters. */
  Parameters& getRawParameters();
  /*! Get const reference to the class for raw NDDO parameters. */
  const Parameters& getRawParameters() const;

  const ElementParameters& getElementParameters();
  const ElementPairParameters& getElementPairParameters();
  const OneCenterIntegralContainer& getOneCenterIntegrals();

  BasisFunctions getBasisFunctions() const;

 private:
  ElementParameters elementParameters_;
  ElementPairParameters elementPairParameters_;
  OneCenterIntegralContainer oneCenterIntegrals_;
  Parameters rawParameters_;

  unsigned int nElectronsForUnchargedSpecies_ = 0;
  std::vector<double> coreCharges_;
  Utils::AtomsOrbitalsIndexes aoIndexes_;

  BasisFunctions basisFunctions_;
  bool hasDiatomicParameters_;
};

} // namespace nddo
} // namespace Sparrow
} // namespace Scine

#endif // SPARROW_NDDOINITIALIZER_H


text:
package com.b2international.collections;

import com.b2international.collections.deser.PrimitiveCollectionDeserializers;
import com.b2international.collections.ser.PrimitiveCollectionSerializers;
import com.fasterxml.jackson.databind.module.SimpleModule;

/**
 * @since 4.7
 */
public class PrimitiveCollectionModule extends SimpleModule {

	private static final long serialVersionUID = 19058019506637309L;

	public PrimitiveCollectionModule() {
		super("PrimitiveCollectionModule", ModuleVersion.instance.version());
	}

	@Override
	public void setupModule(SetupContext context) {
		super.setupModule(context);
		context.addSerializers(new PrimitiveCollectionSerializers());
		context.addDeserializers(new PrimitiveCollectionDeserializers());
	}

}


text:
layout: post
title: Casa linha
tags: archviz b3d 2k18
published: false
---

published


text:
// +build windows

package winkernel

import (
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/kubernetes/pkg/proxy"

	"net"
	"strings"
	"testing"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

const testHostName = "test-hostname"
const macAddress = "00-11-22-33-44-55"
const clusterCIDR = "192.168.1.0/24"
const destinationPrefix = "192.168.2.0/24"
const providerAddress = "10.0.0.3"
const guid = "123ABC"

type fakeHealthChecker struct {
	services  map[types.NamespacedName]uint16
	endpoints map[types.NamespacedName]int
}

func newFakeHealthChecker() *fakeHealthChecker {
	return &fakeHealthChecker{
		services:  map[types.NamespacedName]uint16{},
		endpoints: map[types.NamespacedName]int{},
	}
}
func (fake *fakeHealthChecker) SyncServices(newServices map[types.NamespacedName]uint16) error {
	fake.services = newServices
	return nil
}

func (fake *fakeHealthChecker) SyncEndpoints(newEndpoints map[types.NamespacedName]int) error {
	fake.endpoints = newEndpoints
	return nil
}

type fakeHNS struct{}

func newFakeHNS() *fakeHNS {
	return &fakeHNS{}
}
func (hns fakeHNS) getNetworkByName(name string) (*hnsNetworkInfo, error) {
	var remoteSubnets []*remoteSubnetInfo
	rs := &remoteSubnetInfo{
		destinationPrefix: destinationPrefix,
		isolationId:       4096,
		providerAddress:   providerAddress,
		drMacAddress:      macAddress,
	}
	remoteSubnets = append(remoteSubnets, rs)
	return &hnsNetworkInfo{
		id:            strings.ToUpper(guid),
		name:          name,
		networkType:   "Overlay",
		remoteSubnets: remoteSubnets,
	}, nil
}
func (hns fakeHNS) getEndpointByID(id string) (*endpointsInfo, error) {
	return nil, nil
}
func (hns fakeHNS) getEndpointByIpAddress(ip string, networkName string) (*endpointsInfo, error) {
	_, ipNet, _ := net.ParseCIDR(destinationPrefix)

	if ipNet.Contains(net.ParseIP(ip)) {
		return &endpointsInfo{
			ip:         ip,
			isLocal:    true,
			macAddress: macAddress,
			hnsID:      guid,
			hns:        hns,
		}, nil
	}
	return nil, nil

}
func (hns fakeHNS) createEndpoint(ep *endpointsInfo, networkName string) (*endpointsInfo, error) {
	return &endpointsInfo{
		ip:         ep.ip,
		isLocal:    ep.isLocal,
		macAddress: ep.macAddress,
		hnsID:      guid,
		hns:        hns,
	}, nil
}
func (hns fakeHNS) deleteEndpoint(hnsID string) error {
	return nil
}
func (hns fakeHNS) getLoadBalancer(endpoints []endpointsInfo, isILB bool, isDSR bool, sourceVip string, vip string, protocol uint16, internalPort uint16, externalPort uint16) (*loadBalancerInfo, error) {
	return &loadBalancerInfo{
		hnsID: guid,
	}, nil
}
func (hns fakeHNS) deleteLoadBalancer(hnsID string) error {
	return nil
}
func NewFakeProxier(syncPeriod time.Duration, minSyncPeriod time.Duration, clusterCIDR string, hostname string, nodeIP net.IP, networkType string) *Proxier {
	sourceVip := "192.168.1.2"
	hnsNetworkInfo := &hnsNetworkInfo{
		name:        "TestNetwork",
		networkType: networkType,
	}
	proxier := &Proxier{
		portsMap:         make(map[localPort]closeable),
		serviceMap:       make(proxyServiceMap),
		serviceChanges:   newServiceChangeMap(),
		endpointsMap:     make(proxyEndpointsMap),
		endpointsChanges: newEndpointsChangeMap(hostname),
		clusterCIDR:      clusterCIDR,
		hostname:         testHostName,
		nodeIP:           nodeIP,
		healthChecker:    newFakeHealthChecker(),
		network:          *hnsNetworkInfo,
		sourceVip:        sourceVip,
		hostMac:          macAddress,
		isDSR:            false,
		hns:              newFakeHNS(),
	}
	return proxier
}

func TestCreateServiceVip(t *testing.T) {
	syncPeriod := 30 * time.Second
	proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "Overlay")
	if proxier == nil {
		t.Error()
	}

	svcIP := "10.20.30.41"
	svcPort := 80
	svcNodePort := 3001
	svcExternalIPs := "50.60.70.81"
	svcPortName := proxy.ServicePortName{
		NamespacedName: makeNSN("ns1", "svc1"),
		Port:           "p80",
	}
	timeoutSeconds := v1.DefaultClientIPServiceAffinitySeconds

	makeServiceMap(proxier,
		makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
			svc.Spec.Type = "NodePort"
			svc.Spec.ClusterIP = svcIP
			svc.Spec.ExternalIPs = []string{svcExternalIPs}
			svc.Spec.SessionAffinity = v1.ServiceAffinityClientIP
			svc.Spec.SessionAffinityConfig = &v1.SessionAffinityConfig{
				ClientIP: &v1.ClientIPConfig{
					TimeoutSeconds: &timeoutSeconds,
				},
			}
			svc.Spec.Ports = []v1.ServicePort{{
				Name:     svcPortName.Port,
				Port:     int32(svcPort),
				Protocol: v1.ProtocolTCP,
				NodePort: int32(svcNodePort),
			}}
		}),
	)
	makeEndpointsMap(proxier)

	proxier.syncProxyRules()

	if proxier.serviceMap[svcPortName].remoteEndpoint == nil {
		t.Error()
	}
	if proxier.serviceMap[svcPortName].remoteEndpoint.ip != svcIP {
		t.Error()
	}
}
func TestCreateRemoteEndpointOverlay(t *testing.T) {
	syncPeriod := 30 * time.Second
	proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "Overlay")
	if proxier == nil {
		t.Error()
	}

	svcIP := "10.20.30.41"
	svcPort := 80
	svcNodePort := 3001
	svcPortName := proxy.ServicePortName{
		NamespacedName: makeNSN("ns1", "svc1"),
		Port:           "p80",
	}

	makeServiceMap(proxier,
		makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
			svc.Spec.Type = "NodePort"
			svc.Spec.ClusterIP = svcIP
			svc.Spec.Ports = []v1.ServicePort{{
				Name:     svcPortName.Port,
				Port:     int32(svcPort),
				Protocol: v1.ProtocolTCP,
				NodePort: int32(svcNodePort),
			}}
		}),
	)
	makeEndpointsMap(proxier,
		makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
			ept.Subsets = []v1.EndpointSubset{{
				Addresses: []v1.EndpointAddress{{
					IP: epIpAddressRemote,
				}},
				Ports: []v1.EndpointPort{{
					Name: svcPortName.Port,
					Port: int32(svcPort),
				}},
			}}
		}),
	)

	proxier.syncProxyRules()

	if proxier.endpointsMap[svcPortName][0].hnsID != guid {
		t.Errorf("%v does not match %v", proxier.endpointsMap[svcPortName][0].hnsID, guid)
	}
}
func TestCreateRemoteEndpointL2Bridge(t *testing.T) {
	syncPeriod := 30 * time.Second
	proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "L2Bridge")
	if proxier == nil {
		t.Error()
	}

	svcIP := "10.20.30.41"
	svcPort := 80
	svcNodePort := 3001
	svcPortName := proxy.ServicePortName{
		NamespacedName: makeNSN("ns1", "svc1"),
		Port:           "p80",
	}

	makeServiceMap(proxier,
		makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
			svc.Spec.Type = "NodePort"
			svc.Spec.ClusterIP = svcIP
			svc.Spec.Ports = []v1.ServicePort{{
				Name:     svcPortName.Port,
				Port:     int32(svcPort),
				Protocol: v1.ProtocolTCP,
				NodePort: int32(svcNodePort),
			}}
		}),
	)
	makeEndpointsMap(proxier,
		makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
			ept.Subsets = []v1.EndpointSubset{{
				Addresses: []v1.EndpointAddress{{
					IP: epIpAddressRemote,
				}},
				Ports: []v1.EndpointPort{{
					Name: svcPortName.Port,
					Port: int32(svcPort),
				}},
			}}
		}),
	)

	proxier.syncProxyRules()

	if proxier.endpointsMap[svcPortName][0].hnsID != guid {
		t.Errorf("%v does not match %v", proxier.endpointsMap[svcPortName][0].hnsID, guid)
	}
}
func TestCreateLoadBalancer(t *testing.T) {
	syncPeriod := 30 * time.Second
	proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, "testhost", net.ParseIP("10.0.0.1"), "Overlay")
	if proxier == nil {
		t.Error()
	}

	svcIP := "10.20.30.41"
	svcPort := 80
	svcNodePort := 3001
	svcPortName := proxy.ServicePortName{
		NamespacedName: makeNSN("ns1", "svc1"),
		Port:           "p80",
	}

	makeServiceMap(proxier,
		makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
			svc.Spec.Type = "NodePort"
			svc.Spec.ClusterIP = svcIP
			svc.Spec.Ports = []v1.ServicePort{{
				Name:     svcPortName.Port,
				Port:     int32(svcPort),
				Protocol: v1.ProtocolTCP,
				NodePort: int32(svcNodePort),
			}}
		}),
	)
	makeEndpointsMap(proxier,
		makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
			ept.Subsets = []v1.EndpointSubset{{
				Addresses: []v1.EndpointAddress{{
					IP: epIpAddressRemote,
				}},
				Ports: []v1.EndpointPort{{
					Name: svcPortName.Port,
					Port: int32(svcPort),
				}},
			}}
		}),
	)

	proxier.syncProxyRules()

	if proxier.serviceMap[svcPortName].hnsID != guid {
		t.Errorf("%v does not match %v", proxier.serviceMap[svcPortName].hnsID, guid)
	}
}
func makeNSN(namespace, name string) types.NamespacedName {
	return types.NamespacedName{Namespace: namespace, Name: name}
}
func makeServiceMap(proxier *Proxier, allServices ...*v1.Service) {
	for i := range allServices {
		proxier.OnServiceAdd(allServices[i])
	}

	proxier.mu.Lock()
	defer proxier.mu.Unlock()
	proxier.servicesSynced = true
}
func makeTestService(namespace, name string, svcFunc func(*v1.Service)) *v1.Service {
	svc := &v1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:        name,
			Namespace:   namespace,
			Annotations: map[string]string{},
		},
		Spec:   v1.ServiceSpec{},
		Status: v1.ServiceStatus{},
	}
	svcFunc(svc)
	return svc
}

func makeEndpointsMap(proxier *Proxier, allEndpoints ...*v1.Endpoints) {
	for i := range allEndpoints {
		proxier.OnEndpointsAdd(allEndpoints[i])
	}

	proxier.mu.Lock()
	defer proxier.mu.Unlock()
	proxier.endpointsSynced = true
}

func makeTestEndpoints(namespace, name string, eptFunc func(*v1.Endpoints)) *v1.Endpoints {
	ept := &v1.Endpoints{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
		},
	}
	eptFunc(ept)
	return ept
}


text:
package blue.lapis.pore.converter.vector;

import blue.lapis.pore.impl.PoreWorld;

import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3f;
import com.flowpowered.math.vector.Vector3i;
import org.bukkit.Location;
import org.spongepowered.api.world.World;

public class LocationConverter {

    public static Location apply(Location loc, org.spongepowered.api.world.Location spongeLocation) {
        loc.setWorld(PoreWorld.of(spongeLocation.getExtent()));
        loc.setX(spongeLocation.getPosition().getX());
        loc.setY(spongeLocation.getPosition().getY());
        loc.setZ(spongeLocation.getPosition().getZ());
        return loc;
    }

    public static Location of(org.spongepowered.api.world.Location location) {
        return new Location(PoreWorld.of(location.getExtent()), location.getPosition().getX(),
                location.getPosition().getY(), location.getPosition().getZ());
    }

    public static org.spongepowered.api.world.Location of(Location location) {
        return new org.spongepowered.api.world.Location(((PoreWorld) location.getWorld()).getHandle(),
                VectorConverter.create3d(location));
    }

    public static Location fromVector3i(World world, Vector3i locationVector) {
        return new Location(PoreWorld.of(world), locationVector.getX(), locationVector.getY(),
                locationVector.getZ());
    }

    public static Location fromVector3d(World world, Vector3d locationVector) {
        return new Location(PoreWorld.of(world), locationVector.getX(), locationVector.getY(),
                locationVector.getZ());
    }

    public static Location fromVector3f(World world, Vector3f locationVector) {
        return new Location(PoreWorld.of(world), locationVector.getX(), locationVector.getY(),
                locationVector.getZ());
    }

    //TODO: should EulerDirection be used instead of Vector3f?
    public static Location fromVector3iWithRotation(World world, Vector3i locationVector,
            Vector3f rotationVector) {
        return new Location(PoreWorld.of(world), locationVector.getX(), locationVector.getY(),
                locationVector.getZ(),
                rotationVector.getY(), rotationVector.getX());
    }

    public static Location fromVector3dwithRotation(World world, Vector3d locationVector,
            Vector3f rotationVector) {
        return new Location(PoreWorld.of(world), locationVector.getX(), locationVector.getY(),
                locationVector.getZ(),
                rotationVector.getY(), rotationVector.getX());
    }

    public static Location fromVector3fwithRotation(World world, Vector3f locationVector,
            Vector3f rotationVector) {
        return new Location(PoreWorld.of(world), locationVector.getX(), locationVector.getY(),
                locationVector.getZ(),
                rotationVector.getY(), rotationVector.getX());
    }

}


text:
@interface NSString (AcceptExtras)

-(NSData*)convertHexToData;
- (NSString *)stringByRemovingControlCharacters;
-(NSInteger)instr:(NSString*)substring;
-(NSString *) leftPadStringWithPadding:(NSString *)padding;
-(NSString *) leftPadStringToLength:(int)toLength;
- (NSString*)stringByEncodingHTMLEntities ;
- (BOOL)contains:(NSString*)string;

+ (NSString*)hexFromStr:(NSString*)str;
+ (NSString *)hexToString:(NSString *)string;
+(NSString *) hexToASCII:(NSString *)hexString;
+ (NSString *)getMaskedPANForReceipt:(NSString *)PAN;

-(NSString *)wrapByLength:(NSUInteger)length;
@end