"""
This module defines the StructuredDomain class,
that represents a generic neuroimaging kind of domain
This is meant to provide a unified API to deal with n-d imaged and meshes.

Author: Bertrand Thirion, 2010
"""
from __future__ import absolute_import
import numpy as np
import scipy.sparse as sp

from nibabel import load, Nifti1Image, save

from nipy.io.nibcompat import get_header, get_affine
from nipy.algorithms.graph import (WeightedGraph, wgraph_from_coo_matrix,
                                   wgraph_from_3d_grid)

from nipy.externals.six import string_types

##############################################################
# Ancillary functions
##############################################################

def smatrix_from_3d_array(mask, nn=18):
    """Create a sparse adjacency matrix from an array

    Parameters
    ----------
    mask : 3d array,
           input array, interpreted as a mask
    nn: int, optional
        3d neighboring system to be chosen within {6, 18, 26}

    Returns
    -------
    coo_mat: a sparse coo matrix,
             adjacency of the neighboring system

    """
    ijk = np.array(np.where(mask)).T
    return smatrix_from_3d_idx(ijk, nn)

def smatrix_from_3d_idx(ijk, nn=18):
    """Create a sparse adjacency matrix from 3d index system

    Parameters
    ----------
    idx:array of shape (n_samples, 3), type int
        indexes of certain positions in a 3d space
    nn: int, optional
        3d neighboring system to be chosen within {6, 18, 26}

    Returns
    -------
    coo_mat: a sparse coo matrix,
             adjacency of the neighboring system

    """
    G = wgraph_from_3d_grid(ijk, nn)
    return G.to_coo_matrix()

def smatrix_from_nd_array(mask, nn=0):
    """Create a sparse adjacency matrix from an arbitrary nd array

    Parameters
    ----------
    mask : nd array,
           input array, interpreted as a mask
    nn: int, optional
        nd neighboring system, unsused at the moment

    Returns
    -------
    coo_mat: a sparse coo matrix,
             adjacency of the neighboring system

    """
    idx = np.array(np.where(mask)).T
    return smatrix_from_nd_idx(idx, nn)

def smatrix_from_nd_idx(idx, nn=0):
    """Create a sparse adjacency matrix from nd index system

    Parameters
    ----------
    idx:array of shape (n_samples, dim), type int
        indexes of certain positions in a nd space
    nn: int, optional
        nd neighboring system, unused at the moment

    Returns
    -------
    coo_mat: a sparse coo matrix,
             adjacency of the neighboring system

    """
    n = idx.shape[0]
    dim = idx.shape[1]
    nidx = idx - idx.min(0)
    eA = []
    eB = []

    # compute the edges in each possible direction
    for d in range(dim):
        mi = nidx.max(0) + 2
        a = np.hstack((1, np.cumprod(mi[:dim - 1])))
        v1 = np.dot(nidx, a)
        assert(np.size(v1) == np.size(np.unique(v1)))
        o1 = np.argsort(v1)
        sv1 = v1[o1]
        nz = np.squeeze(np.nonzero(sv1[:n - 1] - sv1[1:] == - 1))
        nz = np.reshape(nz, np.size(nz))
        eA.append(o1[nz])
        eB.append(o1[nz + 1])
        nidx = np.roll(nidx, 1, 1)

    eA = np.concatenate(eA)
    eB = np.concatenate(eB)
    E = 2 * np.size(eA)
    # create a graph structure
    if E == 0:
        return sp.coo_matrix((n, n))

    edges = np.vstack((np.hstack((eA, eB)), np.hstack((eB, eA)))).T
    weights = np.ones(E)
    G = WeightedGraph(n, edges, weights)
    return G.to_coo_matrix()

def array_affine_coord(mask, affine):
    """Compute coordinates from a boolean array and an affine transform

    Parameters
    ----------
    mask: nd array,
           input array, interpreted as a mask
    affine: (n+1, n+1) matrix,
            affine transform that maps the mask points to some embedding space

    Returns
    -------
    coords: array of shape(sum(mask>0), n),
            the computed coordinates

    """
    idx = np.array(np.where(mask)).T
    return idx_affine_coord(idx, affine)

def idx_affine_coord(idx, affine):
    """Compute coordinates from a set of indexes and an affine transform

    Parameters
    ----------
    idx:array of shape (n_samples, dim), type int
        indexes of certain positions in a nd space
    affine: (n+1, n+1) matrix,
            affine transform that maps the mask points to some embedding space

    Returns
    -------
    coords: array of shape(sum(mask>0), n),
            the computed coordinates

    """
    size = idx.shape[0]
    hidx = np.hstack((idx, np.ones((size, 1))))
    coord = np.dot(hidx, affine.T)[:, 0:-1]
    return coord

def reduce_coo_matrix(mat, mask):
    """Reduce a supposedly coo_matrix to the vertices in the mask

    Parameters
    ----------
    mat: sparse coo_matrix,
         input matrix
    mask: boolean array of shape mat.shape[0],
          desired elements

    """
    G = wgraph_from_coo_matrix(mat)
    K = G.subgraph(mask)
    if K is None:
        return None
    return K.to_coo_matrix()

#################################################################
# Functions to instantiate StructuredDomains
#################################################################
def domain_from_binary_array(mask, affine=None, nn=0):
    """Return a StructuredDomain from an n-d array

    Parameters
    ----------
    mask: np.array instance
          a supposedly boolean array that repesents the domain
    affine: np.array, optional
            affine transform that maps the array coordinates
            to some embedding space
            by default, this is np.eye(dim+1, dim+1)
    nn: neighboring system considered
        unsued at the moment

    """
    dim = len(mask.shape)
    if affine is None:
        affine = np.eye(dim + 1)
    mask = mask > 0
    vol = np.absolute(np.linalg.det(affine)) * np.ones(np.sum(mask))
    coord = array_affine_coord(mask, affine)
    topology = smatrix_from_nd_array(mask)
    return StructuredDomain(dim, coord, vol, topology)

def domain_from_image(mim, nn=18):
    """Return a StructuredDomain instance from the input mask image

    Parameters
    ----------
    mim: NiftiIImage instance, or string path toward such an image
         supposedly a mask (where is used to crate the DD)
    nn: int, optional
        neighboring system considered from the image
        can be 6, 18 or 26

    Returns
    -------
    The corresponding StructuredDomain instance

    """
    if isinstance(mim, string_types):
        iim = load(mim)
    else:
        iim = mim
    return domain_from_binary_array(iim.get_data(), get_affine(iim), nn)

def grid_domain_from_binary_array(mask, affine=None, nn=0):
    """Return a NDGridDomain from an n-d array

    Parameters
    ----------
    mask: np.array instance
          a supposedly boolean array that repesents the domain
    affine: np.array, optional
            affine transform that maps the array coordinates
            to some embedding space
            by default, this is np.eye(dim+1, dim+1)
    nn: neighboring system considered
        unsued at the moment

    """
    dim = len(mask.shape)
    shape = mask.shape
    if affine is None:
        affine = np.eye(dim + 1)

    mask = mask > 0
    ijk = np.array(np.where(mask)).T
    vol = np.absolute(np.linalg.det(affine[:3, 0:3])) * np.ones(np.sum(mask))
    topology = smatrix_from_nd_idx(ijk, nn)
    return NDGridDomain(dim, ijk, shape, affine, vol, topology)

def grid_domain_from_image(mim, nn=18):
    """Return a NDGridDomain instance from the input mask image

    Parameters
    ----------
    mim: NiftiIImage instance, or string path toward such an image
         supposedly a mask (where is used to crate the DD)
    nn: int, optional
        neighboring system considered from the image
        can be 6, 18 or 26

    Returns
    -------
    The corresponding NDGridDomain instance

    """
    if isinstance(mim, string_types):
        iim = load(mim)
    else:
        iim = mim
    return grid_domain_from_binary_array(iim.get_data(), get_affine(iim), nn)

def grid_domain_from_shape(shape, affine=None):
    """Return a NDGridDomain from an n-d array

    Parameters
    ----------
    shape: tuple
      the shape of a rectangular domain.
    affine: np.array, optional
      affine transform that maps the array coordinates
      to some embedding space.
      By default, this is np.eye(dim+1, dim+1)

    """
    dim = len(shape)
    if affine is None:
        affine = np.eye(dim + 1)

    rect = np.ones(shape)
    ijk = np.array(np.where(rect)).T
    vol = (np.absolute(np.linalg.det(affine[:3, 0:3])) *
           np.ones(int(np.sum(rect))))
    topology = smatrix_from_nd_idx(ijk, 0)
    return NDGridDomain(dim, ijk, shape, affine, vol, topology)

################################################################
# Domain from mesh
################################################################

class MeshDomain(object):
    """
    temporary class to handle meshes
    """

    def __init__(self, coord, triangles):
        """Initialize mesh domain instance

        Parameters
        ----------
        coord: array of shape (n_vertices, 3),
               the node coordinates
        triangles: array of shape(n_triables, 3),
                   indices of the nodes per triangle

        """
        self.coord = coord
        self.triangles = triangles
        self.V = len(coord)
        # fixme: implement consistency checks

    def area(self):
        """Return array of areas for each node

        Returns
        -------
        area: array of shape self.V,
              area of each node

        """
        E = len(self.triangles)
        narea = np.zeros(self.V)

        def _area(a, b):
            """Area spanned by the vectors(a,b) in 3D
            """
            c = np.array([a[1] * b[2] - a[2] * b[1],
                          - a[0] * b[2] + a[2] * b[0],
                          a[0] * b[1] - a[1] * b[0]])
            return np.sqrt((c ** 2).sum())

        for e in range(E):
            i, j, k = self.triangles[e]
            a = self.coord[i] - self.coord[k]
            b = self.coord[j] - self.coord[k]
            ar = _area(a, b)
            narea[i] += ar
            narea[j] += ar
            narea[k] += ar

        narea /= 6
        # because division by 2 has been 'forgotten' in area computation
        # the area of a triangle is divided into the 3 vertices
        return narea

    def topology(self):
        """Returns a sparse matrix that represents the connectivity in self
        """
        E = len(self.triangles)
        edges = np.zeros((3 * E, 2))
        weights = np.ones(3 * E)

        for i in range(E):
            sa, sb, sc = self.triangles[i]
            edges[3 * i] = np.array([sa, sb])
            edges[3 * i + 1] = np.array([sa, sc])
            edges[3 * i + 2] = np.array([sb, sc])

        G = WeightedGraph(self.V, edges, weights)

        # symmeterize the graph
        G = G.symmeterize()

        # remove redundant edges
        G = G.cut_redundancies()

        # make it a metric graph
        G.set_euclidian(self.coord)
        return G.to_coo_matrix()

def domain_from_mesh(mesh):
    """Instantiate a StructuredDomain from a gifti mesh

    Parameters
    ----------
    mesh: nibabel gifti mesh instance, or path to such a mesh

    """
    if isinstance(mesh, string_types):
        from nibabel.gifti import read
        mesh_ = read(mesh)
    else:
        mesh_ = mesh

    if len(mesh_.darrays) == 2:
        cor, tri = mesh_.darrays
    elif len(mesh_.darrays) == 3:
        cor, nor, tri = mesh_.darrays
    else:
        raise Exception("%d arrays in gifti file (case not handled)" \
                            % len(mesh_.darrays))
    mesh_dom = MeshDomain(cor.data, tri.data)

    vol = mesh_dom.area()
    topology = mesh_dom.topology()
    dim = 2
    return StructuredDomain(dim, mesh_dom.coord, vol, topology)

################################################################
# StructuredDomain class
################################################################

class DiscreteDomain(object):
    """
    Descriptor of a certain domain that consists of discrete elements that
    are characterized by a coordinate system and a topology:
    the coordinate system is specified through a coordinate array
    the topology encodes the neighboring system

    """

    def __init__(self, dim, coord, local_volume, id='', referential=''):
        """Initialize discrete domain instance

        Parameters
        ----------
        dim: int
            the (physical) dimension of the domain.
        coord: array of shape(size, em_dim)
            explicit coordinates of the domain sites.
        local_volume: array of shape(size)
            yields the volume associated with each site.
        id: string, optional
            domain identifier.
        referential: string, optional
            identifier of the referential of the coordinates system.

        Notes
        -----
        Caveat: em_dim may be greater than dim e.g. (meshes coordinate in 3D)
        """
        # dimension
        self.dim = dim

        # number of discrete elements
        self.size = coord.shape[0]

        # coordinate system
        if np.size(coord) == coord.shape[0]:
            coord = np.reshape(coord, (np.size(coord), 1))

        if np.size(coord) == 0:
            self.em_dim = dim
        else:
            self.em_dim = coord.shape[1]

        if self.em_dim < dim:
            raise ValueError('Embedding dimension cannot be smaller than dim')
        self.coord = coord

        # volume
        if np.size(local_volume) != self.size:
            raise ValueError("Inconsistent Volume size")
        if (local_volume < 0).any():
            raise ValueError('Volume should be positive')

        self.local_volume = np.ravel(local_volume)
        self.id = id
        self.referential = referential
        self.features = {}

    def copy(self):
        """Returns a copy of self
        """
        new_dom = DiscreteDomain(self.dim, self.coord.copy(),
                                  self.local_volume.copy(), self.id,
                                  self.referential)
        for fid in list(self.features.keys()):
            new_dom.set_feature(fid, self.get_feature(fid).copy())
        return new_dom

    def get_coord(self):
        """Returns self.coord
        """
        return self.coord

    def get_volume(self):
        """Returns self.local_volume
        """
        return self.local_volume

    def connected_components(self):
        """returns a labelling of the domain into connected components
        """
        if self.topology is not None:
            return wgraph_from_coo_matrix(self.topology).cc()
        else:
            return []

    def mask(self, bmask, id=''):
        """Returns an DiscreteDomain instance that has been further masked
        """
        if bmask.size != self.size:
            raise ValueError('Invalid mask size')

        svol = self.local_volume[bmask]
        scoord = self.coord[bmask]
        DD = DiscreteDomain(self.dim, scoord, svol, id, self.referential)

        for fid in list(self.features.keys()):
            f = self.features.pop(fid)
            DD.set_feature(fid, f[bmask])
        return DD

    def set_feature(self, fid, data, override=True):
        """Append a feature 'fid'

        Parameters
        ----------
        fid: string,
             feature identifier
        data: array of shape(self.size, p) or self.size
              the feature data

        """
        if data.shape[0] != self.size:
            raise ValueError('Wrong data size')

        if (fid in self.features) & (override == False):
            return

        self.features.update({fid: data})

    def get_feature(self, fid):
        """Return self.features[fid]
        """
        return self.features[fid]

    def representative_feature(self, fid, method):
        """Compute a statistical representative of the within-Foain feature

        Parameters
        ----------
        fid: string, feature id
        method: string, method used to compute a representative
                to be chosen among 'mean', 'max', 'median', 'min'

        """
        f = self.get_feature(fid)
        if method == "mean":
            return np.mean(f, 0)
        if method == "min":
            return np.min(f, 0)
        if method == "max":
            return np.max(f, 0)
        if method == "median":
            return np.median(f, 0)

    def integrate(self, fid):
        """Integrate  certain feature over the domain and returns the result

        Parameters
        ----------
        fid : string,  feature identifier,
              by default, the 1 function is integrataed, yielding domain volume

        Returns
        -------
        lsum = array of shape (self.feature[fid].shape[1]),
               the result

        """
        if fid is None:
            return np.sum(self.local_volume)
        ffid = self.features[fid]
        if np.size(ffid) == ffid.shape[0]:
            ffid = np.reshape(ffid, (self.size, 1))
        slv = np.reshape(self.local_volume, (self.size, 1))
        return np.sum(ffid * slv, 0)

class StructuredDomain(DiscreteDomain):
    """
    Besides DiscreteDomain attributed, StructuredDomain has a topology,
    which allows many operations (morphology etc.)
    """

    def __init__(self, dim, coord, local_volume, topology, did='',
                 referential=''):
        """Initialize structured domain instance

        Parameters
        ----------
        dim: int,
             the (physical) dimension of the domain
        coord: array of shape(size, em_dim),
               explicit coordinates of the domain sites
        local_volume: array of shape(size),
                      yields the volume associated with each site
        topology: sparse binary coo_matrix of shape (size, size),
                  that yields the neighboring locations in the domain
        did: string, optional,
             domain identifier
        referential: string, optional,
                     identifier of the referential of the coordinates system

        """
        DiscreteDomain.__init__(self, dim, coord, local_volume, id,
                                referential)

        # topology
        if topology is not None:
            if topology.shape != (self.size, self.size):
                raise ValueError('Incompatible shape for topological model')
        self.topology = topology

    def mask(self, bmask, did=''):
        """Returns a StructuredDomain instance that has been further masked
        """
        td = DiscreteDomain.mask(self, bmask)
        stopo = reduce_coo_matrix(self.topology, bmask)
        dd = StructuredDomain(self.dim, td.coord, td.local_volume,
                            stopo, did, self.referential)

        for fid in list(td.features.keys()):
            dd.set_feature(fid, td.features.pop(fid))
        return dd

class NDGridDomain(StructuredDomain):
    """
    Particular instance of StructuredDomain, that receives
    3 additional variables:
    affine: array of shape (dim+1, dim+1),
            affine transform that maps points to a coordinate system
    shape: dim-tuple,
           shape of the domain
    ijk: array of shape(size, dim), int
         grid coordinates of the points

    This is to allow easy conversion to images when dim==3,
    and for compatibility with previous classes

    """

    def __init__(self, dim, ijk, shape, affine, local_volume, topology,
                referential=''):
        """Initialize ndgrid domain instance

        Parameters
        ----------
        dim: int,
             the (physical) dimension of the domain
        ijk: array of shape(size, dim), int
             grid coordinates of the points
        shape: dim-tuple,
           shape of the domain
        affine: array of shape (dim+1, dim+1),
            affine transform that maps points to a coordinate system
        local_volume: array of shape(size),
                      yields the volume associated with each site
        topology: sparse binary coo_matrix of shape (size, size),
                  that yields the neighboring locations in the domain
        referential: string, optional,
                     identifier of the referential of the coordinates system

        Notes
        -----
        FIXME: local_volume might be computed on-the-fly as |det(affine)|
        """
        # shape
        if len(shape) != dim:
            raise ValueError('Incompatible shape and dim')
        self.shape = shape

        # affine
        if affine.shape != (dim + 1, dim + 1):
            raise ValueError('Incompatible dim and affine')
        self.affine = affine

        # ijk
        if (np.size(ijk) == ijk.shape[0]) & (np.size(ijk) > 0):
            ijk = np.reshape(ijk, (ijk.size, 1))
            if (ijk.max(0) + 1 > shape).any():
                raise ValueError('Provided indices do not fit within shape')
        self.ijk = ijk

        # coord
        coord = idx_affine_coord(ijk, affine)

        StructuredDomain.__init__(self, dim, coord, local_volume, topology)

    def mask(self, bmask):
        """Returns an instance of self that has been further masked
        """
        if bmask.size != self.size:
            raise ValueError('Invalid mask size')

        svol = self.local_volume[bmask]
        stopo = reduce_coo_matrix(self.topology, bmask)
        sijk = self.ijk[bmask]
        DD = NDGridDomain(self.dim, sijk, self.shape, self.affine, svol,
                          stopo, self.referential)

        for fid in list(self.features.keys()):
            f = self.features.pop(fid)
            DD.set_feature(fid, f[bmask])
        return DD

    def to_image(self, path=None, data=None):
        """Write itself as a binary image, and returns it

        Parameters
        ----------
        path: string, path of the output image, if any
        data: array of shape self.size,
              data to put in the nonzer-region of the image

        """
        if data is None:
            wdata = np.zeros(self.shape, np.int8)
        else:
            wdata = np.zeros(self.shape, data.dtype)
        wdata[self.ijk[:, 0], self.ijk[:, 1], self.ijk[:, 2]] = 1
        if data is not None:
            if data.size != self.size:
                raise ValueError('incorrect data size')
            wdata[wdata > 0] = data

        nim = Nifti1Image(wdata, self.affine)
        get_header(nim)['descrip'] = ('mask image representing domain %s'
                                      % self.id)
        if path is not None:
            save(nim, path)
        return nim

    def make_feature_from_image(self, path, fid=''):
        """Extract the information from an image to make it a domain a feature

        Parameters
        ----------
        path: string or Nifti1Image instance,
              the image from which one wished to extract data
        fid: string, optional
             identifier of the resulting feature.
             if '', the feature is not stored

        Returns
        -------
        the correponding set of values

        """
        if isinstance(path, string_types):
            nim = load(path)
        else:
            nim = path

        if (get_affine(nim) != self.affine).any():
            raise ValueError('nim and self do not have the same referential')

        data = nim.get_data()
        feature = data[self.ijk[:, 0], self.ijk[:, 1], self.ijk[:, 2]]
        if fid is not '':
            self.features[fid] = feature

        return feature

{'repo_name': 'nipy/nipy', 'stars': '274', 'repo_language': 'Python', 'file_name': 'enn_demo.py', 'mime_type': 'text/x-python', 'hash': 4668329629793018673, 'source_dataset': 'data'}


# Copyright 2013 the V8 project authors. All rights reserved.
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1.  Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
# 2.  Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

KDE JS Test

On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".

PASS successfullyParsed is true

TEST COMPLETE

{'repo_name': 'nodejs/node-v8', 'stars': '218', 'repo_language': 'JavaScript', 'file_name': 'array-prototype-lastindexof.js', 'mime_type': 'text/plain', 'hash': -8036577885766407272, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<scenario boes="2.1.5">
    <title>Test Scenario</title>
    <icon>7</icon>
    <id>campaign</id>
    <version>2.6.7</version>
    <language>en-US</language>
    <author>
        <name>BoE Test Suite</name>
        <email>nowhere@example.com</email>
    </author>
    <text>
        <teaser>Teaser 1</teaser>
        <teaser>Teaser 2</teaser>
        <icon>12</icon>
        <intro-msg><![CDATA[Welcome!!!    To the test scenario!]]></intro-msg>
    </text>
    <ratings>
        <content>R</content>
        <difficulty>3</difficulty>
    </ratings>
    <flags>
        <adjust-difficulty>true</adjust-difficulty>
        <legacy>false</legacy>
        <custom-graphics>false</custom-graphics>
    </flags>
    <creator>
        <type>oboe</type>
        <version>2.5.3</version>
        <os></os>
    </creator>
    <game>
        <num-towns>3</num-towns>
        <out-width>2</out-width>
        <out-height>1</out-height>
        <start-town>7</start-town>
        <town-start x="24" y="28" />
        <outdoor-start x="1" y="3" />
        <sector-start x="12" y="21" />
    </game>
    <editor>
        <default-ground>2</default-ground>
        <last-out-section x="0" y="0" />
        <last-town>0</last-town>
    </editor>
</scenario>

{'repo_name': 'calref/cboe', 'stars': '109', 'repo_language': 'C++', 'file_name': 'boe_test.xcscheme', 'mime_type': 'text/xml', 'hash': 4897383010814056287, 'source_dataset': 'data'}


/*
 * =============================================================================
 *
 *   Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
 *
 *   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.
 *
 * =============================================================================
 */
package org.thymeleaf.expression;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.util.Validate;

/**
 *

 *   Expression Object for retrieving externalized/internationalized messages from inside Thymeleaf Standard Expressions.
 *

 *

 *   An object of this class is usually available in variable evaluation expressions with the name
 *   {@code #messages}.
 *

 *
 * @author Daniel Fernández
 *
 * @since 1.0
 *
 */
public class Messages {

    private static final String[] NO_PARAMETERS = new String[0];

    private final ITemplateContext context;

    public String msg(final String messageKey) {
        return msgWithParams(messageKey, NO_PARAMETERS);
    }

    public String msg(final String messageKey, final Object messageParameter0) {
        return msgWithParams(messageKey, new Object[] { messageParameter0 });
    }

    public String msg(final String messageKey, final Object messageParameter0, final Object messageParameter1) {
        return msgWithParams(messageKey, new Object[] { messageParameter0, messageParameter1 });
    }

    public String msg(final String messageKey, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return msgWithParams(messageKey, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public String msgWithParams(final String messageKey, final Object[] messageParameters) {
        return this.context.getMessage(null, messageKey, messageParameters, true);
    }

    public String msgOrNull(final String messageKey) {
        return msgOrNullWithParams(messageKey, NO_PARAMETERS);
    }

    public String msgOrNull(final String messageKey, final Object messageParameter0) {
        return msgOrNullWithParams(messageKey, new Object[] { messageParameter0 });
    }

    public String msgOrNull(final String messageKey, final Object messageParameter0, final Object messageParameter1) {
        return msgOrNullWithParams(messageKey, new Object[] { messageParameter0, messageParameter1 });
    }

    public String msgOrNull(final String messageKey, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return msgOrNullWithParams(messageKey, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public String msgOrNullWithParams(final String messageKey, final Object[] messageParameters) {
        return this.context.getMessage(null, messageKey, messageParameters, false);
    }

    public String[] arrayMsg(final Object[] messageKeys) {
        return arrayMsgWithParams(messageKeys, NO_PARAMETERS);
    }

    public String[] arrayMsg(final Object[] messageKeys, final Object messageParameter0) {
        return arrayMsgWithParams(messageKeys, new Object[] { messageParameter0 });
    }

    public String[] arrayMsg(final Object[] messageKeys, final Object messageParameter0, final Object messageParameter1) {
        return arrayMsgWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1 });
    }

    public String[] arrayMsg(final Object[] messageKeys, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return arrayMsgWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public String[] arrayMsgWithParams(final Object[] messageKeys, final Object[] messageParameters) {
        Validate.notNull(messageKeys, "Message keys cannot be null");
        final String[] result = new String[messageKeys.length];
        for (int i = 0; i < messageKeys.length; i++) {
            result[i] =
               this.context.getMessage(null, (String)messageKeys[i], messageParameters, true);
        }
        return result;
    }

    public String[] arrayMsgOrNull(final Object[] messageKeys) {
        return arrayMsgOrNullWithParams(messageKeys, NO_PARAMETERS);
    }

    public String[] arrayMsgOrNull(final Object[] messageKeys, final Object messageParameter0) {
        return arrayMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0 });
    }

    public String[] arrayMsgOrNull(final Object[] messageKeys, final Object messageParameter0, final Object messageParameter1) {
        return arrayMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1 });
    }

    public String[] arrayMsgOrNull(final Object[] messageKeys, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return arrayMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public String[] arrayMsgOrNullWithParams(final Object[] messageKeys, final Object[] messageParameters) {
        Validate.notNull(messageKeys, "Message keys cannot be null");
        final String[] result = new String[messageKeys.length];
        for (int i = 0; i < messageKeys.length; i++) {
            result[i] =
                    this.context.getMessage(null, (String) messageKeys[i], messageParameters, false);
        }
        return result;
    }

    public List<String> listMsg(final List<String> messageKeys) {
        return listMsgWithParams(messageKeys, NO_PARAMETERS);
    }

    public List<String> listMsg(final List<String> messageKeys, final Object messageParameter0) {
        return listMsgWithParams(messageKeys, new Object[] { messageParameter0 });
    }

    public List<String> listMsg(final List<String> messageKeys, final Object messageParameter0, final Object messageParameter1) {
        return listMsgWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1 });
    }

    public List<String> listMsg(final List<String> messageKeys, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return listMsgWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public List<String> listMsgWithParams(final List<String> messageKeys, final Object[] messageParameters) {
        Validate.notNull(messageKeys, "Message keys cannot be null");
        return doMsg(true, messageKeys, messageParameters);
    }

    public List<String> listMsgOrNull(final List<String> messageKeys) {
        return listMsgOrNullWithParams(messageKeys, NO_PARAMETERS);
    }

    public List<String> listMsgOrNull(final List<String> messageKeys, final Object messageParameter0) {
        return listMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0 });
    }

    public List<String> listMsgOrNull(final List<String> messageKeys, final Object messageParameter0, final Object messageParameter1) {
        return listMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1 });
    }

    public List<String> listMsgOrNull(final List<String> messageKeys, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return listMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public List<String> listMsgOrNullWithParams(final List<String> messageKeys, final Object[] messageParameters) {
        Validate.notNull(messageKeys, "Message keys cannot be null");
        return doMsg(false, messageKeys, messageParameters);
    }

    public Set<String> setMsg(final Set<String> messageKeys) {
        return setMsgWithParams(messageKeys, NO_PARAMETERS);
    }

    public Set<String> setMsg(final Set<String> messageKeys, final Object messageParameter0) {
        return setMsgWithParams(messageKeys, new Object[] { messageParameter0 });
    }

    public Set<String> setMsg(final Set<String> messageKeys, final Object messageParameter0, final Object messageParameter1) {
        return setMsgWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1 });
    }

    public Set<String> setMsg(final Set<String> messageKeys, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return setMsgWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public Set<String> setMsgWithParams(final Set<String> messageKeys, final Object[] messageParameters) {
        Validate.notNull(messageKeys, "Message keys cannot be null");
        return new LinkedHashSet<String>(doMsg(true, messageKeys, messageParameters));
    }

    public Set<String> setMsgOrNull(final Set<String> messageKeys) {
        return setMsgOrNullWithParams(messageKeys, NO_PARAMETERS);
    }

    public Set<String> setMsgOrNull(final Set<String> messageKeys, final Object messageParameter0) {
        return setMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0 });
    }

    public Set<String> setMsgOrNull(final Set<String> messageKeys, final Object messageParameter0, final Object messageParameter1) {
        return setMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1 });
    }

    public Set<String> setMsgOrNull(final Set<String> messageKeys, final Object messageParameter0, final Object messageParameter1, final Object messageParameter2) {
        return setMsgOrNullWithParams(messageKeys, new Object[] { messageParameter0, messageParameter1, messageParameter2 });
    }

    public Set<String> setMsgOrNullWithParams(final Set<String> messageKeys, final Object[] messageParameters) {
        Validate.notNull(messageKeys, "Message keys cannot be null");
        return new LinkedHashSet<String>(doMsg(false, messageKeys, messageParameters));
    }

    private List<String> doMsg(final boolean useAbsentMessageRepresentation, final Iterable<String> messageKeys, final Object... messageParameters) {
        final List<String> result = new ArrayList<String>(5);
        for (final String messageKey : messageKeys) {
            result.add(
                    this.context.getMessage(null, messageKey, messageParameters, useAbsentMessageRepresentation));
        }
        return result;
    }

    public Messages(final ITemplateContext context) {
        super();
        Validate.notNull(context, "Context cannot be null");
        this.context = context;
    }

}

{'repo_name': 'thymeleaf/thymeleaf', 'stars': '1921', 'repo_language': 'Java', 'file_name': 'MANIFEST.MF', 'mime_type': 'text/plain', 'hash': 5368635600237572677, 'source_dataset': 'data'}


<?php

namespace InstagramScraper\Model;

/**
 * Class Media
 * @package InstagramScraper\Model
 */
class ReelMedia extends AbstractModel
{
    /**
     * @var string
     */
    protected $id;

    /**
     * @var string
     */
    protected $caption;

    /**
     * @var string
     */
    protected $code;

    /**
     * @var int
     */
    protected $expiringAt;

    /**
     * @var string
     */
    protected $image;

    /**
     * @var Account
     */
    protected $user;

    /**
     * @var Account[]
     */
    protected $mentions;

    /**
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getCaption()
    {
        return $this->caption;
    }

    /**
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @return string
     */
    public function getExpiringAt()
    {
        return $this->expiringAt;
    }

    /**
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * @return Account
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @return Account[]
     */
    public function getMentions()
    {
        return $this->mentions;
    }

    /**
     * @param $value
     * @param $prop
     * @param $arr
     */
    protected function initPropertiesCustom($value, $prop, $arr)
    {
        switch ($prop) {
            case 'id':
                $this->id = $value;
                break;
            case 'caption':
                $this->caption = isset($arr[$prop]['text']) ? $arr[$prop]['text'] : null;
                break;
            case 'code':
                $this->code = $value;
                break;
            case 'expiring_at':
                $this->expiringAt = (int)$value;
                break;
            case 'reel_mentions':
                foreach ($arr[$prop] as $mention) {
                    if (!$mention['user']) {
                        continue;
                    }

                    $this->mentions[] = Account::create($mention['user']);
                }
                break;
            case 'user':
                $this->user = Account::create($arr[$prop]);
                break;
            case 'image_versions2':
                foreach ($arr[$prop]['candidates'] as $candidate) {
                    if (!$candidate['url']) {
                        continue;
                    }

                    $this->image = $candidate['url'];
                    break;
                }
                break;
        }
    }
}

{'repo_name': 'postaddictme/instagram-php-scraper', 'stars': '1860', 'repo_language': 'PHP', 'file_name': 'InstagramTest.php', 'mime_type': 'text/x-php', 'hash': 3972295835591529727, 'source_dataset': 'data'}


# mattermost postgres worker
apiVersion: v1
kind: Pod
metadata:
  name: mattermost-database
  labels:
    app: mattermost
    role: mattermost-database
spec:
  containers:
  - name: mattermost-postgres
    image: postgres:12.2
    ports:
      - containerPort: 5432
    env:
      - name: POSTGRES_HOST_AUTH_METHOD
        value: "trust"

{'repo_name': 'gravitational/workshop', 'stars': '1870', 'repo_language': 'Go', 'file_name': 'debug.yaml', 'mime_type': 'text/plain', 'hash': -7806424854704694159, 'source_dataset': 'data'}


/*=============================================================================
    Copyright (c) 2005-2012 Joel de Guzman
    Copyright (c) 2005-2006 Dan Marsden

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_FUSION_DEQUE_AT_IMPL_09122006_2017)
#define BOOST_FUSION_DEQUE_AT_IMPL_09122006_2017

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/container/deque/detail/keyed_element.hpp>

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/identity.hpp>

#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/add_reference.hpp>

namespace boost { namespace fusion
{
    struct deque_tag;

    namespace extension
    {
        template<typename T>
        struct at_impl;

        template<>
        struct at_impl<deque_tag>
        {
            template<typename Sequence, typename N>
            struct apply
            {
                typedef typename Sequence::next_up next_up;
                typedef typename Sequence::next_down next_down;
                BOOST_MPL_ASSERT_RELATION(next_down::value, !=, next_up::value);

                static int const offset = next_down::value + 1;
                typedef mpl::int_<(N::value + offset)> adjusted_index;
                typedef typename
                    detail::keyed_element_value_at<Sequence, adjusted_index>::type
                element_type;

                typedef typename
                    add_reference<
                      typename mpl::eval_if<
                      is_const<Sequence>,
                      add_const<element_type>,
                      mpl::identity<element_type> >::type
                    >::type
                type;

                BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
                static type call(Sequence& seq)
                {
                    return seq.get(adjusted_index());
                }
            };
        };
    }
}}

#endif

{'repo_name': 'Source-Python-Dev-Team/Source.Python', 'stars': '107', 'repo_language': 'Python', 'file_name': 'readme.md', 'mime_type': 'text/plain', 'hash': 5671787242158687180, 'source_dataset': 'data'}


// ------------------------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>

// Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt

namespace Microsoft.Graph
{
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;

    /// <summary>
    /// The type WorkbookFunctionsXnpvRequestBody.
    /// </summary>
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public partial class WorkbookFunctionsXnpvRequestBody
    {

        /// <summary>
        /// Gets or sets Rate.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "rate", Required = Newtonsoft.Json.Required.Default)]
        public Newtonsoft.Json.Linq.JToken Rate { get; set; }

        /// <summary>
        /// Gets or sets Values.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "values", Required = Newtonsoft.Json.Required.Default)]
        public Newtonsoft.Json.Linq.JToken Values { get; set; }

        /// <summary>
        /// Gets or sets Dates.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "dates", Required = Newtonsoft.Json.Required.Default)]
        public Newtonsoft.Json.Linq.JToken Dates { get; set; }

    }
}

{'repo_name': 'microsoftgraph/msgraph-sdk-dotnet', 'stars': '322', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -7634442356822523345, 'source_dataset': 'data'}


@aws-sdk/client-polly

[![NPM version](https://img.shields.io/npm/v/@aws-sdk/client-polly/beta.svg)](https://www.npmjs.com/package/@aws-sdk/client-polly)
[![NPM downloads](https://img.shields.io/npm/dm/@aws-sdk/client-polly.svg)](https://www.npmjs.com/package/@aws-sdk/client-polly)

For SDK usage, please step to [SDK readme](https://github.com/aws/aws-sdk-js-v3).

{'repo_name': 'aws/aws-sdk-js-v3', 'stars': '355', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 7841971543717169474, 'source_dataset': 'data'}


## Guidelines for submitting bugs:

All non security bugs can be filed on the Issues tracker:

<https://github.com/tpm2-software/tpm2-tools/issues>

Security sensitive bugs should be emailed to a maintainer or to Intel
via the guidelines here:

<https://security-center.intel.com/VulnerabilityHandlingGuidelines.aspx>

## Guidelines for submitting changes:

All changes should be introduced via github pull requests. This allows anyone to
comment and provide feedback in lieu of having a mailing list. For pull requests
opened by non-maintainers, any maintainer may review and merge that pull request.
For maintainers, they either must have their pull request reviewed by another
maintainer if possible, or leave the PR open for at least 24 hours, we consider
this the window for comments.

All tests must pass on Travis CI for the merge to occur.
All changes must not introduce superfluous whitespace changes or whitespace errors.
All changes should adhere to the coding standard documented under misc.

### Guideline for merging changes:
Changes should be merged with the "rebase" option on github to avoid merge commits.
This provides for a clear linear history.

{'repo_name': 'tpm2-software/tpm2-tools', 'stars': '311', 'repo_language': 'C', 'file_name': 'RELEASE.md', 'mime_type': 'text/plain', 'hash': -1661408254834117170, 'source_dataset': 'data'}


# Copyright 2019-2020 OmiseGO Pte Ltd
#
# 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.

defmodule OMG.Watcher.BlockGetter.Status do
  @moduledoc """
  Keeps track and exposes the current status of `OMG.Watcher.BlockGetter`.

  The reason to have this is that the parent `OMG.Watcher.BlockGetter` is doing a lot of synchronous heavy lifting and
  can easily become unresponsive when syncing (especially when catching up a lot of blocks).

  Expects current status to be eagerly pushed to it.
  """

  alias OMG.Watcher.BlockGetter.Core

  def start_link() do
    Agent.start_link(fn -> nil end, name: __MODULE__)
  end

  @doc """
  Overwrites the currently stored status with the provided one
  """
  @spec update(Core.chain_ok_response_t()) :: :ok
  def update(status), do: Agent.update(__MODULE__, fn _old_status -> status end)

  @doc """
  Retrieves the freshest information about `OMG.Watcher.BlockGetter`'s status.
  Prefer `OMG.Watcher.BlockGetter.get_events/0` to this
  """
  @spec get_events() :: {:ok, Core.chain_ok_response_t()}
  def get_events(), do: Agent.get(__MODULE__, fn status -> {:ok, status} end)
end

{'repo_name': 'omgnetwork/elixir-omg', 'stars': '184', 'repo_language': 'Elixir', 'file_name': 'watcher_info_entrypoint', 'mime_type': 'text/plain', 'hash': -9009343468165596187, 'source_dataset': 'data'}


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 *
 */
namespace DebugKit\Panel;

use Cake\Cache\Cache;
use DebugKit\Cache\Engine\DebugEngine;
use DebugKit\DebugPanel;

/**
 * A panel for spying on cache engines.
 */
class CachePanel extends DebugPanel
{

    /**
     * The cache spy instances used.
     *
     * @var DebugEngine[]
     */
    protected $_instances = [];

    /**
     * Initialize - install cache spies.
     *
     * @return void
     */
    public function initialize()
    {
        foreach (Cache::configured() as $name) {
            $config = Cache::getConfig($name);
            if (isset($config['className']) && $config['className'] instanceof DebugEngine) {
                $instance = $config['className'];
            } elseif (isset($config['className'])) {
                Cache::drop($name);
                $instance = new DebugEngine($config);
                Cache::setConfig($name, $instance);
            }
            if (isset($instance)) {
                $this->_instances[$name] = $instance;
            }
        }
    }

    /**
     * Get the data for this panel
     *
     * @return array
     */
    public function data()
    {
        $metrics = [];
        foreach ($this->_instances as $name => $instance) {
            $metrics[$name] = $instance->metrics();
        }

        return [
            'metrics' => $metrics
        ];
    }
}

{'repo_name': 'cloudfoundry/php-buildpack', 'stars': '125', 'repo_language': 'PHP', 'file_name': 'server-defaults.conf', 'mime_type': 'text/plain', 'hash': -8643858330442517384, 'source_dataset': 'data'}


Version: @VERSION@
Release: @BUILD_NUMBER@

%define __spec_install_post %{nil}
%define debug_package       %{nil}
%define __os_install_post   %{nil}

Name: @PACKAGE_NAME@
Summary: @PACKAGE_SUMMARY@
License: Apache 2.0
URL: @PACKAGE_URL@
Packager: Greg Szabo
@PACKAGE_ADDITIONAL_HEADER@

%description
@PACKAGE_DESCRIPTION@

%pre
if ! %{__grep} -q '^%{name}:' /etc/passwd ; then
  useradd -r -b %{_sysconfdir} %{name}
  mkdir -p %{_sysconfdir}/%{name}
  chmod 755 %{_sysconfdir}/%{name}
  chown %{name}.%{name} %{_sysconfdir}/%{name}
fi

%prep
# Nothing to do here. - It is done in the Makefile.

%build
# Nothing to do here.

%install
cd %{name}-%{version}-%{release}
%{__cp} -a * %{buildroot}

%post
sudo -Hu %{name} %{name} node init --home %{_sysconfdir}/%{name} 2B24DEE2364762300168DF19B6C18BCE2D399EA2
systemctl daemon-reload

%preun
systemctl stop %{name} 2> /dev/null || :

%postun
systemctl daemon-reload

%files
%ghost %attr(0755, %{name}, %{name}) %dir %{_sysconfdir}/%{name}
%{_bindir}/*
%{_sysconfdir}/systemd/system/*
%{_sysconfdir}/systemd/system-preset/*
%dir %{_datadir}/%{name}
%{_datadir}/%{name}/*
%dir %{_defaultlicensedir}/%{name}
%doc %{_defaultlicensedir}/%{name}/LICENSE

{'repo_name': 'U-Network/UNetwork', 'stars': '188', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 8426581667045694244, 'source_dataset': 'data'}


/*
 * Copyright (c) 2009-2011 Lockheed Martin Corporation
 *
 * 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.
 */
package org.eurekastreams.web.client.ui.common.stream;

import org.eurekastreams.server.domain.Person;
import org.eurekastreams.server.domain.dto.FeaturedStreamDTO;
import org.eurekastreams.web.client.events.EventBus;
import org.eurekastreams.web.client.events.Observer;
import org.eurekastreams.web.client.events.data.AddedFeaturedStreamResponseEvent;
import org.eurekastreams.web.client.model.FeaturedStreamModel;
import org.eurekastreams.web.client.ui.common.dialog.BaseDialogContent;
import org.eurekastreams.web.client.ui.common.form.elements.BasicTextAreaFormElement;
import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * Dialog content for creating or editing a stream view.
 */
public class FeatureDialogContent extends BaseDialogContent
{

    /**
     * Container flow panel.
     */
    private final FlowPanel container = new FlowPanel();

    /**
     * Main flow panel.
     */
    private final FlowPanel body = new FlowPanel();

    /**
     * Default constructor.
     *
     * @param featuredStreamDTO
     *            the featured stream.
     */
    public FeatureDialogContent(final FeaturedStreamDTO featuredStreamDTO)
    {
        Label saveButton = new Label("");
        saveButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().saveChangesButton());

        body.add(new Label("Stream Name: " + featuredStreamDTO.getDisplayName()));

        final BasicTextAreaFormElement textArea = new BasicTextAreaFormElement(Person.MAX_JOB_DESCRIPTION_LENGTH,
                "Description", "description", featuredStreamDTO.getDescription(), "", true);

        body.add(textArea);
        body.add(saveButton);

        saveButton.addClickHandler(new ClickHandler()
        {
            public void onClick(final ClickEvent event)
            {
                featuredStreamDTO.setDescription(textArea.getValue());
                FeaturedStreamModel.getInstance().insert(featuredStreamDTO);
            }
        });

        EventBus.getInstance().addObserver(AddedFeaturedStreamResponseEvent.class,
                new Observer<AddedFeaturedStreamResponseEvent>()
                {
                    public void update(final AddedFeaturedStreamResponseEvent event)
                    {
                        close();
                    }
                });

        container.add(body);

    }

    /**
     * Gets the body panel.
     *
     * @return the body.
     */
    public Widget getBody()
    {
        return container;
    }

    /**
     * Gets the CSS name.
     *
     * @return the class.
     */
    @Override
    public String getCssName()
    {
        return StaticResourceBundle.INSTANCE.coreCss().featureDialog();
    }

    /**
     * Gets the title.
     *
     * @return the title.
     */
    public String getTitle()
    {
        return "Feature Stream";
    }
}

{'repo_name': 'lmco/eurekastreams', 'stars': '171', 'repo_language': 'Java', 'file_name': 'DisplayInfoSettableDataPopulatorTest.java', 'mime_type': 'text/x-java', 'hash': -8477492613770444652, 'source_dataset': 'data'}


// <eddie_source_header>
// This file is part of Eddie/AirVPN software.
// Copyright (C)2014-2019 AirVPN (support@airvpn.org) / https://airvpn.org
//
// Eddie is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Eddie is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Eddie. If not, see <http://www.gnu.org/licenses/>.
// </eddie_source_header>

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Eddie.Core;

namespace Eddie.Forms
{
	public class UiClient : Eddie.Core.UiClient
	{
		public static UiClient Instance;
		public Forms.Main MainWindow;
		public Forms.WindowSplash SplashWindow;

		public ApplicationContext AppContext;
		public Eddie.Forms.Engine Engine;

		public override bool Init(string environmentCommandLine)
		{
			Instance = this;

			AppContext = new ApplicationContext();

			base.Init(environmentCommandLine);

			GuiUtils.Init();

			SplashWindow = new Forms.WindowSplash();
			SplashWindow.Show();

			if(Engine == null)
				Engine = new Eddie.Forms.Engine(environmentCommandLine);
			Engine.TerminateEvent += Engine_TerminateEvent;
			Engine.UiManager.Add(this);

			Engine.Start();

			return true;
		}

		public void OnUnhandledException(string source, Exception e)
		{
			if (Engine != null)
				Engine.OnUnhandledException(source, e);
		}

		private void Engine_TerminateEvent()
		{
			if (SplashWindow != null)
				SplashWindow.RequestClose();

			if (MainWindow != null)
				MainWindow.RequestClose();

			if (AppContext != null)
			    AppContext.ExitThread();

			if (GuiUtils.IsUnix ()) {
				System.Windows.Forms.Application.Exit();
			}
			//Application.Exit(); // Removed in 2.12, otherwise lock Core thread. Still required in Linux edition.
		}

		public override Json Command(Json data)
		{
			string cmd = data["command"].Value as string;
			if (cmd == "ui.show.manifest")
			{
				MainWindow.OnShowText("Json Data", Data.ToJsonPretty());
				return null;
			}
			else
				return Engine.UiManager.SendCommand(data, this);
		}

		public override void OnReceive(Json data)
		{
			base.OnReceive(data);

			string cmd = data["command"].Value as string;

            if (cmd == "test2")
			{
				Forms.WindowMan w = new Forms.WindowMan(); // ClodoTemp
				w.ShowDialog();
			}
			else if (cmd == "log")
			{
				if (data["type"].Value as string == "fatal")
				{
					if (SplashWindow != null)
						SplashWindow.OnMessageError(data["message"].Value as string);
					else if (MainWindow != null)
						MainWindow.OnMessageError(data["message"].Value as string);
					else
						GuiUtils.MessageBoxError(null, data["message"].Value as string);
				}
			}
			else if (cmd == "init.step")
			{
				if(SplashWindow != null)
					SplashWindow.SetStatus(data["message"].Value as string);
			}
			else if (cmd == "engine.ui")
			{
				Form.Skin.ClearFontCache(); // Splash loaded before options

				SplashWindow.RequestMain();
			}
			else if (cmd == "ui.restarted")
			{
				// Hide Splash when waiting elevated subprocess
				SplashWindow.RequestClose();
			}
			else if (cmd == "ui.notification")
			{
				if (MainWindow != null)
					MainWindow.ShowWindowsNotification(data["level"].Value as string, data["message"].Value as string);
			}
			else if (cmd == "ui.main-status")
			{
				string appIcon = data["app_icon"].Value as string;
				string appColor = data["app_color"].Value as string;
				string actionIcon = data["action_icon"].Value as string;
				string actionCommand = data["action_command"].Value as string;
				string actionText = data["action_text"].Value as string;
				if (MainWindow != null)
					MainWindow.SetMainStatus(appIcon, appColor, actionIcon, actionCommand, actionText);
			}
			else if (cmd == "ui.status")
			{
				string textFull = data["full"].Value as string;
				string textShort = textFull;
				if (data.HasKey("short"))
					textShort = data["short"].Value as string;
				if (MainWindow != null)
					MainWindow.SetStatus(textFull, textShort);
			}
			else if (cmd == "ui.updater.available")
			{
				MainWindow.ShowUpdater();
			}
			else if (cmd == "ui.frontmessage")
			{
				if (UiClient.Instance.MainWindow != null)
					UiClient.Instance.MainWindow.OnFrontMessage(data["message"].Value as Json);
			}
			else if (cmd == "system.report.progress")
			{
				string step = data["step"].Value as string;
				string text = data["body"].Value as string;
				int perc = Conversions.ToInt32(data["perc"].Value, 0);

				if (MainWindow != null)
					MainWindow.OnSystemReport(step, text, perc);
			}
		}
	}
}

{'repo_name': 'AirVPN/Eddie', 'stars': '278', 'repo_language': 'C++', 'file_name': 'control', 'mime_type': 'text/plain', 'hash': 4959325087335100095, 'source_dataset': 'data'}


/*
 * Copyright (c) 2015 Cisco and/or its affiliates.
 * 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.
 */
#ifndef included_clib_mhash_h
#define included_clib_mhash_h

/*
  Copyright (c) 2010 Eliot Dresselhaus

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <vppinfra/format.h>
#include <vppinfra/hash.h>
#include <vppinfra/heap.h>

/* Hash table plus vector of keys. */
typedef struct
{
  /* Vector or heap used to store keys.  Hash table stores keys as byte
     offsets into this vector. */
  u8 *key_vector_or_heap;

  /* Byte offsets of free keys in vector (used to store free keys when
     n_key_bytes > 1). */
  u32 *key_vector_free_indices;

  u8 **key_tmps;

  /* Possibly fixed size of key.
     0 means keys are vectors of u8's.
     1 means keys are null terminated c strings. */
#define MHASH_VEC_STRING_KEY 0
#define MHASH_C_STRING_KEY 1
  u32 n_key_bytes;

  /* Seed value for Jenkins hash. */
  u32 hash_seed;

  /* Hash table mapping key -> value. */
  uword *hash;

  /* Format function for keys. */
  format_function_t *format_key;
} mhash_t;

void mhash_init (mhash_t * h, uword n_value_bytes, uword n_key_bytes);

always_inline void
mhash_init_c_string (mhash_t * h, uword n_value_bytes)
{
  mhash_init (h, n_value_bytes, MHASH_C_STRING_KEY);
}

always_inline void
mhash_init_vec_string (mhash_t * h, uword n_value_bytes)
{
  mhash_init (h, n_value_bytes, MHASH_VEC_STRING_KEY);
}

always_inline void *
mhash_key_to_mem (mhash_t * h, uword key)
{
  if (key == ~0)
    {
      u8 *key_tmp;

      int my_cpu = os_get_thread_index ();
      vec_validate (h->key_tmps, my_cpu);
      key_tmp = h->key_tmps[my_cpu];
      return key_tmp;
    }
  return vec_elt_at_index (h->key_vector_or_heap, key);
}

hash_pair_t *mhash_get_pair (mhash_t * h, const void *key);
uword mhash_set_mem (mhash_t * h, void *key, uword * new_value,
		     uword * old_value);
uword mhash_unset (mhash_t * h, void *key, uword * old_value);

always_inline uword *
mhash_get (mhash_t * h, const void *key)
{
  hash_pair_t *p = mhash_get_pair (h, key);
  return p ? &p->value[0] : 0;
}

always_inline uword
mhash_set (mhash_t * h, void *key, uword new_value, uword * old_value)
{
  return mhash_set_mem (h, key, &new_value, old_value);
}

always_inline uword
mhash_unset_key (mhash_t * h, uword key, uword * old_value)
{
  void *k = mhash_key_to_mem (h, key);
  return mhash_unset (h, k, old_value);
}

always_inline uword
mhash_value_bytes (mhash_t * m)
{
  hash_t *h = hash_header (m->hash);
  return hash_value_bytes (h);
}

always_inline uword
mhash_elts (mhash_t * m)
{
  return hash_elts (m->hash);
}

always_inline uword
mhash_key_vector_is_heap (mhash_t * h)
{
  return h->n_key_bytes <= 1;
}

always_inline void
mhash_free (mhash_t * h)
{
  if (mhash_key_vector_is_heap (h))
    heap_free (h->key_vector_or_heap);
  else
    vec_free (h->key_vector_or_heap);
  vec_free (h->key_vector_free_indices);
  hash_free (h->hash);
}

#define mhash_foreach(k,v,mh,body)				\
do {								\
  hash_pair_t * _mhash_foreach_p;				\
  hash_foreach_pair (_mhash_foreach_p, (mh)->hash, ({		\
    (k) = mhash_key_to_mem ((mh), _mhash_foreach_p->key);	\
    (v) = &_mhash_foreach_p->value[0];				\
    body;							\
  }));								\
} while (0)

format_function_t format_mhash_key;

#endif /* included_clib_mhash_h */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */

{'repo_name': 'FDio/vpp', 'stars': '423', 'repo_language': 'C', 'file_name': 'functions.bash', 'mime_type': 'text/plain', 'hash': 4449432119293947016, 'source_dataset': 'data'}


/*
 * Copyright 2011-2020 GatlingCorp (https://gatling.io)
 *
 * 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.
 */

package io.gatling.recorder.scenario

import java.io.{ File, IOException }
import java.nio.file.{ Path, Paths }
import java.util.Locale

import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.collection.immutable.SortedMap

import io.gatling.commons.util.Io._
import io.gatling.commons.util.PathHelper._
import io.gatling.commons.util.StringHelper._
import io.gatling.commons.validation._
import io.gatling.recorder.config.RecorderConfiguration
import io.gatling.recorder.har._
import io.gatling.recorder.scenario.template.SimulationTemplate
import io.gatling.recorder.util.HttpUtils._

import com.typesafe.scalalogging.StrictLogging
import io.netty.handler.codec.http._

private[recorder] object ScenarioExporter extends StrictLogging {

  private val EventsGrouping = 100

  private def packageAsFolderPath(separator: String)(implicit config: RecorderConfiguration) =
    config.core.pkg.replace(".", separator)

  private def classNameToFolderName(config: RecorderConfiguration): String =
    config.core.className.toLowerCase(Locale.ROOT)

  def simulationFilePath(implicit config: RecorderConfiguration): Path = {
    val path = config.core.simulationsFolder + File.separator + packageAsFolderPath(File.separator)
    getFolder(path) / s"${config.core.className}.scala"
  }

  private def resourcesFolderPath(implicit config: RecorderConfiguration): Path = {
    val path = config.core.resourcesFolder + File.separator + packageAsFolderPath(File.separator) + File.separator + classNameToFolderName(config)
    getFolder(path)
  }

  private def requestBodyFileName(request: RequestElement) =
    s"${request.id.toString.leftPad(4, "0")}_request.${request.fileExtension}"

  def requestBodyRelativeFilePath(request: RequestElement)(implicit config: RecorderConfiguration): String =
    packageAsFolderPath("/") + "/" + classNameToFolderName(config) + "/" + requestBodyFileName(request)

  private def responseBodyFileName(request: RequestElement) =
    s"${request.id.toString.leftPad(4, "0")}_response.${request.responseFileExtension}"

  def responseBodyRelativeFilePath(request: RequestElement)(implicit config: RecorderConfiguration): String =
    packageAsFolderPath("/") + "/" + classNameToFolderName(config) + "/" + responseBodyFileName(request)

  def exportScenario(harFilePath: String)(implicit config: RecorderConfiguration): Validation[Unit] =
    safely(error => s"Error while processing HAR file: $error") {
      val transactions = HarReader.readFile(harFilePath, config.filters.filters)

      if (transactions.isEmpty) {
        "the selected file doesn't contain any valid HTTP requests".failure
      } else {
        val scenarioElements = transactions.map {
          case HttpTransaction(request, response) =>
            val element = RequestElement(request, response)
            TimedScenarioElement(request.timestamp, response.timestamp, element)
        }

        ScenarioExporter.saveScenario(ScenarioDefinition(scenarioElements, tags = Nil)).success
      }
    }

  def saveScenario(scenarioElements: ScenarioDefinition)(implicit config: RecorderConfiguration): Unit = {
    require(!scenarioElements.isEmpty)

    val output = renderScenarioAndDumpBodies(scenarioElements)

    withCloseable(simulationFilePath.outputStream) {
      _.write(output.getBytes(config.core.encoding))
    }
  }

  private def renderScenarioAndDumpBodies(scenario: ScenarioDefinition)(implicit config: RecorderConfiguration): String = {
    // Aggregate headers
    val filteredHeaders = Set(HttpHeaderNames.COOKIE, HttpHeaderNames.CONTENT_LENGTH, HttpHeaderNames.HOST) ++
      (if (config.http.automaticReferer) Set(HttpHeaderNames.REFERER) else Set.empty)

    val scenarioElements = scenario.elements
    val mainRequestElements = scenarioElements.collect { case req: RequestElement => req }
    val requestElements = mainRequestElements.flatMap(req => req :: req.nonEmbeddedResources)
    requestElements.foreach { requestElement =>
      if (requestElement.headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true)) {
        requestElement.headers.remove(HttpHeaderNames.CONNECTION)
      }

      val authorizationHeaders = requestElement.headers.getAll(HttpHeaderNames.AUTHORIZATION)
      requestElement.headers.set(HttpHeaderNames.AUTHORIZATION, authorizationHeaders.asScala.filterNot(_.startsWith("Basic ")).asJava)
    }

    val baseUrl = getBaseUrl(mainRequestElements)
    val baseHeaders = getBaseHeaders(requestElements)
    val protocolConfigElement = new ProtocolDefinition(baseUrl, baseHeaders)

    // extract the request elements and set all the necessary
    val elements = scenarioElements.map {
      case reqEl: RequestElement =>
        reqEl.nonEmbeddedResources.foreach(_.makeRelativeTo(baseUrl))
        reqEl.makeRelativeTo(baseUrl)
      case el => el
    }

    // FIXME mutability!!!
    requestElements.zipWithIndex.map { case (reqEl, index) => reqEl.setId(index) }

    // dump request & response bodies if needed
    requestElements.foreach(
      el =>
        el.body.foreach {
          case RequestBodyBytes(bytes) => dumpBody(requestBodyFileName(el), bytes)
          case _                       =>
        }
    )

    if (config.http.checkResponseBodies) {
      requestElements.foreach(
        el =>
          el.responseBody.foreach {
            case ResponseBodyBytes(bytes) => dumpBody(responseBodyFileName(el), bytes)
            case _                        =>
          }
      )
    }

    val headers: Map[Int, Seq[(String, String)]] = {

      @tailrec
      def generateHeaders(elements: Seq[RequestElement], headers: Map[Int, List[(String, String)]]): Map[Int, List[(String, String)]] = elements match {
        case Seq() => headers
        case element +: others =>
          val acceptedHeaders = element.headers.entries.asScala
            .map(e => e.getKey -> e.getValue)
            .toList
            .filterNot {
              case (headerName, headerValue) =>
                val isFiltered = containsIgnoreCase(filteredHeaders, headerName) || isHttp2PseudoHeader(headerName)
                val isAlreadyInBaseHeaders = getIgnoreCase(baseHeaders, headerName).contains(headerValue)
                val isPostWithFormParams = element.method == HttpMethod.POST.name && HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED
                  .contentEqualsIgnoreCase(headerValue)
                val isEmptyContentLength = HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(headerName) && headerValue == "0"
                isFiltered || isAlreadyInBaseHeaders || isPostWithFormParams || isEmptyContentLength
            }
            .sortBy(_._1)

          val newHeaders = if (acceptedHeaders.isEmpty) {
            element.filteredHeadersId = None
            headers

          } else {
            val headersSeq = headers.toSeq
            headersSeq.indexWhere {
              case (_, existingHeaders) => existingHeaders == acceptedHeaders
            } match {
              case -1 =>
                element.filteredHeadersId = Some(element.id)
                headers + (element.id -> acceptedHeaders)
              case index =>
                element.filteredHeadersId = Some(headersSeq(index)._1)
                headers
            }
          }

          generateHeaders(others, newHeaders)
      }

      SortedMap(generateHeaders(requestElements, Map.empty).toSeq: _*)
    }

    val newScenarioElements = getChains(elements)

    SimulationTemplate.render(config.core.pkg, config.core.className, protocolConfigElement, headers, config.core.className, newScenarioElements)
  }

  private def getBaseHeaders(requestElements: Seq[RequestElement]): HttpHeaders = {

    def getMostFrequentHeaderValue(headerName: String): Option[String] = {
      val headers = requestElements.flatMap(_.headers.getAll(headerName).asScala)

      if (headers.isEmpty || headers.length != requestElements.length)
        // a header has to be defined on all requestElements to be turned into a common one
        None
      else {
        val headersValuesOccurrences = headers.groupBy(identity).mapValues(_.size).toSeq
        val mostFrequentValue = headersValuesOccurrences.maxBy(_._2)._1
        Some(mostFrequentValue)
      }
    }

    val baseHeaders = new DefaultHttpHeaders(false)
    ProtocolDefinition.BaseHeadersAndProtocolMethods.names.asScala.foreach { headerName =>
      getMostFrequentHeaderValue(headerName) match {
        case Some(mostFrequentValue) => baseHeaders.add(headerName, mostFrequentValue)
        case _                       =>
      }
    }

    baseHeaders
  }

  private def getBaseUrl(requestElements: Seq[RequestElement]): String = {
    val urlsOccurrences = requestElements.map(_.baseUrl).groupBy(identity).mapValues(_.size).toSeq

    urlsOccurrences.maxBy(_._2)._1
  }

  private def getChains(scenarioElements: Seq[ScenarioElement]): Either[Seq[ScenarioElement], List[Seq[ScenarioElement]]] =
    if (scenarioElements.size > ScenarioExporter.EventsGrouping)
      Right(scenarioElements.grouped(ScenarioExporter.EventsGrouping).toList)
    else
      Left(scenarioElements)

  private def dumpBody(fileName: String, content: Array[Byte])(implicit config: RecorderConfiguration): Unit = {
    withCloseable((resourcesFolderPath / fileName).outputStream) { fw =>
      try {
        fw.write(content)
      } catch {
        case e: IOException => logger.error(s"Error, while dumping body $fileName...", e)
      }
    }
  }
  private def getFolder(folderPath: String): Path = Paths.get(folderPath).mkdirs()
}

{'repo_name': 'gatling/gatling', 'stars': '4782', 'repo_language': 'Scala', 'file_name': 'JdbcFeederSourceSpec.scala', 'mime_type': 'text/plain', 'hash': -282395351756848534, 'source_dataset': 'data'}


.shapefilter-box {
    background: $white !important;
    padding: 12px 8px;
    border: 1px solid;
    border-color: $shade-light;
    &:hover {
        background: $shade-light;
    }
}

.shapefilter-text {
    color: $shade-dark;
}

.shapefilter-option {
    &:hover {
        background: $shade-light;
    }
}

.shapefilter-actions {
    :not(last-child) {
        margin-left: 0.2em;
    }
}

{'repo_name': 'raster-foundry/raster-foundry', 'stars': '123', 'repo_language': 'Scala', 'file_name': 'main.yml', 'mime_type': 'text/plain', 'hash': -3376320685187901295, 'source_dataset': 'data'}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace OpenRA.Primitives
{
	public class ConcurrentCache<T, U> : IReadOnlyDictionary<T, U>
	{
		readonly ConcurrentDictionary<T, U> cache;
		readonly Func<T, U> loader;

		public ConcurrentCache(Func<T, U> loader, IEqualityComparer<T> c)
		{
			if (loader == null)
				throw new ArgumentNullException("loader");

			this.loader = loader;
			cache = new ConcurrentDictionary<T, U>(c);
		}

		public ConcurrentCache(Func<T, U> loader)
			: this(loader, EqualityComparer<T>.Default) { }

		public U this[T key]
		{
			get { return cache.GetOrAdd(key, loader); }
		}

		public bool ContainsKey(T key) { return cache.ContainsKey(key); }
		public bool TryGetValue(T key, out U value) { return cache.TryGetValue(key, out value); }
		public int Count { get { return cache.Count; } }
		public ICollection<T> Keys { get { return cache.Keys; } }
		public ICollection<U> Values { get { return cache.Values; } }
		public IEnumerator<KeyValuePair<T, U>> GetEnumerator() { return cache.GetEnumerator(); }
		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
	}
}

{'repo_name': 'OpenRA/OpenRA', 'stars': '8352', 'repo_language': 'C#', 'file_name': 'Program.cs', 'mime_type': 'text/x-c++', 'hash': 2481120184845603243, 'source_dataset': 'data'}


# Ezhil Programming Language example
# (C) முத்தையா அண்ணாமலை 2013
# இது ஒரு எழில் தமிழ் நிரலாக்க மொழி உதாரணம்

C = 3e8 # Speed of light in m/s
C = C/1e3 # move to km/s
roundtrip_around_equator = 249901.47 #in mi
roundtrip_around_equator = roundtrip_around_equator*16e-1 #in km

time_for_light_to_travel = roundtrip_around_equator/C

பதிப்பி "circumference of earth is",roundtrip_around_equator
பதிப்பி "time for light to travel around earth =", time_for_light_to_travel, "seconds\n"

roundtrip_around_equator = 249901.47*16e-1 #in km
time_for_light_to_travel = roundtrip_around_equator/C

பதிப்பி "In 60 seconds light to travels around earth ", 600e-2/time_for_light_to_travel, "times"

#alternative answer
dia_at_equator = 40000 #in km
t_rt = dia_at_equator/C
பதிப்பி "time for 1 roundtrip = ",t_rt," seconds\n"
பதிப்பி "roundtrips per second = ",1/t_rt," times"

{'repo_name': 'Ezhil-Language-Foundation/Ezhil-Lang', 'stars': '131', 'repo_language': 'Roff', 'file_name': 'ezhil_parser.txt', 'mime_type': 'text/plain', 'hash': 1227534400626071296, 'source_dataset': 'data'}


/*
Copyright 2014 The Kubernetes Authors.

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.
*/

package cache

import (
	"errors"
	"fmt"
	"io"
	"math/rand"
	"net"
	"net/url"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	"github.com/golang/glog"
	apierrs "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/clock"
	"k8s.io/apimachinery/pkg/util/naming"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/watch"
)

// Reflector watches a specified resource and causes all changes to be reflected in the given store.
type Reflector struct {
	// name identifies this reflector. By default it will be a file:line if possible.
	name string
	// metrics tracks basic metric information about the reflector
	metrics *reflectorMetrics

	// The type of object we expect to place in the store.
	expectedType reflect.Type
	// The destination to sync up with the watch source
	store Store
	// listerWatcher is used to perform lists and watches.
	listerWatcher ListerWatcher
	// period controls timing between one watch ending and
	// the beginning of the next one.
	period       time.Duration
	resyncPeriod time.Duration
	ShouldResync func() bool
	// clock allows tests to manipulate time
	clock clock.Clock
	// lastSyncResourceVersion is the resource version token last
	// observed when doing a sync with the underlying store
	// it is thread safe, but not synchronized with the underlying store
	lastSyncResourceVersion string
	// lastSyncResourceVersionMutex guards read/write access to lastSyncResourceVersion
	lastSyncResourceVersionMutex sync.RWMutex
}

var (
	// We try to spread the load on apiserver by setting timeouts for
	// watch requests - it is random in [minWatchTimeout, 2*minWatchTimeout].
	minWatchTimeout = 5 * time.Minute
)

// NewNamespaceKeyedIndexerAndReflector creates an Indexer and a Reflector
// The indexer is configured to key on namespace
func NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interface{}, resyncPeriod time.Duration) (indexer Indexer, reflector *Reflector) {
	indexer = NewIndexer(MetaNamespaceKeyFunc, Indexers{"namespace": MetaNamespaceIndexFunc})
	reflector = NewReflector(lw, expectedType, indexer, resyncPeriod)
	return indexer, reflector
}

// NewReflector creates a new Reflector object which will keep the given store up to
// date with the server's contents for the given resource. Reflector promises to
// only put things in the store that have the type of expectedType, unless expectedType
// is nil. If resyncPeriod is non-zero, then lists will be executed after every
// resyncPeriod, so that you can use reflectors to periodically process everything as
// well as incrementally processing the things that change.
func NewReflector(lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {
	return NewNamedReflector(naming.GetNameFromCallsite(internalPackages...), lw, expectedType, store, resyncPeriod)
}

// reflectorDisambiguator is used to disambiguate started reflectors.
// initialized to an unstable value to ensure meaning isn't attributed to the suffix.
var reflectorDisambiguator = int64(time.Now().UnixNano() % 12345)

// NewNamedReflector same as NewReflector, but with a specified name for logging
func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {
	reflectorSuffix := atomic.AddInt64(&reflectorDisambiguator, 1)
	r := &Reflector{
		name: name,
		// we need this to be unique per process (some names are still the same) but obvious who it belongs to
		metrics:       newReflectorMetrics(makeValidPrometheusMetricLabel(fmt.Sprintf("reflector_"+name+"_%d", reflectorSuffix))),
		listerWatcher: lw,
		store:         store,
		expectedType:  reflect.TypeOf(expectedType),
		period:        time.Second,
		resyncPeriod:  resyncPeriod,
		clock:         &clock.RealClock{},
	}
	return r
}

func makeValidPrometheusMetricLabel(in string) string {
	// this isn't perfect, but it removes our common characters
	return strings.NewReplacer("/", "_", ".", "_", "-", "_", ":", "_").Replace(in)
}

// internalPackages are packages that ignored when creating a default reflector name. These packages are in the common
// call chains to NewReflector, so they'd be low entropy names for reflectors
var internalPackages = []string{"client-go/tools/cache/"}

// Run starts a watch and handles watch events. Will restart the watch if it is closed.
// Run will exit when stopCh is closed.
func (r *Reflector) Run(stopCh <-chan struct{}) {
	glog.V(3).Infof("Starting reflector %v (%s) from %s", r.expectedType, r.resyncPeriod, r.name)
	wait.Until(func() {
		if err := r.ListAndWatch(stopCh); err != nil {
			utilruntime.HandleError(err)
		}
	}, r.period, stopCh)
}

var (
	// nothing will ever be sent down this channel
	neverExitWatch <-chan time.Time = make(chan time.Time)

	// Used to indicate that watching stopped so that a resync could happen.
	errorResyncRequested = errors.New("resync channel fired")

	// Used to indicate that watching stopped because of a signal from the stop
	// channel passed in from a client of the reflector.
	errorStopRequested = errors.New("Stop requested")
)

// resyncChan returns a channel which will receive something when a resync is
// required, and a cleanup function.
func (r *Reflector) resyncChan() (<-chan time.Time, func() bool) {
	if r.resyncPeriod == 0 {
		return neverExitWatch, func() bool { return false }
	}
	// The cleanup function is required: imagine the scenario where watches
	// always fail so we end up listing frequently. Then, if we don't
	// manually stop the timer, we could end up with many timers active
	// concurrently.
	t := r.clock.NewTimer(r.resyncPeriod)
	return t.C(), t.Stop
}

// ListAndWatch first lists all items and get the resource version at the moment of call,
// and then use the resource version to watch.
// It returns error if ListAndWatch didn't even try to initialize watch.
func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error {
	glog.V(3).Infof("Listing and watching %v from %s", r.expectedType, r.name)
	var resourceVersion string

	// Explicitly set "0" as resource version - it's fine for the List()
	// to be served from cache and potentially be delayed relative to
	// etcd contents. Reflector framework will catch up via Watch() eventually.
	options := metav1.ListOptions{ResourceVersion: "0"}
	r.metrics.numberOfLists.Inc()
	start := r.clock.Now()
	list, err := r.listerWatcher.List(options)
	if err != nil {
		return fmt.Errorf("%s: Failed to list %v: %v", r.name, r.expectedType, err)
	}
	r.metrics.listDuration.Observe(time.Since(start).Seconds())
	listMetaInterface, err := meta.ListAccessor(list)
	if err != nil {
		return fmt.Errorf("%s: Unable to understand list result %#v: %v", r.name, list, err)
	}
	resourceVersion = listMetaInterface.GetResourceVersion()
	items, err := meta.ExtractList(list)
	if err != nil {
		return fmt.Errorf("%s: Unable to understand list result %#v (%v)", r.name, list, err)
	}
	r.metrics.numberOfItemsInList.Observe(float64(len(items)))
	if err := r.syncWith(items, resourceVersion); err != nil {
		return fmt.Errorf("%s: Unable to sync list result: %v", r.name, err)
	}
	r.setLastSyncResourceVersion(resourceVersion)

	resyncerrc := make(chan error, 1)
	cancelCh := make(chan struct{})
	defer close(cancelCh)
	go func() {
		resyncCh, cleanup := r.resyncChan()
		defer func() {
			cleanup() // Call the last one written into cleanup
		}()
		for {
			select {
			case <-resyncCh:
			case <-stopCh:
				return
			case <-cancelCh:
				return
			}
			if r.ShouldResync == nil || r.ShouldResync() {
				glog.V(4).Infof("%s: forcing resync", r.name)
				if err := r.store.Resync(); err != nil {
					resyncerrc <- err
					return
				}
			}
			cleanup()
			resyncCh, cleanup = r.resyncChan()
		}
	}()

	for {
		// give the stopCh a chance to stop the loop, even in case of continue statements further down on errors
		select {
		case <-stopCh:
			return nil
		default:
		}

		timeoutSeconds := int64(minWatchTimeout.Seconds() * (rand.Float64() + 1.0))
		options = metav1.ListOptions{
			ResourceVersion: resourceVersion,
			// We want to avoid situations of hanging watchers. Stop any wachers that do not
			// receive any events within the timeout window.
			TimeoutSeconds: &timeoutSeconds,
		}

		r.metrics.numberOfWatches.Inc()
		w, err := r.listerWatcher.Watch(options)
		if err != nil {
			switch err {
			case io.EOF:
				// watch closed normally
			case io.ErrUnexpectedEOF:
				glog.V(1).Infof("%s: Watch for %v closed with unexpected EOF: %v", r.name, r.expectedType, err)
			default:
				utilruntime.HandleError(fmt.Errorf("%s: Failed to watch %v: %v", r.name, r.expectedType, err))
			}
			// If this is "connection refused" error, it means that most likely apiserver is not responsive.
			// It doesn't make sense to re-list all objects because most likely we will be able to restart
			// watch where we ended.
			// If that's the case wait and resend watch request.
			if urlError, ok := err.(*url.Error); ok {
				if opError, ok := urlError.Err.(*net.OpError); ok {
					if errno, ok := opError.Err.(syscall.Errno); ok && errno == syscall.ECONNREFUSED {
						time.Sleep(time.Second)
						continue
					}
				}
			}
			return nil
		}

		if err := r.watchHandler(w, &resourceVersion, resyncerrc, stopCh); err != nil {
			if err != errorStopRequested {
				glog.Warningf("%s: watch of %v ended with: %v", r.name, r.expectedType, err)
			}
			return nil
		}
	}
}

// syncWith replaces the store's items with the given list.
func (r *Reflector) syncWith(items []runtime.Object, resourceVersion string) error {
	found := make([]interface{}, 0, len(items))
	for _, item := range items {
		found = append(found, item)
	}
	return r.store.Replace(found, resourceVersion)
}

// watchHandler watches w and keeps *resourceVersion up to date.
func (r *Reflector) watchHandler(w watch.Interface, resourceVersion *string, errc chan error, stopCh <-chan struct{}) error {
	start := r.clock.Now()
	eventCount := 0

	// Stopping the watcher should be idempotent and if we return from this function there's no way
	// we're coming back in with the same watch interface.
	defer w.Stop()
	// update metrics
	defer func() {
		r.metrics.numberOfItemsInWatch.Observe(float64(eventCount))
		r.metrics.watchDuration.Observe(time.Since(start).Seconds())
	}()

loop:
	for {
		select {
		case <-stopCh:
			return errorStopRequested
		case err := <-errc:
			return err
		case event, ok := <-w.ResultChan():
			if !ok {
				break loop
			}
			if event.Type == watch.Error {
				return apierrs.FromObject(event.Object)
			}
			if e, a := r.expectedType, reflect.TypeOf(event.Object); e != nil && e != a {
				utilruntime.HandleError(fmt.Errorf("%s: expected type %v, but watch event object had type %v", r.name, e, a))
				continue
			}
			meta, err := meta.Accessor(event.Object)
			if err != nil {
				utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", r.name, event))
				continue
			}
			newResourceVersion := meta.GetResourceVersion()
			switch event.Type {
			case watch.Added:
				err := r.store.Add(event.Object)
				if err != nil {
					utilruntime.HandleError(fmt.Errorf("%s: unable to add watch event object (%#v) to store: %v", r.name, event.Object, err))
				}
			case watch.Modified:
				err := r.store.Update(event.Object)
				if err != nil {
					utilruntime.HandleError(fmt.Errorf("%s: unable to update watch event object (%#v) to store: %v", r.name, event.Object, err))
				}
			case watch.Deleted:
				// TODO: Will any consumers need access to the "last known
				// state", which is passed in event.Object? If so, may need
				// to change this.
				err := r.store.Delete(event.Object)
				if err != nil {
					utilruntime.HandleError(fmt.Errorf("%s: unable to delete watch event object (%#v) from store: %v", r.name, event.Object, err))
				}
			default:
				utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", r.name, event))
			}
			*resourceVersion = newResourceVersion
			r.setLastSyncResourceVersion(newResourceVersion)
			eventCount++
		}
	}

	watchDuration := r.clock.Now().Sub(start)
	if watchDuration < 1*time.Second && eventCount == 0 {
		r.metrics.numberOfShortWatches.Inc()
		return fmt.Errorf("very short watch: %s: Unexpected watch close - watch lasted less than a second and no items received", r.name)
	}
	glog.V(4).Infof("%s: Watch close - %v total %v items received", r.name, r.expectedType, eventCount)
	return nil
}

// LastSyncResourceVersion is the resource version observed when last sync with the underlying store
// The value returned is not synchronized with access to the underlying store and is not thread-safe
func (r *Reflector) LastSyncResourceVersion() string {
	r.lastSyncResourceVersionMutex.RLock()
	defer r.lastSyncResourceVersionMutex.RUnlock()
	return r.lastSyncResourceVersion
}

func (r *Reflector) setLastSyncResourceVersion(v string) {
	r.lastSyncResourceVersionMutex.Lock()
	defer r.lastSyncResourceVersionMutex.Unlock()
	r.lastSyncResourceVersion = v

	rv, err := strconv.Atoi(v)
	if err == nil {
		r.metrics.lastResourceVersion.Set(float64(rv))
	}
}

{'repo_name': 'hasura/gitkube', 'stars': '3241', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': -6945913180549879788, 'source_dataset': 'data'}


# Node.js 应用部署

如果是使用 egg 框架开发的应用，强烈推荐使用 `egg-scripts` 进行部署，使用 egg 提供的一系列解决方案，包括但不限于:

- 灵活的启动参数
- [Node.js 性能平台](https://www.aliyun.com/product/nodejs)
- [egg-alinode](https://github.com/eggjs/egg-alinode)

egg 提供了从部署、进程守护、监控、问题排查等一系列的解决方案。详情见[egg 部署文档](https://eggjs.org/zh-cn/core/deployment.html)

划重点:

1、如果你没有任何服务端应用部署运维经验，直接生产环境执行 `sudo npm run prod` 即可或选择集成度更高的 Serverless 场景下的[SSR 框架](https://github.com/ykfe/ssr)使用。
2、如果你有相关经验建议使用 `egg-scripts` 部署 而不是 `pm2`。原因见[文档](https://eggjs.org/zh-cn/faq.html#%E8%BF%9B%E7%A8%8B%E7%AE%A1%E7%90%86%E4%B8%BA%E4%BB%80%E4%B9%88%E6%B2%A1%E6%9C%89%E9%80%89%E5%9E%8B-pm2)]

## 部署流程

有两种部署策略

1、将整个项目文件除 node_modules 以及 build 文件夹之外的所有文件打成 zip 包，然后上传到服务器，在服务器上执行`npm i && npm run prod`来进行依赖的安装以及生成产物的构建和生产环境的服务启动
2、如果你对`npm run prod`这个命令到底干了什么非常熟悉，也可以直接本地构建然后将构建的产物上传，然后修改`prod`脚本，使得服务端只需要进行`Node`服务的启动而不需要执行`Webpack`构建命令

## 使用 nginx 来做负载均衡和端口代理

nginx 作为负载和代理服务可以实现在服务器上的静态资源托管、多应用 route 级别转发等基本需求。

- install

```bash
$ sudo yum install nginx
```

### nginx 托管静态资源

```js
server {
    listen       80;
    server_name  yourServerName;
    root         your/folder;
    index  index.html;
    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;
    location / {}
    error_page 404 /404.html;
        location = /40x.html {
    }
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}
```

### nginx 开机自启

```bash
$ systemctl enable nginx
$ systemctl restart nginx
```

### 修改用户

nginx 文件首行默认用户为 nginx，需要修改为当前用户名。

### 本地代理某端口的服务

```js
location / {
    proxy_pass http://127.0.0.1:7001;
    proxy_hide_header 'x-frame-options';
    #root   html;
    #index  index.html index.htm;
}
```

### 启动

```bash
$ sudo nginx -c /usr/local/etc/nginx/nginx.conf
```

{'repo_name': 'ykfe/egg-react-ssr', 'stars': '1317', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -4112893601570401894, 'source_dataset': 'data'}