text:
"""
runprofileserver.py

    Starts a lightweight Web server with profiling enabled.

Credits for kcachegrind support taken from lsprofcalltree.py go to:
 David Allouche
 Jp Calderone & Itamar Shtull-Trauring
 Johan Dahlin
"""

import sys
from datetime import datetime

from django.conf import settings
from django.core.management.base import CommandError

from django_extensions.management.utils import signalcommand
from django_extensions.compat import CompatibilityBaseCommand as BaseCommand

try:
    from django.contrib.staticfiles.handlers import StaticFilesHandler
    USE_STATICFILES = 'django.contrib.staticfiles' in settings.INSTALLED_APPS
except ImportError as e:
    USE_STATICFILES = False

class KCacheGrind(object):
    def __init__(self, profiler):
        self.data = profiler.getstats()
        self.out_file = None

    def output(self, out_file):
        self.out_file = out_file
        self.out_file.write('events: Ticks\n')
        self._print_summary()
        for entry in self.data:
            self._entry(entry)

    def _print_summary(self):
        max_cost = 0
        for entry in self.data:
            totaltime = int(entry.totaltime * 1000)
            max_cost = max(max_cost, totaltime)
        self.out_file.write('summary: %d\n' % (max_cost,))

    def _entry(self, entry):
        out_file = self.out_file

        code = entry.code
        if isinstance(code, str):
            out_file.write('fn=%s\n' % code)
        else:
            out_file.write('fl=%s\n' % code.co_filename)
            out_file.write('fn=%s\n' % code.co_name)

        inlinetime = int(entry.inlinetime * 1000)
        if isinstance(code, str):
            out_file.write('0  %s\n' % inlinetime)
        else:
            out_file.write('%d %d\n' % (code.co_firstlineno, inlinetime))

        # recursive calls are counted in entry.calls
        if entry.calls:
            calls = entry.calls
        else:
            calls = []

        if isinstance(code, str):
            lineno = 0
        else:
            lineno = code.co_firstlineno

        for subentry in calls:
            self._subentry(lineno, subentry)
        out_file.write("\n")

    def _subentry(self, lineno, subentry):
        out_file = self.out_file
        code = subentry.code
        if isinstance(code, str):
            out_file.write('cfn=%s\n' % code)
            out_file.write('calls=%d 0\n' % (subentry.callcount,))
        else:
            out_file.write('cfl=%s\n' % code.co_filename)
            out_file.write('cfn=%s\n' % code.co_name)
            out_file.write('calls=%d %d\n' % (subentry.callcount, code.co_firstlineno))

        totaltime = int(subentry.totaltime * 1000)
        out_file.write('%d %d\n' % (lineno, totaltime))

class Command(BaseCommand):
    help = "Starts a lightweight Web server with profiling enabled."
    args = '[optional port number, or ipaddr:port]'

    def add_arguments(self, parser):
        parser.add_argument(
            '--noreload', action='store_false', dest='use_reloader',
            default=True,
            help='Tells Django to NOT use the auto-reloader.')
        parser.add_argument(
            '--adminmedia', dest='admin_media_path', default='',
            help='Specifies the directory from which to serve admin media.')
        parser.add_argument(
            '--prof-path', dest='prof_path', default='/tmp',
            help='Specifies the directory which to save profile information '
            'in.')
        parser.add_argument(
            '--prof-file', dest='prof_file',
            default='{path}.{duration:06d}ms.{time}',
            help='Set filename format, default if '
            '"{path}.{duration:06d}ms.{time}".')
        parser.add_argument(
            '--nomedia', action='store_true', dest='no_media', default=False,
            help='Do not profile MEDIA_URL and ADMIN_MEDIA_URL')
        parser.add_argument(
            '--use-cprofile', action='store_true', dest='use_cprofile',
            default=False,
            help='Use cProfile if available, this is disabled per default '
            'because of incompatibilities.')
        parser.add_argument(
            '--kcachegrind', action='store_true', dest='use_lsprof',
            default=False,
            help='Create kcachegrind compatible lsprof files, this requires '
            'and automatically enables cProfile.')

        if USE_STATICFILES:
            parser.add_argument(
                '--nostatic', action="store_false", dest='use_static_handler',
                default=True,
                help='Tells Django to NOT automatically serve static files '
                'at STATIC_URL.')
            parser.add_argument(
                '--insecure', action="store_true", dest='insecure_serving',
                default=False,
                help='Allows serving static files even if DEBUG is False.')

    @signalcommand
    def handle(self, addrport='', *args, **options):
        import django
        import socket
        import errno
        from django.core.servers.basehttp import run
        try:
            from django.core.servers.basehttp import get_internal_wsgi_application as WSGIHandler
        except ImportError:
            from django.core.handlers.wsgi import WSGIHandler  # noqa

        try:
            from django.core.servers.basehttp import AdminMediaHandler
            HAS_ADMINMEDIAHANDLER = True
        except ImportError:
            HAS_ADMINMEDIAHANDLER = False

        try:
            from django.core.servers.basehttp import WSGIServerException as wsgi_server_exc_cls
        except ImportError:  # Django 1.6
            wsgi_server_exc_cls = socket.error

        if args:
            raise CommandError('Usage is runserver %s' % self.args)
        if not addrport:
            addr = ''
            port = '8000'
        else:
            try:
                addr, port = addrport.split(':')
            except ValueError:
                addr, port = '', addrport
        if not addr:
            addr = '127.0.0.1'

        if not port.isdigit():
            raise CommandError("%r is not a valid port number." % port)

        use_reloader = options.get('use_reloader', True)
        shutdown_message = options.get('shutdown_message', '')
        no_media = options.get('no_media', False)
        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        def inner_run():
            import os
            import time
            try:
                import hotshot
                HAS_HOTSHOT = True
            except ImportError:
                HAS_HOTSHOT = False  # python 3.x
            USE_CPROFILE = options.get('use_cprofile', False)
            USE_LSPROF = options.get('use_lsprof', False)
            if USE_LSPROF:
                USE_CPROFILE = True
            if USE_CPROFILE:
                try:
                    import cProfile
                    USE_CPROFILE = True
                except ImportError:
                    print("cProfile disabled, module cannot be imported!")
                    USE_CPROFILE = False
            if USE_LSPROF and not USE_CPROFILE:
                raise CommandError("Kcachegrind compatible output format required cProfile from Python 2.5")

            if not HAS_HOTSHOT and not USE_CPROFILE:
                raise CommandError("Hotshot profile library not found. (and not using cProfile)")

            prof_path = options.get('prof_path', '/tmp')

            prof_file = options.get('prof_file', '{path}.{duration:06d}ms.{time}')
            if not prof_file.format(path='1', duration=2, time=3):
                prof_file = '{path}.{duration:06d}ms.{time}'
                print("Filename format is wrong. Default format used: '{path}.{duration:06d}ms.{time}'.")

            def get_exclude_paths():
                exclude_paths = []
                media_url = getattr(settings, 'MEDIA_URL', None)
                if media_url:
                    exclude_paths.append(media_url)
                static_url = getattr(settings, 'STATIC_URL', None)
                if static_url:
                    exclude_paths.append(static_url)
                admin_media_prefix = getattr(settings, 'ADMIN_MEDIA_PREFIX', None)
                if admin_media_prefix:
                    exclude_paths.append(admin_media_prefix)
                return exclude_paths

            def make_profiler_handler(inner_handler):
                def handler(environ, start_response):
                    path_info = environ['PATH_INFO']
                    # when using something like a dynamic site middleware is could be necessary
                    # to refetch the exclude_paths every time since they could change per site.
                    if no_media and any(path_info.startswith(p) for p in get_exclude_paths()):
                        return inner_handler(environ, start_response)
                    path_name = path_info.strip("/").replace('/', '.') or "root"
                    profname = "%s.%d.prof" % (path_name, time.time())
                    profname = os.path.join(prof_path, profname)
                    if USE_CPROFILE:
                        prof = cProfile.Profile()
                    else:
                        prof = hotshot.Profile(profname)
                    start = datetime.now()
                    try:
                        return prof.runcall(inner_handler, environ, start_response)
                    finally:
                        # seeing how long the request took is important!
                        elap = datetime.now() - start
                        elapms = elap.seconds * 1000.0 + elap.microseconds / 1000.0
                        if USE_LSPROF:
                            kg = KCacheGrind(prof)
                            with open(profname, 'w') as f:
                                kg.output(f)
                        elif USE_CPROFILE:
                            prof.dump_stats(profname)
                        profname2 = prof_file.format(path=path_name, duration=int(elapms), time=int(time.time()))
                        profname2 = os.path.join(prof_path, "%s.prof" % profname2)
                        if not USE_CPROFILE:
                            prof.close()
                        os.rename(profname, profname2)
                return handler

            print("Validating models...")
            if hasattr(self, 'check'):
                self.check(display_num_errors=True)
            else:
                self.validate(display_num_errors=True)
            print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE))
            print("Development server is running at http://%s:%s/" % (addr, port))
            print("Quit the server with %s." % quit_command)
            path = options.get('admin_media_path', '')
            if not path:
                admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
                if os.path.isdir(admin_media_path):
                    path = admin_media_path
                else:
                    path = os.path.join(django.__path__[0], 'contrib/admin/media')
            try:
                handler = WSGIHandler()
                if HAS_ADMINMEDIAHANDLER:
                    handler = AdminMediaHandler(handler, path)
                if USE_STATICFILES:
                    use_static_handler = options.get('use_static_handler', True)
                    insecure_serving = options.get('insecure_serving', False)
                    if use_static_handler and (settings.DEBUG or insecure_serving):
                        handler = StaticFilesHandler(handler)
                handler = make_profiler_handler(handler)
                run(addr, int(port), handler)
            except wsgi_server_exc_cls as e:
                # Use helpful error messages instead of ugly tracebacks.
                ERRORS = {
                    errno.EACCES: "You don't have permission to access that port.",
                    errno.EADDRINUSE: "That port is already in use.",
                    errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
                }
                if not isinstance(e, socket.error):  # Django < 1.6
                    ERRORS[13] = ERRORS.pop(errno.EACCES)
                    ERRORS[98] = ERRORS.pop(errno.EADDRINUSE)
                    ERRORS[99] = ERRORS.pop(errno.EADDRNOTAVAIL)
                try:
                    if not isinstance(e, socket.error):  # Django < 1.6
                        error_text = ERRORS[e.args[0].args[0]]
                    else:
                        error_text = ERRORS[e.errno]
                except (AttributeError, KeyError):
                    error_text = str(e)
                sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n')
                # Need to use an OS exit because sys.exit doesn't work in a thread
                os._exit(1)
            except KeyboardInterrupt:
                if shutdown_message:
                    print(shutdown_message)
                sys.exit(0)
        if use_reloader:
            from django.utils import autoreload
            autoreload.main(inner_run)
        else:
            inner_run()


text:
namespace openlr
{
class RoadInfoGetter;

bool PointsAreClose(m2::PointD const & p1, m2::PointD const & p2);

double EdgeLength(Graph::Edge const & e);

bool EdgesAreAlmostEqual(Graph::Edge const & e1, Graph::Edge const & e2);

// TODO(mgsergio): Remove when unused.
std::string LogAs2GisPath(Graph::EdgeVector const & path);
std::string LogAs2GisPath(Graph::Edge const & e);

template <typename T, typename U,
          std::enable_if_t<!(std::is_signed<T>::value ^ std::is_signed<U>::value), int> = 0>
std::common_type_t<T, U> AbsDifference(T const a, U const b)
{
  return a >= b ? a - b : b - a;
}

bool PassesRestriction(Graph::Edge const & e, FunctionalRoadClass const restriction,
                       int const frcThreshold, RoadInfoGetter & infoGetter);
}  // namespace openlr

redpajama_set_name: RedPajamaGithub


text:
var fs = require('fs');
var path = require('path');

/*
 process.argv[0] - node.exe
 process.argv[1] - file location
 process.argv[2] - coverageType
 process.argv[3] - phantomJs path
 process.argv[4] - number of analyzed scenarios
 process.argv[5] - feature selectors
 process.argv[6]... - script paths to ignore
* */

var ScenarioGenerator = require(path.resolve(__dirname, "scenarioGeneratorModules/ScenarioGenerator.js")).ScenarioGenerator;

ScenarioGenerator.includeNecessaryFilesPlugin();

ScenarioGenerator.prioritization = process.argv[2] || "test";
ScenarioGenerator.phantomJsPath = process.argv[3] || "";
ScenarioGenerator.MAX_NUMBER_OF_SCENARIOS = process.argv[4] != null ? parseInt(process.argv[4]) : 100;
ScenarioGenerator.selector = process.argv[5] || "*";

ScenarioGenerator.scriptPathsToIgnore = [];

var i = 6;
while(process.argv[i] != null)
{
    ScenarioGenerator.scriptPathsToIgnore.push(process.argv[i]);
    i++;
}

ScenarioGenerator.shouldPrintDetailedMessages = true;

ScenarioGenerator.generateAdditionalMouseMoveEvents = true;
ScenarioGenerator.generateAdditionalTimingEvents = false;

var pageName = "page";
ScenarioGenerator.prioritization = process.argv[3] || ScenarioGenerator.PRIORITIZATION.symbolicNewCoverage;
ScenarioGenerator.MAX_NUMBER_OF_SCENARIOS = process.argv[4] != null ? parseInt(process.argv[4]) : 50;

console.log("Starting scenario generator: ", ScenarioGenerator.prioritization, ScenarioGenerator.MAX_NUMBER_OF_SCENARIOS);

var scenarioModelPath = path.resolve(__dirname, "model.js");
var generatedScenariosFile = path.resolve(__dirname, "generatedScenarios.txt");
var filteredScenariosFile = path.resolve(__dirname, "filteredScenarios.txt");
var coverageFile = path.resolve(__dirname, "achievedCoverage.txt");
var visitedCodeTemplatePath = path.resolve(__dirname, "viewExecutedCode.html")
var achievedCoveragePath = path.resolve(__dirname, "achievedCoverage.txt");

var startTime = Date.now();

ScenarioGenerator.generateScenarios(scenarioModelPath, pageName, function(scenarios, message, coverage)
{
    console.log("ScenarioGenerator", message);

    console.log("The process has achieved statement coverage: " + (coverage != null ? coverage.statementCoverage : 0));

    fs.writeFileSync(coverageFile, getCoverageData());

    fs.writeFileSync(generatedScenariosFile, JSON.stringify(scenarios.getAllScenarios()));
    fs.writeFileSync(filteredScenariosFile, JSON.stringify(scenarios.getSubsumedProcessedScenarios()));

    var markupCode = ScenarioGenerator.generateVisitedMarkup();

    var template = fs.readFileSync(visitedCodeTemplatePath, {encoding:"utf8"});
    var content = template.replace("{SOURCE_CODE}", markupCode);

    fs.writeFileSync(visitedCodeTemplatePath , content);
    fs.writeFileSync(achievedCoveragePath, ScenarioGenerator.coverages[ScenarioGenerator.coverages.length - 1].statementCoverage);
});

function getCoverageData()
{
    var data = "";

    ScenarioGenerator.coverages.forEach(function(item, index)
    {
        data += item.expressionCoverage + "@" + item.branchCoverage + "@" + item.statementCoverage;

        if(index != ScenarioGenerator.coverages.length - 1)
        {
            data += "\r\n";
        }
    });

    return data;
}


text:
import styled from 'styled-components';

const Title = styled.h2`
	font-size: 18px;
	color: #727272;
	margin-bottom: 20px;
	margin-left: 15px;
	font-family: 'Roboto Mono', monospace;
`;

export default Title;


text:
Crea tus librerías y tests con mocha

# para hacer la prueba del error "sin acceso"
`chmod 000 files/sinAcceso.txt`

# para volver a la normalidad
`chmod 500 files/sinAcceso.txt`


text:
#import "NSIndexPath+CKSupport.h"

@implementation NSIndexPath (CKSupport)

+ (NSIndexPath *)indexPathForItem:(NSInteger)item inSection:(NSInteger)section
{
  return [NSIndexPath indexPathWithIndexes:(const NSUInteger []){section, item} length:2];
}

- (NSInteger)section
{
  return [self indexAtPosition:0];
}

- (NSInteger)row
{
  return [self indexAtPosition:1];
}

- (NSInteger)item
{
  return [self indexAtPosition:1];
}

@end


text:
package v1

// PowerVSServiceEndpointApplyConfiguration represents an declarative configuration of the PowerVSServiceEndpoint type for use
// with apply.
type PowerVSServiceEndpointApplyConfiguration struct {
	Name *string `json:"name,omitempty"`
	URL  *string `json:"url,omitempty"`
}

// PowerVSServiceEndpointApplyConfiguration constructs an declarative configuration of the PowerVSServiceEndpoint type for use with
// apply.
func PowerVSServiceEndpoint() *PowerVSServiceEndpointApplyConfiguration {
	return &PowerVSServiceEndpointApplyConfiguration{}
}

// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *PowerVSServiceEndpointApplyConfiguration) WithName(value string) *PowerVSServiceEndpointApplyConfiguration {
	b.Name = &value
	return b
}

// WithURL sets the URL field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the URL field is set to the value of the last call.
func (b *PowerVSServiceEndpointApplyConfiguration) WithURL(value string) *PowerVSServiceEndpointApplyConfiguration {
	b.URL = &value
	return b
}


text:
Adriana</h>

Software Engineer
        Blockchain Enthusiast

        Welcome to my digital portfolio. This is where I showcase all the cool projects that I have enjoyed working on lately. Please
        feel free to contact me.

        Project
        Blog


text:
//
//  SCNumberKeyBoard.h
//
//  Created by ShiCang on 15/5/19.
//  Copyright (c) 2015年 ShiCang. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface SCNumberKeyBoard : UIView

@property (weak, nonatomic) IBOutlet UIButton *enterButton;

/**
 *  Class Method : show number keyboard for all text field on view controller.
 *  类方法:为某一个视图控制器的所有text field控件添加数字键盘。
 */
+ (void)showOnViewController:(UIViewController *)viewController
                       block:(void(^)(UITextField *textField, NSString *number))block;

/**
 *  Class Method : show number keyboard for a text field.
 *  类方法:为某一个text field控件添加数字键盘。
 */
+ (instancetype)showWithTextField:(UITextField *)textField
                            block:(void(^)(UITextField *textField, NSString *number))block;

/**
 *  Intance Method : show number keyboard for a text field.
 *  实例方法:为某一个text field控件添加数字键盘。
 */
- (instancetype)initWithTextField:(UITextField *)textField
                            block:(void(^)(UITextField *textField, NSString *number))block;

/**
 *  Close Keyboard
 */
- (void)dismiss;

@end


text:
.v-middle, .ui-carousel .carousel-btn {
  display: block;
  position: absolute;
  top: 50%;
  -webkit-transform: translate(0, -50%);
  -ms-transform: translate(0, -50%);
  -o-transform: translate(0, -50%);
  transform: translate(0, -50%); }

@font-face {
  font-family: "ui-carousel";
  src: url("fonts/ui-carousel.eot");
  src: url("fonts/ui-carousel.eot?#iefix") format("embedded-opentype"), url("fonts/ui-carousel.woff") format("woff"), url("fonts/ui-carousel.ttf") format("truetype"), url("fonts/ui-carousel.svg#ui-carousel") format("svg");
  font-weight: normal;
  font-style: normal; }

[data-icon]:before {
  font-family: "ui-carousel" !important;
  content: attr(data-icon);
  font-style: normal !important;
  font-weight: normal !important;
  font-variant: normal !important;
  text-transform: none !important;
  speak: none;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale; }

[class^="ui-icon-"]:before,
[class*=" ui-icon-"]:before {
  font-family: "ui-carousel" !important;
  font-style: normal !important;
  font-weight: normal !important;
  font-variant: normal !important;
  text-transform: none !important;
  speak: none;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale; }

.ui-icon-prev:before {
  content: "\61"; }

.ui-icon-next:before {
  content: "\62"; }

.ui-icon-dot:before {
  content: "\63"; }

.notifier-close {
  color: #fff;
  opacity: 0.5; }
  .notifier-close:hover {
    opacity: 0.8; }

.ui-carousel {
  display: block;
  margin-bottom: 30px; }
  .ui-carousel .carousel-wrapper {
    position: relative; }
  .ui-carousel .track-wrapper {
    position: relative;
    display: block;
    overflow: hidden;
    margin: 0;
    padding: 0; }
  .ui-carousel .track {
    position: relative;
    top: 0;
    left: 0;
    display: block; }
  .ui-carousel .slide {
    float: left;
    height: 100%;
    min-height: 1px; }
  .ui-carousel .carousel-btn {
    position: absolute;
    z-index: 10;
    background-color: transparent;
    outline: none;
    border: none;
    font-size: 20px;
    opacity: .75; }
    .ui-carousel .carousel-btn:hover {
      opacity: 1; }
  .ui-carousel .carousel-prev .carousel-btn {
    left: -25px; }
  .ui-carousel .carousel-next .carousel-btn {
    right: -25px; }
  .ui-carousel .carousel-disable {
    opacity: 0.5; }
    .ui-carousel .carousel-disable .carousel-btn:hover {
      opacity: .75; }

.carousel-dots {
  position: absolute;
  bottom: -30px;
  display: block;
  width: 100%;
  padding: 0;
  margin: 0;
  list-style: none;
  text-align: center; }
  .carousel-dots li {
    position: relative;
    display: inline-block;
    width: 15px;
    height: 15px;
    margin: 0 5px;
    padding: 0;
    cursor: pointer; }
    .carousel-dots li button {
      font-size: 0;
      line-height: 0;
      display: block;
      width: 15px;
      height: 15px;
      padding: 5px;
      cursor: pointer;
      color: transparent;
      border: 0;
      outline: none;
      background: transparent; }
      .carousel-dots li button:before {
        font-family: ui-carousel;
        font-size: 9px;
        line-height: 15px;
        position: absolute;
        top: 0px;
        left: 0px;
        width: 15px;
        height: 15px;
        content: "\63";
        text-align: center;
        opacity: 0.25;
        color: black;
        -webkit-font-smoothing: antialiased; }
    .carousel-dots li.carousel-active button:before {
      opacity: .75; }


text:
How to contribute
===================================

First of all, thank you for contributing!

The mailing list
----------------

For general questions or if you are having trouble getting started, try the
`Google Genomics Discuss mailing list <https://groups.google.com/forum/#!forum/google-genomics-discuss>`_.
It's a good way to sync up with other people who use googlegenomics including the core developers. You can subscribe
by sending an email to ``google-genomics-discuss+subscribe@googlegroups.com`` or just post using
the `web forum page <https://groups.google.com/forum/#!forum/google-genomics-discuss>`_.

Local development
-----------------

With Maven you can locally install a SNAPSHOT version of the code, to use from other projects
directly without having to wait for the Maven repository. Use:

`mvn install`

to run the full tests and do a local install. You can also use

`mvn install -DskipITs`

to run only the unit tests and do a local install. This is faster.

Submitting issues
-----------------

If you are encountering a bug in the code or have a feature request in mind - file away!

Submitting a pull request
-------------------------

If you are ready to contribute code, Github provides a nice `overview on how to create a pull request
<https://help.github.com/articles/creating-a-pull-request>`_.

Some general rules to follow:

* Do your work in `a fork <https://help.github.com/articles/fork-a-repo>`_ of this repo.
* Create a branch for each update that you're working on.
  These branches are often called "feature" or "topic" branches. Any changes
  that you push to your feature branch will automatically be shown in the pull request.
* Keep your pull requests as small as possible. Large pull requests are hard to review.
  Try to break up your changes into self-contained and incremental pull requests.
* The first line of commit messages should be a short (<80 character) summary,
  followed by an empty line and then any details that you want to share about the commit.
* Please try to follow the existing syntax style

When you submit or change your pull request, the Travis build system will automatically run tests.
If your pull request fails to pass tests, review the test log, make changes and
then push them to your feature branch to be tested again.

Contributor License Agreements
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All pull requests are welcome. Before we can submit them though, there is a legal hurdle we have to jump.
You'll need to fill out either the individual or corporate Contributor License Agreement
(CLA).

* If you are an individual writing original source code and you're sure you
  own the intellectual property, then you'll need to sign an `individual CLA
  <https://developers.google.com/open-source/cla/individual>`_.
* If you work for a company that wants to allow you to contribute your work,
  then you'll need to sign a `corporate CLA
  <https://developers.google.com/open-source/cla/corporate>`_.

Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.


text:
"""A base class session manager.

Authors:

* Zach Sailer
"""

#-----------------------------------------------------------------------------
#  Copyright (C) 2013  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

import uuid
import sqlite3

from tornado import web

from IPython.config.configurable import LoggingConfigurable
from IPython.utils.py3compat import unicode_type

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------

class SessionManager(LoggingConfigurable):

    # Session database initialized below
    _cursor = None
    _connection = None
    _columns = {'session_id', 'name', 'path', 'kernel_id'}

    @property
    def cursor(self):
        """Start a cursor and create a database called 'session'"""
        if self._cursor is None:
            self._cursor = self.connection.cursor()
            self._cursor.execute("""CREATE TABLE session
                (session_id, name, path, kernel_id)""")
        return self._cursor

    @property
    def connection(self):
        """Start a database connection"""
        if self._connection is None:
            self._connection = sqlite3.connect(':memory:')
            self._connection.row_factory = self.row_factory
        return self._connection

    def __del__(self):
        """Close connection once SessionManager closes"""
        self.cursor.close()

    def session_exists(self, name, path):
        """Check to see if the session for a given notebook exists"""
        self.cursor.execute("SELECT * FROM session WHERE name=? AND path=?", (name, path))
        reply = self.cursor.fetchone()
        if reply is None:
            return False
        else:
            return True

    def new_session_id(self):
        "Create a uuid for a new session"
        return unicode_type(uuid.uuid4())

    def create_session(self, name=None, path=None, kernel_id=None):
        """Creates a session and returns its model"""
        session_id = self.new_session_id()
        return self.save_session(session_id, name=name, path=path, kernel_id=kernel_id)

    def save_session(self, session_id, name=None, path=None, kernel_id=None):
        """Saves the items for the session with the given session_id

        Given a session_id (and any other of the arguments), this method
        creates a row in the sqlite session database that holds the information
        for a session.

        Parameters
        ----------
        session_id : str
            uuid for the session; this method must be given a session_id
        name : str
            the .ipynb notebook name that started the session
        path : str
            the path to the named notebook
        kernel_id : str
            a uuid for the kernel associated with this session

        Returns
        -------
        model : dict
            a dictionary of the session model
        """
        self.cursor.execute("INSERT INTO session VALUES (?,?,?,?)",
            (session_id, name, path, kernel_id)
        )
        return self.get_session(session_id=session_id)

    def get_session(self, **kwargs):
        """Returns the model for a particular session.

        Takes a keyword argument and searches for the value in the session
        database, then returns the rest of the session's info.

        Parameters
        ----------
        **kwargs : keyword argument
            must be given one of the keywords and values from the session database
            (i.e. session_id, name, path, kernel_id)

        Returns
        -------
        model : dict
            returns a dictionary that includes all the information from the
            session described by the kwarg.
        """
        if not kwargs:
            raise TypeError("must specify a column to query")

        conditions = []
        for column in kwargs.keys():
            if column not in self._columns:
                raise TypeError("No such column: %r", column)
            conditions.append("%s=?" % column)

        query = "SELECT * FROM session WHERE %s" % (' AND '.join(conditions))

        self.cursor.execute(query, list(kwargs.values()))
        model = self.cursor.fetchone()
        if model is None:
            q = []
            for key, value in kwargs.items():
                q.append("%s=%r" % (key, value))

            raise web.HTTPError(404, u'Session not found: %s' % (', '.join(q)))
        return model

    def update_session(self, session_id, **kwargs):
        """Updates the values in the session database.

        Changes the values of the session with the given session_id
        with the values from the keyword arguments.

        Parameters
        ----------
        session_id : str
            a uuid that identifies a session in the sqlite3 database
        **kwargs : str
            the key must correspond to a column title in session database,
            and the value replaces the current value in the session
            with session_id.
        """
        self.get_session(session_id=session_id)

        if not kwargs:
            # no changes
            return

        sets = []
        for column in kwargs.keys():
            if column not in self._columns:
                raise TypeError("No such column: %r" % column)
            sets.append("%s=?" % column)
        query = "UPDATE session SET %s WHERE session_id=?" % (', '.join(sets))
        self.cursor.execute(query, list(kwargs.values()) + [session_id])

    @staticmethod
    def row_factory(cursor, row):
        """Takes sqlite database session row and turns it into a dictionary"""
        row = sqlite3.Row(cursor, row)
        model = {
            'id': row['session_id'],
            'notebook': {
                'name': row['name'],
                'path': row['path']
            },
            'kernel': {
                'id': row['kernel_id'],
            }
        }
        return model

    def list_sessions(self):
        """Returns a list of dictionaries containing all the information from
        the session database"""
        c = self.cursor.execute("SELECT * FROM session")
        return list(c.fetchall())

    def delete_session(self, session_id):
        """Deletes the row in the session database with given session_id"""
        # Check that session exists before deleting
        self.get_session(session_id=session_id)
        self.cursor.execute("DELETE FROM session WHERE session_id=?", (session_id,))


text:
import { NgModule } from '@angular/core';
import { SearchButtonComponent } from './search-button.component';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [ SearchButtonComponent ],
  exports:    [ SearchButtonComponent ],
  imports: [ FormsModule ]
})
export class SearchButtonModule { }


text:
require "stone_deploy/version"

module StoneDeploy
  # Your code goes here...
end


text:
/*********************************************************************************
*     File Name           :     collection.js
*     Created By          :     Jone Casper
*     Creation Date       :     [2014-03-05 18:37]
*     Last Modified       :     [2014-04-08 10:31]
*     Description         :     Backchart collection for amcharts
**********************************************************************************/

(function(root, name, factory) {
	"use strict";
	if (typeof define === 'function' && define.amd) {
		define(['jquery','../backchart.base/collection'], function($, base) {
			return factory($, base);
		});
	}else if(typeof module !== 'undefined' && module.exports && typeof require === 'function'){
		var $ = require("jquery"),
		base = require("../backchart.base/collection");
		module.exports = factory($, base);
	}else{
		var namespaces = name.split("."),
		//scope = (root.jQuery || root.ender || root.$ || root || this),
		scope = root || this;
		for (var i=0; i<namespaces.length; i++) {
			var p = namespaces[i],
				ex = scope[p];
			scope = scope[p] = (i === namespaces.length - 1) ?
				factory(
					(root.jQuery || window.jQuery),
					root.backchart.base.collection
				):
				(ex || {});
		}
	}
}(this, "backchart.amcharts.collection", function($, basecollection) {
	/**
	 * Backbchart amcharts collection
	 *
	 * One collection will contained one or more amcharts models.When you bind one collection to an view, the renderOptions corresponding to the graphs + valueAxes(GaugeAxis) options.The categoryAxis will be set in view because one chart only have one categoryAxis!
	 * About renderOptions configuration detail, please see [amcharts/view.onCollection]{@link amcharts/view:amcharts.onCollection}
	 * @module amcharts/collection
	 * @requires jquery
	 * @requires base/collection
	 * @this {Backbone.Collection}
	 */
	var backchartAmchartsCollection = basecollection.extend(
		/**
		* @lends module:amcharts/collection.prototype
		*/
		{
	});
	return backchartAmchartsCollection;
}));


text:
package org.arquillian.container.chameleon.deployment.api;

import org.jboss.arquillian.container.test.api.DeploymentConfiguration;
import org.jboss.arquillian.container.test.spi.client.deployment.AutomaticDeployment;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.shrinkwrap.api.Archive;

public abstract class AbstractAutomaticDeployment implements AutomaticDeployment {

    @Override
    public DeploymentConfiguration generateDeploymentScenario(TestClass testClass) {
        final Archive<?> archive = build(testClass);

        if (archive != null) {

            DeploymentConfiguration.DeploymentContentBuilder deploymentContentBuilder =
                DeploymentConfigurationPopulator.populate(testClass, archive);

            return deploymentContentBuilder.get();
        }

        // It is safe to return null, we cannot return Optional since core runs on Java5
        return null;
    }

    protected abstract Archive<?> build(TestClass testClass);

}


text:
| [Contents](../README.md#table-of-contents) | [Overview](../README.md#scxml-overview) | [Examples](../Examples/README.md) | [Editor](https://alexzhornyak.github.io/ScxmlEditor-Tutorial/) | [Forum](https://github.com/alexzhornyak/SCXML-tutorial/discussions) |
|---|---|---|---|---|

# [\<foreach\>](https://www.w3.org/TR/scxml/#foreach)

**[Video version](https://youtu.be/pWLSQczu-mo)**

Allows an SCXML application to iterate through a collection in the data model and to execute the actions contained within it for each item in the collection.

## Attribute Details

Name	Required	Type	Default Value	Valid Values	Description

array	true	Value expression	none	A value expression that evaluates to an iterable collection	The <foreach> element will iterate over a shallow copy of this collection

item	true	xsd:string	none	Any variable name that is valid in the specified data model	A variable that stores a different item of the collection in each iteration of the loop

index	false	xsd:string	none	Any variable name that is valid in the specified data model	A variable that stores the current iteration index upon each iteration of the foreach loop

## Example (EcmaScript datamodel)
![Foreach_Example](../Images/Foreach_Example.gif)
Source code

```xml
<scxml datamodel="ecmascript" name="ScxmlForeach" version="1.0" xmlns="http://www.w3.org/2005/07/scxml">
	<datamodel>
		<data expr="[ 0, 0, 0 ]" id="t_INPUTS"/>
	</datamodel>
	<parallel id="p">
		<state id="state_3">
			<state id="state_3_off">
				<transition cond="_event.data==1" event="event.2" target="state_3_on"/>
			</state>
			<state id="state_3_on">
				<transition cond="! (_event.data==1)" event="event.2" target="state_3_off"/>
			</state>
		</state>
		<state id="state_2">
			<state id="state_2_off">
				<transition cond="_event.data==1" event="event.1" target="state_2_on"/>
			</state>
			<state id="state_2_on">
				<transition cond="! (_event.data==1)" event="event.1" target="state_2_off"/>
			</state>
		</state>
		<state id="state_1">
			<state id="state_1_off">
				<transition cond="_event.data==1" event="event.0" target="state_1_on"/>
			</state>
			<state id="state_1_on">
				<transition cond="! (_event.data==1)" event="event.0" target="state_1_off"/>
			</state>
		</state>
		<state id="inputs">
			<state id="configuration">
				<onentry>
					<foreach array="t_INPUTS" index="varIndex" item="varItem">
						<send eventexpr="'event.' + varIndex">
							<content expr="varItem"/>
						</send>
					</foreach>
				</onentry>
				<transition event="change.inputs" target="configuration">
					<assign expr="_event.data.x" location="t_INPUTS[0]"/>
					<assign expr="_event.data.y" location="t_INPUTS[1]"/>
					<assign expr="_event.data.z" location="t_INPUTS[2]"/>
				</transition>
			</state>
		</state>
	</parallel>
</scxml>
```

## Example (Lua datamodel)
![foreach](https://user-images.githubusercontent.com/18611095/28258527-57452600-6ada-11e7-9102-8260dbaecb19.png)

```xml
<scxml datamodel="lua" initial="Shape1" name="Scxml" version="1.0" xmlns="http://www.w3.org/2005/07/scxml">
	<datamodel>
		<data id="VarCollection">{ [1]='a', [2]='b', [3]='c' }</data>
	</datamodel>
	<state id="Shape1">
		<onentry>
			<foreach array="VarCollection" index="indexCollection" item="itemCollection">
				<log expr="indexCollection" label="indexCollection"/>
				<log expr="itemCollection" label="itemCollection"/>
			</foreach>
		</onentry>
		<transition target="End"/>
	</state>
	<final id="End"/>
</scxml>
```

**Output:**
> \[Log\] itemCollection: "a"

> \[Log\] indexCollection: 1

> \[Log\] itemCollection: "b"

> \[Log\] indexCollection: 2

> \[Log\] itemCollection: "c"

> \[Log\] indexCollection: 3

## [W3C IRP tests](https://www.w3.org/Voice/2013/scxml-irp)

### [1. Test 150](https://www.w3.org/Voice/2013/scxml-irp/150/test150.txml)
In the foreach element, the SCXML processor MUST declare a new variable if the one specified by 'item' is not already defined.

![test150](https://user-images.githubusercontent.com/18611095/28815054-abc8411a-76a8-11e7-923a-80a038569707.png)

```xml
<scxml datamodel="lua" initial="s0" name="Scxml_Test150" version="1.0" xmlns="http://www.w3.org/2005/07/scxml">
	<datamodel>
		<data id="Var1"/>
		<data id="Var2"/>
		<data id="Var3">
    {1,2,3}
		</data>
	</datamodel>
	<state id="s0">
		<onentry>
			<foreach array="Var3" index="Var2" item="Var1"/>
			<raise event="foo"/>
		</onentry>
		<transition event="error" target="fail"/>
		<transition event="*" target="s1"/>
	</state>
	<state id="s1">
		<onentry>
			<foreach array="Var3" index="Var5" item="Var4"/>
			<raise event="bar"/>
		</onentry>
		<transition event="error" target="fail"/>
		<transition event="*" target="s2"/>
	</state>
	<state id="s2">
		<transition cond="Var4 ~= nil" target="pass"/>
		<transition target="fail"/>
	</state>
	<final id="pass">
		<onentry>
			<log expr="'pass'" label="Outcome"/>
		</onentry>
	</final>
	<final id="fail">
		<onentry>
			<log expr="'fail'" label="Outcome"/>
		</onentry>
	</final>
</scxml>
```

### [2. Test 151](https://www.w3.org/Voice/2013/scxml-irp/151/test151.txml)
In the foreach element, if 'index' is present, the SCXML processor MUST declare a new variable if the one specified by 'index' is not already defined.

![test151](https://user-images.githubusercontent.com/18611095/28815279-7de42524-76a9-11e7-8911-45f37e40c263.png)

```xml
<scxml datamodel="lua" initial="s0" name="Scxml_Test151" version="1.0" xmlns="http://www.w3.org/2005/07/scxml">
	<datamodel>
		<data id="Var1"/>
		<data id="Var2"/>
		<data id="Var3">
    {1,2,3}
		</data>
	</datamodel>
	<state id="s0">
		<onentry>
			<foreach array="Var3" index="Var2" item="Var1"/>
			<raise event="foo"/>
		</onentry>
		<transition event="error" target="fail"/>
		<transition event="*" target="s1"/>
	</state>
	<state id="s1">
		<onentry>
			<foreach array="Var3" index="Var5" item="Var4"/>
			<raise event="bar"/>
		</onentry>
		<transition event="error" target="fail"/>
		<transition event="*" target="s2"/>
	</state>
	<state id="s2">
		<transition cond="Var5 ~= nil" target="pass"/>
		<transition target="fail"/>
	</state>
	<final id="pass">
		<onentry>
			<log expr="'pass'" label="Outcome"/>
		</onentry>
	</final>
	<final id="fail">
		<onentry>
			<log expr="'fail'" label="Outcome"/>
		</onentry>
	</final>
</scxml>
```

### [3. Test 152](https://www.w3.org/Voice/2013/scxml-irp/152/test152.txml)
In the foreach element, if 'array' does not evaluate to a legal iterable collection, or if 'item' does not specify a legal variable name, the SCXML processor MUST terminate execution of the foreach element and the block that contains it, and place the error **error.execution** on the internal event queue.

![test152](https://user-images.githubusercontent.com/18611095/28815789-346a425a-76ab-11e7-9762-d53bc189ed90.png)

```xml
<scxml datamodel="lua" initial="s0" name="Scxml_Test152" version="1.0" xmlns="http://www.w3.org/2005/07/scxml" xmlns:conf="http://www.w3.org/2005/scxml-conformance">
	<datamodel>
		<data expr="0" id="Var1"/>
		<data id="Var2"/>
		<data id="Var3"/>
		<data expr="7" id="Var4"/>
		<data id="Var5">
    {1,2,3}
		</data>
	</datamodel>
	<state id="s0">
		<onentry>
			<foreach array="Var4" index="Var3" item="Var2">
				<assign expr="Var1 + 1" location="Var1"/>
			</foreach>
			<raise event="foo"/>
		</onentry>
		<transition event="error.execution" target="s1"/>
		<transition event="*" target="fail"/>
	</state>
	<state id="s1">
		<onentry>
			<foreach array="Var5" index="Var3" item="'continue'">
				<assign expr="Var1 + 1" location="Var1"/>
			</foreach>
			<raise event="bar"/>
		</onentry>
		<transition event="error.execution" target="s2"/>
		<transition event="bar" target="fail"/>
	</state>
	<state id="s2">
		<transition cond="Var1==0" target="pass"/>
		<transition target="fail"/>
	</state>
	<final id="pass">
		<onentry>
			<log expr="'pass'" label="Outcome"/>
		</onentry>
	</final>
	<final id="fail">
		<onentry>
			<log expr="'fail'" label="Outcome"/>
		</onentry>
	</final>
</scxml>
```

### [4. Test 153](https://www.w3.org/Voice/2013/scxml-irp/153/test153.txml)
When evaluating foreach, the SCXML processor MUST start with the first item in the collection and proceed to the last item in the iteration order that is defined for the collection. For each item in the collection in turn, the processor MUST assign it to the item variable.

![test153](https://user-images.githubusercontent.com/18611095/28816034-03eddf0a-76ac-11e7-8e85-a7ee385acffc.png)

### [5. Test 155](https://www.w3.org/Voice/2013/scxml-irp/155/test155.txml)
When evaluating foreach, for each item, after making the assignment, the SCXML processor MUST evaluate its child executable content. It MUST then proceed to the next item in iteration order.

![test155](https://user-images.githubusercontent.com/18611095/28816237-cabcfc06-76ac-11e7-8e09-21846995c194.png)

### [6. Test 156](https://www.w3.org/Voice/2013/scxml-irp/156/test156.txml)
If the evaluation of any child element of foreach causes an error, the processor MUST cease execution of the foreach element and the block that contains it.

![test156](https://user-images.githubusercontent.com/18611095/28816367-4c7ca0c0-76ad-11e7-8503-8a8aa846bfd4.png)

### [7. Test 525](https://www.w3.org/Voice/2013/scxml-irp/525/test525.txml)
The SCXML processor MUST act as if it has made a shallow copy of the collection produced by the evaluation of 'array'. Specifically, modifications to the collection during the execution of foreach MUST NOT affect the iteration behavior.

![test525](https://user-images.githubusercontent.com/18611095/28816516-cc8af83e-76ad-11e7-9e63-0159c628ac39.png)

| [TOP](#top-anchor) | [Contents](../README.md#table-of-contents) | [Overview](../README.md#scxml-overview) | [Examples](../Examples/README.md) | [Editor](https://alexzhornyak.github.io/ScxmlEditor-Tutorial/) | [Forum](https://github.com/alexzhornyak/SCXML-tutorial/discussions) |
|---|---|---|---|---|---|


text:
package io.oasp.gastronomy.restaurant.general.service.impl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;

import io.oasp.gastronomy.restaurant.general.logic.impl.config.DefaultRolesPrefixPostProcessor;
import io.oasp.module.security.common.api.accesscontrol.AccessControlProvider;
import io.oasp.module.security.common.base.accesscontrol.AccessControlSchemaProvider;
import io.oasp.module.security.common.impl.accesscontrol.AccessControlProviderImpl;
import io.oasp.module.security.common.impl.accesscontrol.AccessControlSchemaProviderImpl;

/**
 * This configuration class provides factory methods for several Spring security related beans.
 *
 */
@Configuration
public class WebSecurityBeansConfig {

  /**
   * This method provides a new instance of {@code AccessControlProvider}
   *
   * @return the newly created {@code AccessControlProvider}
   */
  @Bean
  public AccessControlProvider accessControlProvider() {

    return new AccessControlProviderImpl();
  }

  /**
   * This method provides a new instance of {@code AccessControlSchemaProvider}
   *
   * @return the newly created {@code AccessControlSchemaProvider}
   */
  @Bean
  public AccessControlSchemaProvider accessControlSchemaProvider() {

    return new AccessControlSchemaProviderImpl();
  }

  /**
   * This method provides a new instance of {@code CsrfTokenRepository}
   *
   * @return the newly created {@code CsrfTokenRepository}
   */
  @Bean
  public CsrfTokenRepository csrfTokenRepository() {

    return new HttpSessionCsrfTokenRepository();
  }

  /**
   * This method provides a new instance of {@code DefaultRolesPrefixPostProcessor}
   *
   * @return the newly create {@code DefaultRolesPrefixPostProcessor}
   */
  @Bean
  public static DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {

    // By default Spring-Security is setting the prefix "ROLE_" for all permissions/authorities.
    // We disable this undesired behavior here...
    return new DefaultRolesPrefixPostProcessor("");
  }
}


text:
<?php

declare(strict_types=1);

namespace Marcgoertz\Shorten;

final class Shorten
{
    private const ENTITIES_PATTERN = '/&#?[a-zA-Z0-9]+;/i';
    private const TAGS_AND_ENTITIES_PATTERN = '/<\/?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;/i';
    private const SELF_CLOSING_TAGS = [
        'area',
        'base',
        'br',
        'col',
        'embed',
        'hr',
        'img',
        'input',
        'link',
        'meta',
        'param',
        'source',
        'track',
        'wbr',
        'command',
        'keygen',
        'menuitem',
    ];

    /**
     * Safely truncate text containing markup.
     *
     * @param string $markup         text containing markup
     * @param int    $length         maximum length of truncated text
     * @param string $appendix       text added after truncated text
     * @param bool   $appendixInside add appendix to last content in tags,
     *                               increases $length by 1
     * @param bool   $wordsafe       wordsafe truncation
     * @param string $delimiter      delimiter for wordsafe truncation
     *
     * @return string                truncated markup
     */
    public function truncateMarkup(
        string $markup,
        int $length = 400,
        string $appendix = '…',
        bool $appendixInside = false,
        bool $wordsafe = false,
        string $delimiter = ' '
    ): string {
        $truncated = '';
        $lengthOutput = 0;
        $position = 0;
        $tags = [];

        // check for existing entities
        $hasEntities = preg_match(self::ENTITIES_PATTERN, $markup);

        // just return the markup if text does not need be truncated
        if (mb_strlen(trim(strip_tags($markup))) <= $length) {
            return $markup;
        }

        // to avoid UTF-8 multibyte glitches we need entities,
        // but no special characters for tags or existing entities
        $markup = str_replace(
            ['<', '>', '&'],
            ['<', '>', '&'],
            htmlentities($markup, ENT_NOQUOTES, 'UTF-8')
        );

        // loop thru text
        while (
            $lengthOutput < $length &&
            preg_match(
                self::TAGS_AND_ENTITIES_PATTERN,
                $markup,
                $match,
                PREG_OFFSET_CAPTURE,
                $position
            )
        ) {
            list($tag, $positionTag) = $match[0];

            // add text leading up to the tag or entity
            $text = substr($markup, $position, $positionTag - $position);
            if ($lengthOutput + mb_strlen($text) > $length) {
                $truncated .= mb_substr($text, 0, $length - $lengthOutput);
                $lengthOutput = $length;
                break;
            }
            $truncated .= $text;
            $lengthOutput += mb_strlen($text);

            // add tags and entities
            if ($tag[0] === '&') {
                // handle the entity...
                $truncated .= $tag;
                // ... which is only one character
                $lengthOutput++;
            } else {
                // handle the tag
                $tagName = $match[1][0];
                if ($tag[1] === '/') {
                    // this is a closing tag
                    $openingTag = array_pop($tags);
                    // check that tags are properly nested
                    assert($openingTag === $tagName);
                    $truncated .= $tag;
                } elseif ($tag[mb_strlen($tag) - 2] === '/') {
                    // self-closing tag in XML dialect
                    $truncated .= $tag;
                } elseif (in_array($tagName, self::SELF_CLOSING_TAGS)) {
                    // self-closing tag in non-XML dialect
                    $truncated .= $tag;
                } else {
                    // opening tag
                    $truncated .= $tag;
                    $tags[] = $tagName;
                }
            }

            // continue after the tag
            $position = $positionTag + mb_strlen($tag);
        }

        // add any remaining text
        if ($lengthOutput < $length && $position < mb_strlen($markup)) {
            $truncated .= mb_substr($markup, $position, $length - $lengthOutput);
        }

        // if the words shouldn't be cut in the middle...
        if ($wordsafe) {
            // ... search the last occurance of the delimiter...
            $spacepos = mb_strrpos($truncated, $delimiter);
            if (isset($spacepos)) {
                // ... and cut the text in this position
                $truncated = mb_substr($truncated, 0, $spacepos);
            }
        }

        // add appendix to last tag content
        if ($appendixInside) {
            $truncated .= $appendix;
        }

        // close any open tags
        while (!empty($tags)) {
            $truncated .= sprintf('</%s>', array_pop($tags));
        }

        // decode entities again if markup did not contain any entities
        if ($hasEntities === 0) {
            $truncated = html_entity_decode($truncated, ENT_COMPAT, 'UTF-8');
        }

        if ($appendixInside) {
            return $truncated;
        } else {
            return $truncated . $appendix;
        }
    }
}


text:
<?php
namespace Crud\Traits;

use Crud\Event\Subject;

trait RedirectTrait
{

    /**
     * Change redirect configuration
     *
     * If both `$name` and `$config` is empty all redirection
     * rules will be returned.
     *
     * If `$name` is provided and `$config` is null, the named
     * redirection configuration is returned.
     *
     * If both `$name` and `$config` is provided, the configuration
     * is changed for the named rule.
     *
     * $config should contain the following keys:
     *  - type : name of the reader
     *  - key  : the key to read inside the reader
     *  - url  : the URL to redirect to
     *
     * @param null|string $name Name of the redirection rule
     * @param null|array $config Redirection configuration
     * @return mixed
     */
    public function redirectConfig($name = null, $config = null)
    {
        if ($name === null && $config === null) {
            return $this->config('redirect');
        }

        $path = sprintf('redirect.%s', $name);
        if ($config === null) {
            return $this->config($path);
        }

        return $this->config($path, $config);
    }

    /**
     * Returns the redirect_url for this request, with a fallback to the referring page
     *
     * @param string $default Default URL to use redirect_url is not found in request or data
     * @return mixed
     */
    protected function _refererRedirectUrl($default = null)
    {
        $controller = $this->_controller();
        return $this->_redirectUrl($controller->referer($default, true));
    }

    /**
     * Returns the redirect_url for this request.
     *
     * @param string $default Default URL to use redirect_url is not found in request or data
     * @return mixed
     */
    protected function _redirectUrl($default = null)
    {
        $url = $default;
        $request = $this->_request();

        if (!empty($request->data['redirect_url'])) {
            $url = $request->data['redirect_url'];
        } elseif (!empty($request->query['redirect_url'])) {
            $url = $request->query['redirect_url'];
        }

        return $url;
    }

    /**
     * Called for all redirects inside CRUD
     *
     * @param \Crud\Event\Subject $subject Event subject
     * @param string|array $url URL
     * @param int $status Status code
     * @param bool $exit Whether to exit script or not
     * @return void
     */
    protected function _redirect(Subject $subject, $url = null, $status = null, $exit = true)
    {
        $url = $this->_redirectUrl($url);

        $subject->url = $url;
        $subject->status = $status;
        $subject->exit = $exit;
        $this->_trigger('beforeRedirect', $subject);

        $controller = $this->_controller();
        $controller->redirect($subject->url, $subject->status, $subject->exit);
        return $controller->response;
    }
}


text:
$(document).ready(function() {
  // step 1
  $("#comment-form").submit(function(event){
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: $(this).attr('action'),
      data: $(this).serialize(),
      dataType: "html"
    }).done(function(response){ //step 6
      $(".comment-display").append(response)
      $("#comment-body").val("");
    });
  });
});


text:
Easy Ruby on Rails application and environment configuration.

## What is Envious?
Envious is used to configure environment variables for Ruby on Rails 3 applications. It allows you to add configuration variables without the need to add configuration files to your repository.

Envious works by supplying your with an `environment_vars.yml` configuration file. When your Rails app is loaded, configurations options from this file are also loaded and added to the local Environment variable hash. The configuration options can then be accessed using the `ENV[KEY]` syntax.

## Installation

Add this line to your application's Gemfile:

    gem 'envious'

And then execute:

    $ bundle install

Or install it yourself as:

    $ gem install envious

After installation, run the following to create `config/environment_vars.yml`, and add it to your `.gitignore`.

    $ rails generate envious:setup

## Usage

Setting up configuration with Envious is easy. To begin, simply add some variables to your `config/environment_vars.yml` that you would like available in the `ENV` hash. Keep in mind that Envious uses `Rails.env` to allow configuration based on your current environment.
```yaml
development:
  USERNAME: "cat"

production:
  USERNAME: "dog"

API_KEY: "ABCXYZ"
```
In the above case, `ENV["API_KEY"]` will produce `"ABCXYZ"` because any values not under an environment will be available in all environments. In development `ENV["USERNAME"]`  will be `"cat", and it will be `"dog"` in production.

Since Envious configuration is loaded when your Rails app loads, the `ENV` hash is available anywhere in your application where you may need to call upon your configuration.

## Using with Heroku
Envious allows easy transfer of local environment variables to heroku using a simple rake task. To copy local settings to Heroku use:

    $ rake envious:heroku:push

The environment used is dependant on Heroku's `RAILS_ENV` configuration setting. If it is blank, Envious assumes it is using `production`. Changing this setting on Heroku is simple. To change Heroku's `RAILS_ENV` to development, use the following command:

    $ heroku config:add RAILS_ENV=development

## Using with Cloud66
Envious makes it easy to export environment variables to a file for used on Cloud66 using a rake task. To copy local settings to a file formatted for used in the Cloud66 stack environment variable window use:

    $ rake envious:cloud66:export > vars.txt

This will export your settings in `config/environment_vars.yml` to a file called `vars.txt` in your current directory. This is formatted and ready to be uploaded to Cloud66. By default, this will export your production environment variables.

To export environment variables for other environments, you can use an optional argument to the rake task:

    $ rake envious:cloud66:export[development] > vars.txt

The command above will export all your development environment variables in `config/environment_vars.yml` to a file called `vars.txt`. `development` can be replaced with any other environments to export those values.

## Questions or Problems?

If you have any questions or issues with Envious, please add an [issue on GitHub](https://github.com/RyanNielson/envious/issues), or send a pull request.


text:
{% load i18n %}

{% trans "Categories" %}

        {% for category in categories %}

                        {{ category.name }}

                 {{ category.children }}

        {% endfor %}


text:
#ifndef __LINUX_IPMI_SMI_H
#define __LINUX_IPMI_SMI_H

#include <linux/ipmi_msgdefs.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/ipmi_smi.h>

/* This files describes the interface for IPMI system management interface
   drivers to bind into the IPMI message handler. */

/* Structure for the low-level drivers. */
typedef struct ipmi_smi *ipmi_smi_t;

/*
 * Messages to/from the lower layer.  The smi interface will take one
 * of these to send. After the send has occurred and a response has
 * been received, it will report this same data structure back up to
 * the upper layer.  If an error occurs, it should fill in the
 * response with an error code in the completion code location. When
 * asynchronous data is received, one of these is allocated, the
 * data_size is set to zero and the response holds the data from the
 * get message or get event command that the interface initiated.
 * Note that it is the interfaces responsibility to detect
 * asynchronous data and messages and request them from the
 * interface.
 */
struct ipmi_smi_msg
{
	struct list_head link;

	long    msgid;
	void    *user_data;

	int           data_size;
	unsigned char data[IPMI_MAX_MSG_LENGTH];

	int           rsp_size;
	unsigned char rsp[IPMI_MAX_MSG_LENGTH];

	/* Will be called when the system is done with the message
           (presumably to free it). */
	void (*done)(struct ipmi_smi_msg *msg);
};

struct ipmi_smi_handlers
{
	struct module *owner;

	/* The low-level interface cannot start sending messages to
	   the upper layer until this function is called.  This may
	   not be NULL, the lower layer must take the interface from
	   this call. */
	int (*start_processing)(void       *send_info,
				ipmi_smi_t new_intf);

	/* Called to enqueue an SMI message to be sent.  This
	   operation is not allowed to fail.  If an error occurs, it
	   should report back the error in a received message.  It may
	   do this in the current call context, since no write locks
	   are held when this is run.  If the priority is > 0, the
	   message will go into a high-priority queue and be sent
	   first.  Otherwise, it goes into a normal-priority queue. */
	void (*sender)(void                *send_info,
		       struct ipmi_smi_msg *msg,
		       int                 priority);

	/* Called by the upper layer to request that we try to get
	   events from the BMC we are attached to. */
	void (*request_events)(void *send_info);

	/* Called when the interface should go into "run to
	   completion" mode.  If this call sets the value to true, the
	   interface should make sure that all messages are flushed
	   out and that none are pending, and any new requests are run
	   to completion immediately. */
	void (*set_run_to_completion)(void *send_info, int run_to_completion);

	/* Called to poll for work to do.  This is so upper layers can
	   poll for operations during things like crash dumps. */
	void (*poll)(void *send_info);

	/* Tell the handler that we are using it/not using it.  The
	   message handler get the modules that this handler belongs
	   to; this function lets the SMI claim any modules that it
	   uses.  These may be NULL if this is not required. */
	int (*inc_usecount)(void *send_info);
	void (*dec_usecount)(void *send_info);
};

struct ipmi_device_id {
	unsigned char device_id;
	unsigned char device_revision;
	unsigned char firmware_revision_1;
	unsigned char firmware_revision_2;
	unsigned char ipmi_version;
	unsigned char additional_device_support;
	unsigned int  manufacturer_id;
	unsigned int  product_id;
	unsigned char aux_firmware_revision[4];
	unsigned int  aux_firmware_revision_set : 1;
};

#define ipmi_version_major(v) ((v)->ipmi_version & 0xf)
#define ipmi_version_minor(v) ((v)->ipmi_version >> 4)

/* Take a pointer to a raw data buffer and a length and extract device
   id information from it.  The first byte of data must point to the
   byte from the get device id response after the completion code.
   The caller is responsible for making sure the length is at least
   11 and the command completed without error. */
static inline void ipmi_demangle_device_id(unsigned char *data,
					   unsigned int  data_len,
					   struct ipmi_device_id *id)
{
	id->device_id = data[0];
	id->device_revision = data[1];
	id->firmware_revision_1 = data[2];
	id->firmware_revision_2 = data[3];
	id->ipmi_version = data[4];
	id->additional_device_support = data[5];
	id->manufacturer_id = data[6] | (data[7] << 8) | (data[8] << 16);
	id->product_id = data[9] | (data[10] << 8);
	if (data_len >= 15) {
		memcpy(id->aux_firmware_revision, data+11, 4);
		id->aux_firmware_revision_set = 1;
	} else
		id->aux_firmware_revision_set = 0;
}

/* Add a low-level interface to the IPMI driver.  Note that if the
   interface doesn't know its slave address, it should pass in zero.
   The low-level interface should not deliver any messages to the
   upper layer until the start_processing() function in the handlers
   is called, and the lower layer must get the interface from that
   call. */
int ipmi_register_smi(struct ipmi_smi_handlers *handlers,
		      void                     *send_info,
		      struct ipmi_device_id    *device_id,
		      struct device            *dev,
		      unsigned char            slave_addr);

/*
 * Remove a low-level interface from the IPMI driver.  This will
 * return an error if the interface is still in use by a user.
 */
int ipmi_unregister_smi(ipmi_smi_t intf);

/*
 * The lower layer reports received messages through this interface.
 * The data_size should be zero if this is an asyncronous message.  If
 * the lower layer gets an error sending a message, it should format
 * an error response in the message response.
 */
void ipmi_smi_msg_received(ipmi_smi_t          intf,
			   struct ipmi_smi_msg *msg);

/* The lower layer received a watchdog pre-timeout on interface. */
void ipmi_smi_watchdog_pretimeout(ipmi_smi_t intf);

struct ipmi_smi_msg *ipmi_alloc_smi_msg(void);
static inline void ipmi_free_smi_msg(struct ipmi_smi_msg *msg)
{
	msg->done(msg);
}

/* Allow the lower layer to add things to the proc filesystem
   directory for this interface.  Note that the entry will
   automatically be dstroyed when the interface is destroyed. */
int ipmi_smi_add_proc_entry(ipmi_smi_t smi, char *name,
			    read_proc_t *read_proc, write_proc_t *write_proc,
			    void *data, struct module *owner);

#endif /* __LINUX_IPMI_SMI_H */


text:
<?php
class Admin_recruitment extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->helper('url');
		$this->load->library(array('form_validation', 'session'));
		$this->load->model('admin/Employer_model', 'employer');
		$this->load->model('admin/Jobseeker_model', 'jobseeker');
		$this->load->model('admin/Mail_model', 'mail');
		$this->load->model('UtilModel', 'util');
		$this->load->model('admin/Recruitment_model', 'recruitment');
		// if (!$this->session->userdata['user']['isLogged']) {
		// 	redirect(base_url() . 'admin/login'); // no session established, kick back to login page
		// } else if ($this->session->userdata['user']['role'] != 5 && $this->session->userdata['user']['role'] != 1) {
		// 	redirect(base_url('error/403'));
		// }
		if (!$this->session->userdata['user']['isLogged']) {
			redirect(base_url('404'));
			//redirect(base_url() . 'admin/login'); // no session established, kick back to login page
		} else if ($this->session->userdata['user']['role'] != 5 && $this->session->userdata['user']['role'] != 1) {
			//redirect(base_url('error/403'));
			redirect(base_url('404'));
		}
		//set value to call page
		//active:1
		//aprrove:2
		//disabled:3
	}

	function recruitmentActive() {
		$scripts = array(

			"assets/admin/angularjs/service/recruitment.service.js",
			"assets/admin/angularjs/service/jobseeker.service.js",
			"assets/admin/angularjs/service/employer.service.js",
			"assets/admin/angularjs/controller/recruitment.controller.js");

		$listCountries = $this->employer->getListCountry();
		$head = $this->load->view('admin/head', array(), TRUE);
		$header = $this->load->view('admin/header', array(), TRUE);
		$content = $this->load->view('admin/recruitment/recruitment', array("type" => 1), TRUE);
		$footer = $this->load->view('admin/footer', array(), TRUE);
		$sidemenu = $this->load->view('admin/sidemenu', array('email' => $this->session->userdata['user']['email'],
			'role' => $this->session->userdata['user']['role'],
			'selected' => 'recruitmentManager',
			'sub' => 'recruitmentActive'), TRUE);

		$this->load->view('admin/layout', array('head' => $head,
			'header' => $header,
			'sidemenu' => $sidemenu,
			'content' => $content,
			'footer' => $footer,
			'scripts' => $scripts,
		));
	}
	function recruitmentApprove() {
		$scripts = array(

			"assets/admin/angularjs/service/recruitment.service.js",
			"assets/admin/angularjs/service/jobseeker.service.js",
			"assets/admin/angularjs/service/employer.service.js",
			"assets/admin/angularjs/controller/recruitment.controller.js");

		$listCountries = $this->employer->getListCountry();
		$head = $this->load->view('admin/head', array(), TRUE);
		$header = $this->load->view('admin/header', array(), TRUE);
		$content = $this->load->view('admin/recruitment/recruitment', array("type" => 2), TRUE);
		$footer = $this->load->view('admin/footer', array(), TRUE);
		$sidemenu = $this->load->view('admin/sidemenu', array('email' => $this->session->userdata['user']['email'],
			'role' => $this->session->userdata['user']['role'],
			'selected' => 'recruitmentManager',
			'sub' => 'recruitmentApprove'), TRUE);

		$this->load->view('admin/layout', array('head' => $head,
			'header' => $header,
			'sidemenu' => $sidemenu,
			'content' => $content,
			'footer' => $footer,
			'scripts' => $scripts,
		));
	}
	function recruitmentDisabled() {
		$scripts = array(

			"assets/admin/angularjs/service/recruitment.service.js",
			"assets/admin/angularjs/service/jobseeker.service.js",
			"assets/admin/angularjs/service/employer.service.js",
			"assets/admin/angularjs/controller/recruitment.controller.js");

		$listCountries = $this->employer->getListCountry();
		$head = $this->load->view('admin/head', array(), TRUE);
		$header = $this->load->view('admin/header', array(), TRUE);
		$content = $this->load->view('admin/recruitment/recruitment', array("type" => 3), TRUE);
		$footer = $this->load->view('admin/footer', array(), TRUE);
		$sidemenu = $this->load->view('admin/sidemenu', array('email' => $this->session->userdata['user']['email'],
			'role' => $this->session->userdata['user']['role'],
			'selected' => 'recruitmentManager',
			'sub' => 'recruitmentDisabled'), TRUE);

		$this->load->view('admin/layout', array('head' => $head,
			'header' => $header,
			'sidemenu' => $sidemenu,
			'content' => $content,
			'footer' => $footer,
			'scripts' => $scripts,
		));
	}
	function recruitmentCreate() {
		$scripts = array(
			"assets/admin/angularjs/service/recruitment.service.js",
			"assets/admin/angularjs/service/jobseeker.service.js",
			"assets/admin/angularjs/service/employer.service.js",
			"assets/admin/angularjs/controller/recruitment.controller.js",
		);

		$listCountries = $this->employer->getListCountry();
		$head = $this->load->view('admin/head', array(), TRUE);
		$header = $this->load->view('admin/header', array(), TRUE);
		$content = $this->load->view('admin/recruitment/recruitment-create', array("countryGET" => $listCountries[0]), TRUE);
		$footer = $this->load->view('admin/footer', array(), TRUE);
		$sidemenu = $this->load->view('admin/sidemenu', array('email' => $this->session->userdata['user']['email'],
			'role' => $this->session->userdata['user']['role'],
			'selected' => 'recruitmentManager',
			'sub' => 'recruitmentCreate'), TRUE);

		$this->load->view('admin/layout', array('head' => $head,
			'header' => $header,
			'sidemenu' => $sidemenu,
			'content' => $content,
			'footer' => $footer,
			'scripts' => $scripts,
		));
	}
	function getListEmployer() {
		$output = $this->recruitment->getListEmployer();
		echo json_encode($output);
	}
	function createRecruitment() {
		$rec = json_decode($this->input->post('rec'), true);
		$welfareSelected = $rec['welfareSelected'];
		$employer = $rec['object_employer'];
		$idmapcountry = $rec['rec_job_map_country'];
		$provinceSelected = $rec['provinceSelected'];
		$object_contact_form = $rec['object_contact_form'];
		$object_form = $rec['object_form'];
		$object_form_child = $rec['object_form_child'];
		$object_level = $rec['object_level'];
		$object_salary = $rec['object_salary'];
		$iduser = $this->session->userdata['user']['id'];
		$idemployer = $rec['idemployer'];
		log_message('error', $iduser);
		$data = array(
			'rec_title' => $rec['rec_title'],
			'rec_salary' => "",
			'rec_map_salary' => $object_salary['salary_id'],
			'rec_job_content' => $rec['rec_job_content'],
			'rec_job_time' => $rec['rec_job_time'],
			'rec_job_regimen' => $rec['rec_job_regimen'],
			'rec_job_require' => $rec['rec_job_require'],
			'rec_job_priority' => $rec['rec_job_priority'],
			'rec_job_map_form' => $object_form['fjob_id'], //$rec['rec_job_map_form'],
			'rec_job_map_form_child' => $object_form_child['jcform_id'], //$rec['rec_job_map_form_child'],
			'rec_job_map_level' => $object_level['ljob_id'], //$rec['rec_job_map_level'],
			'rec_job_map_country' => $rec['rec_job_map_country'],
			'rec_job_map_country' => $rec['object_career']['career_id'],
			'rec_contact_name' => $rec['rec_contact_name'],
			'rec_contact_email' => $rec['rec_contact_email'],
			'rec_contact_address' => $rec['rec_contact_address'],
			'rec_contact_phone' => $rec['rec_contact_phone'],
			'rec_contact_mobile' => $rec['rec_contact_mobile'],
			'rec_contact_form' => $object_contact_form['contact_form_id'], //$rec['rec_contact_form'],
			'rec_map_employer' => $employer['employer_id'],
			'rec_is_approve' => true,
			'rec_is_disabled' => false,
			'rec_is_delete' => false,
			'rec_update_at' => date('Y-m-d H:m'),
			'rec_created_at' => date('Y-m-d H:m'));
		$result = $this->recruitment->createRecruitment($data, $welfareSelected, $provinceSelected, $iduser);
		//$result = $this->employer->updateEmployerRecruitmentWelfare($rec['welfareSelected'], $rec['rec_id']);
		log_message('error', $result);
		echo json_encode($result);
	}
	function getListRecruitment($type) {
		$output = $this->recruitment->getListRecruitment($type);
		echo json_encode($output);
	}
	function getRecruitmentApply($idrecruitment) {
		$output = $this->recruitment->getRecruitmentApply($idrecruitment);
		echo json_encode($output);
	}
	function getListSalary() {
		$output = $this->recruitment->getListSalary();
		echo json_encode($output);
	}
	function recruitmentHighLight() {
		$scripts = array(
			"assets/admin/angularjs/service/recruitment.service.js",
			"assets/admin/angularjs/service/jobseeker.service.js",
			"assets/admin/angularjs/service/employer.service.js",
			"assets/admin/angularjs/controller/recruitment.controller.js",
		);

		$listCountries = $this->employer->getListCountry();
		$head = $this->load->view('admin/head', array(), TRUE);
		$header = $this->load->view('admin/header', array(), TRUE);
		$content = $this->load->view('admin/recruitment/recruitment-highlight', array("countryGET" => $listCountries[0]), TRUE);
		$footer = $this->load->view('admin/footer', array(), TRUE);
		$sidemenu = $this->load->view('admin/sidemenu', array('email' => $this->session->userdata['user']['email'],
			'role' => $this->session->userdata['user']['role'],
			'selected' => 'recruitmentManager',
			'sub' => 'recruitmentHighLight'), TRUE);

		$this->load->view('admin/layout', array('head' => $head,
			'header' => $header,
			'sidemenu' => $sidemenu,
			'content' => $content,
			'footer' => $footer,
			'scripts' => $scripts,
		));
	}
	function editShowRecruitment() {
		$rec = json_decode($this->input->post('rec'), true);
		$rec_id = $rec['rec_id'];
		$rec_is_show_top = $rec['rec_is_show_top'];
		$rec_is_show_another = $rec['rec_is_show_another'];
		$data = array(
			'from' => 'recruitment',
			'where' => 'rec_id = ' . $rec_id,
			'data' => array('rec_is_show_top' => $rec_is_show_top, 'rec_is_show_another' => $rec_is_show_another, 'rec_update_at' => date('Y-m-d')));
		$output = $this->recruitment->editShowRecruitment($data);
		echo json_encode($output);
	}

	function disabledRecruitment() {
		$rec = json_decode($this->input->post('rec'), true);
		$rec_id = $rec['rec_id'];
		//$rec_is_show_top = $rec['rec_is_show_top'];
		//$rec_is_show_another = $rec['rec_is_show_another'];
		$data = array(
			'from' => 'recruitment',
			'where' => 'rec_id = ' . $rec_id,
			'data' => array('rec_is_disabled' => $rec['option'], 'rec_update_at' => date('Y-m-d')));
		$output = $this->recruitment->disabledRecruitment($data);
		echo json_encode($output);
	}
	function getRecruitmentShow($type) {
		$output = $this->recruitment->getRecruitmentShow($type);
		echo json_encode($output);
	}
	function getMaxViewRecruitment() {
		$output = $this->recruitment->getNumRecruitmentView();
		echo json_encode($output);
	}
	function removeAllRecruitmentShow() {
		$recruitmentShow = json_decode($this->input->post('recruitmentShow'), true);
		$output = $this->recruitment->removeAllRecruitmentShow($recruitmentShow);
		echo json_encode($output);
	}
	function addRecruitmentShow($recid, $typeShow) {
		$output = $this->recruitment->addRecruitmentShow($recid, $typeShow);
		echo json_encode($output);
	}
	function removeRecruitmentShow() {
		$rec = json_decode($this->input->post('rec'), true);
		$output = $this->recruitment->removeRecruitmentShow($rec);
		echo json_encode($output);
	}
}


text:
/**
 * Created by bokense1 on 23/06/16.
 */
public class Deque {

    public IntNode head = null;

    public boolean empty() {
        return head == null;
    }

    public void addFirst(int value) {
        if (empty()) {
            head = new IntNode(value, null, null);
        } else {
            IntNode newNode = new IntNode(value, null, head);
            head.previous = newNode;
            head = newNode;
        }
    }

    public void addLast(int value) {
        if (empty()) {
            head = new IntNode(value, null, null);
        } else {
            head.addTailChild(value);
        }
    }

    @Override
    public String toString() {
        if (empty()) {
            return "[]";
        } else {
            return "[" + head.toString() + "]";
        }
    }

    public int size() {
        if (empty()) {
            return 0;
        } else {
            int counter = 0;
            IntNode scanner = head;
            while (scanner.next != null) {
                scanner = scanner.next;
                counter++;
            }
            return counter + 1;
        }
    }

    public void removeFirst() {

        if (empty()) {
            throw new NullPointerException();
        } else if (!empty()) {
            if (size() > 1) {
                head = head.next;
                head.previous = null;

            } else if (size() == 1) {
                head = null;
            }
        }
    }

    public int peekFirst() {
        if (empty()) {
            throw new NullPointerException();
        }
        return head.value;
    }

    public int peekLast() {
        if (empty()) {
            throw new NullPointerException();
        }
        IntNode scanner = head;
        while (scanner.hasNext()) {
            scanner = scanner.next;
        }
        return scanner.value;
    }

    public void removeLast() {
        if (empty()) {
            throw new NullPointerException();
        } else if (!empty()) {
            IntNode scanner = head;

            while (scanner.next.next != null) {
                scanner = scanner.next;
            }

            scanner.next = null;
        }
    }

    public boolean containsRec(int valueToSearch) {
        if (empty()) {
            return false;
        }
        return head.childrenContainRec(valueToSearch);
    }

    public boolean containsIter(int valueToSearch) {
        if (empty()) {
            return false;
        }
        IntNode scanner = head;
        while (scanner.hasNext()) {
            if (valueToSearch == scanner.value) {
                return true;
            }
            scanner = scanner.next;
        }
        return valueToSearch == scanner.value;
    }

    public int getIndex(int indexToReturn) {

        if (indexToReturn < 0 || indexToReturn >= size()) {
            throw new IndexOutOfBoundsException();
        }

        int iteration = 0;
        IntNode scanner = head;

        while (scanner.hasNext()) {

            if (indexToReturn == iteration) {
                return scanner.value;
            }

            scanner = scanner.next;
            iteration++;

        }

        return scanner.value;
    }

    public void removeFirstInstanceOf(int removalObject) {

        if (!containsIter(removalObject)){
            System.out.println("no instances of " + removalObject + " found");
        }
        else {

            int indexOfRemoval = 0;

            IntNode scanner = head;

            while (scanner.hasNext()) {

                if (scanner.value == removalObject) {
                    break;
                }

                indexOfRemoval++;
                scanner = scanner.next;
            }

            removeAtIndex(indexOfRemoval);
        }
    }

    public void removeAtIndex(int indexOfRemoval) {

        if (indexOfRemoval < 0 || indexOfRemoval >= size()) {
            throw new IndexOutOfBoundsException();
        }

        if (indexOfRemoval == 0) {
            removeFirst();
        } else if (indexOfRemoval == size() - 1) {
            removeLast();
        } else {

            int iteration = 0;
            IntNode scanner = head;

            while (scanner.hasNext()) {

                if (indexOfRemoval == iteration) {
                    scanner.previous.next = scanner.next;
                    scanner.next.previous = scanner.previous;

                }

                scanner = scanner.next;
                iteration++;

            }

        }

    }

/*
todo:
    toArray
    addALL(int array)
    addAll(int List)
 */

    public class IntNode {
        public int value;
        public IntNode previous = null;
        public IntNode next = null;

        public IntNode(int setValue, IntNode setPrevious, IntNode setNext) {
            this.value = setValue;
            this.previous = setPrevious;
            this.next = setNext;

        }

        public boolean hasNext() {
            return next != null;
        }

        public boolean hasPrevious() {
            return previous != null;
        }

        @Override
        public String toString() {
            String s = String.valueOf(this.value);

            if (this.hasNext()) {
                s += ", " + this.next.toString();
            }

            return s;
        }

        public void addTailChild(int value) {
            if (this.hasNext()) {
                this.next.addTailChild(value);
            } else {
                this.next = new IntNode(value, this, null);
            }
        }

        public boolean childrenContainRec(int valueToSearch) {
            return (valueToSearch == this.value) || (this.next != null ? this.next.childrenContainRec(valueToSearch) : false);
        }
    }
}


text:
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
	C++ class header boilerplate exported from UnrealHeaderTool.
	This is automatically generated by the tools.
	DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/

PRAGMA_DISABLE_DEPRECATION_WARNINGS
enum class EBPLoginStatus : uint8;
struct FBPUniqueNetId;
struct FBlueprintSessionResult;
#ifdef ADVANCEDSESSIONS_AdvancedFriendsInterface_generated_h
#error "AdvancedFriendsInterface.generated.h already included, missing '#pragma once' in AdvancedFriendsInterface.h"
#endif
#define ADVANCEDSESSIONS_AdvancedFriendsInterface_generated_h

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_RPC_WRAPPERS
#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_RPC_WRAPPERS_NO_PURE_DECLS
#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_EVENT_PARMS \
	struct AdvancedFriendsInterface_eventOnPlayerLoginChanged_Parms \
	{ \
		int32 PlayerNum; \
	}; \
	struct AdvancedFriendsInterface_eventOnPlayerLoginStatusChanged_Parms \
	{ \
		EBPLoginStatus PreviousStatus; \
		EBPLoginStatus NewStatus; \
		FBPUniqueNetId PlayerUniqueNetID; \
	}; \
	struct AdvancedFriendsInterface_eventOnPlayerVoiceStateChanged_Parms \
	{ \
		FBPUniqueNetId PlayerId; \
		bool bIsTalking; \
	}; \
	struct AdvancedFriendsInterface_eventOnSessionInviteAccepted_Parms \
	{ \
		FBPUniqueNetId PersonInviting; \
		FBlueprintSessionResult SearchResult; \
	}; \
	struct AdvancedFriendsInterface_eventOnSessionInviteReceived_Parms \
	{ \
		FBPUniqueNetId PersonInviting; \
		FBlueprintSessionResult SearchResult; \
	};

extern ADVANCEDSESSIONS_API  FName ADVANCEDSESSIONS_OnPlayerLoginChanged;
extern ADVANCEDSESSIONS_API  FName ADVANCEDSESSIONS_OnPlayerLoginStatusChanged;
extern ADVANCEDSESSIONS_API  FName ADVANCEDSESSIONS_OnPlayerVoiceStateChanged;
extern ADVANCEDSESSIONS_API  FName ADVANCEDSESSIONS_OnSessionInviteAccepted;
extern ADVANCEDSESSIONS_API  FName ADVANCEDSESSIONS_OnSessionInviteReceived;
#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_CALLBACK_WRAPPERS
#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_STANDARD_CONSTRUCTORS \
	/** Standard constructor, called after all reflected properties have been initialized */ \
	ADVANCEDSESSIONS_API UAdvancedFriendsInterface(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
	DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedFriendsInterface) \
	DECLARE_VTABLE_PTR_HELPER_CTOR(ADVANCEDSESSIONS_API, UAdvancedFriendsInterface); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedFriendsInterface); \
private: \
	/** Private move- and copy-constructors, should never be used */ \
	ADVANCEDSESSIONS_API UAdvancedFriendsInterface(UAdvancedFriendsInterface&&); \
	ADVANCEDSESSIONS_API UAdvancedFriendsInterface(const UAdvancedFriendsInterface&); \
public:

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_ENHANCED_CONSTRUCTORS \
	/** Standard constructor, called after all reflected properties have been initialized */ \
	ADVANCEDSESSIONS_API UAdvancedFriendsInterface(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
	/** Private move- and copy-constructors, should never be used */ \
	ADVANCEDSESSIONS_API UAdvancedFriendsInterface(UAdvancedFriendsInterface&&); \
	ADVANCEDSESSIONS_API UAdvancedFriendsInterface(const UAdvancedFriendsInterface&); \
public: \
	DECLARE_VTABLE_PTR_HELPER_CTOR(ADVANCEDSESSIONS_API, UAdvancedFriendsInterface); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedFriendsInterface); \
	DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedFriendsInterface)

#undef GENERATED_UINTERFACE_BODY_COMMON
#define GENERATED_UINTERFACE_BODY_COMMON() \
	private: \
	static void StaticRegisterNativesUAdvancedFriendsInterface(); \
	friend ADVANCEDSESSIONS_API class UClass* Z_Construct_UClass_UAdvancedFriendsInterface(); \
public: \
	DECLARE_CLASS(UAdvancedFriendsInterface, UInterface, COMPILED_IN_FLAGS(CLASS_Abstract | CLASS_Interface), 0, TEXT("/Script/AdvancedSessions"), ADVANCEDSESSIONS_API) \
	DECLARE_SERIALIZER(UAdvancedFriendsInterface) \
	enum {IsIntrinsic=COMPILED_IN_INTRINSIC};

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_GENERATED_BODY_LEGACY \
		PRAGMA_DISABLE_DEPRECATION_WARNINGS \
	GENERATED_UINTERFACE_BODY_COMMON() \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_STANDARD_CONSTRUCTORS \
	PRAGMA_ENABLE_DEPRECATION_WARNINGS

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_GENERATED_BODY \
	PRAGMA_DISABLE_DEPRECATION_WARNINGS \
	GENERATED_UINTERFACE_BODY_COMMON() \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_ENHANCED_CONSTRUCTORS \
private: \
	PRAGMA_ENABLE_DEPRECATION_WARNINGS

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_INCLASS_IINTERFACE_NO_PURE_DECLS \
protected: \
	virtual ~IAdvancedFriendsInterface() {} \
public: \
	typedef UAdvancedFriendsInterface UClassType; \
	static void Execute_OnPlayerLoginChanged(UObject* O, int32 PlayerNum); \
	static void Execute_OnPlayerLoginStatusChanged(UObject* O, EBPLoginStatus& PreviousStatus, EBPLoginStatus& NewStatus, FBPUniqueNetId& PlayerUniqueNetID); \
	static void Execute_OnPlayerVoiceStateChanged(UObject* O, FBPUniqueNetId PlayerId, bool bIsTalking); \
	static void Execute_OnSessionInviteAccepted(UObject* O, FBPUniqueNetId PersonInviting, FBlueprintSessionResult const& SearchResult); \
	static void Execute_OnSessionInviteReceived(UObject* O, FBPUniqueNetId PersonInviting, FBlueprintSessionResult const& SearchResult); \
	virtual UObject* _getUObject() const = 0;

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_INCLASS_IINTERFACE \
protected: \
	virtual ~IAdvancedFriendsInterface() {} \
public: \
	typedef UAdvancedFriendsInterface UClassType; \
	static void Execute_OnPlayerLoginChanged(UObject* O, int32 PlayerNum); \
	static void Execute_OnPlayerLoginStatusChanged(UObject* O, EBPLoginStatus& PreviousStatus, EBPLoginStatus& NewStatus, FBPUniqueNetId& PlayerUniqueNetID); \
	static void Execute_OnPlayerVoiceStateChanged(UObject* O, FBPUniqueNetId PlayerId, bool bIsTalking); \
	static void Execute_OnSessionInviteAccepted(UObject* O, FBPUniqueNetId PersonInviting, FBlueprintSessionResult const& SearchResult); \
	static void Execute_OnSessionInviteReceived(UObject* O, FBPUniqueNetId PersonInviting, FBlueprintSessionResult const& SearchResult); \
	virtual UObject* _getUObject() const = 0;

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_20_PROLOG \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_EVENT_PARMS

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_28_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_RPC_WRAPPERS \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_CALLBACK_WRAPPERS \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_INCLASS_IINTERFACE \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS

#define MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_28_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_RPC_WRAPPERS_NO_PURE_DECLS \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_CALLBACK_WRAPPERS \
	MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h_23_INCLASS_IINTERFACE_NO_PURE_DECLS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS

#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID MultiUserToolrotoNew_4_15_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsInterface_h

PRAGMA_ENABLE_DEPRECATION_WARNINGS


text:
namespace blink {

extern template class CORE_EXTERN_TEMPLATE_EXPORT LayoutNGMixin<LayoutSVGBlock>;
extern template class CORE_EXTERN_TEMPLATE_EXPORT
    LayoutNGBlockFlowMixin<LayoutSVGBlock>;

// The LayoutNG representation of SVG <text>.
class LayoutNGSVGText final : public LayoutNGBlockFlowMixin<LayoutSVGBlock> {
 public:
  explicit LayoutNGSVGText(Element* element);

  void SubtreeStructureChanged(LayoutInvalidationReasonForTracing);
  // This is called whenever a text layout attribute on the <text> or a
  // descendant <tspan> is changed.
  void SetNeedsPositioningValuesUpdate();
  void SetNeedsTextMetricsUpdate();
  bool NeedsTextMetricsUpdate() const;

  bool IsObjectBoundingBoxValid() const;

 private:
  // LayoutObject override:
  const char* GetName() const override;
  bool IsOfType(LayoutObjectType type) const override;
  bool IsChildAllowed(LayoutObject* child, const ComputedStyle&) const override;
  void AddChild(LayoutObject* child, LayoutObject* before_child) override;
  void RemoveChild(LayoutObject* child) override;
  void InsertedIntoTree() override;
  void WillBeRemovedFromTree() override;
  gfx::RectF ObjectBoundingBox() const override;
  gfx::RectF StrokeBoundingBox() const override;
  gfx::RectF VisualRectInLocalSVGCoordinates() const override;
  void AbsoluteQuads(Vector<gfx::QuadF>& quads,
                     MapCoordinatesFlags mode) const override;
  gfx::RectF LocalBoundingBoxRectForAccessibility() const override;
  void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
  void WillBeDestroyed() override;
  bool NodeAtPoint(HitTestResult& result,
                   const HitTestLocation& hit_test_location,
                   const PhysicalOffset& accumulated_offset,
                   HitTestPhase phase) override;
  PositionWithAffinity PositionForPoint(
      const PhysicalOffset& point_in_contents) const override;

  // LayoutBox override:
  bool CreatesNewFormattingContext() const override;
  void UpdateFromStyle() override;

  // LayoutBlock override:
  void Paint(const PaintInfo&) const override;
  void UpdateBlockLayout(bool relayout_children) override;

  void UpdateFont();
  void UpdateTransformAffectsVectorEffect();

  // bounding_box_* are mutable for on-demand computation in a const method.
  mutable gfx::RectF bounding_box_;
  mutable bool needs_update_bounding_box_ : 1;

  bool needs_text_metrics_update_ : 1;
};

template <>
struct DowncastTraits<LayoutNGSVGText> {
  static bool AllowFrom(const LayoutObject& object) {
    return object.IsNGSVGText();
  }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_SVG_LAYOUT_NG_SVG_TEXT_H_