text:
/*!
  \file fff_array.h
  \brief Basic image object
  \author Alexis Roche
  \date 2005-2006

  This library implements a generic 4-dimensional array object that
  can be used to represent images.
*/

#ifndef FFF_ARRAY
#define FFF_ARRAY

#ifdef __cplusplus
extern "C" {
#endif

#include "fff_base.h"
#include "fff_vector.h"

#include <stddef.h>

#define fff_array_dim(array, axis)					\
  ((axis)==0 ? (array->dimX) : ((axis)==1 ? (array->dimY) : ((axis)==2 ? (array->dimZ) : (array->dimT)) ) )
#define fff_array_offset(array, axis)					\
  ((axis)==0 ? (array->offsetX) : ((axis)==1 ? (array->offsetY) : ((axis)==2 ? (array->offsetZ) : (array->offsetT)) ) )

  /*
    #define fff_array_copy(ares, asrc)		\
    fff_array_compress(ares, asrc, 0, 0, 1, 1)
  */

#define fff_array_new1d(dtype, dx)		\
  fff_array_new(dtype, dx, 1, 1, 1)
#define fff_array_new2d(dtype, dx, dy)		\
  fff_array_new(dtype, dx, dy, 1, 1)
#define fff_array_new3d(dtype, dx, dy, dz)	\
  fff_array_new(dtype, dx, dy, dz, 1)

#define fff_array_view1d(dtype, data, dx, ox)		\
  fff_array_view(dtype, data, dx, 1, 1, 1, ox, 1, 1, 1)
#define fff_array_view2d(dtype, data, dx, dy, ox, oy)		\
  fff_array_view(dtype, data, dx, dy, 1, 1, ox, oy, 1, 1)
#define fff_array_view3d(dtype, data, dx, dy, dz, ox, oy, oz)	\
  fff_array_view(dtype, data, dx, dy, dz, 1, ox, oy, oz, 1)

#define fff_array_get1d(array, x)		\
  fff_array_get(array, x, 0, 0, 0)
#define fff_array_get2d(array, x, y)		\
  fff_array_get(array, x, y, 0, 0)
#define fff_array_get3d(array, x, y)		\
  fff_array_get(array, x, y, z, 0)

#define fff_array_set1d(array, x, a)		\
  fff_array_set(array, x, 0, 0, 0, a)
#define fff_array_set2d(array, x, y, a)		\
  fff_array_set(array, x, y, 0, 0, a)
#define fff_array_set3d(array, x, y, z, a)	\
  fff_array_set(array, x, y, z, 0, a)

#define fff_array_get_block1d(array, x0, x1, fx)			\
  fff_array_get_block(array, x0, x1, fx, 0, 0, 1, 0, 0, 1, 0, 0, 1)
#define fff_array_get_block2d(array, x0, x1, fx, y0, y1, fy)		\
  fff_array_get_block(array, x0, x1, fx, y0, y1, fy, 0, 0, 1, 0, 0, 1)
#define fff_array_get_block3d(array, x0, x1, fx, y0, y1, fy, z0, z1, fz) \
  fff_array_get_block(array, x0, x1, fx, y0, y1, fy, z0, z1, fz, 0, 0, 1)

#define fff_array_get_from_iterator(array, iter)	\
  array->get(iter.data, 0)

#define fff_array_set_from_iterator(array, iter, val)	\
  array->set(iter.data, 0, val)

#define fff_array_iterator_update(iter)	\
      (iter)->update(iter)

  /*!
    \typedef fff_array_ndims
    \brief Image flag type
  */
  typedef enum {
    FFF_ARRAY_1D = 1,   /*!< 1d image */
    FFF_ARRAY_2D = 2,   /*!< 2d image */
    FFF_ARRAY_3D = 3,   /*!< 3d image */
    FFF_ARRAY_4D = 4    /*!< 4d image */
  } fff_array_ndims;

  /*!
    \struct fff_array
    \brief The fff image structure

    Image values are stored in a \c void linear array, the actual
    encoding type being specified by the field \c datatype. The image
    dimension along each axis are encoded by fields starting with \c
    dim, while the \c ndims flag specifies the biggest axis index
    corresponding to a non-unitary dimension; it essentially defines
    whether the image is 1d, 2d, 3d, or 4d. The use of offsets (or
    strides) makes the object independent from any storage
    convention. A pixel with coordinates (\a x, \a y, \a z, \a t) may
    be accessed using a command like:

    \code
    value = im->data[ x*im->offsetX + y*im->offsetY + z*im->offsetZ + t*im->offsetT ];
    \endcode

    Note that this approach makes it possible to extract a sub-image
    from an original image without the need to reallocate memory.
  */
  typedef struct {
    fff_array_ndims ndims; /*!< Image flag */
    fff_datatype datatype; /*!< Image encoding type */
    size_t dimX; /*!< Dimension (number of pixels) along first axis */
    size_t dimY; /*!< Dimension (number of pixels) along second axis */
    size_t dimZ; /*!< Dimension (number of pixels) along third axis */
    size_t dimT; /*!< Dimension (number of pixels) along fourth axis */
    size_t offsetX; /*!< Offset (relative to type) along first axis */
    size_t offsetY; /*!< Offset (relative to type) along second axis */
    size_t offsetZ; /*!< Offset (relative to type) along third axis */
    size_t offsetT; /*!< Offset (relative to type) along fourth axis */
    size_t byte_offsetX; /*!< Offset (in bytes) along first axis */
    size_t byte_offsetY; /*!< Offset (in bytes) along second axis */
    size_t byte_offsetZ; /*!< Offset (in bytes) along third axis */
    size_t byte_offsetT; /*!< Offset (in bytes) along fourth axis */
    void* data; /*!< Image buffer */
    int owner; /*!< Non-zero if the object owns its data */
    double (*get)(const char*, size_t); /*!< Get accessor */
    void (*set)(char*, size_t, double); /*!< Set accessor */
  } fff_array;

  /*!
    \struct fff_array_iterator
    \brief Image iterator structure
  */
  typedef struct {
    size_t idx;
    size_t size;
    char* data;
    size_t x;
    size_t y;
    size_t z;
    size_t t;
    size_t ddimY;
    size_t ddimZ;
    size_t ddimT;
    size_t incX;
    size_t incY;
    size_t incZ;
    size_t incT;
    void (*update)(void*); /*!< Updater */
  } fff_array_iterator;

  /*!
    \brief Constructor for the fff_array structure
    \param datatype image encoding type
    \param dimX number of pixels along the first axis
    \param dimY number of pixels along the second axis
    \param dimZ number of pixels along the third axis
    \param dimT number of pixels along the fourth axis

    This function allocates a new image buffer.
  */
  extern fff_array* fff_array_new(fff_datatype datatype,
				   size_t dimX,
				   size_t dimY,
				   size_t dimZ,
				   size_t dimT);

  /*!
    \brief Destructor for the \c fff_array structure
    \param thisone fff_array member to be deleted
  */
  extern void fff_array_delete(fff_array* thisone);

  /*!
    \brief Array view
    \param datatype image encoding type
    \param buf already allocated image buffer
    \param dimX number of pixels along the first axis
    \param dimY number of pixels along the second axis
    \param dimZ number of pixels along the third axis
    \param dimT number of pixels along the fourth axis
    \param offX offset along the first axis
    \param offY offset along the second axis
    \param offZ offset along the third axis
    \param offT offset along the fourth axis

    This function assumes that the image buffer is already allocated.
  */
  extern fff_array fff_array_view(fff_datatype datatype, void* buf,
				   size_t dimX, size_t dimY, size_t dimZ, size_t dimT,
				   size_t offX, size_t offY, size_t offZ, size_t offT);

  /*!
    \brief Generic function to access a voxel's value
    \param thisone input image
    \param x first coordinate
    \param y second coordinate
    \param z third coordinate
    \param t fourth coordinate

    Get image value at a specific location defined by voxel coordinates.
    Return \c fff_NAN if the position is out of bounds.
 */
  extern double fff_array_get(const fff_array* thisone,
			      size_t x,
			      size_t y,
			      size_t z,
			      size_t t);

  /*!
    \brief Generic function to set one voxel's value
    \param value value to set
    \param thisone input image
    \param x first coordinate
    \param y second coordinate
    \param z third coordinate
    \param t fourth coordinate
  */
  extern void fff_array_set(fff_array* thisone,
			    size_t x,
			    size_t y,
			    size_t z,
			    size_t t,
			    double value);

  /*!
    \brief Set all pixel values to a given constant
    \param thisone image
    \param c constant
  */
  extern void fff_array_set_all(fff_array* thisone, double c);

  /*!
    \brief Extract an image block
    \param thisone input image
    \param x0 first coordinate of the starting point
    \param x1 first coordinate of the finishing point
    \param y0 second coordinate of the starting point
    \param y1 second coordinate of the finishing point
    \param z0 third coordinate of the starting point
    \param z1 third coordinate of the finishing point
    \param t0 fourth coordinate of the starting point
    \param t1 fourth coordinate of the finishing point
    \param fX subsampling factor in the first direction
    \param fY subsampling factor in the second direction
    \param fZ subsampling factor in the third direction
    \param fT subsampling factor in the fourth direction
  */
  extern fff_array fff_array_get_block(const fff_array* thisone,
				       size_t x0, size_t x1, size_t fX,
				       size_t y0, size_t y1, size_t fY,
				       size_t z0, size_t z1, size_t fZ,
				       size_t t0, size_t t1, size_t fT);

  extern void fff_array_extrema (double* min, double* max, const fff_array* thisone);

  extern void fff_array_copy(fff_array* ares, const fff_array* asrc);

  extern void fff_array_compress(fff_array* ares, const fff_array* asrc,
				 double r0, double s0,
				 double r1, double s1);

  extern void fff_array_add (fff_array * x, const fff_array * y);
  extern void fff_array_sub (fff_array * x, const fff_array * y);
  extern void fff_array_div (fff_array * x, const fff_array * y);
  extern void fff_array_mul (fff_array * x, const fff_array * y);

  /*
     Convert image values to [0,clamp-1]; typically clamp = 256.
     Possibly modify the dynamic range if the input value is
     overestimated.  For instance, the reconstructed MRI signal is
     generally encoded in 12 bits (values ranging from 0 to
     4095). Therefore, this operation may result in a loss of
     information.
  */
  extern void fff_array_clamp(fff_array* ares, const fff_array* asrc, double th, int* clamp);

  extern fff_array_iterator fff_array_iterator_init(const fff_array* array);
  extern fff_array_iterator fff_array_iterator_init_skip_axis(const fff_array* array, int axis);

  /*  extern void fff_array_iterator_update(fff_array_iterator* thisone); */
  extern void fff_array_iterate_vector_function(fff_array* array, int axis,
						void(*func)(fff_vector*, void*), void* par);

#ifdef __cplusplus
}
#endif

#endif


text:
import Koa from 'koa'
import logger from 'koa-logger'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import mongo, { MongoClient } from 'mongodb'
import { graphqlKoa, graphiqlKoa } from 'graphql-server-koa'
import schema from './schema'

const app = new Koa()
const router = new Router()
const PORT = 3000
const MONGO_URI = "mongodb://localhost:27017/test"

// Middleware
app.use(logger())
app.use(bodyParser())

// Routes
router.all('/graphql', graphqlKoa({ schema }))
router.get('/graphiql', graphiqlKoa({ endpointURL: '/graphql' }))
app.use(router.routes())
app.use(router.allowedMethods())

!(async () => {
  try {
    mongo.db = await MongoClient.connect(MONGO_URI)
    // Print Schema for Relay
    // updateSchema(schema)

    app.listen(PORT)
  } catch(err) {
    console.error(err)
    process.exit(1)
  } finally {
    console.log(`server running on localhost:${PORT}, database ${MONGO_URI}`)
  }
})()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Frontend\CumpleaniosBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('CumpleaniosBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
package net.aimeizi.spring.testng.example.service;

import net.aimeizi.spring.testng.example.cache.service.ICacheService;
import net.aimeizi.spring.testng.example.common.exceptions.NonExistentUserException;
import net.aimeizi.spring.testng.example.model.User;

import java.util.Collection;

/**
 * Created by 冯靖 on 2014/7/1 0001.
 */
public class UserService implements IUserService {

    //CacheService is injected...
    private ICacheService cacheService;

    /**
     * Adds User
     *
     * @param  user
     * @return boolean whether delete operation is success or not.
     */
    public boolean addUser(User user) {

        getCacheService().getUserMap().put(user.getId(), user);
        if(getCacheService().getUserMap().get(user.getId()).equals(user)) {
            return true;
        }

        return false;
    }

    /**
     * Deletes User
     *
     * @param  user
     * @return boolean whether delete operation is success or not.
     */
    public boolean deleteUser(User user) {
        User removedUser = getCacheService().getUserMap().remove(user.getId());
        if(removedUser != null) {
            return true;
        }
        return false;
    }

    /**
     * Updates User
     *
     * @param  user
     * @throws NonExistentUserException
     */
    public void updateUser(User user) throws NonExistentUserException {
        if(getCacheService().getUserMap().containsKey(user.getId())) {
            getCacheService().getUserMap().put(user.getId(), user);
        } else {
            throw new NonExistentUserException("Non Existent User can not update! User : "+user);
        }
    }

    /**
     * Gets User
     *
     * @param  id
     * @return User
     */
    public User getUserById(String id) {
        return getCacheService().getUserMap().get(id);
    }

    /**
     * Gets User List
     *
     * @return Collection - Collection of Users
     */
    public Collection<User> getUsers() {
        return (Collection<User>) getCacheService().getUserMap().values();
    }

    /**
     * Gets Cache Service
     *
     * @return ICacheService - Cache Service
     */
    public ICacheService getCacheService() {
        return cacheService;
    }

    /**
     * Sets Cache Service
     *
     * @param cacheService
     */
    public void setCacheService(ICacheService cacheService) {
        this.cacheService = cacheService;
    }

}


text:
/*
Background.js

Author: Bayrock
Description: Handles the background processes
*/

// Preferences
chrome.storage.sync.get({
  shoeName: 'Jordan', //default to Jordan
  refreshInterval: 5000, //default to 5 seconds
  shoeSize: '10.5', //default to 10.5
  scanEnabled: true //default to true
}, function(items) {
  // Deliver preferences
  chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      if (request.action == "send")
        sendResponse({
          shoe: items.shoeName,
          interval: items.refreshInterval,
          size: items.shoeSize,
          enabled: items.scanEnabled
        });
    });
});

// Page action
function ValidUrl(tabId, changeInfo, tab) {
  if (tab.url.indexOf('nike.com') > -1 || tab.url.indexOf('twitter.com') > -1) {
		chrome.pageAction.show(tabId);
  }
}

chrome.tabs.onUpdated.addListener(ValidUrl);


text:
namespace Nancy.Demo.CustomModule
{
    using System;

    public class NancyRouteAttribute : Attribute
    {
        /// <summary>
        /// The method for the route
        /// </summary>
        public string Method { get; set; }

        /// <summary>
        /// The path for the route
        /// </summary>
        public string Path { get; set; }

        public NancyRouteAttribute(string method, string path)
        {
            this.Method = method;
            this.Path = path;
        }
    }
}


text:
@interface NSObject (MagicalRecord_DataImport)

- (NSString *) MR_lookupKeyForAttribute:(NSAttributeDescription *)attributeInfo;
- (id) MR_valueForAttribute:(NSAttributeDescription *)attributeInfo;

- (NSString *) MR_lookupKeyForRelationship:(NSRelationshipDescription *)relationshipInfo;
- (id) MR_relatedValueForRelationship:(NSRelationshipDescription *)relationshipInfo;

@end


text:
A new type of sudoku where the computer wants you to lose.

## Rules

- Starts with a 9x9 grid.
- You must set numbers 1 to 9 in the empty squares.
- Numbers can only appear once in each row and column. At the same time, we have 3x3 squares that contain the same numbers only once.
- Well, the computer doesn't wanna play, because it always wins. That's why it has put two timers:
  - Global Timer: If you solve the sudoku before it reaches zero you win.
  - Block-up Timer: When it reaches zero, the computer will do something that will work against you.

## Computer Movements

- **Block Number:** Select a random number and you can't use it until some time.
- **Delete Number:** Remove a random number on your grid. This does not include the numbers that come by default.
- **Blind Screen:** A section of the grid will be covered until some time. If you remember where to set the numbers you can do it.
- **Fake It:** A random number will change. This does not include the numbers that come by default.
- **My turn:** The computer will set a random number in a random blank cell.

## Dificulties

- **Easy:**
  - Global Timer: 10 minutes
  - Block-up Timer: 1 minute
  - Block-up Power Duration: 15 seconds
  - Clues: 40
  - Grid errors: Displayed

- **Normal:**
  - Global Timer: 15 minutes
  - Block-up Timer: 1 minute
  - Block-up Power Duration: 30 seconds
  - Clues: 30
  - Grid errors: Hidden

- **Hard:**
  - Global Timer: 20 minutes
  - Block-up Timer: 30 seconds
  - Block-up Power Duration: 25 seconds
  - Clues: 20
  - Grid errors: Hidden

## Installation

You require [Node.js](https://nodejs.org/) to run.

Install the dependencies:

```sh
$ npm install
```

Afer that for simple start:

```sh
$ npm start
```

To make binaries:

```sh
$ npm run build         # Build all plataforms
$ npm run package-osx   # Only build OS X
$ npm run package-win   # Only build Windows
$ npm run package-linux # Only build Linux
```

## Web View

You can open the file on:

```sh
/src/main.html
```

In any browser for see it in web

# Members

- Alfaro Carrasco, Leonardo Daniel
- Callo Milla, Luis Eduardo
- Teixeira Walters, Jett Manuel


text:
liquibase-db2zos
================


text:
/*
** @constructor
*/
var PortalProxy = function (facade) {
    var app = facade, _self = this, WindowManager, PortletWindow, Resources, Config, LocalDictionary,
    portlets = [], sortPortlets, loadPortletList, init, _isGuestLayout,
    pathToRoot = '../../';

    init = function () {
        WindowManager = app.models.windowManager;
        PortletWindow = app.controllers.portletWindowController || false;
        Resources = app.models.resourceProxy;
        Config = app.config;
        LocalDictionary = app.localDictionary;
    };

    this.getShowPortletFunc = function (portlet) {
        if (!PortletWindow) {
            PortletWindow = app.controllers.portletWindowController || false;
        }
        //Returns a function to the PortalWindowController to open the appropriate window
        //when an icon is clicked in the home screen grid.

        Ti.API.debug("getShowPortletFunc() in PortalProxy");
        return function () {
            if (portlet.url) {
                Ti.API.debug("portlet.url exists in getShowPortletFunc() in PortalProxy");
                WindowManager.openWindow(PortletWindow.key, portlet);
            }
            else {
                Ti.API.debug("portlet.url doesn't exist in getShowPortletFunc() in PortalProxy");
                WindowManager.openWindow(portlet.window);
            }
        };
    };

    this.getPortlets = function () {
        Ti.API.debug("getPortlets() in PortalProxy");
        return portlets;
    };

    sortPortlets = function(a, b) {
        if (!a.title || !b.title) {
            Ti.API.error("Missing a title for one of these:" + JSON.stringify(a) + " & " + JSON.stringify(b));
            return -1;
        }
        // get the values for the configured property from
        // each object and transform them to lower case
        var aprop = a.title.toLowerCase();
        var bprop = b.title.toLowerCase();

        // if the values are identical, indicate an equals
        if (aprop === bprop) {
            return 0;
        }

        // otherwise perform a normal alphabetic sort
        if (aprop > bprop) {
            return 1;
        } else {
            return -1;
        }

    };

    this.getIconUrl = function (p) {
        var _iconUrl;

        if (Resources.getPortletIcon(p.fname)) {
            _iconUrl = Resources.getPortletIcon(p.fname);
        }
        else if (p.iconUrl && p.iconUrl.indexOf('/') == 0) {
            _iconUrl = Config.BASE_PORTAL_URL + p.iconUrl;
        }
        else if (p.iconUrl) {
            _iconUrl = pathToRoot + p.iconUrl;
        }
        else {
            _iconUrl = Config.BASE_PORTAL_URL + '/ResourceServingWebapp/rs/tango/0.8.90/32x32/categories/applications-other.png';
        }

        return _iconUrl;
    };

    loadPortletList = function() {
        Ti.API.debug('loadPortletList() in PortalProxy');
        var layoutUrl, layoutClient, layoutText,
            onRequestComplete, onRequestError, onGetPortletsComplete, onGetPortletsError;

            onGetPortletsComplete = function (e) {
                Ti.API.debug('onGetPortletsComplete with responseHeader: ' + layoutClient.getResponseHeader('Content-Type'));
                var responseJSON, nativeModules = Config.getLocalModules(), module;
                responseJSON = JSON.parse(layoutClient.responseText);
                portlets = responseJSON.layout;

                for (module in nativeModules) {
                    if (nativeModules.hasOwnProperty(module)) {
                        nativeModules[module].added = false;
                    }
                }
                for (var i = 0, iLength = portlets.length; i<iLength; i++ ) {

                    if(nativeModules[portlets[i].fname]) {
                        Ti.API.info("We have a match for " + portlets[i].fname + ", and it is: " + JSON.stringify(nativeModules[portlets[i].fname]));
                        portlets[i] = nativeModules[portlets[i].fname];
                        nativeModules[portlets[i].fname].added = true;
                    }
                }

                for (module in nativeModules) {
                    if (nativeModules.hasOwnProperty(module)) {
                        Ti.API.info("Remaining module: " + JSON.stringify(nativeModules[module]));
                        if(nativeModules[module].title && !nativeModules[module].added && !nativeModules[module].doesRequireLayout) {
                            // As long as the module has a title, hasn't already been added, and doesn't
                            // require the fname for the module to be returned in the personalized layout.
                            portlets.push(nativeModules[module]);
                        }
                        else {
                            Ti.API.debug("Ignoring this prototype artifact in nativeModules: " + JSON.stringify(nativeModules[module]));
                        }
                    }
                }

                portlets.sort(sortPortlets);

                // uPortal 3.2 isn't capable of sending the layout as JSON, so the response
                // will be an XML document with the appropriate JSON contained in a
                // "json-layout" element.  Parse this element as JSON and use the data
                // array as the initial module list.
                // Ti.API.debug("layoutClient XML: " + JSON.stringify(layoutClient.responseXML));

                Ti.App.fireEvent('PortalProxyPortletsLoaded', {user: responseJSON.user});
            };

            onGetPortletsError = function (e) {
                Ti.App.fireEvent("PortalProxyNetworkError", {message: LocalDictionary.couldNotConnectToPortal});
            };

        // Send a request to uPortal's main URL to get a JSON representation of the
        // user layout
        layoutUrl = Config.BASE_PORTAL_URL + Config.PORTAL_CONTEXT + "/layout.json";
        layoutClient = Titanium.Network.createHTTPClient({
            onload: onGetPortletsComplete,
            onerror: onGetPortletsError
        });
        layoutClient.open('GET', layoutUrl, true);
        layoutClient.send();
    };

    this.getPortletsForUser = function() {
        var _portlets;

        Ti.App.fireEvent('PortalProxyGettingPortlets');

        // Get the module list for this user from the portal server and create a
        // layout based on this list.
        _portlets = loadPortletList();
    };

    init();
};


text:
package com.obidea.semantika.database.datatype;

import java.sql.Types;

public class SqlBigInt extends AbstractNumericType<Long>
{
   private static final SqlBigInt mInstance;

   static {
      mInstance = new SqlBigInt();
   }

   private SqlBigInt()
   {
      super("BIGINT");
   }

   public static SqlBigInt getInstance()
   {
      return mInstance;
   }

   @Override
   protected Long parseLexicalForm(String lexicalForm)
   {
      return Long.parseLong(lexicalForm);
   }

   @Override
   public int getType()
   {
      return Types.BIGINT;
   }
}


text:
module.exports = {
	before: function (browser) {
		browser.app = browser.page.app();
		browser.signinPage = browser.page.signin();

		browser.app.navigate();
		browser.app.waitForElementVisible('@signinScreen');
	},
	after: function (browser) {
		browser.end();
	},
	'Signin page should allow users to login': function (browser) {
		browser.signinPage
			.signin();
		browser.app
			.waitForElementVisible('@homeScreen');
	},
	'Signin page should be presented upon signout': function (browser) {
		browser.app
			.signout();
	},
};


text:
(function (angular, jasmine, beforeEach, describe, it) {
    "use strict";

    /* All of the healthBam.userAccountActions module's tests. */
    describe("healthBam.userAccountActions module", function () {

        beforeEach(
            function () {
                /* Load the module to test. */
                angular.mock.module("healthBam.userAccountActions");
            }
        );

        describe("UserAccountActionsController", function () {

            var userAccountActions,
                $componentController,
                locals,
                bindings;

            beforeEach(
                function () {

                    /* Reset variables. */
                    locals = {};
                    bindings = {};

                    /* Inject dependencies. */
                    angular.mock.inject(
                        function ($injector) {
                            $componentController = $injector.get("$componentController");
                            locals.authenticationService = $injector.get("authenticationService");
                            locals.$log = $injector.get("$log");
                            locals.$mdDialog = $injector.get("$mdDialog");
                        }
                    );

                    spyOn(locals.$mdDialog, "show");

                    locals.$mdMedia = jasmine.createSpy(
                        "$mdMedia"
                    );

                    /* Get the controller for the userAccountActions component. */
                    userAccountActions = $componentController(
                        "healthBamUserAccountActions",
                        locals,
                        bindings
                    );
                }
            );

            it("should exist", function () {
                expect(userAccountActions).toEqual(jasmine.any(Object));
            });

            describe("$onInit", function () {

                it("should log loading debug message", function () {
                    spyOn(locals.$log, "debug");
                    userAccountActions.$onInit();
                    expect(locals.$log.debug).toHaveBeenCalledWith(
                        jasmine.any(String),
                        userAccountActions
                    );
                });

            });

            describe("authenticate", function () {

                beforeEach(
                    function () {
                        userAccountActions.$onInit();
                    }
                );

                it("should alias authenticationService.authenticate", function () {
                    expect(userAccountActions.authenticate).toEqual(locals.authenticationService.authenticate);
                });

            });

            describe("isAuthenticated", function () {

                beforeEach(
                    function () {
                        userAccountActions.$onInit();
                    }
                );

                it("should alias authenticationService.isAuthenticated", function () {
                    expect(userAccountActions.isAuthenticated).toEqual(locals.authenticationService.isAuthenticated);
                });

            });

            describe("getUser", function () {

                beforeEach(
                    function () {
                        userAccountActions.$onInit();
                    }
                );

                it("should alias authenticationService.getUser", function () {
                    expect(userAccountActions.getUser).toEqual(locals.authenticationService.getUser);
                });

            });

            describe("logout", function () {

                beforeEach(
                    function () {
                        userAccountActions.$onInit();
                    }
                );

                it("should alias authenticationService.logout", function () {
                    expect(userAccountActions.logout).toEqual(locals.authenticationService.logout);
                });

            });

            describe("viewAccount", function () {

                var dialogOptions,
                    event;

                beforeEach(
                    function () {
                        userAccountActions.$onInit();

                        event = {
                            mock: "event"
                        };

                        dialogOptions = {
                            templateUrl: "/user-account-details.html",
                            controller: "UserAccountDetailsController",
                            controllerAs: "userAccountDetails",
                            targetEvent: event,
                            fullscreen: false,
                            escapeToClose: true
                        };
                    }
                );

                it("should be exposed", function () {
                    expect(userAccountActions.viewAccount).toEqual(jasmine.any(Function));
                });

                it("should open the account details dialog fullscreen", function () {
                    dialogOptions.fullscreen = false;
                    locals.$mdMedia.and.returnValue(true);

                    userAccountActions.viewAccount(event);

                    expect(locals.$mdDialog.show).toHaveBeenCalledWith(dialogOptions);
                    expect(locals.$mdMedia).toHaveBeenCalledWith("gt-sm");
                });

                it("should open the account details dialog not fullscreen", function () {
                    dialogOptions.fullscreen = true;
                    locals.$mdMedia.and.returnValue(false);

                    userAccountActions.viewAccount(event);

                    expect(locals.$mdDialog.show).toHaveBeenCalledWith(dialogOptions);
                    expect(locals.$mdMedia).toHaveBeenCalledWith("gt-sm");
                });

            });

        });

    });

}(window.angular, window.jasmine, window.beforeEach, window.describe, window.it));


text:
package me.panavtec.threaddecoratedview.writer;

import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import me.panavtec.threaddecoratedview.ViewAnnotationProcessor;
import me.panavtec.threaddecoratedview.model.EnclosingView;
import me.panavtec.threaddecoratedview.model.ViewMethod;
import me.panavtec.threaddecoratedview.views.qualifiers.DoNotStrip;

public class EmptyViewStrategy implements ViewWriterStrategy {

  private static final String CLASS_PREFIX = "Null";

  @Override public void writeView(Filer filer, EnclosingView view) throws IOException {
    List<MethodSpec> viewMethods = new ArrayList<>();
    List<ViewMethod> methods = view.getMethods();
    for (ViewMethod method : methods) {
      viewMethods.add(processMethod(method));
    }
    TypeSpec coordinateInjectorClass = createInjectClass(view, viewMethods);
    JavaFile.builder(view.getPackageName(), coordinateInjectorClass)
        .addFileComment("Do not modify this file!")
        .build()
        .writeTo(filer);
  }

  private MethodSpec processMethod(ViewMethod method) {
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getMethodName())
        .addModifiers(Modifier.PUBLIC)
        .returns(ClassName.get(method.getReturnType()));

    List<TypeMirror> parameters = method.getParameters();
    for (int i = 0; i < parameters.size(); i++) {
      String paramName = "param" + i;
      methodBuilder.addParameter(ClassName.get(parameters.get(i)), paramName, Modifier.FINAL);
    }

    methodBuilder.
        addAnnotation(Override.class);

    return methodBuilder.build();
  }

  private TypeSpec createInjectClass(EnclosingView view, List<MethodSpec> viewMethods) {
    ClassName viewType = ClassName.get(view.getPackageName(), view.getClassName());
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(CLASS_PREFIX + view.getClassName())
        .addModifiers(Modifier.PUBLIC)
        .addSuperinterface(viewType)
        .addAnnotation(AnnotationSpec.builder(DoNotStrip.class).build());
    addDecoratedViewMethods(viewMethods, classBuilder);

    return classBuilder.build();
  }

  private void addDecoratedViewMethods(List<MethodSpec> viewMethods,
      TypeSpec.Builder classBuilder) {
    for (MethodSpec methodSpec : viewMethods) {
      classBuilder.addMethod(methodSpec);
    }
  }
}


text:
package datetime

import (
	"github.com/watermint/toolbox/quality/recipe/qtr_endtoend"
	"testing"
)

func TestNow_Exec(t *testing.T) {
	qtr_endtoend.TestRecipe(t, &Now{})
}


text:
#pragma once

#include "StratumGrin.h"

#include "StratumMiner.h"

class StratumMinerGrin : public StratumMinerBase<StratumTraitsGrin> {
public:
  StratumMinerGrin(
      StratumSessionGrin &session,
      const DiffController &diffController,
      const std::string &clientAgent,
      const std::string &workerName,
      int64_t workerId);

  void handleRequest(
      const std::string &idStr,
      const std::string &method,
      const JsonNode &jparams,
      const JsonNode &jroot) override;

private:
  void handleRequest_Submit(const string &idStr, const JsonNode &jparams);
};


text:
<?php
namespace Account\Entity;

use Doctrine\Common\Collections\ArrayCollection;

use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity(repositoryClass="Account\Model\InvestmentRepository")
 * @ORM\Table(name="Investments")
 */
class Investment
{
	/**
	 * @ORM\Id @ORM\Column(type="integer")
	 * @ORM\GeneratedValue(strategy="IDENTITY")
	 */
	private $id;

	/**
	 * @ORM\OneToMany(targetEntity="Account\Entity\BankAccountHistory", mappedBy="investment")
	 */
	private $history;

	/**
	 * @ORM\ManyToOne(targetEntity="Account\Entity\Product", inversedBy="investments")
	 */
	private $product;

	/**
	 * @ORM\ManyToOne(targetEntity="Account\Entity\User", inversedBy="investments")
	 */
	private $user;

	/**
	 * @ORM\Column(type="decimal", precision=10, scale=2)
	 */
	private $amount = 0;

	/**
	 * @ORM\Column(type="datetime")
	 */
	private $date;

	/**
	 * @ORM\Column(type="datetime", nullable=true)
	 */
	private $ended;

	/**
	 * @ORM\Column(type="decimal", precision=3, scale=2, nullable=true)
	 */
	private $rentabilityAchieved;

	/**
	 * @ORM\Column(type="decimal", precision=3, scale=2)
	 */
	private $fee;

	public function __construct(){
		$this->history = new ArrayCollection();
	}

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

	/**
	 *
	 * @return ArrayCollection
	 */
	public function getHistory()
	{
	    return $this->history;
	}

	/**
	 *
	 * @param BankAccountHistory $history
	 * @return Investment
	 */
	public function addHistory(BankAccountHistory $history)
	{
	    $this->history->add($history);
	    return $this;
	}

	/**
	 *
	 * @return Product
	 */
	public function getProduct()
	{
	    return $this->product;
	}

	/**
	 *
	 * @param Product $product
	 * @return Investment
	 */
	public function setProduct(Product $product)
	{
	    $this->product = $product;
	    return $this;
	}

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

	/**
	 *
	 * @param User $user
	 * @return Investment
	 */
	public function setUser(User $user)
	{
	    $this->user = $user;
	    return $this;
	}

	/**
	 *
	 * @return Double
	 */
	public function getAmount()
	{
	    return $this->amount;
	}

	/**
	 *
	 * @param $amount
	 * @return Investment
	 */
	public function setAmount($amount)
	{
	    $this->amount = $amount;
	    return $this;
	}

	/**
	 *
	 * @return \DateTime
	 */
	public function getDate()
	{
	    return $this->date;
	}

	/**
	 *
	 * @param \DateTime $date
	 * @return Investment
	 */
	public function setDate(\DateTime $date)
	{
	    $this->date = $date;
	    return $this;
	}

	/**
	 *
	 * @return \DateTime
	 */
	public function getEnded()
	{
	    return $this->ended;
	}

	/**
	 *
	 * @return boolean
	 */
	public function isEnded()
	{
		return $this->ended != null ? true : false;
	}

	/**
	 *
	 * @param \DateTime $ended
	 * @return Investment
	 */
	public function setEnded(\DateTime $ended)
	{
		$this->ended = $ended;
	    return $this;
	}

	/**
	 *
	 * @return Double
	 */
	public function getRentabilityAchieved()
	{
	    return $this->rentabilityAchieved;
	}

	/**
	 *
	 * @param Double $rentabilityAchieved
	 * @return Investment
	 */
	public function setRentabilityAchieved($rentabilityAchieved)
	{
	    $this->rentabilityAchieved = $rentabilityAchieved;
	    return $this;
	}

	/**
	 *
	 * @return Double
	 */
	public function getFee()
	{
	    return $this->fee;
	}

	/**
	 *
	 * @param Double $fee
	 * @return Investment
	 */
	public function setFee($fee)
	{
	    $this->fee = $fee;
	    return $this;
	}
}


text:
import {getCookie} from 'utils/utils';

export const createChat = (username) => {
  return new Promise((resolve, reject) => {
    let headers = new Headers();
    headers.append('X-CSRFToken', getCookie('csrftoken'));
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');

    fetch('/api/create_chat', {
      method: 'POST',
      credentials: 'same-origin',
      headers: headers,
      body: JSON.stringify({
        username: username
      })
    })
    .then(response => {
      response.json().then(response => resolve(response));
    });
  });
};

export const getCurrentUser = () => {
  return new Promise((resolve, reject) => {
    fetch('/api/get_authenticated_user', {
      method: 'GET',
      credentials: 'same-origin'
    })
    .then(response => {
      response.json().then(user => resolve(user));
    });
  });
};

export const getAllUsers = () => {
  return new Promise((resolve, reject) => {
    fetch('/api/get_all_users', {
      method: 'GET',
      credentials: 'same-origin'
    })
    .then(response => {
      response.json().then(users => resolve(users));
    });
  });
};

export const getUserChats = () => {
  return new Promise((resolve, reject) => {
    fetch('/api/get_user_chats', {
      method: 'GET',
      credentials: 'same-origin'
    })
    .then(response => {
      response.json().then(response => resolve(response));
    });
  });
};

export const loadChatMessages = (chatId, pageNumber) => {
  return new Promise((resolve, reject) => {
    fetch(`/api/load_chat_messages/?page=${pageNumber}&chat_id=${chatId}`, {
      method: 'GET',
      credentials: 'same-origin'
    })
    .then(response => {
      response.json().then(response => resolve(response));
    });
  });
}


text:
package org.bitcoinj.core.listeners;

import org.bitcoinj.core.AbstractBlockChain;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.VerificationException;

/**
 * Listener interface for when a new block on the best chain is seen.
 */
public interface NewBestBlockListener {
    /**
     * Called when a new block on the best chain is seen, after relevant
     * transactions are extracted and sent to us via either
     * {@link TransactionReceivedInBlockListener#receiveFromBlock(Transaction, StoredBlock, AbstractBlockChain.NewBlockType, int)}
     * or {@link TransactionReceivedInBlockListener#notifyTransactionIsInBlock(Sha256Hash, StoredBlock, AbstractBlockChain.NewBlockType, int)}.
     * If this block is causing a re-organise to a new chain, this method is NOT
     * called even though the block may be the new best block: your reorganize
     * implementation is expected to do whatever would normally be done do for a
     * new best block in this case.
     */
    void notifyNewBestBlock(final StoredBlock block) throws VerificationException;
}


text:
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/os/os-proto.h */
/*
 * Copyright 1990,1991,2009 by the Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 *   require a specific license from the United States Government.
 *   It is the responsibility of any person or organization contemplating
 *   export to obtain such a license before exporting.
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 */

/*
 *
 * LIBOS internal function prototypes.
 */

#ifndef KRB5_LIBOS_INT_PROTO__
#define KRB5_LIBOS_INT_PROTO__

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#include <krb5/locate_plugin.h>

/* A single server hostname or address. */
struct server_entry {
    char *hostname;             /* NULL -> use addrlen/addr instead */
    int port;                   /* Used only if hostname set */
    int socktype;               /* May be 0 for UDP/TCP if hostname set */
    int family;                 /* May be 0 (aka AF_UNSPEC) if hostname set */
    size_t addrlen;
    struct sockaddr_storage addr;
};

/* A list of server hostnames/addresses. */
struct serverlist {
    struct server_entry *servers;
    size_t nservers;
};
#define SERVERLIST_INIT { NULL, 0 }

struct remote_address {
    int family;
    int type;
    socklen_t len;
    struct sockaddr_storage saddr;
};

struct sendto_callback_info {
    int (*pfn_callback)(SOCKET fd, void *data, krb5_data *message);
    void (*pfn_cleanup)(void *data, krb5_data *message);
    void *data;
};

krb5_error_code k5_locate_server(krb5_context, const krb5_data *realm,
                                 struct serverlist *,
                                 enum locate_service_type svc, int socktype);

krb5_error_code k5_locate_kdc(krb5_context context, const krb5_data *realm,
                              struct serverlist *serverlist, int get_masters,
                              int socktype);

void k5_free_serverlist(struct serverlist *);

#ifdef HAVE_NETINET_IN_H
krb5_error_code krb5_unpack_full_ipaddr(krb5_context,
                                        const krb5_address *,
                                        krb5_int32 *,
                                        krb5_int16 *);

krb5_error_code krb5_make_full_ipaddr(krb5_context,
                                      krb5_int32,
                                      int,   /* unsigned short promotes to signed int */
                                      krb5_address **);

#endif /* HAVE_NETINET_IN_H */

krb5_error_code k5_try_realm_txt_rr(krb5_context context, const char *prefix,
                                    const char *name, char **realm);

int _krb5_use_dns_realm (krb5_context);
int _krb5_use_dns_kdc (krb5_context);
int _krb5_conf_boolean (const char *);

krb5_error_code k5_sendto(krb5_context context, const krb5_data *message,
                          const struct serverlist *addrs,
                          int socktype1, int socktype2,
                          struct sendto_callback_info *callback_info,
                          krb5_data *reply, struct sockaddr *remoteaddr,
                          socklen_t *remoteaddrlen, int *server_used,
                          int (*msg_handler)(krb5_context, const krb5_data *,
                                             void *),
                          void *msg_handler_data);

krb5_error_code krb5int_get_fq_local_hostname(char *, size_t);

/* The io vector is *not* const here, unlike writev()!  */
int krb5int_net_writev (krb5_context, int, sg_buf *, int);

int k5_getcurtime(struct timeval *tvp);

krb5_error_code k5_expand_path_tokens(krb5_context context,
                                      const char *path_in, char **path_out);
krb5_error_code k5_expand_path_tokens_extra(krb5_context context,
                                            const char *path_in,
                                            char **path_out, ...);

krb5_error_code k5_create_secure_file(krb5_context, const char * pathname);
krb5_error_code k5_sync_disk_file(krb5_context, FILE *fp);
krb5_error_code k5_os_init_context(krb5_context context, profile_t profile,
                                   krb5_flags flags);
void k5_os_free_context(krb5_context);
krb5_error_code k5_os_hostaddr(krb5_context, const char *, krb5_address ***);
krb5_error_code k5_time_with_offset(krb5_timestamp offset,
                                    krb5_int32 offset_usec,
                                    krb5_timestamp *time_out,
                                    krb5_int32 *usec_out);
void k5_set_prompt_types(krb5_context, krb5_prompt_type *);
krb5_error_code k5_clean_hostname(krb5_context, const char *, char *, size_t);
krb5_boolean k5_is_numeric_address(const char *name);
krb5_error_code k5_make_realmlist(const char *realm, char ***realms_out);
krb5_error_code k5_kt_client_default_name(krb5_context context,
                                          char **name_out);
krb5_error_code k5_write_messages(krb5_context, krb5_pointer, krb5_data *,
                                  int);
void k5_init_trace(krb5_context context);

#include "k5-thread.h"
extern k5_mutex_t krb5int_us_time_mutex;

extern unsigned int krb5_max_skdc_timeout;
extern unsigned int krb5_skdc_timeout_shift;
extern unsigned int krb5_skdc_timeout_1;

void k5_hostrealm_free_context(krb5_context);
krb5_error_code hostrealm_profile_initvt(krb5_context context, int maj_ver,
                                         int min_ver,
                                         krb5_plugin_vtable vtable);
krb5_error_code hostrealm_dns_initvt(krb5_context context, int maj_ver,
                                     int min_ver, krb5_plugin_vtable vtable);
krb5_error_code hostrealm_domain_initvt(krb5_context context, int maj_ver,
                                        int min_ver,
                                        krb5_plugin_vtable vtable);

void k5_localauth_free_context(krb5_context);
krb5_error_code localauth_names_initvt(krb5_context context, int maj_ver,
                                       int min_ver, krb5_plugin_vtable vtable);
krb5_error_code localauth_rule_initvt(krb5_context context, int maj_ver,
                                      int min_ver, krb5_plugin_vtable vtable);
krb5_error_code localauth_k5login_initvt(krb5_context context, int maj_ver,
                                         int min_ver,
                                         krb5_plugin_vtable vtable);
krb5_error_code localauth_an2ln_initvt(krb5_context context, int maj_ver,
                                       int min_ver, krb5_plugin_vtable vtable);

#endif /* KRB5_LIBOS_INT_PROTO__ */


text:
/* View for Coeus compatibility */
CREATE OR REPLACE VIEW OSP$PROTOCOL_KEY_PERSONS
(PROTOCOL_NUMBER, SEQUENCE_NUMBER, PERSON_ID, PERSON_NAME, PERSON_ROLE,
NON_EMPLOYEE_FLAG, AFFILIATION_TYPE_CODE, UPDATE_TIMESTAMP, UPDATE_USER)
AS
SELECT
PROTOCOL_NUMBER, SEQUENCE_NUMBER,
DECODE(PERSON_ID,NULL,TO_CHAR(ROLODEX_ID),PERSON_ID) PERSON_ID,
PERSON_NAME, B.DESCRIPTION PERSON_ROLE,
DECODE(PERSON_ID,NULL,'N','Y') NON_EMPLOYEE_FLAG,
AFFILIATION_TYPE_CODE, A.UPDATE_TIMESTAMP UPDATE_TIMESTAMP, A.UPDATE_USER UPDATE_USER
FROM PROTOCOL_PERSONS A, PROTOCOL_PERSON_ROLES B
WHERE B.PROTOCOL_PERSON_ROLE_ID = A.PROTOCOL_PERSON_ROLE_ID AND
A.PROTOCOL_PERSON_ROLE_ID NOT IN ('PI','COI');


text:
/**
 *
 * Implements HPACK HTTP2 header encoding/decoding. See
 *
 * http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-05
 */

#ifndef HPACK_H
#define HPACK_H

#include <stdint.h>
#include <stdbool.h>

#include "log.h"
#include "circular_buffer.h"
#include "header_list.h"
#include "binary_buffer.h"

#define HEADER_TABLE_OVERHEAD 32

#define ESTIMATED_HEADER_NAME_SIZE 10
#define ESTIMATED_HEADER_VALUE_SIZE 20
#define ESTIMATED_HEADER_ENTRY_SIZE HEADER_TABLE_OVERHEAD + \
  ESTIMATED_HEADER_NAME_SIZE + ESTIMATED_HEADER_VALUE_SIZE

typedef struct {
  size_t num_bytes;
  size_t value;
} hpack_decode_quantity_result_t;

typedef struct {
  uint8_t * buf;
  size_t buf_length;
} hpack_encode_result_t;

typedef struct {

  char * name;
  size_t name_length;
  bool free_name;

  char * value;
  size_t value_length;
  bool free_value;

  size_t size_in_table;

  bool from_static_table;

} hpack_header_table_entry_t;

typedef struct {

  struct log_context_t * log;

  // maxiumum size in octets
  size_t max_size;

  // current size in octets as defined by
  // the spec
  size_t current_size;

  circular_buffer_t * header_table;

} hpack_context_t;

void hpack_decode_quantity(const uint8_t * const buf, const size_t length, const uint8_t offset,
                           hpack_decode_quantity_result_t * const result);

bool hpack_encode_quantity(binary_buffer_t * const buf, const uint8_t first_byte, const size_t bit_offset,
                           const size_t quantity);

hpack_context_t * hpack_context_init(const size_t header_table_size, struct log_context_t * context);

void hpack_context_free(hpack_context_t * const context);

void hpack_header_table_adjust_size(hpack_context_t * const context, size_t new_size);

header_list_t * hpack_decode(hpack_context_t * const context, const uint8_t * const buf, const size_t length);

binary_buffer_t * hpack_encode(hpack_context_t * const context, const header_list_t * const header_list,
                               binary_buffer_t * result);

#endif


text:
// Copyright (c) 2018, Smart Projects Holdings Ltd
// All rights reserved.
// See LICENSE file for license details.

/*
 * platform_sockets.h
 *
 * Defines platform specific parts of socket implementation.
 */

#ifndef _WIN32
#error "This header should be included only in Windows build."
#endif

#ifndef PLATFORM_SOCKETS_H_
#define PLATFORM_SOCKETS_H_

// default value for FD_SETSIZE in winsock is 64.
// it's too small if we are oprating large fleets.
#define FD_SETSIZE 1024

// Windows specific headers for socket stuff
#include <winsock2.h>
#include <ws2tcpip.h> // for socklen_t
/* Some weird code can define these macros in Windows headers. */
#ifdef ERROR
#undef ERROR
#endif
#ifdef interface
#undef interface
#endif
#ifdef RELATIVE
#undef RELATIVE
#endif
#ifdef ABSOLUTE
#undef ABSOLUTE
#endif

namespace ugcs
{
namespace vsm
{
namespace sockets
{

// Windows specific socket handle
typedef SOCKET Socket_handle; /* Win */

// Only linux build sets SEND_FLAGS to nonzero.
const int SEND_FLAGS = 0;

}// namespace platform
}
}

#endif /* PLATFORM_SOCKETS_H_ */


text:
var pkgcloud = require('pkgcloud'),
  logging = require('../../../common/logging'),
  config = require('../../../common/config'),
  _ = require('underscore');

var log = logging.getLogger(process.env.PKGCLOUD_LOG_LEVEL || 'debug');

var client = pkgcloud.providers.rackspace.storage.createClient(config.getConfig('rackspace', 1));

client.on('log::*', logging.logFunction);

client.createContainer(process.argv[2], function (err, container) {
  if (err) {
    log.error(err);
    return;
  }

  log.info(container.toJSON());
});


text:
package org.eclipse.php.internal.core.ast.nodes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.php.internal.core.PHPVersion;
import org.eclipse.php.internal.core.ast.match.ASTMatcher;
import org.eclipse.php.internal.core.ast.visitor.Visitor;

/**
 * Represents an assignment statement.
 *
 *
e.g.
 *
 *

 * $a = 5,
 * $a += 5,
 * $a .= $b,
 */
public class Assignment extends Expression implements IOperationNode {

	// '='
	public static final int OP_EQUAL = 0;
	// '+='
	public static final int OP_PLUS_EQUAL = 1;
	// '-='
	public static final int OP_MINUS_EQUAL = 2;
	// '*='
	public static final int OP_MUL_EQUAL = 3;
	// '/='
	public static final int OP_DIV_EQUAL = 4;
	// '.='
	public static final int OP_CONCAT_EQUAL = 5;
	// '%='
	public static final int OP_MOD_EQUAL = 6;
	// '&='
	public static final int OP_AND_EQUAL = 7;
	// '|='
	public static final int OP_OR_EQUAL = 8;
	// '^='
	public static final int OP_XOR_EQUAL = 9;
	// '<<='
	public static final int OP_SL_EQUAL = 10;
	// '>>='
	public static final int OP_SR_EQUAL = 11;

	public static final int OP_NEKUDOTAIM = 12;

	private VariableBase leftHandSide;
	private int operator;
	private Expression rightHandSide;

	/**
	 * The structural property of this node type.
	 */
	public static final ChildPropertyDescriptor LEFT_HAND_SIDE_PROPERTY = new ChildPropertyDescriptor(
			Assignment.class,
			"variable", VariableBase.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$
	public static final SimplePropertyDescriptor OPERATOR_PROPERTY = new SimplePropertyDescriptor(
			Assignment.class, "operator", Integer.class, MANDATORY); //$NON-NLS-1$
	public static final ChildPropertyDescriptor RIGHT_HAND_SIDE_PROPERTY = new ChildPropertyDescriptor(
			Assignment.class, "value", Expression.class, MANDATORY, CYCLE_RISK); //$NON-NLS-1$

	/**
	 * A list of property descriptors (element type:
	 * {@link StructuralPropertyDescriptor}), or null if uninitialized.
	 */
	private static final List<StructuralPropertyDescriptor> PROPERTY_DESCRIPTORS;

	static {
		List<StructuralPropertyDescriptor> properyList = new ArrayList<StructuralPropertyDescriptor>(
				3);
		properyList.add(LEFT_HAND_SIDE_PROPERTY);
		properyList.add(OPERATOR_PROPERTY);
		properyList.add(RIGHT_HAND_SIDE_PROPERTY);
		PROPERTY_DESCRIPTORS = Collections.unmodifiableList(properyList);
	}

	public Assignment(int start, int end, AST ast, VariableBase leftHandSide,
			int operator, Expression rightHandSide) {
		super(start, end, ast);
		if (leftHandSide == null || rightHandSide == null
				|| getOperator(operator) == null) {
			throw new IllegalArgumentException();
		}

		setLeftHandSide(leftHandSide);
		setOperator(operator);
		setRightHandSide(rightHandSide);
	}

	public Assignment(AST ast) {
		super(ast);
	}

	// public Assignment(int start, int end, AST ast, VariableBase leftHandSide,
	// int operator, List expressions) {
	// super(start, end, ast);
	//
	// setLeftHandSide(leftHandSide);
	// setOperator(operator);
	//
	// Expression[] list_expression = (Expression[]) expressions
	// .toArray(new Expression[expressions.size()]);
	// for (Expression expression : list_expression) {
	// setRightHandSide(expression);
	// }
	//
	// }

	public static String getOperator(int operator) {
		switch (operator) {
		case OP_EQUAL:
			return "="; //$NON-NLS-1$
		case OP_PLUS_EQUAL:
			return "+="; //$NON-NLS-1$
		case OP_MINUS_EQUAL:
			return "-="; //$NON-NLS-1$
		case OP_MUL_EQUAL:
			return "*="; //$NON-NLS-1$
		case OP_DIV_EQUAL:
			return "/="; //$NON-NLS-1$
		case OP_MOD_EQUAL:
			return "%="; //$NON-NLS-1$
		case OP_CONCAT_EQUAL:
			return ".="; //$NON-NLS-1$
		case OP_AND_EQUAL:
			return "&="; //$NON-NLS-1$
		case OP_OR_EQUAL:
			return "|="; //$NON-NLS-1$
		case OP_XOR_EQUAL:
			return "^="; //$NON-NLS-1$
		case OP_SL_EQUAL:
			return "<<="; //$NON-NLS-1$
		case OP_SR_EQUAL:
			return ">>="; //$NON-NLS-1$
		case OP_NEKUDOTAIM:
			return ":";
		default:
			throw new IllegalArgumentException();
		}
	}

	public void childrenAccept(Visitor visitor) {
		leftHandSide.accept(visitor);
		rightHandSide.accept(visitor);
	}

	public void traverseTopDown(Visitor visitor) {
		accept(visitor);
		leftHandSide.traverseTopDown(visitor);
		rightHandSide.traverseTopDown(visitor);
	}

	public void traverseBottomUp(Visitor visitor) {
		leftHandSide.traverseBottomUp(visitor);
		rightHandSide.traverseBottomUp(visitor);
		accept(visitor);
	}

	public void toString(StringBuffer buffer, String tab) {
		buffer.append(tab).append("<Assignment"); //$NON-NLS-1$
		appendInterval(buffer);
		buffer.append(" operator='").append(getXmlStringValue(getOperator(operator))).append("'>\n"); //$NON-NLS-1$ //$NON-NLS-2$
		leftHandSide.toString(buffer, TAB + tab);
		buffer.append("\n").append(TAB).append(tab).append("<Value>\n"); //$NON-NLS-1$ //$NON-NLS-2$
		rightHandSide.toString(buffer, TAB + TAB + tab);
		buffer.append("\n").append(TAB).append(tab).append("</Value>\n"); //$NON-NLS-1$ //$NON-NLS-2$
		buffer.append(tab).append("</Assignment>"); //$NON-NLS-1$
	}

	public void accept0(Visitor visitor) {
		final boolean visit = visitor.visit(this);
		if (visit) {
			childrenAccept(visitor);
		}
		visitor.endVisit(this);
	}

	@Override
	public int getType() {
		return ASTNode.ASSIGNMENT;
	}

	/**
	 * @deprecated use {@link #getRightHandSide()}
	 */
	public Expression getValue() {
		return rightHandSide;
	}

	/**
	 * @deprecated use {@link #getLeftHandSide()}
	 */
	public VariableBase getVariable() {
		return leftHandSide;
	}

	/**
	 * Returns the operator of this assignment expression.
	 *
	 * @return the assignment operator
	 */
	public int getOperator() {
		return this.operator;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.php.internal.core.ast.nodes.IOperationNode#getOperationString
	 * ()
	 */
	public String getOperationString() {
		return getOperator(this.getOperator());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.php.internal.core.ast.nodes.IOperationNode#getOperationString
	 * (int)
	 */
	public String getOperationString(int op) {
		return getOperator(op);
	}

	/**
	 * Sets the operator of this assignment expression.
	 *
	 * @param assignmentOperator
	 *            the assignment operator
	 * @exception IllegalArgumentException
	 *                if the argument is incorrect
	 */
	public void setOperator(int assignmentOperator) {
		if (getOperator(assignmentOperator) == null) {
			throw new IllegalArgumentException("Invalid operator"); //$NON-NLS-1$
		}
		preValueChange(OPERATOR_PROPERTY);
		this.operator = assignmentOperator;
		postValueChange(OPERATOR_PROPERTY);
	}

	/**
	 * Returns the left hand side of this assignment expression.
	 *
	 * @return the left hand side node
	 */
	public VariableBase getLeftHandSide() {
		return this.leftHandSide;
	}

	/**
	 * Sets the left hand side of this assignment expression.
	 *
	 * @param expression
	 *            the left hand side node
	 * @exception IllegalArgumentException
	 *                if:
	 *

	 *
the node belongs to a different AST

	 *
the node already has a parent

	 *
a cycle in would be created

	 *

	 */
	public void setLeftHandSide(VariableBase leftHandSide) {
		if (leftHandSide == null) {
			throw new IllegalArgumentException();
		}
		// an Assignment may occur inside a Expression - must check cycles
		ASTNode oldChild = this.leftHandSide;
		preReplaceChild(oldChild, leftHandSide, LEFT_HAND_SIDE_PROPERTY);
		this.leftHandSide = leftHandSide;
		postReplaceChild(oldChild, leftHandSide, LEFT_HAND_SIDE_PROPERTY);
	}

	/**
	 * Returns the right hand side of this assignment expression.
	 *
	 * @return the right hand side node
	 */
	public Expression getRightHandSide() {
		return this.rightHandSide;
	}

	/**
	 * Sets the right hand side of this assignment expression.
	 *
	 * @param expression
	 *            the right hand side node
	 * @exception IllegalArgumentException
	 *                if:
	 *

	 *
the node belongs to a different AST

	 *
the node already has a parent

	 *
a cycle in would be created

	 *

	 */
	public void setRightHandSide(Expression expression) {
		if (expression == null) {
			throw new IllegalArgumentException();
		}
		// an Assignment may occur inside a Expression - must check cycles
		ASTNode oldChild = this.rightHandSide;
		preReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY);
		this.rightHandSide = expression;
		postReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY);
	}

	/*
	 * Method declared on ASTNode.
	 */
	public boolean subtreeMatch(ASTMatcher matcher, Object other) {
		// dispatch to correct overloaded match method
		return matcher.match(this, other);
	}

	@Override
	ASTNode clone0(AST target) {
		final VariableBase left = ASTNode
				.copySubtree(target, getLeftHandSide());
		final Expression right = ASTNode
				.copySubtree(target, getRightHandSide());
		final Assignment result = new Assignment(this.getStart(),
				this.getEnd(), target, left, this.getOperator(), right);
		return result;
	}

	@Override
	List<StructuralPropertyDescriptor> internalStructuralPropertiesForType(
			PHPVersion apiLevel) {
		return PROPERTY_DESCRIPTORS;
	}

	final int internalGetSetIntProperty(SimplePropertyDescriptor property,
			boolean get, int value) {
		if (property == OPERATOR_PROPERTY) {
			if (get) {
				return getOperator();
			} else {
				setOperator((Integer) value);
				return 0;
			}
		}
		// allow default implementation to flag the error
		return super.internalGetSetIntProperty(property, get, value);
	}

	final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property,
			boolean get, ASTNode child) {
		if (property == LEFT_HAND_SIDE_PROPERTY) {
			if (get) {
				return getLeftHandSide();
			} else {
				setLeftHandSide((VariableBase) child);
				return null;
			}
		}
		if (property == RIGHT_HAND_SIDE_PROPERTY) {
			if (get) {
				return getRightHandSide();
			} else {
				setRightHandSide((Expression) child);
				return null;
			}
		}
		// allow default implementation to flag the error
		return super.internalGetSetChildProperty(property, get, child);
	}

}


text:
import json
import asyncio
import logging
import websockets
from datetime import datetime
from fable.logs import log
from fable.back.shell import acquire, release, abandon
from fable.back import notebook
from fable.back import minitex

_log = log('backend')

async def send(ws, code, data=''):
    if not ws:
        _log.error('Cannot send: web socket is None')
        return
    if not ws.open:
        _log.error('Cannot send: web socket is not open')
        return
    try:
        message = json.dumps({'code': code, 'value': data})
        await ws.send(message)
    except Exception:
        _log.exception()

async def recv(ws):
    data = await ws.recv()
    action, value = json.loads(data)
    return action, value

async def run_code(shell, ids, code, doc):
    try:
        await shell.run(code)
        ended = False
        while not ended:
            message, ended = await shell.readout()
            _log.info('Message', message)
            async with shell.run_msg_lock():
                doc.write(ids, message)
                await notebook.save(doc)
                await send(shell.user, 'code_run', {'ids': ids, 'msg': [message]})
    except Exception as e:
        await send(shell.user, 'code_run_error', {'ids': ids, 'error': str(e)})
        _log.exception()

async def run_tex(ws, shell, guid, code, doc):
    path, messages = minitex.parse(code, doc.path)

    await shell.change_path(json.dumps(doc.path))

    doc.change_path(path)
    for message in messages:
        doc.write(guid, message)
    await notebook.save(doc)

    await send(ws, 'code_run', {'ids': guid, 'msg': messages})

async def run_cell(ws, shell, ids, code, doc):
    kind = doc.kind(ids)
    if kind == 'tex':
        await run_tex(ws, shell, ids, code, doc)
    else:
        asyncio.ensure_future(run_code(shell, ids, code, doc))

async def init(ws, name, force=False, detached=False):
    shell = await acquire(name, ws, force='force')

    if shell is None:
        _log.error('could not acquire the shell')
        await send(ws, ['error', 'the notebook is busy'])
        return None, None

    if name == '':
        doc = notebook.Notebook()
        desc = {'version': '1.0', 'running': '', 'cells': []}
        await send(ws, 'opened', desc)
        return shell, doc

    async with shell.run_msg_lock():
        shell.show()
        doc = await notebook.load(name, detached)
        desc = {'version': '1.0', 'running': doc.running, 'cells': doc.cells_dict()}
        await send(ws, 'opened', desc)

    return shell, doc

async def main(ws):
    shell = None
    doc = None
    try:
        while True:
            action, value = await recv(ws)
            if action == 'notebook':
                assert shell is None and doc is None
                shell, doc = await init(ws, value['name'],
                                        value.get('force', False),
                                        value.get('detached', False))
            elif action == 'run':
                await run_cell(ws, shell, value['ids'], value['code'], doc)
            elif action == 'interrupt':
                await shell.interrupt()
            elif action == 'restart':
                doc.restart()
                await shell.restart()
                await notebook.save(doc)
            elif action == 'newcell':
                doc.newcell(value['prev_id'], value['cell_id'])
                await notebook.save(doc)
            elif action == 'change':
                new_kind = doc.change(value['guid'], value['code'])
                if new_kind is not None:
                    await send(ws, 'kind_changed', {'guid': value['guid'], 'kind': new_kind})
                await notebook.save(doc)
    except websockets.exceptions.ConnectionClosed:
        pass
    except Exception:
        _log.exception()
        raise
    finally:
        await release(shell, ws)

def bye():
    abandon()


text:
/*
 * MT_identifier.h
 *
 *  Created on: Aug 15, 2017
 *      Author: sedlazec
 */

#ifndef ANALYSIS_SV_MT_IDENTIFIER_H_
#define ANALYSIS_SV_MT_IDENTIFIER_H_

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <sstream>
#include <map>
using namespace std;

struct segment_str{
	int pos;
	std::string chr;
	bool strand;
	int MQ;
	int read_start;
};

#endif /* ANALYSIS_SV_MT_IDENTIFIER_H_ */


text:
#if !defined ADBASE_LOGGING_HPP_
# error "Not allow include this header."
#endif

#ifndef ADBASE_LOGGING_LOGFILE_HPP_
#define ADBASE_LOGGING_LOGFILE_HPP_

#include <thread>
#include <mutex>
#include <cassert>

namespace adbase {

/**
 * @addtogroup logging adbase::Logging
 */
/*@{*/

class AppendFile;
class LogFile {
public:
	LogFile(const std::string& basename,
			size_t rollSize,
			bool threadSafe = true,
			int flushInterval = 3,
			int checkEveryN = 1024);
	~LogFile();

	void append(const char* logline, int len);
	void flush();
	bool rollFile();

private:
	void appendUnlocked(const char* logline, int len);
	static std::string getLogFileName(const std::string& basename, time_t* now);

	const std::string _basename;
	const size_t _rollSize;
	const int _flushInterval;
	const int _checkEveryN;
	bool _threadSafe;

	int _count;
	time_t _startOfPeriod;
	time_t _lastRoll;
	time_t _lastFlush;
	const static int _kRollPerSeconds = 60 * 60 * 24;

	std::shared_ptr<AppendFile> _file;
	mutable std::mutex _mtx;
};

/*@}*/
}

#endif


text:
package org.eclipse.moquette.server;

import org.eclipse.moquette.server.config.IConfig;
import org.eclipse.moquette.server.config.MemoryConfig;
import org.fusesource.mqtt.client.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import static org.eclipse.moquette.commons.Constants.PERSISTENT_STORE_PROPERTY_NAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 *
 * @author andrea
 */
public class ServerRestartIntegrationTest {
    private static Logger LOG = LoggerFactory.getLogger(ServerRestartIntegrationTest.class);

    Server m_server;
    MQTT m_mqtt;
    BlockingConnection m_subscriber;
    BlockingConnection m_publisher;
    IConfig m_config;

    protected void startServer() throws IOException {
        m_server = new Server();
        final Properties configProps = IntegrationUtils.prepareTestPropeties();
        m_config = new MemoryConfig(configProps);
        m_server.startServer(m_config);
    }

    @Before
    public void setUp() throws Exception {
        startServer();

        m_mqtt = new MQTT();

        m_mqtt.setHost("localhost", 1883);
        m_mqtt.setCleanSession(false);
    }

    @After
    public void tearDown() throws Exception {
        if (m_subscriber != null) {
            m_subscriber.disconnect();
        }

        if (m_publisher != null) {
            m_publisher.disconnect();
        }

        m_server.stopServer();
        File dbFile = new File(m_config.getProperty(PERSISTENT_STORE_PROPERTY_NAME));
        if (dbFile.exists()) {
            dbFile.delete();
        }
    }

    @Test
    public void checkRestartCleanSubscriptionTree() throws Exception {
        m_mqtt.setClientId("Subscriber");
        //subscribe to /topic
        m_subscriber = m_mqtt.blockingConnection();
        m_subscriber.connect();
        Topic[] topics = new Topic[]{new Topic("/topic", QoS.AT_LEAST_ONCE)};
        m_subscriber.subscribe(topics);
        m_subscriber.disconnect();

        //shutdown the server
        m_server.stopServer();
        File dbFile = new File(m_config.getProperty(PERSISTENT_STORE_PROPERTY_NAME));
        if (dbFile.exists()) {
            dbFile.delete();
        }

        //restart the server
        m_server.startServer(IntegrationUtils.prepareTestPropeties());

        //reconnect the Subscriber subscribing to the same /topic but different QoS
        m_subscriber = m_mqtt.blockingConnection();
        m_subscriber.connect();
        topics = new Topic[]{new Topic("/topic", QoS.EXACTLY_ONCE)};
        m_subscriber.subscribe(topics);

        //should be just one registration so a publisher receive one notification
        MQTT mqtt = new MQTT();
        mqtt.setHost("localhost", 1883);
        mqtt.setClientId("Publisher");
        m_publisher = mqtt.blockingConnection();
        m_publisher.connect();
        m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(), QoS.AT_LEAST_ONCE, false);

        //read the messages
        Message msg = m_subscriber.receive();
        msg.ack();
        assertEquals("Hello world MQTT!!", new String(msg.getPayload()));
        //no more messages on the same topic will be received
        assertNull(m_subscriber.receive(1, TimeUnit.SECONDS));
    }

    @Test
    public void checkDontPublishInactiveClientsAfterServerRestart() throws Exception {
        m_mqtt.setClientId("SubPub");
        BlockingConnection conn = subscribeAndPublish("/topic");
        conn.disconnect();

        //shutdown the server
        m_server.stopServer();

        //restart the server
        m_server.startServer(IntegrationUtils.prepareTestPropeties());

        MQTT mqtt = new MQTT();
        mqtt.setHost("localhost", 1883);
        mqtt.setClientId("Publisher");
        m_publisher = mqtt.blockingConnection();
        m_publisher.connect();
        m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(), QoS.AT_MOST_ONCE, false);
    }

    @Test
    public void testClientDoesntRemainSubscribedAfterASubscriptionAndServerRestart() throws Exception {
        m_mqtt.setClientId("Subscriber");
        //subscribe to /topic
        m_subscriber = m_mqtt.blockingConnection();
        m_subscriber.connect();
        Topic[] topics = new Topic[]{new Topic("/topic", QoS.AT_MOST_ONCE)};
        //subscribe /topic
        m_subscriber.subscribe(topics);
        //unsubscribe from /topic
        m_subscriber.unsubscribe(new String[]{"/topic"});
        m_subscriber.disconnect();

        //shutdown the server
        m_server.stopServer();

        //restart the server
        m_server.startServer(IntegrationUtils.prepareTestPropeties());
        //subscriber reconnects
        MQTT mqttSub = new MQTT();
        mqttSub.setHost("localhost", 1883);
        mqttSub.setClientId("Subscriber");
        m_subscriber = mqttSub.blockingConnection();
        m_subscriber.connect();

        //publisher publishes on /topic
        MQTT mqtt = new MQTT();
        mqtt.setHost("localhost", 1883);
        mqtt.setClientId("Publisher");
        m_publisher = mqtt.blockingConnection();
        m_publisher.connect();
        m_publisher.publish("/topic", "Hello world MQTT!!".getBytes(), QoS.AT_LEAST_ONCE, false);

        //Expected
        //the subscriber doesn't get notified (it's fully unsubscribed)
        assertNull(m_subscriber.receive(1, TimeUnit.SECONDS));
    }

    /**
     * Connect subscribe to topic and publish on the same topic
     * */
    private BlockingConnection subscribeAndPublish(String topic) throws Exception {
        BlockingConnection conn = m_mqtt.blockingConnection();
        conn.connect();
        Topic[] topics = new Topic[]{new Topic(topic, QoS.AT_MOST_ONCE)};
        conn.subscribe(topics);
        conn.publish(topic, "Hello world MQTT!!".getBytes(), QoS.AT_MOST_ONCE, false);
        //read the message
        Message msg = conn.receive();
        msg.ack();
        assertEquals("Hello world MQTT!!", new String(msg.getPayload()));
        return conn;
    }
}


text:
/* linux/net/inet/arp.h */
#ifndef _ARP_H
#define _ARP_H

#include <linux/if_arp.h>
#include <linux/hash.h>
#include <net/neighbour.h>

extern struct neigh_table arp_tbl;

static inline u32 arp_hashfn(u32 key, const struct net_device *dev, u32 hash_rnd)
{
	u32 val = key ^ hash32_ptr(dev);

	return val * hash_rnd;
}

static inline struct neighbour *__ipv4_neigh_lookup_noref(struct net_device *dev, u32 key)
{
	struct neigh_hash_table *nht = rcu_dereference_bh(arp_tbl.nht);
	struct neighbour *n;
	u32 hash_val;

	hash_val = arp_hashfn(key, dev, nht->hash_rnd[0]) >> (32 - nht->hash_shift);
	for (n = rcu_dereference_bh(nht->hash_buckets[hash_val]);
	     n != NULL;
	     n = rcu_dereference_bh(n->next)) {
		if (n->dev == dev && *(u32 *)n->primary_key == key)
			return n;
	}

	return NULL;
}

static inline struct neighbour *__ipv4_neigh_lookup(struct net_device *dev, u32 key)
{
	struct neighbour *n;

	rcu_read_lock_bh();
	n = __ipv4_neigh_lookup_noref(dev, key);
	if (n && !atomic_inc_not_zero(&n->refcnt))
		n = NULL;
	rcu_read_unlock_bh();

	return n;
}

extern void	arp_init(void);
extern int	arp_find(unsigned char *haddr, struct sk_buff *skb);
extern int	arp_ioctl(struct net *net, unsigned int cmd, void __user *arg);
extern void     arp_send(int type, int ptype, __be32 dest_ip,
			 struct net_device *dev, __be32 src_ip,
			 const unsigned char *dest_hw,
			 const unsigned char *src_hw, const unsigned char *th);
extern int	arp_mc_map(__be32 addr, u8 *haddr, struct net_device *dev, int dir);
extern void	arp_ifdown(struct net_device *dev);

extern struct sk_buff *arp_create(int type, int ptype, __be32 dest_ip,
				  struct net_device *dev, __be32 src_ip,
				  const unsigned char *dest_hw,
				  const unsigned char *src_hw,
				  const unsigned char *target_hw);
extern void arp_xmit(struct sk_buff *skb);
int arp_invalidate(struct net_device *dev, __be32 ip);

#endif	/* _ARP_H */


text:
from setuptools import setup

setup(
    setup_requires=['pbr>=3.0', 'setuptools>=17.1'],
    pbr=True,
    python_requires=">=3.5.*",
    long_description_content_type='text/markdown; charset=UTF-8',
)


text:
"""MariaDB slave status checker"""

__all__ = ['SlaveStatusCheck']

import MySQLdb
from .base import NagiosPlugin

class SlaveStatusCheck(NagiosPlugin):
    """Class to help us run slave status queries against MariaDB"""
    REPLICATION_LAG_MODE = 'replication_lag'
    SLAVESQL_MODE = 'slave_sql'
    SLAVEIO_MODE = 'slave_io'
    MODES = (REPLICATION_LAG_MODE,
             SLAVESQL_MODE,
             SLAVEIO_MODE)

    def __init__(self, hostname, username, password, connection_name,
                 mode, verbose=False, warning=None, critical=None):
        super(SlaveStatusCheck, self).__init__(warning, critical)

        self.hostname = hostname
        self.username = username
        self.password = password
        self.connection_name = connection_name
        self.verbose = verbose
        self.mode = mode
        self._slave_status = {}

    def run_check(self):
        """Execute the check against the given mode"""
        check_fn = getattr(self, self.mode)
        check_fn()

    def replication_lag(self):
        """Check replication lag thresholds"""
        lag = self._slave_status.get('Seconds_Behind_Master')
        if lag is None:
            self.unknown_state("No replication lag reported")

        if not self.warning or not self.critical:
            self.unknown_state("Warning and critical thresholds undefined")

        lag = int(lag)
        warning = int(self.warning)
        critical = int(self.critical)
        lag_msg = "Slave is {0} seconds behind master | replication_lag={0};{1};{2}".format(lag, warning, critical)

        if lag >= warning and lag < critical:
            self.warning_state(lag_msg)
        elif lag >= critical:
            self.critical_state(lag_msg)

        self.ok_state(lag_msg)

    def slave_sql(self):
        """Check that Slave_SQL_Running = Yes"""
        if self._slave_status.get('Slave_SQL_Running') == "No":
            msg = "Slave sql is not running. Last error: {0}".format(
                self._slave_status.get('Last_SQL_Error'))
            self.critical_state(msg)

        self.ok_state("Slave sql is running")

    def slave_io(self):
        """Check that Slave_IO_Running = Yes"""
        if self._slave_status.get('Slave_IO_Running') == "No":
            msg = "Slave io is not running. Last error: {0}".format(
                self._slave_status.get('Last_IO_Error'))
            self.critical_state(msg)

        self.ok_state("Slave io is running")

    def get_slave_status(self):
        """Run the query!"""
        try:
            sql = 'SHOW SLAVE "{0}" STATUS'.format(self.connection_name)
            conn = None
            conn = MySQLdb.Connection(
                self.hostname,
                self.username,
                self.password)

            curs = conn.cursor(MySQLdb.cursors.DictCursor)
            curs.execute(sql)
            conn.commit()

            self._slave_status = curs.fetchall()[0]
            if self.verbose: # pragma: no cover
                print(self._slave_status)
        except MySQLdb.Error as exc:
            msg = "{0}: {1}".format(exc.args[0], exc.args[1])
            self.unknown_state(msg)
        finally:
            if conn:
                conn.close()


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmEditace_old
#Region "Windows Form Designer generated code "
    <System.Diagnostics.DebuggerNonUserCode()> Public Sub New()
        MyBase.New()
        'This call is required by the Windows Form Designer.
        InitializeComponent()
    End Sub
    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
        If Disposing Then
            If Not components Is Nothing Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(Disposing)
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer
    Public ToolTip1 As System.Windows.Forms.ToolTip
    Public WithEvents Editovat As System.Windows.Forms.Button
    Public WithEvents Smazat As System.Windows.Forms.Button
    Public WithEvents Vse As System.Windows.Forms.RadioButton
    Public WithEvents Slo As System.Windows.Forms.RadioButton
    Public WithEvents Vet As System.Windows.Forms.RadioButton
    Public WithEvents FrameVyhledávat As System.Windows.Forms.GroupBox
    Public WithEvents Ces As System.Windows.Forms.RadioButton
    Public WithEvents FramePodle As System.Windows.Forms.GroupBox
    Public WithEvents Pridat As System.Windows.Forms.Button
    Public WithEvents L As System.Windows.Forms.ComboBox
    Public WithEvents Nalezeno As System.Windows.Forms.ListBox
    Public WithEvents Hledat As System.Windows.Forms.ComboBox
    Public WithEvents Label3 As System.Windows.Forms.Label
    Public WithEvents Label2 As System.Windows.Forms.Label
    Public WithEvents Label1 As System.Windows.Forms.Label
    Public WithEvents Ekv As System.Windows.Forms.GroupBox
    Public WithEvents Konec As System.Windows.Forms.Button
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.Editovat = New System.Windows.Forms.Button
        Me.Smazat = New System.Windows.Forms.Button
        Me.FrameVyhledávat = New System.Windows.Forms.GroupBox
        Me.Vse = New System.Windows.Forms.RadioButton
        Me.Slo = New System.Windows.Forms.RadioButton
        Me.Vet = New System.Windows.Forms.RadioButton
        Me.FramePodle = New System.Windows.Forms.GroupBox
        Me.Ang = New System.Windows.Forms.RadioButton
        Me.Ces = New System.Windows.Forms.RadioButton
        Me.Pridat = New System.Windows.Forms.Button
        Me.Ekv = New System.Windows.Forms.GroupBox
        Me.L = New System.Windows.Forms.ComboBox
        Me.Nalezeno = New System.Windows.Forms.ListBox
        Me.Hledat = New System.Windows.Forms.ComboBox
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Label1 = New System.Windows.Forms.Label
        Me.Konec = New System.Windows.Forms.Button
        Me.FrameVyhledávat.SuspendLayout()
        Me.FramePodle.SuspendLayout()
        Me.Ekv.SuspendLayout()
        Me.SuspendLayout()
        '
        'Editovat
        '
        Me.Editovat.BackColor = System.Drawing.SystemColors.Control
        Me.Editovat.Cursor = System.Windows.Forms.Cursors.Default
        Me.Editovat.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Editovat.Location = New System.Drawing.Point(327, 9)
        Me.Editovat.Name = "Editovat"
        Me.Editovat.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Editovat.Size = New System.Drawing.Size(81, 22)
        Me.Editovat.TabIndex = 6
        Me.Editovat.Text = "E&ditovat vazbu"
        Me.Editovat.UseVisualStyleBackColor = False
        '
        'Smazat
        '
        Me.Smazat.BackColor = System.Drawing.SystemColors.Control
        Me.Smazat.Cursor = System.Windows.Forms.Cursors.Default
        Me.Smazat.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Smazat.Location = New System.Drawing.Point(327, 36)
        Me.Smazat.Name = "Smazat"
        Me.Smazat.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Smazat.Size = New System.Drawing.Size(81, 22)
        Me.Smazat.TabIndex = 7
        Me.Smazat.Text = "S&mazat vazbu"
        Me.Smazat.UseVisualStyleBackColor = False
        '
        'FrameVyhledávat
        '
        Me.FrameVyhledávat.BackColor = System.Drawing.SystemColors.Control
        Me.FrameVyhledávat.Controls.Add(Me.Vse)
        Me.FrameVyhledávat.Controls.Add(Me.Slo)
        Me.FrameVyhledávat.Controls.Add(Me.Vet)
        Me.FrameVyhledávat.ForeColor = System.Drawing.SystemColors.ControlText
        Me.FrameVyhledávat.Location = New System.Drawing.Point(177, 122)
        Me.FrameVyhledávat.Name = "FrameVyhledávat"
        Me.FrameVyhledávat.Padding = New System.Windows.Forms.Padding(0)
        Me.FrameVyhledávat.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.FrameVyhledávat.Size = New System.Drawing.Size(235, 60)
        Me.FrameVyhledávat.TabIndex = 17
        Me.FrameVyhledávat.TabStop = False
        Me.FrameVyhledávat.Text = "Vyhledávat:"
        '
        'Vse
        '
        Me.Vse.BackColor = System.Drawing.SystemColors.Control
        Me.Vse.Checked = True
        Me.Vse.Cursor = System.Windows.Forms.Cursors.Default
        Me.Vse.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Vse.Location = New System.Drawing.Point(9, 24)
        Me.Vse.Name = "Vse"
        Me.Vse.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Vse.Size = New System.Drawing.Size(99, 25)
        Me.Vse.TabIndex = 12
        Me.Vse.TabStop = True
        Me.Vse.Text = "Slovíèka &i fráze"
        Me.Vse.UseVisualStyleBackColor = False
        '
        'Slo
        '
        Me.Slo.BackColor = System.Drawing.SystemColors.Control
        Me.Slo.Cursor = System.Windows.Forms.Cursors.Default
        Me.Slo.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Slo.Location = New System.Drawing.Point(108, 24)
        Me.Slo.Name = "Slo"
        Me.Slo.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Slo.Size = New System.Drawing.Size(69, 25)
        Me.Slo.TabIndex = 13
        Me.Slo.TabStop = True
        Me.Slo.Text = "&Slovíèka"
        Me.Slo.UseVisualStyleBackColor = False
        '
        'Vet
        '
        Me.Vet.BackColor = System.Drawing.SystemColors.Control
        Me.Vet.Cursor = System.Windows.Forms.Cursors.Default
        Me.Vet.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Vet.Location = New System.Drawing.Point(181, 24)
        Me.Vet.Name = "Vet"
        Me.Vet.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Vet.Size = New System.Drawing.Size(52, 25)
        Me.Vet.TabIndex = 14
        Me.Vet.TabStop = True
        Me.Vet.Text = "&Fráze"
        Me.Vet.UseVisualStyleBackColor = False
        '
        'FramePodle
        '
        Me.FramePodle.BackColor = System.Drawing.SystemColors.Control
        Me.FramePodle.Controls.Add(Me.Ang)
        Me.FramePodle.Controls.Add(Me.Ces)
        Me.FramePodle.ForeColor = System.Drawing.SystemColors.ControlText
        Me.FramePodle.Location = New System.Drawing.Point(6, 123)
        Me.FramePodle.Name = "FramePodle"
        Me.FramePodle.Padding = New System.Windows.Forms.Padding(0)
        Me.FramePodle.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.FramePodle.Size = New System.Drawing.Size(165, 59)
        Me.FramePodle.TabIndex = 16
        Me.FramePodle.TabStop = False
        Me.FramePodle.Text = "Vyhledávat podle:"
        '
        'Ang
        '
        Me.Ang.AutoSize = True
        Me.Ang.Checked = True
        Me.Ang.Location = New System.Drawing.Point(72, 28)
        Me.Ang.Name = "Ang"
        Me.Ang.Size = New System.Drawing.Size(81, 17)
        Me.Ang.TabIndex = 11
        Me.Ang.TabStop = True
        Me.Ang.Text = "E&kvivalentu"
        Me.Ang.UseVisualStyleBackColor = True
        '
        'Ces
        '
        Me.Ces.BackColor = System.Drawing.SystemColors.Control
        Me.Ces.Cursor = System.Windows.Forms.Cursors.Default
        Me.Ces.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Ces.Location = New System.Drawing.Point(6, 24)
        Me.Ces.Name = "Ces"
        Me.Ces.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Ces.Size = New System.Drawing.Size(74, 25)
        Me.Ces.TabIndex = 10
        Me.Ces.Text = "È&eského"
        Me.Ces.UseVisualStyleBackColor = False
        '
        'Pridat
        '
        Me.Pridat.BackColor = System.Drawing.SystemColors.Control
        Me.Pridat.Cursor = System.Windows.Forms.Cursors.Default
        Me.Pridat.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Pridat.Location = New System.Drawing.Point(327, 66)
        Me.Pridat.Name = "Pridat"
        Me.Pridat.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Pridat.Size = New System.Drawing.Size(83, 22)
        Me.Pridat.TabIndex = 8
        Me.Pridat.Text = "&Pøidat vazbu"
        Me.Pridat.UseVisualStyleBackColor = False
        '
        'Ekv
        '
        Me.Ekv.BackColor = System.Drawing.SystemColors.Control
        Me.Ekv.Controls.Add(Me.L)
        Me.Ekv.Controls.Add(Me.Nalezeno)
        Me.Ekv.Controls.Add(Me.Hledat)
        Me.Ekv.Controls.Add(Me.Label3)
        Me.Ekv.Controls.Add(Me.Label2)
        Me.Ekv.Controls.Add(Me.Label1)
        Me.Ekv.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Ekv.Location = New System.Drawing.Point(6, 3)
        Me.Ekv.Name = "Ekv"
        Me.Ekv.Padding = New System.Windows.Forms.Padding(0)
        Me.Ekv.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Ekv.Size = New System.Drawing.Size(302, 115)
        Me.Ekv.TabIndex = 15
        Me.Ekv.TabStop = False
        '
        'L
        '
        Me.L.BackColor = System.Drawing.SystemColors.Window
        Me.L.Cursor = System.Windows.Forms.Cursors.Default
        Me.L.ForeColor = System.Drawing.SystemColors.WindowText
        Me.L.Location = New System.Drawing.Point(15, 33)
        Me.L.Name = "L"
        Me.L.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.L.Size = New System.Drawing.Size(65, 21)
        Me.L.TabIndex = 1
        Me.L.Text = "Všechny"
        '
        'Nalezeno
        '
        Me.Nalezeno.BackColor = System.Drawing.SystemColors.Window
        Me.Nalezeno.Cursor = System.Windows.Forms.Cursors.Default
        Me.Nalezeno.ForeColor = System.Drawing.SystemColors.WindowText
        Me.Nalezeno.Location = New System.Drawing.Point(87, 60)
        Me.Nalezeno.Name = "Nalezeno"
        Me.Nalezeno.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Nalezeno.Size = New System.Drawing.Size(205, 43)
        Me.Nalezeno.TabIndex = 5
        '
        'Hledat
        '
        Me.Hledat.BackColor = System.Drawing.SystemColors.Window
        Me.Hledat.Cursor = System.Windows.Forms.Cursors.Default
        Me.Hledat.ForeColor = System.Drawing.SystemColors.WindowText
        Me.Hledat.Location = New System.Drawing.Point(87, 33)
        Me.Hledat.Name = "Hledat"
        Me.Hledat.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Hledat.Size = New System.Drawing.Size(205, 21)
        Me.Hledat.Sorted = True
        Me.Hledat.TabIndex = 3
        '
        'Label3
        '
        Me.Label3.AutoSize = True
        Me.Label3.BackColor = System.Drawing.SystemColors.Control
        Me.Label3.Cursor = System.Windows.Forms.Cursors.Default
        Me.Label3.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Label3.Location = New System.Drawing.Point(18, 15)
        Me.Label3.Name = "Label3"
        Me.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Label3.Size = New System.Drawing.Size(40, 13)
        Me.Label3.TabIndex = 0
        Me.Label3.Text = "&Lekce:"
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.BackColor = System.Drawing.SystemColors.Control
        Me.Label2.Cursor = System.Windows.Forms.Cursors.Default
        Me.Label2.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Label2.Location = New System.Drawing.Point(45, 60)
        Me.Label2.Name = "Label2"
        Me.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Label2.Size = New System.Drawing.Size(40, 13)
        Me.Label2.TabIndex = 4
        Me.Label2.Text = "&Vazba:"
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.BackColor = System.Drawing.SystemColors.Control
        Me.Label1.Cursor = System.Windows.Forms.Cursors.Default
        Me.Label1.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Label1.Location = New System.Drawing.Point(87, 15)
        Me.Label1.Name = "Label1"
        Me.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Label1.Size = New System.Drawing.Size(99, 13)
        Me.Label1.TabIndex = 2
        Me.Label1.Text = "Vy&hledávaný výraz:"
        '
        'Konec
        '
        Me.Konec.BackColor = System.Drawing.SystemColors.Control
        Me.Konec.Cursor = System.Windows.Forms.Cursors.Default
        Me.Konec.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Konec.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Konec.Location = New System.Drawing.Point(327, 96)
        Me.Konec.Name = "Konec"
        Me.Konec.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Konec.Size = New System.Drawing.Size(83, 22)
        Me.Konec.TabIndex = 9
        Me.Konec.Text = "Kone&c"
        Me.Konec.UseVisualStyleBackColor = False
        '
        'frmEditace_old
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.SystemColors.Control
        Me.CancelButton = Me.Konec
        Me.ClientSize = New System.Drawing.Size(421, 194)
        Me.ControlBox = False
        Me.Controls.Add(Me.Editovat)
        Me.Controls.Add(Me.Smazat)
        Me.Controls.Add(Me.FrameVyhledávat)
        Me.Controls.Add(Me.FramePodle)
        Me.Controls.Add(Me.Pridat)
        Me.Controls.Add(Me.Ekv)
        Me.Controls.Add(Me.Konec)
        Me.Cursor = System.Windows.Forms.Cursors.Default
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
        Me.Location = New System.Drawing.Point(357, 249)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "frmEditace_old"
        Me.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Editace vazeb"
        Me.FrameVyhledávat.ResumeLayout(False)
        Me.FramePodle.ResumeLayout(False)
        Me.FramePodle.PerformLayout()
        Me.Ekv.ResumeLayout(False)
        Me.Ekv.PerformLayout()
        Me.ResumeLayout(False)

    End Sub
    Friend WithEvents Ang As System.Windows.Forms.RadioButton
#End Region
End Class


text:
'use strict';

module.exports =  ['$q', '$log', '$http', '$window', authService];

function authService($q, $log, $http, $window){
  $log.debug('authService');
  let service = {};
  let token = null;

  function setToken(_token){
    $log.debug('authService.setToken');
    if(!_token){
      return $q.reject(new Error('no token'));
    }
    $window.localStorage.setItem('token', _token);
    token = _token;
    return $q.resolve(token);
  }

  service.getToken = function(){
    $log.debug('authService.getToken');
    if(token) return $q.resolve(token);
    token = $window.localStorage.getItem('token');
    if(token) return $q.resolve(token);
    return $q.reject(new Error('token not found'));
  };

  service.signup = function(user){
    $log.debug('authService.signup');
    let url = `${__API_URL__}/api/signup`; //eslint-disable-line
    let config = {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    };

    return $http.post(url, user, config)
    .then(res => {
      $log.log('success:', res.data);
      return setToken(res.data);
    })
    .catch(err => {
      $log.error('failure:', err.message);
      return $q.reject(err);
    });
  };

  service.logout = function(){
    $log.debug('authService.logout');
    $window.localStorage.removeItem('token');
    token = null;
    return $q.resolve();
  };

  service.login = function(user){
    $log.debug('authService.login');
    let url = `${__API_URL__}/api/signin`; //eslint-disable-line
    let base64 = $window.btoa(`${user.username}:${user.password}`);
    let config = {
      headers: {
        Accept: 'application/json',
        Authorization: `Basic ${base64}`
      }
    };

    return $http.get(url, config)
    .then(res => {
      $log.log('success', res.data);
      return setToken(res.data);
    })
    .catch(err => {
      $log.error(err.message);
      return $q.reject(err);
    });
  };
  return service;
}


text:
        <button type="button" class="btn btn-sm btn-warning" onClick="printthepage()" id="printb"> Print</button>
        <button onclick="goback('<?php echo $records3; ?>')">Cancel</button>

        Quotation

Customer

Customer Id: <?php foreach ($records as $rec) {
                echo $rec->cuid;
            } ?>

Customer Name: <?php foreach ($records as $rec) {
                echo $rec->cusname;
            } ?>

Phone no.: <?php foreach ($records as $rec) {
                echo $rec->lphone;
            } ?>

E-mail: <?php foreach ($records as $rec) {
                echo $rec->email;
            } ?>

Event

    <?php foreach ($records2 as $rec) { ?>

<?php echo $rec->evcatname ?> at <?php echo $rec->location ?> for 200
            heads on <?php echo $rec->date ?> at <?php echo $rec->start_time ?>

    <?php } ?>

Services

            <?php foreach ($records1 as $rec) { ?>

                    <?php echo $rec->sername ?>

                        <?php echo $rec->serproname ?>

                        <?php echo $rec->address ?>

                        <?php echo $rec->email ?>

                        <?php echo $rec->phone1 ?>

                    (LKR) <?php echo $rec->cost ?>

            <?php } ?>

        Final Cost(LKR):
        <?php foreach ($records as $r) echo $r->finalcost ?>

Thank you for choosing Mask Events for your special event. Hope you
        have a nice experience.

    <?php echo date('Y-m-d'); ?>