text:
<meta charset="utf-8">
(#) Creating a MutableState object with a mutable collection type

!!! WARNING: Creating a MutableState object with a mutable collection type
   This is a warning.

Id
:   `MutableCollectionMutableState`
Summary
:   Creating a MutableState object with a mutable collection type
Severity
:   Warning
Category
:   Correctness
Platform
:   Any
Vendor
:   Jetpack Compose
Identifier
:   androidx.compose.runtime
Feedback
:   https://issuetracker.google.com/issues/new?component=612128
Affects
:   Kotlin and Java files and test sources
Editing
:   This check runs on the fly in the IDE editor
Implementation
:   [Source Code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/compose/runtime/runtime-lint/src/main/java/androidx/compose/runtime/lint/MutableCollectionMutableStateDetector.kt)
Tests
:   [Source Code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/compose/runtime/runtime-lint/src/test/java/androidx/compose/runtime/lint/MutableCollectionMutableStateDetectorTest.kt)
Copyright Year
:   2021

Writes to mutable collections inside a MutableState will not cause a
recomposition - only writes to the MutableState itself will. In most
cases you should either use a read-only collection (such as List or Map)
and assign a new instance to the MutableState when your data changes, or
you can use an snapshot-backed collection such as SnapshotStateList or
SnapshotStateMap which will correctly cause a recomposition when their
contents are modified.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
src/test/test.kt:12:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val listProperty = mutableStateOf(list)
                       --------------

src/test/test.kt:14:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val setFunction = mutableStateOf(mutableSetOf(1))
                      --------------

src/test/test.kt:15:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val setProperty = mutableStateOf(set)
                      --------------

src/test/test.kt:17:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val mapFunction = mutableStateOf(mutableMapOf(1 to 1))
                      --------------

src/test/test.kt:18:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val mapProperty = mutableStateOf(map)
                      --------------

src/test/test.kt:20:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val collectionProperty = mutableStateOf(collection)
                             --------------

src/test/test.kt:28:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val listParameter = mutableStateOf(listParam)
                        --------------

src/test/test.kt:29:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val setParameter = mutableStateOf(setParam)
                       --------------

src/test/test.kt:30:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val mapParameter = mutableStateOf(mapParam)
                       --------------

src/test/test.kt:31:Warning: Creating a MutableState object with a
mutable collection type [MutableCollectionMutableState]

    val collectionProperty = mutableStateOf(collectionParam)
                             --------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`src/test/test.kt`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~kotlin linenumbers
package test

import androidx.compose.runtime.*

val list = mutableListOf(1)
val set = mutableSetOf(1)
val map = mutableMapOf(1 to 1)
val collection: MutableCollection<Int> = list

val listFunction = mutableStateOf(mutableListOf(1))
val listProperty = mutableStateOf(list)

val setFunction = mutableStateOf(mutableSetOf(1))
val setProperty = mutableStateOf(set)

val mapFunction = mutableStateOf(mutableMapOf(1 to 1))
val mapProperty = mutableStateOf(map)

val collectionProperty = mutableStateOf(collection)

fun test(
    listParam: MutableList<Int>,
    setParam: MutableSet<Int>,
    mapParam: MutableMap<Int, Int>,
    collectionParam: MutableCollection<Int>
) {
    val listParameter = mutableStateOf(listParam)
    val setParameter = mutableStateOf(setParam)
    val mapParameter = mutableStateOf(mapParam)
    val collectionProperty = mutableStateOf(collectionParam)
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/compose/runtime/runtime-lint/src/test/java/androidx/compose/runtime/lint/MutableCollectionMutableStateDetectorTest.kt)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `MutableCollectionMutableStateDetector.mutableCollection_stdlib`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=612128.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression annotation like this on the enclosing
  element:

  ```kt
  // Kotlin
  @Suppress("MutableCollectionMutableState")
  fun method() {
     mutableStateOf(...)
  }
  ```

  or

  ```java
  // Java
  @SuppressWarnings("MutableCollectionMutableState")
  void method() {
     mutableStateOf(...);
  }
  ```

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection MutableCollectionMutableState
  problematicStatement()
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <lint>
      <issue id="MutableCollectionMutableState" severity="ignore" />
  </lint>
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'MutableCollectionMutableState'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore MutableCollectionMutableState ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>


text:
function relist!{T<:Real}(m::Model, values::AbstractArray{T},
                 nodekeys::Vector{Symbol}, transform::Bool=false)
  msg = string("relist!{T<:Real}(m::Model, values::AbstractArray{T}, ",
               "nodekeys::Vector{Symbol}, transform::Bool=false) is deprecated")
  Base.depwarn(msg, :relist!)

  x = relist(m, values, nodekeys, transform)
  for key in nodekeys
    m[key].value = x[key]
  end
  update!(m)
end

export tune

@deprecate tune gettune

## Deprecated at 0.9.0

export simulate!

@deprecate simulate! sample!

## Legacy Sampler Code

export amm!, amwg!, bhmc!, bmc3!, bmg!, dgs!, hmc!, mala!, nuts!, rwm!, slice!,
       SliceVariate, slicesimplex!

depwarn2(old::AbstractString, new::AbstractString, funcsym::Symbol) =
  Base.depwarn("$old is deprecated, use $new instead.", funcsym)

depwarnsample(old::AbstractString) = depwarn2(old, "sample!(v)", symbol(old))

## AMM

function AMMTune(x::Vector)
  depwarn2("AMMVariate(x)", "AMMVariate(x, Sigma, logf)", :AMMVariate)
  n = length(x)
  AMMTune(x, fill(NaN, n, n))
end

function amm!(v::AMMVariate, SigmaF::Cholesky{Float64}, logf::Function;
              adapt::Bool=true)
  depwarnsample("amm!")
  if v.tune.m == 0
    v.tune.SigmaL = SigmaF[:L]
  end
  sample!(v, logf, adapt=adapt)
end

#AMWG

function AMWGTune(x::Vector)
  depwarn2("AMWGVariate(x)", "AMWGVariate(x, sigma, logf)", :AMWGVariate)
  AMWGTune(x, NaN)
end

function amwg!{T<:Real}(v::AMWGVariate, sigma::Vector{T}, logf::Function;
                        adapt::Bool=true, batchsize::Integer=50,
                        target::Real=0.44)
  depwarnsample("amwg!")
  if v.tune.m == 0
    v.tune.sigma = adapt ? copy(sigma) : sigma
  end
  v.tune.batchsize = batchsize
  v.tune.target = target
  sample!(v, logf, adapt=adapt)
end

## BHMC

function BHMCTune(x)
  depwarn2("BHMCVariate(x)", "BHMCVariate(x, traveltime, logf)", :BHMCVariate)
  BHMCTune(x, NaN)
end

function bhmc!(v::BHMCVariate, traveltime::Real, logf::Function)
  depwarnsample("bhmc!")
  v.tune.traveltime = traveltime
  sample!(v, logf)
end

## BHMC3

function BMC3(params::ElementOrVector{Symbol}, indexset::Vector{Vector{Int}})
  depwarn2("BMC3(params, indexset)", "BMC3(params)", :BMC3)
  samplerfx = function(model::Model, block::Integer)
    block = SamplingBlock(model, block)
    v = SamplerVariate(block, 0)
    bmc3!(v, indexset, x -> logpdf!(block, x))
    relist(block, v)
  end
  Sampler(params, samplerfx, BMC3Tune())
end

function bmc3!(v::BMC3Variate, logf::Function; k::Integer=1)
  depwarnsample("bmc3!")
  v.tune.k = k
  sample!(v, logf)
end

function bmc3!(v::BMC3Variate, indexset::Vector{Vector{Int}}, logf::Function)
  depwarnsample("bmc3!")
  v.tune.indexset = indexset
  x = v[:]
  idx = rand(v.tune.indexset)
  x[idx] = 1.0 - v[idx]
  if rand() < exp(logf(x) - logf(v.value))
    v[:] = x
  end
  v
end

## BMG

function bmg!(v::BMGVariate, logf::Function; k::Integer=1)
  depwarnsample("bmg!")
  k <= length(v) || throw(ArgumentError("k is greater than length(v)"))
  v.tune.k = k
  sample!(v, logf)
end

## DGS

function dgs!{T<:Real}(v::DGSVariate, support::Matrix{T}, logf::Function)
  depwarnsample("dgs!")
  v.tune.support = support
  sample!(v, x -> exp(logf(x)))
end

function dgs!{T<:Real}(v::DGSVariate, support::Matrix{T},
                       probs::Vector{Float64})
  depwarnsample("dgs!")
  v.tune.support = support
  sample!(v, probs)
end

## HMC

function HMCTune(x)
  depwarn2("HMCVariate(x)",
           "HMCVariate(x, epsilon, L, logfgrad) or" *
           " HMCVariate(x, epsilon, L, Sigma, logfgrad)",
           :HMCVariate)
  HMCTune(x, NaN, 0)
end

function hmc!(v::HMCVariate, epsilon::Real, L::Integer, logfgrad::Function)
  depwarnsample("hmc!")
  v.tune.epsilon = epsilon
  v.tune.L = L
  v.tune.SigmaL = I
  sample!(v, logfgrad)
end

function hmc!(v::HMCVariate, epsilon::Real, L::Integer,
              SigmaF::Cholesky{Float64}, logfgrad::Function)
  depwarnsample("hmc!")
  v.tune.epsilon = epsilon
  v.tune.L = L
  v.tune.SigmaL = SigmaF[:L]
  sample!(v, logfgrad)
end

## MALA

function MALATune(x)
  depwarn2("MALAVariate(x)",
           "MALAVariate(x, epsilon, logfgrad) or" *
           " MALAVariate(x, epsilon, Sigma, logfgrad)",
           :MALAVariate)
  MALATune(x, NaN)
end

function mala!(v::MALAVariate, scale::Real, logfgrad::Function)
  depwarnsample("mala!")
  v.tune.epsilon = scale
  v.tune.SigmaL = I
  sample!(v, logfgrad)
end

function mala!(v::MALAVariate, scale::Real, SigmaF::Cholesky{Float64},
               logfgrad::Function)
  depwarnsample("mala!")
  v.tune.epsilon = scale
  v.tune.SigmaL = SigmaF[:L]
  sample!(v, logfgrad)
end

## NUTS

function NUTSTune(x)
  depwarn2("NUTSVariate(x)",
           "NUTSVariate(x, epsilon, logfgrad) or NUTSVariate(x, logfgrad)",
           :NUTSVariate)
  NUTSTune(x, NaN)
end

function nuts!(v::NUTSVariate, epsilon::Real, logfgrad::Function;
               adapt::Bool=false, target::Real=0.6)
  depwarnsample("nuts!")
  if v.tune.m == 0
    v.tune.epsilon = epsilon
  end
  v.tune.target = target
  sample!(v, logfgrad, adapt=adapt)
end

## RWM

function RWMTune(x)
  depwarn2("RWMVariate(x)", "RWMVariate(x, scale, logf)", :RWMVariate)
  RWMTune(x, NaN)
end

function rwm!{T<:Real}(v::RWMVariate, scale::ElementOrVector{T},
                       logf::Function; proposal::SymDistributionType=Normal)
  depwarnsample("rwm!")
  v.tune.scale = scale
  v.tune.proposal = proposal
  sample!(v, logf)
end

## Slice

function SliceVariate{T<:Real}(x::AbstractVector{T})
  depwarn2("SliceVariate(x)",
           "SliceUnivariate(x, width, logf) or" *
           " SliceMultivariate(x, width, logf)",
           :SliceVariate)
  SamplerVariate{SliceTune{SliceForm}}(x, NaN)
end

function slice!{T<:Real}(v::SamplerVariate{SliceTune{SliceForm}},
                         width::ElementOrVector{T}, logf::Function,
                         stype::Symbol=:multivar)
  depwarnsample("slice!")
  v.tune.width = width
  S = stype == :univar   ? Univariate :
      stype == :multivar ? Multivariate :
        throw(ArgumentError("unsupported slice sampler type $stype"))
  sample!(SamplerVariate{SliceTune{S}}(v, width), logf)
  v
end

## SliceSimplex

function slicesimplex!(v::SliceSimplexVariate, logf::Function; scale::Real=1.0)
  depwarnsample("slicesimplex!")
  0 < scale <= 1 || throw(ArgumentError("scale is not in (0, 1]"))
  v.tune.scale = scale
  sample!(v, logf)
end

redpajama_set_name: RedPajamaGithub


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

public class BuildingGenerator : MonoBehaviour
{
    [SerializeField]
    [Tooltip("Width of streets")]
    private float streetWidth;

    [SerializeField]
    [Tooltip("Distance between the control points placeing the buildings.")]
    private float distanceBetweenBuildingCenters;

    [SerializeField]
    [Tooltip("Amount of jitter in building placement.")]
    [Range(0, 1)]
    private float positionJitter;

    [SerializeField]
    [Tooltip("Curve to determine the height distribution of the builings. \n X-axis determines distance from center from 1 to 0.")]
    private AnimationCurve distributionCurve;

    [SerializeField]
    [Tooltip("Amount of jitter in building heights.")]
    [Range(0, 1)]
    private float heightJitter;

    [SerializeField]
    [Tooltip("Scale applied to generated buildings.")]
    private Vector3 buildingScale;

    [SerializeField]
    [Tooltip("The maximum number of times a building is attempted to be placed before ending placemet.")]
    private int maxPlacementTries;

    [SerializeField]
    [Tooltip("The template for the building to place at the center of the city.")]
    private GameObject cityCenterBuilding;

    [SerializeField]
    [Tooltip("The instance of the tutorial building.")]
    private GameObject tutorialBuilding;

    private ProceduralBuildingCreator buildingCreator;

    /// <summary>
    /// Template for the building to place at the center of the city.
    /// </summary>
    public GameObject CityCenterBuilding
    {
        get
        {
            return cityCenterBuilding;
        }
    }

    /// <summary>
    /// Generates a building.
    /// </summary>
    /// <param name="seed">The procedutral generation seed</param>
    /// <param name="block">The block in which the building is to be generated.</param>
    /// <param name="configuration">The building configuration for this distruct.</param>
    /// <param name="cityBounds">The bounds of the city.</param>
    /// <param name="cityCenter">The center of the city.</param>
    /// <param name="weeniePosition">The location of the Weenie Building in the district.</param>
    /// <returns></returns>
    public Building[] Generate (int seed, Block block, DistrictConfiguration configuration, Bounds cityBounds, Vector3 cityCenter, Vector2 weeniePosition)
    {
        // Set any static variables for procedural buildings
        ProceduralBuilding.Generator = GetComponent<ProceduralBuildingCreator>();
        ProceduralBuilding.BuildingScale = buildingScale;

        List<Building> buildings = new List<Building>();

        // set up pre-calculated variables
        float maxDistance = Mathf.Max(cityBounds.size.x, cityBounds.size.y);
        int floorRange = configuration.MaxFloors - configuration.MinFloors;

        Vector3 min = block.BoundingBox.min;
        Vector3 max = block.BoundingBox.max;
        Vector3 size = block.BoundingBox.size;

        float minRows = min.x + streetWidth;
        float minCols = min.z + streetWidth;

        float maxRows = max.x - streetWidth;
        float maxCols = max.z - streetWidth;

		float root2 = Mathf.Sqrt (2);

        // create a grid of points inside the bounds along the y-axis
        for (float i = minRows; i < Mathf.FloorToInt(maxRows); i += distanceBetweenBuildingCenters)
        {
            for (float j = minCols; j < Mathf.FloorToInt(maxCols); j += distanceBetweenBuildingCenters)
            {
                // Offset this value by the jitter amount
                float xOffset = Random.Range(0, positionJitter) * distanceBetweenBuildingCenters;
                float yOffset = Random.Range(0, positionJitter) * distanceBetweenBuildingCenters;

                Vector2 point = new Vector2(i + xOffset, j + yOffset);

                // Check if control point is within the actual polygon
                if (block.ContainsPoint(point)) // TODO: And doesn't instersect with other pre-built buildings for sure, now we are just reasonably sure
                {
                    Vector3 position = new Vector3(point.x, 0, point.y);

                    Building building;

                    // If this is a Weenie building, use that creator, otherwise procedurally generate a building.
					if (block.ContainsPoint(weeniePosition) && Vector2.Distance(point, weeniePosition) < distanceBetweenBuildingCenters * root2)
                    {
                        building = new TemplateBuilding(this.gameObject.transform, position, configuration.WeenieBuildingTemplate);
                        building.Load();
                    }
                    else
                    {
                        // Determine number of floors based on gaussian distribution
                        float ratioFromCenter = 1f - Vector3.Distance(position, cityCenter) / maxDistance;
                        float buildingHeight = distributionCurve.Evaluate(ratioFromCenter) + Random.Range(0, heightJitter);
                        int numberOfFloors = Mathf.FloorToInt(buildingHeight * floorRange) + configuration.MinFloors;

                        building = new ProceduralBuilding(this.gameObject.transform, position, System.Guid.NewGuid().GetHashCode(), numberOfFloors, configuration);
                        building.Load();
                    }

                    // Add the building
                    buildings.Add(building);
                }
            }
        }

        return buildings.ToArray();
    }

    /// <summary>
    /// Move the tutorial building and places the player character.
    ///</summary>
    /// <param name="location">Location to place the building.</param>
    public Building PlaceTutorialBuilding (Vector3 location)
    {
        // Grab the location of the player relative to the tutorial building
        Vector3 relativePlayerLocation = Game.Player.WorldPosition - tutorialBuilding.transform.position;

        // Move the tutorial building
        tutorialBuilding.transform.position = location;

        // Place the player back on the turoial building
        Game.Player.WorldPosition = tutorialBuilding.transform.position + relativePlayerLocation;

        return new TemplateBuilding(this.gameObject.transform, location, tutorialBuilding);
    }
}


text:
import errno
import os
import stat

from os_brick.remotefs import remotefs as remotefs_brick
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import units

from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder.image import image_utils
from cinder.openstack.common import fileutils
from cinder import utils
from cinder.volume import driver
from cinder.volume.drivers import remotefs as remotefs_drv

LOG = logging.getLogger(__name__)

volume_opts = [
    cfg.StrOpt('glusterfs_shares_config',
               default='/etc/cinder/glusterfs_shares',
               help='File with the list of available gluster shares'),
    cfg.BoolOpt('glusterfs_sparsed_volumes',
                default=True,
                help=('Create volumes as sparsed files which take no space.'
                      'If set to False volume is created as regular file.'
                      'In such case volume creation takes a lot of time.')),
    cfg.BoolOpt('glusterfs_qcow2_volumes',
                default=False,
                help=('Create volumes as QCOW2 files rather than raw files.')),
    cfg.StrOpt('glusterfs_mount_point_base',
               default='$state_path/mnt',
               help='Base dir containing mount points for gluster shares.'),
]

CONF = cfg.CONF
CONF.register_opts(volume_opts)

class GlusterfsDriver(remotefs_drv.RemoteFSSnapDriver, driver.CloneableVD,
                      driver.ExtendVD):
    """Gluster based cinder driver.

    Creates file on Gluster share for using it as block device on hypervisor.

    Operations such as create/delete/extend volume/snapshot use locking on a
    per-process basis to prevent multiple threads from modifying qcow2 chains
    or the snapshot .info file simultaneously.
    """

    driver_volume_type = 'glusterfs'
    driver_prefix = 'glusterfs'
    volume_backend_name = 'GlusterFS'
    VERSION = '1.3.0'

    def __init__(self, execute=processutils.execute, *args, **kwargs):
        self._remotefsclient = None
        super(GlusterfsDriver, self).__init__(*args, **kwargs)
        self.configuration.append_config_values(volume_opts)
        root_helper = utils.get_root_helper()
        self.base = getattr(self.configuration,
                            'glusterfs_mount_point_base',
                            CONF.glusterfs_mount_point_base)
        self._remotefsclient = remotefs_brick.RemoteFsClient(
            'glusterfs', root_helper, execute,
            glusterfs_mount_point_base=self.base)

    def set_execute(self, execute):
        super(GlusterfsDriver, self).set_execute(execute)
        if self._remotefsclient:
            self._remotefsclient.set_execute(execute)

    def do_setup(self, context):
        """Any initialization the volume driver does while starting."""
        super(GlusterfsDriver, self).do_setup(context)

        config = self.configuration.glusterfs_shares_config
        if not config:
            msg = (_("There's no Gluster config file configured (%s)") %
                   'glusterfs_shares_config')
            LOG.warning(msg)
            raise exception.GlusterfsException(msg)
        if not os.path.exists(config):
            msg = (_("Gluster config file at %(config)s doesn't exist") %
                   {'config': config})
            LOG.warning(msg)
            raise exception.GlusterfsException(msg)

        self.shares = {}

        try:
            self._execute('mount.glusterfs', check_exit_code=False)
        except OSError as exc:
            if exc.errno == errno.ENOENT:
                raise exception.GlusterfsException(
                    _('mount.glusterfs is not installed'))
            else:
                raise

        self._refresh_mounts()

    def _unmount_shares(self):
        self._load_shares_config(self.configuration.glusterfs_shares_config)
        for share in self.shares.keys():
            try:
                self._do_umount(True, share)
            except Exception as exc:
                LOG.warning(_LW('Exception during unmounting %s'), exc)

    def _do_umount(self, ignore_not_mounted, share):
        mount_path = self._get_mount_point_for_share(share)
        command = ['umount', mount_path]
        try:
            self._execute(*command, run_as_root=True)
        except processutils.ProcessExecutionError as exc:
            if ignore_not_mounted and 'not mounted' in exc.stderr:
                LOG.info(_LI("%s is already umounted"), share)
            else:
                LOG.error(_LE("Failed to umount %(share)s, reason=%(stderr)s"),
                          {'share': share, 'stderr': exc.stderr})
                raise

    def _refresh_mounts(self):
        try:
            self._unmount_shares()
        except processutils.ProcessExecutionError as exc:
            if 'target is busy' in exc.stderr:
                LOG.warning(_LW("Failed to refresh mounts, reason=%s"),
                            exc.stderr)
            else:
                raise

        self._ensure_shares_mounted()

    def _qemu_img_info(self, path, volume_name):
        return super(GlusterfsDriver, self)._qemu_img_info_base(
            path, volume_name, self.configuration.glusterfs_mount_point_base)

    def check_for_setup_error(self):
        """Just to override parent behavior."""
        pass

    def _local_volume_dir(self, volume):
        hashed = self._get_hash_str(volume['provider_location'])
        path = '%s/%s' % (self.configuration.glusterfs_mount_point_base,
                          hashed)
        return path

    def _update_volume_stats(self):
        """Retrieve stats info from volume group."""
        super(GlusterfsDriver, self)._update_volume_stats()
        data = self._stats

        global_capacity = data['total_capacity_gb']
        global_free = data['free_capacity_gb']

        thin_enabled = (self.configuration.glusterfs_sparsed_volumes or
                        self.configuration.glusterfs_qcow2_volumes)
        if thin_enabled:
            provisioned_capacity = self._get_provisioned_capacity()
        else:
            provisioned_capacity = round(global_capacity - global_free, 2)

        data['provisioned_capacity_gb'] = provisioned_capacity
        data['max_over_subscription_ratio'] = (
            self.configuration.max_over_subscription_ratio)
        data['thin_provisioning_support'] = thin_enabled
        data['thick_provisioning_support'] = not thin_enabled

        self._stats = data

    @remotefs_drv.locked_volume_id_operation
    def create_volume(self, volume):
        """Creates a volume."""

        self._ensure_shares_mounted()

        volume['provider_location'] = self._find_share(volume['size'])

        LOG.info(_LI('casted to %s'), volume['provider_location'])

        self._do_create_volume(volume)

        return {'provider_location': volume['provider_location']}

    def _copy_volume_from_snapshot(self, snapshot, volume, volume_size):
        """Copy data from snapshot to destination volume.

        This is done with a qemu-img convert to raw/qcow2 from the snapshot
        qcow2.
        """

        LOG.debug("snapshot: %(snap)s, volume: %(vol)s, "
                  "volume_size: %(size)s",
                  {'snap': snapshot['id'],
                   'vol': volume['id'],
                   'size': volume_size})

        info_path = self._local_path_volume_info(snapshot['volume'])
        snap_info = self._read_info_file(info_path)
        vol_path = self._local_volume_dir(snapshot['volume'])
        forward_file = snap_info[snapshot['id']]
        forward_path = os.path.join(vol_path, forward_file)

        # Find the file which backs this file, which represents the point
        # when this snapshot was created.
        img_info = self._qemu_img_info(forward_path,
                                       snapshot['volume']['name'])
        path_to_snap_img = os.path.join(vol_path, img_info.backing_file)

        path_to_new_vol = self._local_path_volume(volume)

        LOG.debug("will copy from snapshot at %s", path_to_snap_img)

        if self.configuration.glusterfs_qcow2_volumes:
            out_format = 'qcow2'
        else:
            out_format = 'raw'

        image_utils.convert_image(path_to_snap_img,
                                  path_to_new_vol,
                                  out_format)

        self._set_rw_permissions_for_all(path_to_new_vol)

    @remotefs_drv.locked_volume_id_operation
    def delete_volume(self, volume):
        """Deletes a logical volume."""

        if not volume['provider_location']:
            LOG.warning(_LW('Volume %s does not have '
                            'provider_location specified, '
                            'skipping'), volume['name'])
            return

        self._ensure_share_mounted(volume['provider_location'])

        volume_dir = self._local_volume_dir(volume)
        mounted_path = os.path.join(volume_dir,
                                    self.get_active_image_from_info(volume))

        self._execute('rm', '-f', mounted_path, run_as_root=True)

        # If an exception (e.g. timeout) occurred during delete_snapshot, the
        # base volume may linger around, so just delete it if it exists
        base_volume_path = self._local_path_volume(volume)
        fileutils.delete_if_exists(base_volume_path)

        info_path = self._local_path_volume_info(volume)
        fileutils.delete_if_exists(info_path)

    def _get_matching_backing_file(self, backing_chain, snapshot_file):
        return next(f for f in backing_chain
                    if f.get('backing-filename', '') == snapshot_file)

    def ensure_export(self, ctx, volume):
        """Synchronously recreates an export for a logical volume."""

        self._ensure_share_mounted(volume['provider_location'])

    def create_export(self, ctx, volume):
        """Exports the volume."""
        pass

    def remove_export(self, ctx, volume):
        """Removes an export for a logical volume."""

        pass

    def validate_connector(self, connector):
        pass

    @remotefs_drv.locked_volume_id_operation
    def initialize_connection(self, volume, connector):
        """Allow connection to connector and return connection info."""

        # Find active qcow2 file
        active_file = self.get_active_image_from_info(volume)
        path = '%s/%s/%s' % (self.configuration.glusterfs_mount_point_base,
                             self._get_hash_str(volume['provider_location']),
                             active_file)

        data = {'export': volume['provider_location'],
                'name': active_file}
        if volume['provider_location'] in self.shares:
            data['options'] = self.shares[volume['provider_location']]

        # Test file for raw vs. qcow2 format
        info = self._qemu_img_info(path, volume['name'])
        data['format'] = info.file_format
        if data['format'] not in ['raw', 'qcow2']:
            msg = _('%s must be a valid raw or qcow2 image.') % path
            raise exception.InvalidVolume(msg)

        return {
            'driver_volume_type': 'glusterfs',
            'data': data,
            'mount_point_base': self._get_mount_point_base()
        }

    def terminate_connection(self, volume, connector, **kwargs):
        """Disallow connection from connector."""
        pass

    @remotefs_drv.locked_volume_id_operation
    def extend_volume(self, volume, size_gb):
        volume_path = self.local_path(volume)

        info = self._qemu_img_info(volume_path, volume['name'])
        backing_fmt = info.file_format

        if backing_fmt not in ['raw', 'qcow2']:
            msg = _('Unrecognized backing format: %s')
            raise exception.InvalidVolume(msg % backing_fmt)

        # qemu-img can resize both raw and qcow2 files
        image_utils.resize_image(volume_path, size_gb)

    def _do_create_volume(self, volume):
        """Create a volume on given glusterfs_share.

        :param volume: volume reference
        """

        volume_path = self.local_path(volume)
        volume_size = volume['size']

        LOG.debug("creating new volume at %s", volume_path)

        if os.path.exists(volume_path):
            msg = _('file already exists at %s') % volume_path
            LOG.error(msg)
            raise exception.InvalidVolume(reason=msg)

        if self.configuration.glusterfs_qcow2_volumes:
            self._create_qcow2_file(volume_path, volume_size)
        else:
            if self.configuration.glusterfs_sparsed_volumes:
                self._create_sparsed_file(volume_path, volume_size)
            else:
                self._create_regular_file(volume_path, volume_size)

        self._set_rw_permissions_for_all(volume_path)

    def _ensure_shares_mounted(self):
        """Mount all configured GlusterFS shares."""

        self._mounted_shares = []

        self._load_shares_config(self.configuration.glusterfs_shares_config)

        for share in self.shares.keys():
            try:
                self._ensure_share_mounted(share)
                self._mounted_shares.append(share)
            except Exception as exc:
                LOG.error(_LE('Exception during mounting %s'), exc)

        LOG.debug('Available shares: %s', self._mounted_shares)

    def _ensure_share_mounted(self, glusterfs_share):
        """Mount GlusterFS share.

        :param glusterfs_share: string
        """
        mount_path = self._get_mount_point_for_share(glusterfs_share)
        self._mount_glusterfs(glusterfs_share)

        # Ensure we can write to this share
        group_id = os.getegid()
        current_group_id = utils.get_file_gid(mount_path)
        current_mode = utils.get_file_mode(mount_path)

        if group_id != current_group_id:
            cmd = ['chgrp', group_id, mount_path]
            self._execute(*cmd, run_as_root=True)

        if not (current_mode & stat.S_IWGRP):
            cmd = ['chmod', 'g+w', mount_path]
            self._execute(*cmd, run_as_root=True)

        self._ensure_share_writable(mount_path)

    def _find_share(self, volume_size_for):
        """Choose GlusterFS share among available ones for given volume size.

        Current implementation looks for greatest capacity.
        :param volume_size_for: int size in GB
        """

        if not self._mounted_shares:
            raise exception.GlusterfsNoSharesMounted()

        greatest_size = 0
        greatest_share = None

        for glusterfs_share in self._mounted_shares:
            capacity = self._get_available_capacity(glusterfs_share)[0]
            if capacity > greatest_size:
                greatest_share = glusterfs_share
                greatest_size = capacity

        if volume_size_for * units.Gi > greatest_size:
            raise exception.GlusterfsNoSuitableShareFound(
                volume_size=volume_size_for)
        return greatest_share

    def _mount_glusterfs(self, glusterfs_share):
        """Mount GlusterFS share to mount path."""
        mnt_flags = []
        if self.shares.get(glusterfs_share) is not None:
            mnt_flags = self.shares[glusterfs_share].split()
        try:
            self._remotefsclient.mount(glusterfs_share, mnt_flags)
        except processutils.ProcessExecutionError:
            LOG.error(_LE("Mount failure for %(share)s."),
                      {'share': glusterfs_share})
            raise

    def backup_volume(self, context, backup, backup_service):
        """Create a new backup from an existing volume.

        Allow a backup to occur only if no snapshots exist.
        Check both Cinder and the file on-disk.  The latter is only
        a safety mechanism to prevent further damage if the snapshot
        information is already inconsistent.
        """

        snapshots = self.db.snapshot_get_all_for_volume(context,
                                                        backup['volume_id'])
        snap_error_msg = _('Backup is not supported for GlusterFS '
                           'volumes with snapshots.')
        if len(snapshots) > 0:
            raise exception.InvalidVolume(snap_error_msg)

        volume = self.db.volume_get(context, backup['volume_id'])

        volume_dir = self._local_volume_dir(volume)
        active_file_path = os.path.join(
            volume_dir,
            self.get_active_image_from_info(volume))

        info = self._qemu_img_info(active_file_path, volume['name'])

        if info.backing_file is not None:
            LOG.error(_LE('No snapshots found in database, but %(path)s has '
                          'backing file %(backing_file)s!'),
                      {'path': active_file_path,
                       'backing_file': info.backing_file})
            raise exception.InvalidVolume(snap_error_msg)

        if info.file_format != 'raw':
            msg = _('Backup is only supported for raw-formatted '
                    'GlusterFS volumes.')
            raise exception.InvalidVolume(msg)

        return super(GlusterfsDriver, self).backup_volume(
            context, backup, backup_service)


text:
class GameObject;
class aiNode;
class aiScene;

struct Mesh
{
	const char* name_mesh = nullptr;

	//--Vertices
	uint id_vertices = 0;
	uint num_vertices = 0;
	float* vertices = nullptr;

	//-- Indices
	uint id_indices = 0;
	uint num_indices = 0;
	uint* indices = nullptr;

	//-- UVs
	uint id_uv = 0;
	uint num_uv = 0;
	float* uvs = nullptr;

	//-- Normals
	uint id_normal = 0;
	uint num_normal = 0;
	float* normals = nullptr;

	std::string directory;
	std::string tx_directory;

};

class ModuleMesh : public Module
{
public:
	ModuleMesh(Application* app, const char* name, bool start_enabled = true);
	~ModuleMesh();

	bool Init(Json& config);
	bool Start();
	update_status PreUpdate(float dt);
	update_status Update(float dt);
	update_status PostUpdate(float dt);
	bool CleanUp();

	bool  LoadFBX(const char* path);
	Mesh* LoadMesh(const char* path);

	void  Load(aiNode* node, const aiScene* scene, GameObject* parent,const char* scene_folder);

	bool ImportMesh(const aiMesh* mesh, std::string& output_file, const char* scene_folder);
	bool SaveMesh(Mesh& mesh, std::string& output_file,const char* scene_folder);

public:
	bool scene_found = false;

};

#endif // !__MODULEMESH_H__


text:
{#-
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

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

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
-#}
{% for field, values in changes.items() %}
{% if field == 'Description': %}
- **{{ field }}**:

Diff:

~~~~
{{ values }}
~~~~

{% else %}
- **{{ field }}**: {{ values[0] }} --> {{ values[1] }}
{% endif %}
{% endfor %}


text:
import os, json
from twisted.trial import unittest
from twisted.internet import defer
from wormhole.twisted.transcribe import Wormhole, WrongPasswordError
from .. import invitation
from .common import BasedirMixin, NodeRunnerMixin, TwoNodeMixin, fake_transport
from ..errors import CommandError

class Invite(BasedirMixin, NodeRunnerMixin, unittest.TestCase):
    # low-level test of the Invitation class
    def test_one(self):
        basedir1 = os.path.join(self.make_basedir(), "node1")
        self.createNode(basedir1)
        n1 = self.startNode(basedir1)

        sp = b"alice signed payload"
        maybe_code = None
        cid = n1.db.insert(
            "INSERT INTO addressbook"
            " (petname,"
            "  invitation_state, when_invited, invitation_code,"
            "  wormhole_payload)"
            " VALUES (?, ?,?,?, ?)",
            ("bob",
             invitation.INVITE_WAITING_FOR_CODE, 0, maybe_code,
             sp.encode("hex")))
        n1.db.commit()

        i = n1.agent.im.create_invitation(cid)
        d1 = i._debug_when_got_code = defer.Deferred()
        d2 = i.activate()
        # this requires a server roundtrip to allocate the channel, so the
        # code won't be known yet
        rows = list(n1.db.execute("SELECT * from addressbook").fetchall())
        self.failUnlessEqual(len(rows), 1)
        r = rows[0]
        self.failUnlessEqual(r["id"], cid)
        self.failUnlessEqual(r["invitation_code"], None)
        self.failUnlessEqual(r["wormhole"], None)
        self.failUnlessEqual(r["wormhole_payload"], sp.encode("hex"))

        def _got_code(code):
            self.code = code
            rows = list(n1.db.execute("SELECT * from addressbook").fetchall())
            self.failUnlessEqual(len(rows), 1)
            r = rows[0]
            self.failUnlessEqual(r["invitation_code"], code)
            wormhole_data = r["wormhole"]
            json.loads(wormhole_data)
            self.failUnlessEqual(r["wormhole_payload"], sp.encode("hex"))

            w = Wormhole(i.appid, i.relay)
            w.set_code(code)
            d3 = w.get_data(b"bob signed payload")
            return d3 # wait for bob's side to finish
        d1.addCallback(_got_code)
        def _bob_done(alice_data):
            self.failUnlessEqual(alice_data, sp)
            return d2 # now wait for alice's side to finish
        d1.addCallback(_bob_done)
        def _alice_done(bob_data):
            self.failUnlessEqual(bob_data, b"bob signed payload")
        d1.addCallback(_alice_done)
        return d1

    def test_duplicate_code(self):
        basedir1 = os.path.join(self.make_basedir(), "node1")
        self.createNode(basedir1)
        n1 = self.startNode(basedir1)
        code = "123-code"
        tports = {"local": fake_transport()}
        n1.agent.command_invite(u"petname-from-1", code,
                                override_transports=tports)
        self.failUnlessRaises(CommandError,
                              n1.agent.command_invite, u"new-petname", code)

class Two(TwoNodeMixin, unittest.TestCase):
    def test_two(self):
        nA, nB = self.make_nodes()
        d = self.add_new_channel_with_invitation(nA, nB)
        def _done((entA,entB)):
            self.failUnlessEqual(entA["their_verfkey"], entB["my_verfkey"])
            self.failUnlessEqual(entB["their_verfkey"], entA["my_verfkey"])
        d.addCallback(_done)
        return d

    def test_external_code(self):
        nA, nB = self.make_nodes()
        code = "123-code"

        d1 = defer.Deferred()
        nA.agent.command_invite(u"petname-from-A", code,
                                override_transports=self.tports1,
                                _debug_when_done=d1)
        d2 = defer.Deferred()
        nB.agent.command_invite(u"petname-from-B", code,
                                override_transports=self.tports2,
                                _debug_when_done=d2)
        d1.addCallback(lambda _: d2)
        def _done(res):
            entA = nA.agent.command_list_addressbook()[0]
            entB = nB.agent.command_list_addressbook()[0]
            self.failUnlessEqual(entA["their_verfkey"], entB["my_verfkey"])
            self.failUnlessEqual(entB["their_verfkey"], entA["my_verfkey"])
            rows = list(nA.db.execute("SELECT * from addressbook").fetchall())
            self.failUnlessEqual(len(rows), 1)
            r = rows[0]
            self.failUnlessEqual(r["id"], entA["cid"])
            self.failUnlessEqual(r["invitation_code"], code)
            self.failUnlessEqual(r["wormhole"], None)
            self.failUnlessEqual(r["wormhole_payload"], None)
        d1.addCallback(_done)
        return d1

    def test_wrong_password(self):
        nA, nB = self.make_nodes()
        code = "123-code"

        d1 = defer.Deferred()
        nA.agent.command_invite(u"petname-from-A", code,
                                override_transports=self.tports1,
                                _debug_when_done=d1)
        d2 = defer.Deferred()
        nB.agent.command_invite(u"petname-from-B", code+"WRONG",
                                override_transports=self.tports2,
                                _debug_when_done=d2)
        d3 = self.assertFailure(d1, WrongPasswordError)
        d3.addCallback(lambda _: self.assertFailure(d2, WrongPasswordError))
        def _done(res):
            self.failUnlessEqual(nA.agent.command_list_addressbook(), [])
            self.failUnlessEqual(nB.agent.command_list_addressbook(), [])
        d3.addCallback(_done)
        return d3


text:
package net.i2p.data;

/*
 * free (adj.): unencumbered; not under the control of others
 * Written by jrandom in 2003 and released into the public domain
 * with no warranty of any kind, either expressed or implied.
 * It probably won't make your computer catch on fire, or eat
 * your children, but it might.  Use at your own risk.
 *
 */

import java.io.Serializable;

/**
 * Wrap up an array of bytes so that they can be compared and placed in hashes,
 * maps, and the like.
 *
 */
public class ByteArray implements Serializable, Comparable {
    private byte[] _data;
    private int _valid;
    private int _offset;

    public ByteArray() {
    }

    /**
     *  Sets valid = data.length, unless data is null
     *  Sets offset = 0
     *  @param data may be null
     */
    public ByteArray(byte[] data) {
        _data = data;
        _valid = (data != null ? data.length : 0);
    }

    /**
     *  Sets offset = offset
     *  Sets valid = length
     *  @param data may be null but why would you do that
     */
    public ByteArray(byte[] data, int offset, int length) {
        _data = data;
        _offset = offset;
        _valid = length;
    }

    public byte[] getData() {
        return _data;
    }

    /** Warning, does not set valid */
    public void setData(byte[] data) {
        _data = data;
    }

    /**
     * Count how many of the bytes in the array are 'valid'.
     * this property does not necessarily have meaning for all byte
     * arrays.
     */
    public int getValid() { return _valid; }
    public void setValid(int valid) { _valid = valid; }
    public int getOffset() { return _offset; }
    public void setOffset(int offset) { _offset = offset; }

    @Override
    public final boolean equals(Object o) {
        if (o == this) return true;
        if (o == null) return false;
        if (o instanceof ByteArray) {
            ByteArray ba = (ByteArray)o;
            return compare(getData(), _offset, _valid, ba.getData(), ba.getOffset(), ba.getValid());
        }

        try {
            byte val[] = (byte[]) o;
            return compare(getData(), _offset, _valid, val, 0, val.length);
        } catch (Throwable t) {
            return false;
        }
    }

    private static final boolean compare(byte[] lhs, int loff, int llen, byte[] rhs, int roff, int rlen) {
        return (llen == rlen) && DataHelper.eq(lhs, loff, rhs, roff, llen);
    }

    public final int compareTo(Object obj) {
        if (obj.getClass() != getClass()) throw new ClassCastException("invalid object: " + obj);
        return DataHelper.compareTo(_data, ((ByteArray)obj).getData());
    }

    @Override
    public final int hashCode() {
        return DataHelper.hashCode(getData());
    }

    @Override
    public String toString() {
        return super.toString() + "/" + DataHelper.toString(getData(), 32) + "." + _valid;
    }

    public final String toBase64() {
        return Base64.encode(_data, _offset, _valid);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	Copyright 2014 Bernd Vogt and others.

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

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

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.sourcepit.b2.examples.reactor</groupId>
		<artifactId>common-config</artifactId>
		<version>1.0.0-SNAPSHOT</version>
		<relativePath>../common-config/module.xml</relativePath>
	</parent>

	<artifactId>rcp.help</artifactId>
	<packaging>pom</packaging>

</project>


text:
'use strict';

const getDictionaries = require('./hunspell-dictionaries');
const getSpellChecker = require('./hunspell-checker');
const SpellSuggester = require('./hunspell-suggester');

getDictionaries
  .then(dictionaries => {
    return dictionaries.en_GB;
  })
  .then(dictionary => {
    const suggester = new SpellSuggester(dictionary);

    // suggester.initialise()
    //   .then(() => {
        suggester
          .suggest('color')
          .then(response => {
            console.log(response);
          });
    //   })
    // ;

    return dictionary;
  })
  .then(getSpellChecker)
  .then(checker => {
    console.log(checker.check('the'));
    console.log(checker.check('colour'));
    console.log(checker.check('colourr'));
    console.log(checker.check('color'));
  })
  .catch(exception => {
    console.log(exception);
  })
;


text:
require('dotenv').config();

// This jazz here if so we can use all the fancy sass on server side renders... this was a pain
import csshook from 'css-modules-require-hook/preset'; // import hook before routes

import express from 'express';
import path from 'path';
import mongoose from 'mongoose';
import jwt from 'express-jwt';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
// import knex from 'knex';
import session from 'express-session';

import config from './config';

import { renderPage } from '../client/renderers/server';
// CUSTOM ROUTERS
import authRouter from './src/auth/localAuth';
import signupRouter from './src/api/routes/signup';
import loginRouter from './src/api/routes/login';
import githubRouter from './src/api/github';
import githubAuthRouter from './src/auth/githubAuth';

// CUSTOM MIDDLEWARE
import { isAuthenticated } from './src/middleware/isAuthenticated';

const app = express();
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
}));
// const PROD = process.env.NODE_ENV === 'production';
const DEV = process.env.NODE_ENV === 'development';
mongoose.Promise = require('bluebird');

const options = {
  useMongoClient: true,
  promiseLibrary: require('bluebird'),
};
if (DEV) {
  mongoose.connect(process.env.MONGO_LOCAL_URI, options)
    .then((success) => {
      console.info('Success connect to mongo', process.env.MONGO_LOCAL_URI);
    })
    .catch((err) => {
      console.info('Error connecting to mongo', err);
    });
}

app.use(express.static(path.join(__dirname, '../public')));
// app.use('/favicon.ico', express.static(path.join(__dirname, '../public/favicon.ico')));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'src/views'));
// app.use();
app.use(cookieParser());
app.use(bodyParser.json());
app.use((req, res, next) => {
  // console.log(' WHAT IS HAPPEINGN IN HERE?????', req.headers);
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
  next();
});
// Runs our check on the tokens sent from client on every request
app.use(githubAuthRouter);
app.use(isAuthenticated);
app.use(authRouter);
app.use('/signup', signupRouter);
app.use('/login', loginRouter);
app.use('/api/github', githubRouter);
app.use('/test', (req, res) => {
  res.send({ Hello: 'uTile is Served' });
});

app.get('*', jwt({ secret: process.env.JWT_SECRET, credentialsRequired: false }), (req, res) => {
  // console.log(' WHAT IS THE MAIN RENDER REQ LOCAL KEYS?', Object.keys(res.locals));
  const { initalContent, initalState } = renderPage(req, res);
  // console.log(' WHAT IS THE INITAL STATE???/', req.session);
  res.render('index', { initalContent, initalState });
});

// Serve the files on port 3000.
app.listen(config.port, () => {
  console.info('Example app listening on port 3000!!!!!!!!! !\n');
});


text:
MIME-Version: 1.0
Server: CERN/3.0
Date: Sunday, 24-Nov-96 22:44:04 GMT
Content-Type: text/html
Content-Length: 6668
Last-Modified: Thursday, 10-Oct-96 14:15:00 GMT

<title>CS 537 - Sample Questions</title>

 CS 537 - Sample Questions and Answers

Q.1: Relational Algebra and SQL

Consider the following schema used by the Campus Book Store:

 TOY(toyno, toyname, toytype, color, price)

 BOOK(bookno, bookname, booktype, price)

 MANUF(mname, address, phone)

 STOCK(itemno, mname,, quantity)

In the above, primary keys are in boldface. You can assume that each
STOCK.itemno value refers either to a toy or a book (but not to both).
Each manufacturer can make toys or books or both. Express the following
queries in the relational algebra and in SQL:

 Print the phone numbers of manufacturers who make a toy of type
"bicycle" and a book of type "animal story"

 Print the toy types where every known manufacturer makes at least one toy of that type.

 Print the names of manufacturers who make both a toy of type "truck" and a book of type "bedtime story"

 Print the names of purple toys made by "Acme Toy Company" where the store has at least 100 of them in stock

 Print the phone numbers of the manufacturers who make the most expensive book known to the store.

Answer. (last updated : Thu Oct 10 10:13:56 EDT 1996)

Q.2: Files

Consider a relation R with 10 attributes, some of variable size.

 Suggest a record structure for tuples of R.

 Suggest a page structure for pages of R.

 Instead of storing an entire tuple as a record ("horizontal partitioning"
of a relation), another alternative is store each column value for
all tuples contiguously ("vertical partitioning"). Why is vertical
partitioning usually a bad idea?

 The records on a page usually belong to the same relation. Why is it
a bad idea to store records of multiple relations on the same page?

 Find one counter example to each of the last two questions (i.e.,
one query for which vertical partitioning is good, and one for which
it is good to store multiple relations' records on the same page).

Answer.

Q.3: Indexes

Consider a B+-tree index.

 Write pseudo code for the insertion algorithm for a leaf page,
involving splitting in case of overflow.

 Change the pseudo-code to consider redistribution with a neighbor.

 In what cases does each approach make sense: consider many vs few
concurrent users, desire to minimize disk usage, etc.

Answer.

Q.4: Memory Management

Consider the LRU replacement policy for a buffer pool.

 Describe a database query processing scenario for which LRU is
ideally suited.

 Describe a scenario for which LRU is terrible.

 What is the principle behind LRU, and why does the principle fail
for the second scenario?

 Is there some way to improve LRU to correctly apply the principle
(or to work in more cases)?

Answer.

Q.5: Memory Management

Suppose there is enough main memory (say 1 GB) in the system to hold
relation R (400 MB) and relation S (400 MB). Now you want to join
R and S using a nested loops join.

 Is there a difference now between tuple-at-a-time nested loops join
and page-at-a-time nested loops join?

 How about blocked nested loops join?

 Of all the algorithms we learnt, what would you recommend as the
best one to use?

 Find a counter-example where your answer to the previous question
is invalid.

Answer.

Q.6: Join Algorithms

Consider the problem of joining a 1,000,000 tuple relation R with a 50,000
tuple relation S. In both relations, 5 tuples fit on a page. The system's
page size is 1K bytes and the join predicate specifies an equality join
between attributes R.a and S.b.

 Explain how the GRACE hash join algorithm works.

 What will the total I/O cost be to perform GRACE hash join of R and
S assuming that there is just enough memory available?

 Discuss the memory needs of GRACE hash join. What is the worst-case
scenario, and when might this occur?

 Can the GRACE hash join be used to compute a non-equality join? Explain
why or why not.

Answer.

Q.7: Query Processing

You are asked to write a duplicate-eliminating projection operation for
a new relational DBMS. Your boss is an expert on join algorithms and you
want to impress by adapting join techniques to this problem.

 How can sorting be used for projection? How would you make efficient
use of main-memory for this task?

 How can hashing be used, and how would you make efficient use of
main-memory for this task?

 Now can you get yourself a promotion by showing your boss that the
same code can be used for processing aggregates (GROUPBY) as well?

Answer.

Q.8: Query Optimization

The System-R optimizer (Selinger paper) describes one particular query
optimization algorithm for SQL queries.

 Where is the assumption about uniform distribution of column values
used? How would you change it if histograms were maintained about the
column frequency distributions?

 What is the notion of "interesting orders"? If System-R supported
a GRACE hash join, is there an analogous notion?

 How would you change the cost formulas for access paths to take
into account the difference between sequential and random I/O?

 What equivalence transformations of the relational algebra
make join optimization a large search problem?

 Show an example where the System-R optimizer would not even
consider the optimal query plan.

Answer.

Q.9: Query Optimization

There are several heuristics which are also used in query optimization.

 Demonstrate selection pushdown, and a case where it doesnt work.

 Demonstrate projection pushdwon, and a case where it doesnt work.

 Consider a query with expensive selections and projections, in addition
to joins. Can you suggest an extension to the System-R optimizer join
enumeration strategy that will also consider the appropriate
placement of expensive selections and projections?

Answer.


text:
#include <scsi/libiscsi.h>
#include <scsi/scsi_transport_iscsi.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi.h>

#include "be_iscsi.h"

extern struct iscsi_transport beiscsi_iscsi_transport;

/**
 * beiscsi_session_create - creates a new iscsi session
 * @cmds_max: max commands supported
 * @qdepth: max queue depth supported
 * @initial_cmdsn: initial iscsi CMDSN
 */
struct iscsi_cls_session *beiscsi_session_create(struct iscsi_endpoint *ep,
						 u16 cmds_max,
						 u16 qdepth,
						 u32 initial_cmdsn)
{
	struct Scsi_Host *shost;
	struct beiscsi_endpoint *beiscsi_ep;
	struct iscsi_cls_session *cls_session;
	struct beiscsi_hba *phba;
	struct iscsi_session *sess;
	struct beiscsi_session *beiscsi_sess;
	struct beiscsi_io_task *io_task;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_session_create\n");

	if (!ep) {
		SE_DEBUG(DBG_LVL_1, "beiscsi_session_create: invalid ep\n");
		return NULL;
	}
	beiscsi_ep = ep->dd_data;
	phba = beiscsi_ep->phba;
	shost = phba->shost;
	if (cmds_max > beiscsi_ep->phba->params.wrbs_per_cxn) {
		shost_printk(KERN_ERR, shost, "Cannot handle %d cmds."
			     "Max cmds per session supported is %d. Using %d. "
			     "\n", cmds_max,
			      beiscsi_ep->phba->params.wrbs_per_cxn,
			      beiscsi_ep->phba->params.wrbs_per_cxn);
		cmds_max = beiscsi_ep->phba->params.wrbs_per_cxn;
	}

	cls_session = iscsi_session_setup(&beiscsi_iscsi_transport,
					  shost, cmds_max,
					  sizeof(*beiscsi_sess),
					  sizeof(*io_task),
					  initial_cmdsn, ISCSI_MAX_TARGET);
	if (!cls_session)
		return NULL;
	sess = cls_session->dd_data;
	beiscsi_sess = sess->dd_data;
	beiscsi_sess->bhs_pool =  pci_pool_create("beiscsi_bhs_pool",
						   phba->pcidev,
						   sizeof(struct be_cmd_bhs),
						   64, 0);
	if (!beiscsi_sess->bhs_pool)
		goto destroy_sess;

	return cls_session;
destroy_sess:
	iscsi_session_teardown(cls_session);
	return NULL;
}

/**
 * beiscsi_session_destroy - destroys iscsi session
 * @cls_session:	pointer to iscsi cls session
 *
 * Destroys iSCSI session instance and releases
 * resources allocated for it.
 */
void beiscsi_session_destroy(struct iscsi_cls_session *cls_session)
{
	struct iscsi_session *sess = cls_session->dd_data;
	struct beiscsi_session *beiscsi_sess = sess->dd_data;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_session_destroy\n");
	pci_pool_destroy(beiscsi_sess->bhs_pool);
	iscsi_session_teardown(cls_session);
}

/**
 * beiscsi_conn_create - create an instance of iscsi connection
 * @cls_session: ptr to iscsi_cls_session
 * @cid: iscsi cid
 */
struct iscsi_cls_conn *
beiscsi_conn_create(struct iscsi_cls_session *cls_session, u32 cid)
{
	struct beiscsi_hba *phba;
	struct Scsi_Host *shost;
	struct iscsi_cls_conn *cls_conn;
	struct beiscsi_conn *beiscsi_conn;
	struct iscsi_conn *conn;
	struct iscsi_session *sess;
	struct beiscsi_session *beiscsi_sess;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_conn_create ,cid"
		 "from iscsi layer=%d\n", cid);
	shost = iscsi_session_to_shost(cls_session);
	phba = iscsi_host_priv(shost);

	cls_conn = iscsi_conn_setup(cls_session, sizeof(*beiscsi_conn), cid);
	if (!cls_conn)
		return NULL;

	conn = cls_conn->dd_data;
	beiscsi_conn = conn->dd_data;
	beiscsi_conn->ep = NULL;
	beiscsi_conn->phba = phba;
	beiscsi_conn->conn = conn;
	sess = cls_session->dd_data;
	beiscsi_sess = sess->dd_data;
	beiscsi_conn->beiscsi_sess = beiscsi_sess;
	return cls_conn;
}

/**
 * beiscsi_bindconn_cid - Bind the beiscsi_conn with phba connection table
 * @beiscsi_conn: The pointer to  beiscsi_conn structure
 * @phba: The phba instance
 * @cid: The cid to free
 */
static int beiscsi_bindconn_cid(struct beiscsi_hba *phba,
				struct beiscsi_conn *beiscsi_conn,
				unsigned int cid)
{
	if (phba->conn_table[cid]) {
		SE_DEBUG(DBG_LVL_1,
			 "Connection table already occupied. Detected clash\n");
		return -EINVAL;
	} else {
		SE_DEBUG(DBG_LVL_8, "phba->conn_table[%d]=%p(beiscsi_conn)\n",
			 cid, beiscsi_conn);
		phba->conn_table[cid] = beiscsi_conn;
	}
	return 0;
}

/**
 * beiscsi_conn_bind - Binds iscsi session/connection with TCP connection
 * @cls_session: pointer to iscsi cls session
 * @cls_conn: pointer to iscsi cls conn
 * @transport_fd: EP handle(64 bit)
 *
 * This function binds the TCP Conn with iSCSI Connection and Session.
 */
int beiscsi_conn_bind(struct iscsi_cls_session *cls_session,
		      struct iscsi_cls_conn *cls_conn,
		      u64 transport_fd, int is_leading)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct beiscsi_conn *beiscsi_conn = conn->dd_data;
	struct Scsi_Host *shost =
		(struct Scsi_Host *)iscsi_session_to_shost(cls_session);
	struct beiscsi_hba *phba = (struct beiscsi_hba *)iscsi_host_priv(shost);
	struct beiscsi_endpoint *beiscsi_ep;
	struct iscsi_endpoint *ep;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_conn_bind\n");
	ep = iscsi_lookup_endpoint(transport_fd);
	if (!ep)
		return -EINVAL;

	beiscsi_ep = ep->dd_data;

	if (iscsi_conn_bind(cls_session, cls_conn, is_leading))
		return -EINVAL;

	if (beiscsi_ep->phba != phba) {
		SE_DEBUG(DBG_LVL_8,
			 "beiscsi_ep->hba=%p not equal to phba=%p\n",
			 beiscsi_ep->phba, phba);
		return -EEXIST;
	}

	beiscsi_conn->beiscsi_conn_cid = beiscsi_ep->ep_cid;
	beiscsi_conn->ep = beiscsi_ep;
	beiscsi_ep->conn = beiscsi_conn;
	SE_DEBUG(DBG_LVL_8, "beiscsi_conn=%p conn=%p ep_cid=%d\n",
		 beiscsi_conn, conn, beiscsi_ep->ep_cid);
	return beiscsi_bindconn_cid(phba, beiscsi_conn, beiscsi_ep->ep_cid);
}

/**
 * beiscsi_ep_get_param - get the iscsi parameter
 * @ep: pointer to iscsi ep
 * @param: parameter type identifier
 * @buf: buffer pointer
 *
 * returns iscsi parameter
 */
int beiscsi_ep_get_param(struct iscsi_endpoint *ep,
			   enum iscsi_param param, char *buf)
{
	struct beiscsi_endpoint *beiscsi_ep = ep->dd_data;
	int len = 0;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_conn_get_param, param= %d\n", param);

	switch (param) {
	case ISCSI_PARAM_CONN_PORT:
		len = sprintf(buf, "%hu\n", beiscsi_ep->dst_tcpport);
		break;
	case ISCSI_PARAM_CONN_ADDRESS:
		if (beiscsi_ep->ip_type == BE2_IPV4)
			len = sprintf(buf, "%pI4\n", &beiscsi_ep->dst_addr);
		else
			len = sprintf(buf, "%pI6\n", &beiscsi_ep->dst6_addr);
		break;
	default:
		return -ENOSYS;
	}
	return len;
}

int beiscsi_set_param(struct iscsi_cls_conn *cls_conn,
		      enum iscsi_param param, char *buf, int buflen)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct iscsi_session *session = conn->session;
	int ret;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_conn_set_param, param= %d\n", param);
	ret = iscsi_set_param(cls_conn, param, buf, buflen);
	if (ret)
		return ret;
	/*
	 * If userspace tried to set the value to higher than we can
	 * support override here.
	 */
	switch (param) {
	case ISCSI_PARAM_FIRST_BURST:
		if (session->first_burst > 8192)
			session->first_burst = 8192;
		break;
	case ISCSI_PARAM_MAX_RECV_DLENGTH:
		if (conn->max_recv_dlength > 65536)
			conn->max_recv_dlength = 65536;
		break;
	case ISCSI_PARAM_MAX_BURST:
		if (session->max_burst > 262144)
			session->max_burst = 262144;
		break;
	case ISCSI_PARAM_MAX_XMIT_DLENGTH:
		if ((conn->max_xmit_dlength > 65536) ||
		    (conn->max_xmit_dlength == 0))
			conn->max_xmit_dlength = 65536;
	default:
		return 0;
	}

	return 0;
}

/**
 * beiscsi_get_host_param - get the iscsi parameter
 * @shost: pointer to scsi_host structure
 * @param: parameter type identifier
 * @buf: buffer pointer
 *
 * returns host parameter
 */
int beiscsi_get_host_param(struct Scsi_Host *shost,
			   enum iscsi_host_param param, char *buf)
{
	struct beiscsi_hba *phba = (struct beiscsi_hba *)iscsi_host_priv(shost);
	int status = 0;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_get_host_param, param= %d\n", param);
	switch (param) {
	case ISCSI_HOST_PARAM_HWADDRESS:
		status = beiscsi_get_macaddr(buf, phba);
		if (status < 0) {
			SE_DEBUG(DBG_LVL_1, "beiscsi_get_macaddr Failed\n");
			return status;
		}
		break;
	default:
		return iscsi_host_get_param(shost, param, buf);
	}
	return status;
}

int beiscsi_get_macaddr(char *buf, struct beiscsi_hba *phba)
{
	struct be_cmd_resp_get_mac_addr *resp;
	struct be_mcc_wrb *wrb;
	unsigned int tag, wrb_num;
	unsigned short status, extd_status;
	struct be_queue_info *mccq = &phba->ctrl.mcc_obj.q;
	int rc;

	if (phba->read_mac_address)
		return sysfs_format_mac(buf, phba->mac_address,
					ETH_ALEN);

	tag = be_cmd_get_mac_addr(phba);
	if (!tag) {
		SE_DEBUG(DBG_LVL_1, "be_cmd_get_mac_addr Failed\n");
		return -EBUSY;
	} else
		wait_event_interruptible(phba->ctrl.mcc_wait[tag],
					 phba->ctrl.mcc_numtag[tag]);

	wrb_num = (phba->ctrl.mcc_numtag[tag] & 0x00FF0000) >> 16;
	extd_status = (phba->ctrl.mcc_numtag[tag] & 0x0000FF00) >> 8;
	status = phba->ctrl.mcc_numtag[tag] & 0x000000FF;
	if (status || extd_status) {
		SE_DEBUG(DBG_LVL_1, "Failed to get be_cmd_get_mac_addr"
				    " status = %d extd_status = %d\n",
				    status, extd_status);
		free_mcc_tag(&phba->ctrl, tag);
		return -EAGAIN;
	}
	wrb = queue_get_wrb(mccq, wrb_num);
	free_mcc_tag(&phba->ctrl, tag);
	resp = embedded_payload(wrb);
	memcpy(phba->mac_address, resp->mac_address, ETH_ALEN);
	rc = sysfs_format_mac(buf, phba->mac_address,
			       ETH_ALEN);
	phba->read_mac_address = 1;
	return rc;
}

/**
 * beiscsi_conn_get_stats - get the iscsi stats
 * @cls_conn: pointer to iscsi cls conn
 * @stats: pointer to iscsi_stats structure
 *
 * returns iscsi stats
 */
void beiscsi_conn_get_stats(struct iscsi_cls_conn *cls_conn,
			    struct iscsi_stats *stats)
{
	struct iscsi_conn *conn = cls_conn->dd_data;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_conn_get_stats\n");
	stats->txdata_octets = conn->txdata_octets;
	stats->rxdata_octets = conn->rxdata_octets;
	stats->dataout_pdus = conn->dataout_pdus_cnt;
	stats->scsirsp_pdus = conn->scsirsp_pdus_cnt;
	stats->scsicmd_pdus = conn->scsicmd_pdus_cnt;
	stats->datain_pdus = conn->datain_pdus_cnt;
	stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt;
	stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt;
	stats->r2t_pdus = conn->r2t_pdus_cnt;
	stats->digest_err = 0;
	stats->timeout_err = 0;
	stats->custom_length = 0;
	strcpy(stats->custom[0].desc, "eh_abort_cnt");
	stats->custom[0].value = conn->eh_abort_cnt;
}

/**
 * beiscsi_set_params_for_offld - get the parameters for offload
 * @beiscsi_conn: pointer to beiscsi_conn
 * @params: pointer to offload_params structure
 */
static void  beiscsi_set_params_for_offld(struct beiscsi_conn *beiscsi_conn,
					  struct beiscsi_offload_params *params)
{
	struct iscsi_conn *conn = beiscsi_conn->conn;
	struct iscsi_session *session = conn->session;

	AMAP_SET_BITS(struct amap_beiscsi_offload_params, max_burst_length,
		      params, session->max_burst);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params,
		      max_send_data_segment_length, params,
		      conn->max_xmit_dlength);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, first_burst_length,
		      params, session->first_burst);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, erl, params,
		      session->erl);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, dde, params,
		      conn->datadgst_en);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, hde, params,
		      conn->hdrdgst_en);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, ir2t, params,
		      session->initial_r2t_en);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, imd, params,
		      session->imm_data_en);
	AMAP_SET_BITS(struct amap_beiscsi_offload_params, exp_statsn, params,
		      (conn->exp_statsn - 1));
}

/**
 * beiscsi_conn_start - offload of session to chip
 * @cls_conn: pointer to beiscsi_conn
 */
int beiscsi_conn_start(struct iscsi_cls_conn *cls_conn)
{
	struct iscsi_conn *conn = cls_conn->dd_data;
	struct beiscsi_conn *beiscsi_conn = conn->dd_data;
	struct beiscsi_endpoint *beiscsi_ep;
	struct beiscsi_offload_params params;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_conn_start\n");
	memset(&params, 0, sizeof(struct beiscsi_offload_params));
	beiscsi_ep = beiscsi_conn->ep;
	if (!beiscsi_ep)
		SE_DEBUG(DBG_LVL_1, "In beiscsi_conn_start , no beiscsi_ep\n");

	beiscsi_conn->login_in_progress = 0;
	beiscsi_set_params_for_offld(beiscsi_conn, &params);
	beiscsi_offload_connection(beiscsi_conn, &params);
	iscsi_conn_start(cls_conn);
	return 0;
}

/**
 * beiscsi_get_cid - Allocate a cid
 * @phba: The phba instance
 */
static int beiscsi_get_cid(struct beiscsi_hba *phba)
{
	unsigned short cid = 0xFFFF;

	if (!phba->avlbl_cids)
		return cid;

	cid = phba->cid_array[phba->cid_alloc++];
	if (phba->cid_alloc == phba->params.cxns_per_ctrl)
		phba->cid_alloc = 0;
	phba->avlbl_cids--;
	return cid;
}

/**
 * beiscsi_put_cid - Free the cid
 * @phba: The phba for which the cid is being freed
 * @cid: The cid to free
 */
static void beiscsi_put_cid(struct beiscsi_hba *phba, unsigned short cid)
{
	phba->avlbl_cids++;
	phba->cid_array[phba->cid_free++] = cid;
	if (phba->cid_free == phba->params.cxns_per_ctrl)
		phba->cid_free = 0;
}

/**
 * beiscsi_free_ep - free endpoint
 * @ep:	pointer to iscsi endpoint structure
 */
static void beiscsi_free_ep(struct beiscsi_endpoint *beiscsi_ep)
{
	struct beiscsi_hba *phba = beiscsi_ep->phba;

	beiscsi_put_cid(phba, beiscsi_ep->ep_cid);
	beiscsi_ep->phba = NULL;
}

/**
 * beiscsi_open_conn - Ask FW to open a TCP connection
 * @ep:	endpoint to be used
 * @src_addr: The source IP address
 * @dst_addr: The Destination  IP address
 *
 * Asks the FW to open a TCP connection
 */
static int beiscsi_open_conn(struct iscsi_endpoint *ep,
			     struct sockaddr *src_addr,
			     struct sockaddr *dst_addr, int non_blocking)
{
	struct beiscsi_endpoint *beiscsi_ep = ep->dd_data;
	struct beiscsi_hba *phba = beiscsi_ep->phba;
	struct be_queue_info *mccq = &phba->ctrl.mcc_obj.q;
	struct be_mcc_wrb *wrb;
	struct tcp_connect_and_offload_out *ptcpcnct_out;
	unsigned short status, extd_status;
	struct be_dma_mem nonemb_cmd;
	unsigned int tag, wrb_num;
	int ret = -ENOMEM;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_open_conn\n");
	beiscsi_ep->ep_cid = beiscsi_get_cid(phba);
	if (beiscsi_ep->ep_cid == 0xFFFF) {
		SE_DEBUG(DBG_LVL_1, "No free cid available\n");
		return ret;
	}
	SE_DEBUG(DBG_LVL_8, "In beiscsi_open_conn, ep_cid=%d\n",
		 beiscsi_ep->ep_cid);
	phba->ep_array[beiscsi_ep->ep_cid -
		       phba->fw_config.iscsi_cid_start] = ep;
	if (beiscsi_ep->ep_cid > (phba->fw_config.iscsi_cid_start +
				  phba->params.cxns_per_ctrl * 2)) {
		SE_DEBUG(DBG_LVL_1, "Failed in allocate iscsi cid\n");
		goto free_ep;
	}

	beiscsi_ep->cid_vld = 0;
	nonemb_cmd.va = pci_alloc_consistent(phba->ctrl.pdev,
				sizeof(struct tcp_connect_and_offload_in),
				&nonemb_cmd.dma);
	if (nonemb_cmd.va == NULL) {
		SE_DEBUG(DBG_LVL_1,
			 "Failed to allocate memory for mgmt_open_connection"
			 "\n");
		beiscsi_put_cid(phba, beiscsi_ep->ep_cid);
		return -ENOMEM;
	}
	nonemb_cmd.size = sizeof(struct tcp_connect_and_offload_in);
	memset(nonemb_cmd.va, 0, nonemb_cmd.size);
	tag = mgmt_open_connection(phba, dst_addr, beiscsi_ep, &nonemb_cmd);
	if (!tag) {
		SE_DEBUG(DBG_LVL_1,
			 "mgmt_open_connection Failed for cid=%d\n",
			 beiscsi_ep->ep_cid);
		beiscsi_put_cid(phba, beiscsi_ep->ep_cid);
		pci_free_consistent(phba->ctrl.pdev, nonemb_cmd.size,
				    nonemb_cmd.va, nonemb_cmd.dma);
		return -EAGAIN;
	} else {
		wait_event_interruptible(phba->ctrl.mcc_wait[tag],
					 phba->ctrl.mcc_numtag[tag]);
	}
	wrb_num = (phba->ctrl.mcc_numtag[tag] & 0x00FF0000) >> 16;
	extd_status = (phba->ctrl.mcc_numtag[tag] & 0x0000FF00) >> 8;
	status = phba->ctrl.mcc_numtag[tag] & 0x000000FF;
	if (status || extd_status) {
		SE_DEBUG(DBG_LVL_1, "mgmt_open_connection Failed"
				    " status = %d extd_status = %d\n",
				    status, extd_status);
		free_mcc_tag(&phba->ctrl, tag);
		pci_free_consistent(phba->ctrl.pdev, nonemb_cmd.size,
			    nonemb_cmd.va, nonemb_cmd.dma);
		goto free_ep;
	} else {
		wrb = queue_get_wrb(mccq, wrb_num);
		free_mcc_tag(&phba->ctrl, tag);

		ptcpcnct_out = embedded_payload(wrb);
		beiscsi_ep = ep->dd_data;
		beiscsi_ep->fw_handle = ptcpcnct_out->connection_handle;
		beiscsi_ep->cid_vld = 1;
		SE_DEBUG(DBG_LVL_8, "mgmt_open_connection Success\n");
	}
	pci_free_consistent(phba->ctrl.pdev, nonemb_cmd.size,
			    nonemb_cmd.va, nonemb_cmd.dma);
	return 0;

free_ep:
	beiscsi_free_ep(beiscsi_ep);
	return -EBUSY;
}

/**
 * beiscsi_ep_connect - Ask chip to create TCP Conn
 * @scsi_host: Pointer to scsi_host structure
 * @dst_addr: The IP address of Target
 * @non_blocking: blocking or non-blocking call
 *
 * This routines first asks chip to create a connection and then allocates an EP
 */
struct iscsi_endpoint *
beiscsi_ep_connect(struct Scsi_Host *shost, struct sockaddr *dst_addr,
		   int non_blocking)
{
	struct beiscsi_hba *phba;
	struct beiscsi_endpoint *beiscsi_ep;
	struct iscsi_endpoint *ep;
	int ret;

	SE_DEBUG(DBG_LVL_8, "In beiscsi_ep_connect\n");
	if (shost)
		phba = iscsi_host_priv(shost);
	else {
		ret = -ENXIO;
		SE_DEBUG(DBG_LVL_1, "shost is NULL\n");
		return ERR_PTR(ret);
	}

	if (phba->state != BE_ADAPTER_UP) {
		ret = -EBUSY;
		SE_DEBUG(DBG_LVL_1, "The Adapter state is Not UP\n");
		return ERR_PTR(ret);
	}

	ep = iscsi_create_endpoint(sizeof(struct beiscsi_endpoint));
	if (!ep) {
		ret = -ENOMEM;
		return ERR_PTR(ret);
	}

	beiscsi_ep = ep->dd_data;
	beiscsi_ep->phba = phba;
	beiscsi_ep->openiscsi_ep = ep;
	ret = beiscsi_open_conn(ep, NULL, dst_addr, non_blocking);
	if (ret) {
		SE_DEBUG(DBG_LVL_1, "Failed in beiscsi_open_conn\n");
		goto free_ep;
	}

	return ep;

free_ep:
	iscsi_destroy_endpoint(ep);
	return ERR_PTR(ret);
}

/**
 * beiscsi_ep_poll - Poll to see if connection is established
 * @ep:	endpoint to be used
 * @timeout_ms: timeout specified in millisecs
 *
 * Poll to see if TCP connection established
 */
int beiscsi_ep_poll(struct iscsi_endpoint *ep, int timeout_ms)
{
	struct beiscsi_endpoint *beiscsi_ep = ep->dd_data;

	SE_DEBUG(DBG_LVL_8, "In  beiscsi_ep_poll\n");
	if (beiscsi_ep->cid_vld == 1)
		return 1;
	else
		return 0;
}

/**
 * beiscsi_close_conn - Upload the  connection
 * @ep: The iscsi endpoint
 * @flag: The type of connection closure
 */
static int beiscsi_close_conn(struct  beiscsi_endpoint *beiscsi_ep, int flag)
{
	int ret = 0;
	unsigned int tag;
	struct beiscsi_hba *phba = beiscsi_ep->phba;

	tag = mgmt_upload_connection(phba, beiscsi_ep->ep_cid, flag);
	if (!tag) {
		SE_DEBUG(DBG_LVL_8, "upload failed for cid 0x%x\n",
			 beiscsi_ep->ep_cid);
		ret = -EAGAIN;
	} else {
		wait_event_interruptible(phba->ctrl.mcc_wait[tag],
					 phba->ctrl.mcc_numtag[tag]);
		free_mcc_tag(&phba->ctrl, tag);
	}
	return ret;
}

/**
 * beiscsi_unbind_conn_to_cid - Unbind the beiscsi_conn from phba conn table
 * @phba: The phba instance
 * @cid: The cid to free
 */
static int beiscsi_unbind_conn_to_cid(struct beiscsi_hba *phba,
				      unsigned int cid)
{
	if (phba->conn_table[cid])
		phba->conn_table[cid] = NULL;
	else {
		SE_DEBUG(DBG_LVL_8, "Connection table Not occupied.\n");
		return -EINVAL;
	}
	return 0;
}

/**
 * beiscsi_ep_disconnect - Tears down the TCP connection
 * @ep:	endpoint to be used
 *
 * Tears down the TCP connection
 */
void beiscsi_ep_disconnect(struct iscsi_endpoint *ep)
{
	struct beiscsi_conn *beiscsi_conn;
	struct beiscsi_endpoint *beiscsi_ep;
	struct beiscsi_hba *phba;
	unsigned int tag;
	unsigned short savecfg_flag = CMD_ISCSI_SESSION_SAVE_CFG_ON_FLASH;

	beiscsi_ep = ep->dd_data;
	phba = beiscsi_ep->phba;
	SE_DEBUG(DBG_LVL_8, "In beiscsi_ep_disconnect for ep_cid = %d\n",
			     beiscsi_ep->ep_cid);

	if (!beiscsi_ep->conn) {
		SE_DEBUG(DBG_LVL_8, "In beiscsi_ep_disconnect, no "
			 "beiscsi_ep\n");
		return;
	}
	beiscsi_conn = beiscsi_ep->conn;
	iscsi_suspend_queue(beiscsi_conn->conn);

	SE_DEBUG(DBG_LVL_8, "In beiscsi_ep_disconnect ep_cid = %d\n",
		 beiscsi_ep->ep_cid);

	tag = mgmt_invalidate_connection(phba, beiscsi_ep,
					    beiscsi_ep->ep_cid, 1,
					    savecfg_flag);
	if (!tag) {
		SE_DEBUG(DBG_LVL_1,
			 "mgmt_invalidate_connection Failed for cid=%d\n",
			  beiscsi_ep->ep_cid);
	} else {
		wait_event_interruptible(phba->ctrl.mcc_wait[tag],
					 phba->ctrl.mcc_numtag[tag]);
		free_mcc_tag(&phba->ctrl, tag);
	}

	beiscsi_close_conn(beiscsi_ep, CONNECTION_UPLOAD_GRACEFUL);
	beiscsi_free_ep(beiscsi_ep);
	beiscsi_unbind_conn_to_cid(phba, beiscsi_ep->ep_cid);
	iscsi_destroy_endpoint(beiscsi_ep->openiscsi_ep);
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>LayoutSkeleton Properties</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Reference

LayoutSkeleton Properties

The properties of the LayoutSkeleton class are listed below. For a complete list of LayoutSkeleton class members, see the LayoutSkeleton Members topic.

Public Instance Properties

ContentType	 The content type output by this layout.

Footer	 The footer for the layout format.

Header	 The header for the layout format.

IgnoresException	 Flag indicating if this layout handles exceptions

See Also

        LayoutSkeleton Class | log4net.Layout Namespace

          Copyright 2001-2006 The Apache Software Foundation.

Generated from assembly log4net [1.2.10.0]


text:
/**
 * Filtering module
 */

import Semnext  = require('../src/models/semnext');

import * as _ from 'underscore';

module Filter {
  export function valid(input: string[], callback): void {
    let promises = [];
    for (var i in input) {
      (function(gene) {
        promises.push(new Promise((resolve, reject) => {
          Semnext.fetchCustomMatrix(input[i], (error, data) => {
            if (error) {
              resolve();
            } else {
              resolve( gene );
            }
          });
        }));
      })(input[i]);
    }
    Promise.all(promises).then((result) => {
      callback(result);
    });
  }
}

export = Filter;


text:
package gwt.material.design.demo.client.application.incubator.infinitescroll.service;

import com.google.gwt.user.client.rpc.AsyncCallback;
import gwt.material.design.demo.client.application.datatable.table.People;

public interface TestServiceAsync {
    void getPeople(int startIndex, int viewSize, AsyncCallback<People> async);
}


text:
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2.Settings;

public class AssetsUpdater {

	public static void main(String[] args) {
		Settings defaultSettings = new Settings();
		Settings trilinearSettings = new Settings();

		trilinearSettings.filterMag = TextureFilter.Linear;
		trilinearSettings.filterMin = TextureFilter.MipMapLinearLinear;

		updateAtlas("gui", defaultSettings );
		updateAtlas("planets", trilinearSettings);
		updateAtlas("player1", trilinearSettings);
		updateAtlas("ships", trilinearSettings);
		updateAtlas("tilemap", defaultSettings);
	}

	static private void updateAtlas(String name, Settings settings) {
		TexturePacker2.process(settings, "atlas/" + name, "assets/atlas", name);
	}
}


text:
django-djsani
==============

Django apps for the Health and Counseling Centre

Start of the academic year is June 1st.

# Apache Configuration

    # Health & Counceling medical forms app
    <Location /campus-life/medical/forms>
    WSGIProcessGroup djsani
    WSGIApplicationGroup djsani
    </Location>
    WSGIDaemonProcess djsani user=www-data group=www-data processes=1 threads=5
    #WSGIImportScript /d2/django_projects/djsani/wsgi process-group=djsani application-group=djsani
    WSGIScriptAlias /campus-life/medical/forms "/data2/django_projects/djsani/wsgi.py"

# odbc.ini configuration

    [MSSQL-PYTHON]
    Description             = PortalMSSQL
    Driver                  = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
    #Driver                  = FreeTDS [works with tools like osql, isql, etc
    Server                  = 10.2.6.24
    Port                    = 1433
    User                    = xxxxxxxxx
    Password                = xxxxxxxxx
    Database                = ICS_NET
    Trace                   = Yes
    TraceFile               = /tmp/odbc.trace
    TDS_Version             = 8.0

# odbcinst.ini configuration

    [FreeTDS]
    Description     = TDS driver (Sybase/MS SQL)
    Driver          = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
    Setup           = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
    CPTimeout       =
    CPReuse         =
    FileUsage       = 1

# Informix schemas

    /opt/carsi/schema/student/

    CCAthleteMedicalHistory
    CCAthletePrivacyWaiver
    CCAthleteReportingWaiver
    CCAthleteRiskWaiver
    CCAthleteSickleCellWaiver
    CCStudentHealthInsurance
    CCStudentMedicalContentType
    CCStudentMedicalHistory
    CCStudentMedicalLogEntry
    CCStudentMedicalManager
    CCStudentMeniWaiver

    cd /opt/carsi/schema/student
    make co F=CCAthleteMedicalHistory
    make tbuildy F=CCAthleteMedicalHistory
    make ci F=CCAthleteMedicalHistory L="new fields for athlete health history"

# Notes

Reminder for sqlalchemy and informix with Django:

Informix Boolean uses SMALLINT on the DDL side (0 or 1)
and on the Python side we deal in True or False. For
Django templates you have to use explicit comparisons:

{% if oo == "True" %}

whereas the following will resolve to true:

{% if oo %}

if oo has a value of "False".


text:
package controllers.actions

import java.util.UUID

import akka.util.Timeout
import models.{AuthenticatedRequest, EmpRef, UserName}
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.mvc._
import play.api.test.FakeRequest
import uk.gov.hmrc.auth.core.retrieve.Name
import uk.gov.hmrc.http.SessionKeys

import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps

class NoSessionCheckActionSpec extends PlaySpec with ScalaFutures with GuiceOneAppPerSuite {

  class Harness() extends NoSessionCheckActionImpl {
    def callTransform[A](request: AuthenticatedRequest[A]): Future[Either[Result, AuthenticatedRequest[A]]] =
      refine(request)
  }

  implicit val timeout: Timeout = 5 seconds

  "No Session Check Action" when {
    "there is a session" must {
      "leave the request unfiltered" in {
        val requestWithSessionID = AuthenticatedRequest(
          EmpRef.empty,
          UserName(Name(None, None)),
          FakeRequest("", "")
            .withSession(SessionKeys.sessionId -> s"session-${UUID.randomUUID}")
        )
        val result               = new Harness().callTransform(requestWithSessionID)
        whenReady(result) {
          _ mustBe Right(requestWithSessionID)
        }
      }
    }

    "the session is not set" must {
      "redirect user to home page controller " in {
        val request = AuthenticatedRequest(EmpRef.empty, UserName(Name(None, None)), FakeRequest("", ""))
        val result  = new Harness().callTransform(request)

        whenReady(result) { call: Either[Result, AuthenticatedRequest[_]] =>
          call match {
            case Left(callResult) =>
              val headers: Map[String, String] = callResult.header.headers
              headers.getOrElse("Location", "") must include("/payrollbik/registered-benefits-expenses")
            case Right(_)         => fail("Result not a Left")
          }
        }
      }
    }
  }

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>IInformazioniProdotto</title>
<meta name="date" content="2015-02-13">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

gameshop.advance.interfaces

Interface IInformazioniProdotto

All Known Implementing Classes:

InformazioniProdotto

public interface IInformazioniProdotto

Interfaccia remota per l'esportazione delle classi che la implementano tramite
 Java RMI, IInformazioniProdotto consente di modificare le informazioni relative a un prodotto del catalogo.

Method Summary

Methods

Modifier and Type
Method and Description

void
setDescrizione(IDescrizioneProdotto descrizione)

Aggiunge descrizioni prodotto

void
setOrdinati(int ordinati)

void
setPrenotati(int prenotati)

Method Detail

setDescrizione

void setDescrizione(IDescrizioneProdotto descrizione)

Aggiunge descrizioni prodotto

Parameters:

descrizione -

setPrenotati

void setPrenotati(int prenotati)
                  throws QuantityException

Parameters:

prenotati -

Throws:

QuantityException

setOrdinati

void setOrdinati(int ordinati)
                 throws QuantityException

Parameters:

ordinati -

Throws:

QuantityException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
printf "\nHighlighting inline code blocks...\n"

old_string='<code>'
new_string='<code class="inline_code">'

if [ -e "../notebooks/" ]
then
    find ../notebooks -iname '*.html' | xargs sed -i "s/$old_string/$new_string/g"
else
    find notebooks -iname '*.html' | xargs sed -i "s/$old_string/$new_string/g"
fi

printf "  Highlighted inline code blocks.\n"


text:
<?php
  //iniciamos sesión - SIEMPRE TIENE QUE ESTAR EN LA PRIMERA LÍNEA
  session_start();
  include("conexion.proc.php");
?>

<!DOCTYPE html>

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

    <title>MyContacts</title>

    <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

    <link href="css/agency.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>

                <?php
                  if(isset($_SESSION['usu_nombre']) ){
                    echo "".$_SESSION['usu_nombre']."";
                ?>

                          Mis contactos

                        Añadir contacto

                        Log Out

 <?php
  if(isset($_SESSION['error_contacto'])){
    echo"".$_SESSION['error_contacto']."";
  }
?>

<?php
   extract($_REQUEST);

   $sql = "SELECT  * FROM tbl_usuario WHERE tbl_usuario.usu_id = ".$_SESSION['usu_id'];
   //echo $sql;
   $usuarios = mysqli_query($conexion, $sql);

   if(mysqli_num_rows($usuarios)>0){

      while($usuario = mysqli_fetch_array($usuarios)){

        echo "<form name='modificar_usuario' action='modificar_usuario.proc.php?usu_id=".$usuario['usu_id']."' id='contact_form' runat='server'>";

        echo "
 ";
        echo " <h7 class='control'>Nombre :</h7>
 <h7 class='control'>Email :</h7>
 <h7 class='control'> Contraseña :</h7>
 <h7 class='control'> Repite Contraseña :</h7>

 </h7>

";

        echo "<input type='text' name='nombre' placeholder='Nombre usuario' value='".$usuario['usu_nombre']."' class='form-control'/>
";
        echo "<input type='email' name='email' placeholder='email@email.com' value='".$usuario['usu_email']."' class='form-control'/>
" ;
        echo "<input type='password' name='password' placeholder='Contraseña' value='".$usuario['usu_password']."' class='form-control'/>
";
        echo "<input type='password' name='repite_password' placeholder='Repite Contraseña' value='".$usuario['usu_password']."' class='form-control'/>
";
        echo "<input type='text' style='display:none;' name='usu_id' value=".$usuario['usu_id']." />";
        ;
        echo "
";;
         ?>

<h7 class='control'> Eliminar cuenta: </h7>

<a href='#' onclick='return Confirmar(<?php echo $usuario['usu_id']?>);'>

         <?php
        echo "

<button type='submit' class='page-scroll btn btn-xl'>Modificar contacto</button>
";

      }
} else{
       // echo "No tienes contactos, agrega a uno!";
      }
?>

   <?php }
     else {
        //como han intentado acceder de manera incorrecta, redirigimos a la página login.php con un mensaje de error
        $_SESSION['error']="PILLÍN! Tienes que loguearte primero!";
        header("location: login.php");
      }

      //end if(isset($_SESSION['mail'])){
      ?>

                    Copyright © Eric y Marc Petit 2017

Contacto

Terms of Use


text:
package by.auto.test.model;

import com.google.common.collect.ForwardingSet;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by aleksey.dobrovolsky on 4/29/2017.
 */
public class Contacts extends ForwardingSet<ContactObject> {

    @Override
    protected Set<ContactObject> delegate() {
        return delegate;
    }

    private Set<ContactObject> delegate;

    public Contacts(Contacts contacts) {
        this.delegate = new HashSet<ContactObject>(contacts.delegate);
    }
    public Contacts() {
        this.delegate = new HashSet<ContactObject>();
    }

    public Contacts withAdded (ContactObject contact){
        Contacts contacts = new Contacts(this);
        contacts.add(contact);
        return contacts;
    }

    public Contacts without (ContactObject group){
        Contacts contacts = new Contacts(this);
        contacts.remove(group);
        return contacts;
    }
}