text:
/*
* WebTemplate 1.0
* Luca Vercelli 2017
* Released under MIT license
*/
package com.example.myapp.login.filters;

import javax.inject.Inject;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;

import com.example.myapp.login.actions.TokenManager;
import com.example.myapp.main.util.AbstractRequestFilter;

/**
 * Filter for token-based (JWT) authentication. Currently not used.
 *
 * @see https://stackoverflow.com/questions/26777083
 */
@WebFilter(filterName = "tokenFilter", value = "/secured/*")
public class TokenFilter
		extends AbstractRequestFilter /* may use ContainerRequestFilter ? */ {

	public static final String AUTHENTICATION_SCHEME = "Bearer"; // JWT
																	// standard

	@Inject
	TokenManager tokenManager;

	@Inject
	private Logger LOG;

	/**
	 * Do filter
	 */
	@Override
	public boolean filterRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// Get the Authorization header from the request
		String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

		// Validate the Authorization header
		if (!isTokenBasedAuthentication(authorizationHeader)) {
			abortWithUnauthorized(request, response);
			return false;
		}

		// Extract the token from the Authorization header
		String token = authorizationHeader.substring(AUTHENTICATION_SCHEME.length()).trim();

		// Validate the token
		boolean valid = tokenManager.validateToken(token, request.getRemoteAddr());

		LOG.info("TokenFilter finished.");

		if (!valid) {
			abortWithUnauthorized(request, response);
			return false;
		}

		return true;
	}

	/**
	 * Check if the Authorization header is valid. It must not be null and must
	 * be prefixed with "Bearer" plus a whitespace Authentication scheme
	 * comparison must be case-insensitive
	 *
	 * @param authorizationHeader
	 * @return
	 */
	private boolean isTokenBasedAuthentication(String authorizationHeader) {

		return authorizationHeader != null
				&& authorizationHeader.toLowerCase().startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
	}

	/**
	 * Abort the filter chain with a 401 status code. The "WWW-Authenticate" is
	 * sent along with the response.
	 *
	 * @param request
	 * @param response
	 */
	private void abortWithUnauthorized(HttpServletRequest request, HttpServletResponse response) {

		response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
		response.setHeader(HttpHeaders.WWW_AUTHENTICATE, AUTHENTICATION_SCHEME);
	}

}


text:
package net.kikuchy.genum.internal;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

/**
 * Created by kikuchy on 2015/11/03.
 */
public final class StringUtil {
    public static boolean isCanonicalClassName(String str) {
        int idx = str.lastIndexOf('.');
        return idx > 0 && (idx + 1) < str.length() && StringUtils.isAsciiPrintable(str) && isUpperCase(str.charAt(idx + 1));
    }

    public static boolean isUpperCase(int charCode) {
        return charCode >= 'A' && charCode <= 'Z';
    }

    public static Pair<String, String> splitPackageNameAndClassName(String str) {
        int idx = str.lastIndexOf('.');
        return Pair.of(str.substring(0, idx), str.substring(idx + 1));
    }

    public static String toUpperUnderscored(String str) {
        if (str.contains("-")) {
            // hyphenated
            return StringUtils.upperCase(StringUtils.replace(str, "-", "_"));
        } else if (str.contains(" ")) {
            // spaced
            return StringUtils.upperCase(StringUtils.replace(str, " ", "_"));
        } else if (str.contains("_")) {
            // upper underscored or lower underscored
            return StringUtils.upperCase(str);
        } else {
            // maybe upper camel or lower camel
            String lc = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, str);
            return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, lc);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
@interface ViewController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextView *tvInput;
@property (weak, nonatomic) IBOutlet UIButton *btnAnalyze;
@property (weak, nonatomic) IBOutlet UITextView *tvOutput;
@property (weak, nonatomic) IBOutlet UISwitch *switchLive;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tvInput.delegate = self;
    self.tvInput.layer.cornerRadius = 5;
    self.tvOutput.layer.cornerRadius = 5;
    self.btnAnalyze.layer.cornerRadius = 5;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITextView Delegate
-(void)textViewDidChange:(UITextView *)textView
{
    [self displayOutputForText:textView.text isFinal:NO];
}

#pragma mark - Actions
- (IBAction)actionAnalyze:(id)sender {
    [self displayOutputForText:self.tvInput.text isFinal:YES];
    [self.tvInput resignFirstResponder];
}
#pragma mark - methods
-(void)displayOutputForText:(NSString*)text isFinal:(BOOL)isFinal
{
    __block MBProgressHUD *hud;
    if (isFinal) {
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.minSize = CGSizeMake(150.f, 100.f);
        // Back to indeterminate mode
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.mode = MBProgressHUDModeIndeterminate;
            hud.labelText = NSLocalizedString(@"Parsing...", @"HUD parsing title");
        });
    }
    __weak typeof(self) weakSelf = self;
    [ParserKit parseText:text isFinal:isFinal completion:^(NSDictionary * _Nonnull result, NSString * _Nonnull originalText) {
        //Parsing complete
        if (isFinal) {
            UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            hud.customView = imageView;
            hud.mode = MBProgressHUDModeCustomView;
            hud.labelText = NSLocalizedString(@"Completed", @"HUD completed title");
            [hud hide:YES afterDelay:0.5];
        }

        NSString *jsonString = [MNParserAPI jsonForDictionary:result prettyPrint:YES];
        if (self.switchLive.on || isFinal ) {
            weakSelf.tvOutput.text = jsonString;
        }
    }];
}
@end


text:
<?php

declare(strict_types=1);

namespace UCSDMath\CronScheduler;

/**
 * CronScheduler is the default implementation of {@link CronSchedulerInterface} which
 * provides routine CronScheduler methods that are commonly used in the framework.
 *
 * {@link AbstractCronScheduler} is basically a base class for various Cron routines
 * which this class extends.
 *
 * Method list: (+) @api, (-) protected or private visibility.
 *
 * (+) CronSchedulerInterface __construct();
 * (+) void __destruct();
 *
 * @author Daryl Eisner <deisner@ucsd.edu>
 */
class CronScheduler extends AbstractCronScheduler implements CronSchedulerInterface
{
    /**
     * Constants.
     *
     * @var string VERSION The version number
     *
     * @api
     */
    public const VERSION = '2.5.0';

    //--------------------------------------------------------------------------

    /**
     * Properties.
     */

    //--------------------------------------------------------------------------

    /**
     * Constructor.
     *
     * @api
     */
    public function __construct()
    {
        parent::__construct();
    }

    //--------------------------------------------------------------------------

    /**
     * Destructor.
     *
     * @api
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    //--------------------------------------------------------------------------
}


text:
/*
 * Dispatch to the right ffitarget file. This file is PyObjC specific, in a
 * normal build the build environment copies the file to the right location or
 * sets up the right include flags. We want to do neither because that would
 * make building fat binaries harder.
 */
#if defined(__i386__)

#include "../src/x86/ffitarget.h"

#elif defined(__ppc__)

#include "../src/powerpc/ffitarget.h"

#else

#errror "Unsupported CPU type"

#endif


text:
//
// pch.h
// Header for standard system include files.
//

#pragma once

#include <collection.h>
#include <robuffer.h>
#include "App.xaml.h"


text:
<?php

namespace FlintCMS\Bundle\FrontBundle\Twig\Node;
/**
 *
 * @author camm (camm@flintinteractive.com.au)
 */
class FlintRegionNode extends \Twig_Node implements \Twig_NodeOutputInterface
{
    /**
     * @param Twig_Node_Expression $expr
     * @param Twig_Node_Expression|null $variables
     * @param bool $only
     * @param $lineno
     * @param null $tag
     */
    public function __construct(\Twig_Node_Expression $expr, \Twig_Node_Expression $variables = null, $only = false, $lineno, $tag = null)
    {
        parent::__construct(array('expr' => $expr, 'variables' => $variables), array('only' => (Boolean)$only), $lineno, $tag);
    }

    /**
     * @param Twig_Compiler $compiler
     * @return void
     */
    public function compile(\Twig_Compiler $compiler)
    {
        $compiler->addDebugInfo($this);

        $compiler
                ->write("\$region = ")
                ->subcompile($this->getNode('expr'))
                ->raw(";\n")
                ->write("echo \$this->env->getExtension('pure')->renderRegion(")
                ->raw('$this->env, $region, ');

        if (false === $this->getAttribute('only')) {
            if (null === $this->getNode('variables')) {
                $compiler->raw('$context');
            } else {
                $compiler
                        ->raw('array_merge($context, ')
                        ->subcompile($this->getNode('variables'))
                        ->raw(')');
            }
        } else {
            if (null === $this->getNode('variables')) {
                $compiler->raw('array()');
            } else {
                $compiler->subcompile($this->getNode('variables'));
            }
        }

        $compiler->raw(");\n");
    }
}


text:
package transform

import (
	"testing"

	"github.com/drone/drone-exec/yaml"

	"github.com/franela/goblin"
)

func Test_env(t *testing.T) {

	g := goblin.Goblin(t)
	g.Describe("environment variables", func() {

		g.It("should be copied", func() {
			envs := map[string]string{"CI": "drone"}

			c := newConfig(&yaml.Container{
				Environment: map[string]string{},
			})

			Environ(c, envs)
			g.Assert(c.Pipeline[0].Environment["CI"]).Equal("drone")
		})
	})
}


text:
package com.adyen.service.resource.payout;

import com.adyen.Client;
import com.adyen.Service;
import com.adyen.service.Resource;

public class ConfirmThirdParty extends Resource {
    public ConfirmThirdParty(Service service) {
        super(service, service.getClient().getConfig().getEndpoint() + "/pal/servlet/Payout/" + Client.PAYOUT_API_VERSION + "/confirmThirdParty", null);
    }
}


text:
#include "gm.h"
#include "SkRegion.h"

// This GM exercises the use case found in crbug.com/423834.
// The following pattern:
//    save();
//    clipRect(rect, noAA);
//    drawRect(bigRect, noAA);
//    restore();
//
//    drawRect(rect, noAA);
// can leave 1 pixel wide remnants of the first rect.
static void Draw(SkCanvas* canvas, const SkRect& rect) {
        SkPaint p;
        p.setAntiAlias(false);

        const SkRect bigRect = SkRect::MakeWH(600, 600);

        canvas->save();
            // draw a black rect through the clip
            canvas->save();
                canvas->clipRect(rect);
                canvas->drawRect(bigRect, p);
            canvas->restore();

            // now draw the white rect on top
            p.setColor(SK_ColorWHITE);
            canvas->drawRect(rect, p);
        canvas->restore();
}

DEF_SIMPLE_GM_BG(clipdrawdraw, canvas, 512, 512, 0xFFCCCCCC) {
        // Vertical remnant
        const SkRect rect1 = SkRect::MakeLTRB(136.5f, 137.5f, 338.5f, 293.5f);

        // Horizontal remnant
        // 179.488 rounds the right way (i.e., 179), 179.499 rounds the wrong way (i.e., 180)
        const SkRect rect2 = SkRect::MakeLTRB(207.5f, 179.499f, 530.5f, 429.5f);

        Draw(canvas, rect1);
        Draw(canvas, rect2);
}

///////////////////////////////////////////////////////////////////////////////////////////////////

DEF_SIMPLE_GM(clip_region, canvas, 256, 256) {
    SkRegion rgn({ 10, 10, 100, 100 });

    canvas->save();
    canvas->clipRegion(rgn);
    canvas->drawColor(SK_ColorRED);
    canvas->restore();

    SkRect bounds = { 30, 30, 80, 80 };
    canvas->saveLayer(&bounds, nullptr);
    canvas->clipRegion(rgn);
    canvas->drawColor(SK_ColorBLUE);
    canvas->restore();
}


text:
namespace query_tiles {

// A destination for all interesting events from internal components.
class LogSink {
 public:
  virtual ~LogSink() = default;

  // To be called when status of fetcher or manager changes.
  virtual void OnServiceStatusChanged() = 0;

  // To be called when the tile gorup raw data is available.
  virtual void OnTileDataAvailable() = 0;
};

}  // namespace query_tiles

#endif  // COMPONENTS_QUERY_TILES_INTERNAL_LOG_SINK_H_


text:
var Collection = require('../../../lib/waterline/collection'),
    assert = require('assert');

describe('Collection Query', function() {

  describe('.destroy()', function() {
    var query;

    before(function(done) {

      // Extend for testing purposes
      var Model = Collection.extend({
        identity: 'user',
        adapter: 'foo',
        attributes: {
          name: {
            type: 'string',
            defaultsTo: 'Foo Bar'
          },
          doSomething: function() {}
        }
      });

      // Fixture Adapter Def
      var adapterDef = { destroy: function(col, options, cb) { return cb(null); }};
      new Model({ adapters: { foo: adapterDef }}, function(err, coll) {
        if(err) done(err);
        query = coll;
        done();
      });
    });

    it('should not return an error', function(done) {
      query.destroy({}, function(err) {
        assert(!err);
        done();
      });
    });

    it('should allow a query to be built using deferreds', function(done) {
      query.destroy()
      .where({})
      .exec(function(err) {
        assert(!err);
        done();
      });
    });

  });
});


text:
title: "FAQ"
description: "Answers to frequently asked questions."
lead: "Answers to frequently asked questions."
date: 2020-10-06T08:49:31+00:00
lastmod: 2020-10-06T08:49:31+00:00
draft: false
images: []
menu:
  docs:
    parent: "help"
weight: 630
toc: true
---

## Hyas?

Doks is a [Hyas theme](https://gethyas.com/themes/) build by the creator of Hyas.

## Footer notice?

Please keep it in place.

## Keyboard shortcuts for search?

- focus: `/`
- select: `↓` and `↑`
- open: `Enter`
- close: `Esc`

## Other documentation?

- [Netlify](https://docs.netlify.com/)
- [Hugo](https://gohugo.io/documentation/)

## Can I get support?

Create a topic:

- [Netlify Community](https://community.netlify.com/)
- [Hugo Forums](https://discourse.gohugo.io/)
- [Doks Discussions](https://github.com/h-enk/doks/discussions)

## Contact the creator?

Send `h-enk` a message:

- [Netlify Community](https://community.netlify.com/)
- [Hugo Forums](https://discourse.gohugo.io/)
- [Doks Discussions](https://github.com/h-enk/doks/discussions)


text:
#include "eliminateSerEnums.h"

#include "frontends/p4/enumInstance.h"

namespace P4 {

const IR::Node* DoEliminateSerEnums::preorder(IR::Type_SerEnum* serEnum) {
    if (getParent<IR::P4Program>()) return nullptr;  // delete the declaration
    return serEnum->type;
}

const IR::Node* DoEliminateSerEnums::postorder(IR::Type_Name* type) {
    auto canontype = typeMap->getTypeType(getOriginal(), true);
    if (!canontype->is<IR::Type_SerEnum>()) return type;
    if (findContext<IR::TypeNameExpression>() != nullptr)
        // This will be resolved by the caller.
        return type;
    auto enumType = canontype->to<IR::Type_SerEnum>();
    LOG2("Replacing " << type << " with " << enumType->type);
    return enumType->type;
}

/// process enum expression, e.g., X.a
const IR::Node* DoEliminateSerEnums::postorder(IR::Member* expression) {
    auto ei = EnumInstance::resolve(getOriginal<IR::Member>(), typeMap);
    if (!ei) return expression;
    if (auto sei = ei->to<SerEnumInstance>()) {
        LOG2("Replacing " << expression << " with " << sei->value);
        return sei->value;
    }
    return expression;
}

}  // namespace P4


text:
#import "FirebaseInstallations/Source/Tests/Utils/FIRInstallationsItem+Tests.h"

#import "FirebaseCore/Extension/FirebaseCoreInternal.h"

#import "FirebaseInstallations/Source/Library/InstallationsStore/FIRInstallationsStoredAuthToken.h"

@implementation FIRInstallationsItem (Tests)

+ (FIRInstallationsItem *)createUnregisteredInstallationItem {
  FIRInstallationsItem *item = [[FIRInstallationsItem alloc] initWithAppID:@"appID"
                                                           firebaseAppName:kFIRDefaultAppName];
  item.firebaseInstallationID = @"firebaseInstallationID";
  item.registrationStatus = FIRInstallationStatusUnregistered;

  return item;
}

+ (FIRInstallationsItem *)createRegisteredInstallationItem {
  FIRInstallationsItem *item = [self createRegisteredInstallationItemWithAppID:@"appID"
                                                                       appName:kFIRDefaultAppName];
  item.firebaseInstallationID = @"firebaseInstallationID";
  item.registrationStatus = FIRInstallationStatusRegistered;

  return item;
}

+ (FIRInstallationsItem *)createCorruptedItem {
  FIRInstallationsItem *item = [self createRegisteredInstallationItemWithAppID:@"appID"
                                                                       appName:kFIRDefaultAppName];
  item.firebaseInstallationID = nil;

  return item;
}

+ (FIRInstallationsItem *)createRegisteredInstallationItemWithAppID:(NSString *)appID
                                                            appName:(NSString *)appName {
  FIRInstallationsItem *item = [[FIRInstallationsItem alloc] initWithAppID:appID
                                                           firebaseAppName:appName];
  item.firebaseInstallationID = [FIRInstallationsItem generateFID];
  item.refreshToken = @"refreshToken";
  item.registrationStatus = FIRInstallationStatusRegistered;

  FIRInstallationsStoredAuthToken *authToken = [[FIRInstallationsStoredAuthToken alloc] init];
  authToken.token = @"auth-token";
  authToken.expirationDate = [NSDate dateWithTimeIntervalSinceNow:2 * 60 * 60];
  item.authToken = authToken;

  return item;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="android.adhoctalent.com.aplicacion12.Autentificacion">

    <android.support.design.widget.TextInputLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="50dp"
        android:layout_marginLeft="32dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="32dp"
        app:layout_constraintRight_toRightOf="parent"
        android:id="@+id/textInputLayout">

        <EditText
            android:id="@+id/edUsuario"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Proporciona tu nombre" />
    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="32dp"
        android:text="Entrar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textInputLayout" />
</android.support.constraint.ConstraintLayout>


text:
package com.intellij.hibernate.model.enums;

import org.jetbrains.annotations.NonNls;
import com.intellij.util.xml.NamedEnum;

public enum FetchType implements NamedEnum {
  JOIN("join"), SELECT("select");

  private final String myValue;

  private FetchType(final @NonNls String value) {
    myValue = value;
  }

  public String getValue() {
    return myValue;
  }
}


text:
from protmapper import MappedSite
from indra.statements import *
from indra.util import unicode_strs
from indra.preassembler.sitemapper import default_mapper as sm, MappedStatement
from indra.preassembler.sitemapper import _valid_position_str

def test_check_agent_mod():
    mapk1_valid = Agent('MAPK1',
                        mods=[ModCondition('phosphorylation', 'T', '185'),
                              ModCondition('phosphorylation', 'Y', '187')],
                        db_refs={'UP': 'P28482'})
    mapped_sites_valid, _ = sm._map_agent_sites(mapk1_valid)
    assert not mapped_sites_valid, mapped_sites_valid

    mapk1_invalid = Agent('MAPK1',
                          mods=[ModCondition('phosphorylation', 'T', '183'),
                                ModCondition('phosphorylation', 'Y', '185')],
                          db_refs={'UP': 'P28482'})
    mapped_sites_invalid, new_agent = sm._map_agent_sites(mapk1_invalid)
    assert len(mapped_sites_invalid) == 2
    assert isinstance(mapped_sites_invalid[0], MappedSite)
    map183 = mapped_sites_invalid[0]
    assert (map183.up_id, map183.orig_res, map183.orig_pos,
            map183.mapped_res, map183.mapped_pos) == \
        ('P28482', 'T', '183', 'T', '185'), map183
    map185 = mapped_sites_invalid[1]
    assert (map185.up_id, map185.orig_res, map185.orig_pos,
            map185.mapped_res, map185.mapped_pos) == \
        ('P28482', 'Y', '185', 'Y', '187'), map183
    assert len(new_agent.mods) == 2
    assert new_agent.mods[0].matches(ModCondition('phosphorylation',
                                                  'T', '185'))
    assert new_agent.mods[1].matches(ModCondition('phosphorylation',
                                                  'Y', '187'))
    assert unicode_strs((mapk1_valid, mapk1_invalid, mapped_sites_invalid,
                         mapped_sites_valid, map183, map185, new_agent))

def test_site_map_modification():
    mapk1_invalid = Agent('MAPK1',
                          mods=[ModCondition('phosphorylation', 'T', '183'),
                                ModCondition('phosphorylation', 'Y', '185')],
                          db_refs={'UP': 'P28482'})
    mapk3_invalid = Agent('MAPK3',
                          mods=[ModCondition('phosphorylation', 'T', '201')],
                          db_refs={'UP': 'P27361'})
    map2k1_invalid = Agent('MAP2K1',
                           mods=[ModCondition('phosphorylation', 'S', '217'),
                                 ModCondition('phosphorylation', 'S', '221')],
                           db_refs={'UP': 'Q02750'})

    st1 = Phosphorylation(mapk1_invalid, mapk3_invalid, 'Y', '203')
    st2 = Phosphorylation(map2k1_invalid, mapk1_invalid, 'Y', '218')
    res = sm.map_sites([st1, st2])

    assert len(res) == 2
    valid_stmts, mapped_stmts = res
    assert isinstance(valid_stmts, list)
    assert isinstance(mapped_stmts, list)
    assert len(valid_stmts) == 0
    assert len(mapped_stmts) == 2
    # MAPK1 -> MAPK3
    mapped_stmt1 = mapped_stmts[0]
    assert isinstance(mapped_stmt1, MappedStatement)
    assert mapped_stmt1.original_stmt == st1
    assert isinstance(mapped_stmt1.mapped_mods, list)
    assert len(mapped_stmt1.mapped_mods) == 4, mapped_stmt1.mapped_mods
    ms = mapped_stmt1.mapped_stmt
    assert isinstance(ms, Statement)
    agent1 = ms.enz
    agent2 = ms.sub
    assert agent1.name == 'MAPK1'
    assert len(agent1.mods) == 2
    assert agent1.mods[0].matches(ModCondition('phosphorylation', 'T', '185'))
    assert agent1.mods[1].matches(ModCondition('phosphorylation', 'Y', '187'))
    assert agent2.mods[0].matches(ModCondition('phosphorylation', 'T', '202'))
    assert ms.residue == 'Y'
    assert ms.position == '204'

    # MAP2K1 -> MAPK1
    mapped_stmt2 = mapped_stmts[1]
    assert isinstance(mapped_stmt2, MappedStatement)
    assert mapped_stmt2.original_stmt == st2
    assert isinstance(mapped_stmt2.mapped_mods, list)
    assert len(mapped_stmt2.mapped_mods) == 5, mapped_stmt2.mapped_mods
    ms = mapped_stmt2.mapped_stmt
    assert isinstance(ms, Statement)
    agent1 = ms.enz
    agent2 = ms.sub
    assert agent1.name == 'MAP2K1'
    assert len(agent1.mods) == 2
    assert agent1.mods[0].matches(ModCondition('phosphorylation', 'S', '218'))
    assert agent1.mods[1].matches(ModCondition('phosphorylation', 'S', '222'))
    assert len(agent2.mods) == 2
    assert agent2.mods[0].matches(ModCondition('phosphorylation', 'T', '185'))
    assert agent2.mods[1].matches(ModCondition('phosphorylation', 'Y', '187'))
    # The incorrect phosphorylation residue is passed through to the new
    # statement unchanged
    assert ms.residue == 'Y'
    assert ms.position == '218'
    # Check for unicode
    assert unicode_strs((mapk1_invalid, mapk3_invalid, map2k1_invalid, st1,
                         st2, res, valid_stmts, mapped_stmts))

def test_site_map_activity_modification():
    mc = [ModCondition('phosphorylation', 'T', '183'),
          ModCondition('phosphorylation', 'Y', '185')]
    mapk1 = Agent('MAPK1', mods=mc, db_refs={'UP': 'P28482'})

    st1 = ActiveForm(mapk1, 'kinase', True)
    (valid, mapped) = sm.map_sites([st1])
    assert len(valid) == 0
    assert len(mapped) == 1
    ms = mapped[0]
    mm = ms.mapped_mods
    assert (mm[0].gene_name, mm[0].orig_res, mm[0].orig_pos, mm[0].mapped_res,
            mm[0].mapped_pos) == ('MAPK1', 'T', '183', 'T', '185')
    assert (mm[1].gene_name, mm[1].orig_res, mm[1].orig_pos, mm[1].mapped_res,
            mm[1].mapped_pos) == ('MAPK1', 'Y', '185', 'Y', '187')
    assert ms.original_stmt == st1
    assert ms.mapped_stmt.agent.mods[0].matches(ModCondition('phosphorylation',
                                                             'T', '185'))
    assert ms.mapped_stmt.agent.mods[1].matches(ModCondition('phosphorylation',
                                                             'Y', '187'))
    assert unicode_strs((mc, mapk1, st1, valid, mapped))

def test_site_map_selfmodification():
    mapk1_invalid = Agent('MAPK1',
                          mods=[ModCondition('phosphorylation', 'T', '183')],
                          db_refs={'UP': 'P28482'})
    st1 = Autophosphorylation(mapk1_invalid, 'Y', '185')
    (valid, mapped) = sm.map_sites([st1])
    assert len(valid) == 0
    assert len(mapped) == 1
    mapped_stmt = mapped[0]
    mm = mapped_stmt.mapped_mods
    assert (mm[0].gene_name, mm[0].orig_res, mm[0].orig_pos, mm[0].mapped_res,
            mm[0].mapped_pos) == ('MAPK1', 'T', '183', 'T', '185')
    assert (mm[1].gene_name, mm[1].orig_res, mm[1].orig_pos, mm[1].mapped_res,
            mm[1].mapped_pos) == ('MAPK1', 'Y', '185', 'Y', '187')
    ms = mapped_stmt.mapped_stmt
    agent1 = ms.enz
    assert agent1.mods[0].matches(ModCondition('phosphorylation', 'T', '185'))
    assert ms.residue == 'Y'
    assert ms.position == '187'
    assert unicode_strs((mapk1_invalid, st1, valid, mapped))

# The following Statements are all handled by the same block of code and hence
# can be tested in similar fashion

def test_site_map_complex():
    (mapk1_invalid, mapk3_invalid) = get_invalid_mapks()
    st1 = Complex([mapk1_invalid, mapk3_invalid])
    res = sm.map_sites([st1])
    check_validated_mapks(res, st1)

def test_site_map_gef():
    (mapk1_invalid, mapk3_invalid) = get_invalid_mapks()
    st1 = Gef(mapk1_invalid, mapk3_invalid)
    res = sm.map_sites([st1])
    check_validated_mapks(res, st1)

def test_site_map_gap():
    (mapk1_invalid, mapk3_invalid) = get_invalid_mapks()
    st1 = Gap(mapk1_invalid, mapk3_invalid)
    res = sm.map_sites([st1])
    check_validated_mapks(res, st1)

def test_site_map_activation():
    (mapk1_invalid, mapk3_invalid) = get_invalid_mapks()
    st1 = Activation(mapk1_invalid, mapk3_invalid, 'kinase')
    res = sm.map_sites([st1])
    check_validated_mapks(res, st1)

def test_site_map_hgnc():
    """Make sure site mapping is done even if only HGNC ID is given."""
    (mapk1_invalid, mapk3_invalid) = get_invalid_mapks()
    mapk1_invalid.db_refs = {'HGNC': '6871'}
    st1 = ActiveForm(mapk1_invalid, 'kinase', True)
    (valid, mapped) = sm.map_sites([st1])
    assert len(valid) == 0
    assert len(mapped) == 1

def test_site_map_within_bound_condition():
    # Here, we test to make sure that agents within a bound condition are
    # site-mapped
    (mapk1_invalid, mapk3_invalid) = get_invalid_mapks()

    # Add an agent to the bound condition for the object of the statement
    mapk3_invalid.bound_conditions = [BoundCondition(mapk1_invalid)]
    st1 = Activation(mapk1_invalid, mapk3_invalid, 'kinase')

    # Map sites
    res = sm.map_sites([st1])

    # Extract the mapped statement
    mapped_statements = res[1]
    assert len(mapped_statements) == 1
    mapped_s = mapped_statements[0].mapped_stmt

    # Verify that the agent in the object's bound condition got site-mapped
    validate_mapk1(mapped_s.obj.bound_conditions[0].agent)

def test_invalid_position():
    stmt = Phosphorylation._from_json({
        'enz': {'name': 'CFD'},
        'sub': {'name': 'HP'},
        'residue': 'F',
        'position': '2.59'
    })
    valid, mapped = sm.map_sites(stmts=[stmt])
    assert not valid
    assert not mapped

def test_valid_pos_str():
    assert _valid_position_str('5') is True
    assert _valid_position_str('005') is False
    assert _valid_position_str('5.5') is False
    assert _valid_position_str('xxx') is False
    assert _valid_position_str(None) is True
    assert _valid_position_str('') is False

def get_invalid_mapks():
    """A handy function for getting the invalid MAPK agents we want."""
    mapk1_invalid = Agent('MAPK1',
                          mods=[ModCondition('phosphorylation', 'T', '183'),
                                ModCondition('phosphorylation', 'Y', '185')],
                          db_refs={'UP': 'P28482'})
    mapk3_invalid = Agent('MAPK3',
                          mods=[ModCondition('phosphorylation', 'T', '201'),
                                ModCondition('phosphorylation', 'Y', '203')],
                          db_refs={'UP': 'P27361'})
    assert unicode_strs((mapk1_invalid, mapk3_invalid))
    return (mapk1_invalid, mapk3_invalid)

def check_validated_mapks(res, st1):
    """Validate that the invalid MAPKs have been fixed appropriately."""
    assert len(res) == 2
    valid_stmts = res[0]
    mapped_stmts = res[1]
    assert isinstance(valid_stmts, list)
    assert isinstance(mapped_stmts, list)
    assert len(valid_stmts) == 0
    assert len(mapped_stmts) == 1
    mapped_stmt = mapped_stmts[0]
    assert isinstance(mapped_stmt, MappedStatement)
    assert mapped_stmt.original_stmt == st1
    assert isinstance(mapped_stmt.mapped_mods, list)
    assert len(mapped_stmt.mapped_mods) == 4
    ms = mapped_stmt.mapped_stmt
    assert isinstance(ms, Statement)
    agents = ms.agent_list()
    assert len(agents) == 2
    agent1 = agents[0]
    agent2 = agents[1]
    validate_mapk1(agent1)
    assert agent2.mods[0].matches(ModCondition('phosphorylation', 'T', '202'))
    assert agent2.mods[1].matches(ModCondition('phosphorylation', 'Y', '204'))
    assert unicode_strs((res, st1))

def validate_mapk1(agent1):
    assert agent1.name == 'MAPK1'
    assert len(agent1.mods) == 2
    assert agent1.mods[0].matches(ModCondition('phosphorylation', 'T', '185'))
    assert agent1.mods[1].matches(ModCondition('phosphorylation', 'Y', '187'))


text:
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef QUICHE_COMMON_PLATFORM_DEFAULT_QUICHE_PLATFORM_IMPL_QUICHE_UDP_SOCKET_PLATFORM_IMPL_H_
#define QUICHE_COMMON_PLATFORM_DEFAULT_QUICHE_PLATFORM_IMPL_QUICHE_UDP_SOCKET_PLATFORM_IMPL_H_

#include <sys/socket.h>
#include <unistd.h>

#include <cstddef>
#include <cstdint>

namespace quiche {

constexpr size_t kCmsgSpaceForGooglePacketHeaderImpl = 0;

inline bool GetGooglePacketHeadersFromControlMessageImpl(
    struct ::cmsghdr* /*cmsg*/, char** /*packet_headers*/,
    size_t* /*packet_headers_len*/) {
  return false;
}

inline void SetGoogleSocketOptionsImpl(int /*fd*/) {}

}  // namespace quiche

#endif  // QUICHE_COMMON_PLATFORM_DEFAULT_QUICHE_PLATFORM_IMPL_QUICHE_UDP_SOCKET_PLATFORM_IMPL_H_


text:
/*
 * File: version.cpp
 * -----------------
 * This file implements functions for checking the version number of the
 * Stanford C++ library, its Java back-end, and the project properties
 * file (.pro).
 *
 * @author Marty Stepp
 * @version 2016/09/24
 * - bug fix for std::quick_exit function
 * @version 2015/07/05
 * - removed static global Platform variable, replaced by getPlatform as needed
 * @version 2014/11/13
 * - ifdef'd out macroIntegerToDate function to remove unused function warning on some platforms
 * @since 2014/10/31
 */

#include "private/version.h"
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "private/platform.h"

namespace version {
#ifdef SPL_PROJECT_VERSION
/*
 * converts an 8-digit integer into a YYYY/MM/DD date string,
 * e.g. 20140907 -> "2014/09/07"
 * needed because I can't have a string as a -D command-line defined flag
 */
static std::string macroIntegerToDate(int macroInteger) {
    int year = (macroInteger / 10000);          // 2014
    int month = (macroInteger % 10000 / 100);   // 09
    int day = (macroInteger % 100);             // 07
    std::ostringstream out;
    out << std::setw(4) << std::setfill('0') << year
        << "/" << std::setw(2) << std::setfill('0') << month
        << "/" << std::setw(2) << std::setfill('0') << day;
    return out.str();
}
#endif // SPL_PROJECT_VERSION

static void ensureJavaBackEndVersionHelper(std::string minVersion) {
    std::string backendVersion = stanfordcpplib::getPlatform()->cpplib_getJavaBackEndVersion();
    if (backendVersion < minVersion) {
        // use stderr directly rather than cerr because graphical console is unreachable
        fputs("\n", stderr);
        fputs("***\n", stderr);
        fputs("*** STANFORD C++ LIBRARY ERROR:\n", stderr);
        fputs("*** The Java back-end library 'spl.jar' detected is too old\n", stderr);
        fputs("*** and is not compatible with this version of the C++ library.\n", stderr);
        fputs("*** Exiting immediately to avoid compatibility errors.\n", stderr);
        fputs("*** Please update your spl.jar to a newer compatible version.\n", stderr);
        fprintf(stderr, "*** Java back-end spl.jar found: %s\n", backendVersion.c_str());
        fprintf(stderr, "*** Minimum version accepted   : %s\n", minVersion.c_str());
        fputs("***\n", stderr);
        fputs("\n", stderr);
        fflush(stderr);

        std::exit(1);
    }
}

static void ensureProjectVersionHelper(std::string minVersion) {
#ifdef SPL_PROJECT_VERSION
    std::string projectVersion = macroIntegerToDate(SPL_PROJECT_VERSION);
#else
    std::string projectVersion = "";
#endif

    if (projectVersion < minVersion) {
        fputs("\n", stderr);
        fputs("***\n", stderr);
        fputs("*** STANFORD C++ LIBRARY ERROR:\n", stderr);
        fputs("*** Your project's properties (from your .pro file) are too old\n", stderr);
        fputs("*** and are not compatible with this version of the C++ library.\n", stderr);
        fputs("*** Exiting immediately to avoid compatibility errors.\n", stderr);
        fputs("*** Please update your .pro to a newer compatible version.\n", stderr);
        fprintf(stderr, "*** Your .pro version found : %s\n", projectVersion.c_str());
        fprintf(stderr, "*** Minimum version accepted: %s\n", minVersion.c_str());
        fputs("***\n", stderr);
        fputs("\n", stderr);
        fflush(stderr);

        std::exit(1);
    }
}

void ensureJavaBackEndVersion(std::string minVersion) {
    if (minVersion.empty()) {
        minVersion = STANFORD_JAVA_BACKEND_MINIMUM_VERSION;
    }
    ensureJavaBackEndVersionHelper(minVersion);
}

void ensureProjectVersion(std::string minVersion) {
    if (minVersion.empty()) {
#ifdef SPL_MINIMUM_PROJECT_VERSION
        minVersion = SPL_MINIMUM_PROJECT_VERSION;
#else
        minVersion = STANFORD_CPP_PROJECT_MINIMUM_VERSION;
#endif
    }
    ensureProjectVersionHelper(minVersion);
}

std::string getCppLibraryVersion() {
    return STANFORD_CPP_LIB_VERSION;
}

std::string getJavaBackEndVersion() {
    return stanfordcpplib::getPlatform()->cpplib_getJavaBackEndVersion();
}

/*
 * Returns version of project properties as defined in .pro file.
 */
std::string getProjectVersion() {
#ifdef SPL_PROJECT_VERSION
    // 20141031 -> "2014/10/31"
    std::ostringstream out;
    out << (SPL_PROJECT_VERSION / 10000);         // 2014
    out << "/";
    out << (SPL_PROJECT_VERSION % 10000 / 100);   // 10
    out << "/";
    out << (SPL_PROJECT_VERSION % 100);           // 31
    return out.str();
#endif
    return "";
}

} // namespace version


text:
package loon.action.map.heuristics;

import loon.action.map.AStarFindHeuristic;
import loon.utils.MathUtils;

public class EuclideanNoSQR implements AStarFindHeuristic {

	public float getScore(float sx, float sy, float tx, float ty) {
		return MathUtils.pow((sx - tx), 2) + MathUtils.pow((sy - ty), 2);
	}

	public int getType() {
		return EUCLIDEAN_NOSQR;
	}

}


text:
module PropulsionUnits {
    "use strict";

    // abstract class
    export class PropulsionUnit implements Interfaces.IProduceAccelerate {
        constructor() { }

        public produceAcceleration(): number {
            return 0;
        }
    }
}


text:
from __future__ import unicode_literals, print_function, division
import sys
import time
import math
import gitime.database as db

unix_now = lambda: math.floor(time.time())

class User(object):
    """ Contains user data that is shared between invoices """

    def __init__(self, rowid=1):
        meta = db.query_user(rowid)
        if not meta:
            print("User with rowid %s doesn't exist." %rowid, file=sys.stderr)
            sys.exit()
        self.rowid = rowid
        self.rate = meta[0]
        self.rounding = meta[1]
        self.timer_running = bool(meta[2])
        self.timer_start = meta[3]
        self.timer_total = meta[4]
        self.active_invoice_rowid = meta[5] if len(meta) == 6 else 0

    def _timer_db_update(self):
        """ Set the timer on the database to match
            the timer of this object
        """
        db.update(lambda c: c.execute("""
            UPDATE user SET timer_running=?, timer_start=?, timer_total=?
            WHERE rowid=?
        """, (int(self.timer_running), self.timer_start,
              self.timer_total, self.rowid
            )
        ))

    def start_timer(self):
        if self.timer_running:
            print("The timer is already running!", file=sys.stderr)
            sys.exit()
        self.timer_running = True
        self.timer_start = unix_now()
        self._timer_db_update()

    def reset_timer(self):
        self.timer_running = False
        self.timer_start = 0
        self.timer_total = 0
        self._timer_db_update()

    def pause_timer(self):
        if not self.timer_running:
            print("The timer isn't running.", file=sys.stderr)
            sys.exit()
        self.timer_running = False
        self.timer_total += unix_now() - self.timer_start
        self._timer_db_update()

    def time_tracked(self, inv=None):
        rounding = inv.rounding if inv else self.rounding
        if self.timer_running:
            return round((unix_now() - self.timer_start + self.timer_total
                ) / 3600.0 / rounding) * rounding
        else:
            return round(self.timer_total / 3600.0 / rounding) * rounding

    def set_rate(self, r):
        self.rate = r
        db.update(lambda c: c.execute("""
            UPDATE user SET rate=? WHERE rowid=?
        """, (self.rate, self.rowid)))

    def set_rounding(self, r):
        self.rounding = r
        db.update(lambda c: c.execute("""
            UPDATE user SET rounding=? WHERE rowid=?
        """, (self.rounding, self.rowid)))

    def set_active_invoice(self, rowid):
        self.active_invoice_rowid = rowid
        db.update(lambda c: c.execute("""
            UPDATE user SET active_invoice=? WHERE rowid=?
        """, (self.active_invoice_rowid, self.rowid)))


text:
package pl.kjaklik.maven.jstprecompile.compiler;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

/**
 * @author Krzysiek Jaklik
 *         created: 18.10.12 10:29
 */
public interface TemplateCompiler {

    void prepare();
    boolean isPrepared();

    String getNamespace();
    void setNamespace(String namespace);

    String getClassName();
    void setClassName(String className);

    String getOptions();
    void setOptions(String options);

    boolean isSupportDevMode();
    void setDevModeBaseDir(File baseDir);
    File getDevModeBaseDir();

    void compileGroup(Iterable<File> templates, File output);
    void compileGroup(Iterable<File> templates, Writer output) throws IOException;

    void devCompileGroup(Iterable<File>  templates, File output);
    void devCompileGroup(Iterable<File>  templates, Writer output) throws IOException;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Schaereria argentina f. albosuffusa Gyeln.

### Remarks
null


text:
import React, { Component } from 'react';
import ReactRouter, { Link } from 'react-router';
import styles from '../styles/index';
import MainContainer from './MainContainer';

class Home extends Component {
  render() {
    return (
      <MainContainer>

Github Battle

Some fancy motto

        <Link to='playerone'>
          <button type='button' className='btn btn-lg btn-success'>Get Started</button>
        </Link>
      </MainContainer>
    );
  }
}

export default Home;


text:
package xworker.gswt.actions;

import org.xmeta.ActionContext;
import org.xmeta.Thing;

import xworker.gswt.Action;
import xworker.gswt.SimpleGame;

public class Visible extends Action{
	public Visible(Thing thing, ActionContext actionContext){
		super(thing, actionContext);
	}

	@Override
	public void doAction(SimpleGame game, ActionContext actionContext) {
		actor.visible = true;
		this.finished = true;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <bean id="aclCache" class="org.springframework.security.acls.domain.EhCacheBasedAclCache">
        <constructor-arg ref="aclEhCache"/>
    </bean>

    <bean id="aclEhCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="cacheName" value="aclCache"/>
    </bean>

	<!-- 从数据库中读取信息,把这些信息提供给aclService使用 -->
    <bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy">
        <constructor-arg ref="dataSource"/>
        <constructor-arg ref="aclCache"/>
        <constructor-arg>
            <bean class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
                <constructor-arg>
                    <list>
                        <ref local="adminRole"/>
                        <ref local="adminRole"/>
                        <ref local="adminRole"/>
                    </list>
                </constructor-arg>
            </bean>
        </constructor-arg>
        <constructor-arg>
            <bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"/>
        </constructor-arg>
    </bean>
	<!-- 变更授权,抑或是修改其他的ace信息,都需要控制操作者的权限,
		 这里配置的三个权限将对应于上述的三种修改操作,我们把它配置成只
		 有ROLE_ADMIN才能执行这三种修改操作。 -->
    <bean id="adminRole" class="org.springframework.security.core.authority.GrantedAuthorityImpl">
        <constructor-arg value="ROLE_ADMIN"/>
    </bean>
	<!-- 配置aclService -->
    <bean id="aclService" class="org.springframework.security.acls.jdbc.JdbcMutableAclService">
        <constructor-arg ref="dataSource"/>
        <constructor-arg ref="lookupStrategy"/>
        <constructor-arg ref="aclCache"/>
        <property name="classIdentityQuery" value="SELECT @@IDENTITY"/>
		<property name="sidIdentityQuery" value="SELECT @@IDENTITY"/>
    </bean>
	<!-- 对delete操作起作用的表决器
		 只对Message这个类起作用,而且可以限制只有管理和删除权限的用户可以执行删除操作-->
    <bean id="aclDeleteVoter" class="com.sjg.voter.IdParameterAclEntryVoter">
        <constructor-arg ref="aclService"/>
        <constructor-arg value="ACL_DELETE"/>
        <constructor-arg>
            <list>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.ADMINISTRATION"/>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.DELETE"/>
            </list>
        </constructor-arg>
        <property name="processDomainObjectClass" value="com.sjg.AclDomainClass"/>
    </bean>
	<!-- 将这个表决器aclMessageDeleteVoter添加到AccessDecisionManager中 -->
    <bean id="aclAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="decisionVoters">
            <list>
                <bean class="org.springframework.security.access.vote.RoleVoter"/>
                <ref local="aclDeleteVoter"/>
            </list>
        </property>
    </bean>

	<!-- 配置afterInvocation,使用后置判断的方式,将用户无权查看的信息,
		  从MessageService返回的结果集中过滤掉。
		 后置判断有两种形式,一种用来控制单个对象,另一种可以过滤集合。
		 afterAclRead可以控制单个对象是否可以显示,afterAclCollectionRead则
		用来过滤集合中哪些对象可以显示
	 -->
    <bean id="afterAclRead" class="org.springframework.security.acls.afterinvocation.AclEntryAfterInvocationProvider">
        <constructor-arg ref="aclService"/>
        <constructor-arg>
            <list>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.ADMINISTRATION"/>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.READ"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="afterAclCollectionRead" class="org.springframework.security.acls.afterinvocation.AclEntryAfterInvocationCollectionFilteringProvider">
        <constructor-arg ref="aclService"/>
        <constructor-arg>
            <list>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.ADMINISTRATION"/>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.READ"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="afterAclCreate" class="com.sjg.afterinvocation.CreateAclEntryAfterInvocationProvider">
        <constructor-arg ref="aclService"/>
        <constructor-arg>
            <list>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.ADMINISTRATION"/>
            </list>
        </constructor-arg>
        <property name="processDomainObjectClass" value="com.sjg.AclDomainClass"/>
        <property name="handlers">
            <list>
                <ref local="aclHandler"/>
            </list>
        </property>
    </bean>

     <bean id="afterAclDelete" class="com.sjg.afterinvocation.DeleteAclEntryAfterInvocationProvider">
        <constructor-arg ref="aclService"/>
        <constructor-arg>
            <list>
                <util:constant static-field="org.springframework.security.acls.domain.BasePermission.ADMINISTRATION"/>
            </list>
        </constructor-arg>
        <property name="processDomainObjectClass" value="com.sjg.AclDomainClass"/>
        <property name="handlers">
            <list>
                <ref local="aclHandler"/>
            </list>
        </property>
    </bean>

    <bean id="aclHandler" class="com.sjg.handler.DefaultAclHandler">
        <property name="mutableAclService" ref="aclService"/>
    </bean>

</beans>


text: function countSteps(b,a,c){b=Math.floor(b/a);if(c){return b%c}return b}module.exports=countSteps;


text:
import random
import sqlite3
from player_last_names import player_last_names
from player_first_names import player_first_names
from game_variables import age, potential, def_iq, off_iq, decision_making, court_awareness, strength, fatigue, stamina, shooting_touch, all_star_quality, height, wingspan, vertical, speed, passing, dribbling, shot_layup, shot_midrange, shot_close, shot_three, shot_ft, steal, block, major_bonus, minor_bonus, rebounding
from game_variables import all_star_threshold, all_star_bonus, all_star_stat_min, all_star_stat_max, number_of_teams
from game_variables import team_name_options
from team_init import Team
from game_variables import budget

def create_stat(stat): # assumes a min/max tuple as input
	min = stat[0]	   # helper function that aids in class object creation
	max = stat[1]
	selection = random.randrange(min, max)
	return selection

def rating_to_letter_grade(rating): # helper function that converts number ratings to letter grades
	if rating >= 95:
		letter_grade = "A+"
	elif rating <= 94 and rating >= 90:
		letter_grade = "A"
	elif rating <=	89 and rating >= 85:
		letter_grade = "A-"
	elif rating <= 84 and rating >= 80:
		letter_grade = "B+"
	elif rating <= 79 and rating >= 75:
		letter_grade = "B"
	elif rating <= 74 and rating >= 70:
		letter_grade = "B-"
	elif rating <= 69 and rating >= 65:
		letter_grade = "C+"
	elif rating <= 64 and rating >= 60:
		letter_grade = "C"
	elif rating <= 59 and rating >= 55:
		letter_grade = "C-"
	elif rating <= 54 and rating >= 50:
		letter_grade = "D+"
	elif rating <= 49 and rating >= 45:
		letter_grade = "D"
	elif rating <= 44 and rating >= 40:
		letter_grade = "D-"
	elif rating <=39:
		letter_grade = "F"
	return letter_grade

def cm_to_in(height):  # heights are stored in cm, this converst to feet/inches for ui output
	in_high = height / 2.54
	feet_high = int(in_high / 12)
	remainder = int(in_high % 12)
	feet_inches = str(feet_high) + "'" + str(remainder) + '"'
	return feet_inches

# Player database table structure for future reference
# database.execute('''CREATE TABLE player_db (Id integer primary key,
# 	league_id REFERENCES league_table(Id),
# 	team_id REFERENCES team_db(Id),
# 	salary, name, age, potential, def_iq, off_iq, decision_making, court_awareness, strength, fatigue, stamina, shooting_touch,
# 	height, wingspan, vertical, speed, passing, dribbling, shot_layup, shot_close, shot_midrange, shot_three, shot_ft, steal, rebounding,
# 	block, birthday, position)''')

class Player:
	def __init__(self, league_id):
		self.league_id = league_id
		self.db_id = 0 # default value, gets updated when stored in database
		self.name = random.choice(player_first_names) + " " + random.choice(player_last_names)
		self.age = create_stat(age)
		self.potential = create_stat(potential)
		self.def_iq = create_stat(def_iq)
		self.off_iq = create_stat(off_iq)
		self.decision_making = create_stat(decision_making)
		self.court_awareness = create_stat(court_awareness)
		self.strength = create_stat(strength)
		self.fatigue = create_stat(fatigue)
		self.stamina = create_stat(stamina)
		self.shooting_touch = create_stat(shooting_touch)
		self.all_star_quality = create_stat(all_star_quality)
		self.height = create_stat(height)
		self.wingspan = self.height + create_stat(wingspan)
		self.vertical = create_stat(vertical)
		self.speed = create_stat(speed)
		self.passing = create_stat(passing)
		self.dribbling = create_stat(dribbling)
		self.shot_layup = create_stat(shot_layup)
		self.shot_close = create_stat(shot_close)
		self.shot_midrange = create_stat(shot_midrange)
		self.shot_three = create_stat(shot_three)
		self.shot_ft = create_stat(shot_ft)
		self.steal = create_stat(steal)
		self.rebounding = create_stat(rebounding)
		self.block = create_stat(block)
		self.birthday = random.randrange(0, (number_of_teams * 4))
		self.team = ''
		self.salary = 1 # placeholder for league minimum, need transformation in player subclasses that creates salary based on player ability
		self.position = ''
		self.role = '' # players role on team starter, bench etc
		self.full_abilities = [
			'court_awareness',
			'decision_making',
			'passing',
			'dribbling',
			'steal',
			'def_iq',
			'off_iq',
			'speed',
			'strength',
			'stamina',
			'shot_layup',
			'shot_close',
			'shot_midrange',
			'shot_three',
			'rebounding',
			'block'
			]

	def all_star_modifier(self):
		if self.all_star_quality >= all_star_threshold:
			essentials = self.player_get_essentials()
			for rating in essentials:
				setattr(self, rating, getattr(self, rating) + all_star_bonus)
				while getattr(self, rating) < all_star_stat_min:
					setattr(self, rating, getattr(self, rating) + all_star_bonus)
				if getattr(self, rating)  > all_star_stat_max:
					setattr(self, rating, all_star_stat_max)
		else:
			pass

	def change_role(self, new_role):
		self.role = new_role
		return self.role

	def show_rating(self):
		total = 0
		for rating in self.full_abilities:
			total += getattr(self, rating)
		overall_rating = total / 16 # possibly replace with len(full_abilities)
		return overall_rating

	def show_letter_grade(self):
		return rating_to_letter_grade(self.show_rating())

	def player_game_growth(self):
		essentials = self.player_get_essentials()
		if self.age < 30:  # this works but feels cumbersome, might be worth having a parabolic function that returns bonus
			rating_bonus = 1
			for rating in essentials:
				if self.potential >= 85:
					if random.randrange(1,100) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				elif self.potential >= 70 and self.potential <= 84:
					if random.randrange(1,300) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				elif self.potential >= 55 and self.potential <= 69:
					if random.randrange(1,400) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				elif self.potential <= 54:
					if random.randrange(1,500) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				if getattr(self, rating) >= 99:
					setattr(self, rating, 99)
		elif self.age >= 30:
			rating_bonus = -1
			for rating in essentials:
				if self.potential >= 85:
					if random.randrange(1,500) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				elif self.potential >= 70 and self.potential <= 84:
					if random.randrange(1,400) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				elif self.potential >= 55 and self.potential <= 69:
					if random.randrange(1,300) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				elif self.potential <= 54:
					if random.randrange(1,100) == 15:
						setattr(self, rating, getattr(self, rating) + rating_bonus)
				if getattr(self, rating) <= 10:
					setattr(self, rating, 10)

	def player_birthday_check(self, game_day):
		if self.birthday == game_day:
			self.age += 1
		return self.age

	def player_offseason_growth(self):
		young_range = (18)
		prime_range = (25)
		beyond_prime = (30)
		older = (33)
		oldest = (36)
		def growth_modifier():
			if self.potential >= 85:
				return 5
			elif self.potential >= 70 and self.potential <= 84:
				return 4
			elif self.potential >= 55 and self.potential <= 69:
				return 3
			elif self.potential <= 54:
				return 2
		off_season_growth = growth_modifier()
		if self.age in range(young_range,prime_range):
			off_season_growth += random.randrange(2,6)
		elif self.age in range(prime_range,beyond_prime):
			off_season_growth += random.randrange(1,3)
		elif self.age in range(beyond_prime,older):
			off_season_growth += random.randrange(-5,0)
		elif self.age in range(older, oldest):
			off_season_growth += random.randrange(-8,-3)
		elif self.age in range(older, oldest):
			off_season_growth += random.randrange(-8,-5)
		for rating in self.full_abilities:
			setattr(self, rating, getattr(self, rating) + random.randrange(off_season_growth - 4, off_season_growth - 1))
			if getattr(self, rating) >= 99:
				setattr(self, rating, 99)
		return self.full_abilities # not sure if the return here is necessary

	def insert_player(self): # puts the player class object into the player database table
		connection = sqlite3.connect('league.db')
		database = connection.cursor()
		player_attributes = (self.league_id, self.team, self.name, self.age, self.potential, self.def_iq, self.off_iq,
			self.decision_making, self.court_awareness, self.strength, self.fatigue, self.stamina, self.shooting_touch,
			self.height, self.wingspan, self.vertical, self.speed, self.passing,
			self.dribbling, self.shot_layup, self.shot_close, self.shot_midrange, self.shot_three,
			self.shot_ft, self.steal, self.rebounding, self.block, self.birthday, self.salary, self.position, self.role)

		database.execute('''INSERT INTO player_db
		(league_id, team_id, name, age, potential, def_iq, off_iq, decision_making, court_awareness,
			strength, fatigue, stamina, shooting_touch, height, wingspan, vertical,
			speed, passing, dribbling, shot_layup, shot_close, shot_midrange, shot_three, shot_ft, steal,
			rebounding, block, birthday, salary, position, role)
			VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', player_attributes)
		connection.commit()
		self.db_id = database.lastrowid
		connection.close()

	def update_player(self):
		connection = sqlite3.connect('league.db')
		database = connection.cursor()
		player_attributes = (self.league_id, self.team, self.age, self.potential, self.def_iq, self.off_iq,
			self.decision_making, self.court_awareness, self.strength, self.fatigue, self.stamina, self.shooting_touch,
			self.height, self.wingspan, self.vertical, self.speed, self.passing,
			self.dribbling, self.shot_layup, self.shot_close, self.shot_midrange, self.shot_three,
			self.shot_ft, self.steal, self.rebounding, self.block, self.birthday, self.salary, self.position, self.role, self.db_id, self.league_id)
		database.execute('''UPDATE player_db
			SET league_id=?,
			team_id=?,
			age=?,
			potential=?,
			def_iq=?,
			off_iq=?,
			decision_making=?,
			court_awareness=?,
			strength=?,
			fatigue=?,
			stamina=?,
			shooting_touch=?,
			height=?,
			wingspan=?,
			vertical=?,
			speed=?,
			passing=?,
			dribbling=?,
			shot_layup=?,
			shot_close=?,
			shot_midrange=?,
			shot_three=?,
			shot_ft=?,
			steal=?,
			rebounding=?,
			block=?,
			birthday=?,
			salary=?,
			position=?
			role=?
			WHERE 'Id' = ? AND 'league_id' = ? ''', player_attributes) # name isn't uniqe in db, but name is unique within league
		print "player", self.name,  "updated"
		connection.commit()
		connection.close()

		#########################
		#
		# Player database table structure for future reference
		#
		# database.execute('''CREATE TABLE player_db (Id integer primary key,
		# 	league_id REFERENCES league_table(Id),
		# 	team_id REFERENCES team_db(Id),
		# 	salary, name, age, potential, def_iq, off_iq, decision_making, court_awareness, strength, fatigue, stamina, shooting_touch,
		# 	height, wingspan, vertical, speed, passing, dribbling, shot_layup, shot_close, shot_midrange, shot_three, shot_ft, steal, rebounding,
		# 	block, birthday, position, role)''')
		#
		#########################

	def player_get_essentials(self):
		if self.position == 'PG':
			return [
			'court_awareness',
			'decision_making',
			'passing',
			'dribbling',
			'steal',
			'def_iq',
			'off_iq',
			'speed']
		elif self.position == 'SG':
			return [
			'off_iq',
			'decision_making',
			'steal',
			'passing',
			'speed',
			'def_iq',
			'dribbling',
			'court_awareness'
			]
		elif self.position == 'SF':
			return [
			'court_awareness',
			'decision_making',
			'speed',
			'passing',
			'rebounding',
			'def_iq',
			'off_iq',
			'dribbling'
			]
		elif self.position == 'PF':
			return [
			'court_awareness',
			'decision_making',
			'rebounding',
			'block',
			'speed',
			'def_iq',
			'off_iq',
			'passing'
			]
		elif self.position == 'C':
			return [
			'court_awareness',
			'decision_making',
			'rebounding',
			'block',
			'speed',
			'def_iq',
			'off_iq',
			'passing'
			]

	def PG_modifier(self):
		self.court_awareness = major_bonus(self.court_awareness)
		self.decision_making = major_bonus(self.decision_making)
		self.passing = major_bonus(self.passing)
		self.dribbling = major_bonus(self.dribbling)
		self.steal = major_bonus(self.steal)
		self.off_iq = major_bonus(self.off_iq)
		self.speed = major_bonus(self.speed)
		self.height += random.randrange(1,5)
		self.shot_layup += self.shooting_touch
		self.shot_ft += self.shooting_touch
		self.shot_three += self.shooting_touch
		self.position = "PG"

	def SG_modifier(self):
		self.shot_layup = major_bonus(self.shot_layup)
		self.shot_midrange = major_bonus(self.shot_midrange)
		self.shot_three = major_bonus(self.shot_three)
		self.off_iq = major_bonus(self.off_iq)
		self.steal = major_bonus(self.steal)
		self.speed = major_bonus(self.speed)
		self.decision_making = major_bonus(self.decision_making)
		self.shooting_touch = minor_bonus(self.shooting_touch)
		self.height += random.randrange(4 , 10)
		self.shot_midrange += self.shooting_touch
		self.shot_ft += self.shooting_touch
		self.shot_three += self.shooting_touch
		self.position = "SG"

	def SF_modifier(self):
		self.court_awareness = major_bonus(self.court_awareness)
		self.decision_making = major_bonus(self.decision_making)
		self.shot_three = minor_bonus(self.shot_three)
		self.rebounding = major_bonus(self.rebounding)
		self.shot_midrange = minor_bonus(self.shot_midrange)
		self.off_iq = major_bonus(self.off_iq)
		self.def_iq = major_bonus(self.def_iq)
		self.speed = minor_bonus(self.shot_three)
		self.shot_layup = minor_bonus(self.shot_layup)
		self.height += random.randrange(9 , 19)
		self.shot_layup += self.shooting_touch
		self.shot_ft += self.shooting_touch
		self.shot_three += self.shooting_touch
		self.shot_midrange += self.shooting_touch
		self.position = "SF"

	def PF_modifier(self):
		self.def_iq = major_bonus(self.def_iq)
		self.decision_making = major_bonus(self.decision_making)
		self.rebounding= major_bonus(self.rebounding)
		self.shot_close = major_bonus(self.shot_close)
		self.block = major_bonus(self.block)
		self.off_iq = minor_bonus(self.off_iq)
		self.def_iq = major_bonus(self.def_iq)
		self.height += random.randrange(18 , 25)
		self.shot_layup += self.shooting_touch
		self.shot_close += self.shooting_touch
		self.shot_midrange += self.shooting_touch
		self.position = "PF"

	def C_modifier(self):
		self.decision_making = major_bonus(self.decision_making)
		self.rebounding= major_bonus(self.rebounding)
		self.shot_close = major_bonus(self.shot_close)
		self.block = major_bonus(self.block)
		self.off_iq = major_bonus(self.off_iq)
		self.def_iq = major_bonus(self.off_iq)
		self.height += random.randrange(22 , 28)
		self.shot_layup += self.shooting_touch
		self.shot_close += self.shooting_touch
		self.position = "C"

	def player_set_position(self):
		# one time run on inital player setup

		position = random.randrange(1, 6)
		# set position
		if position == 1:
			self.PG_modifier()
		elif position == 2:
			self.SG_modifier()
		elif position == 3:
			self.SF_modifier()
		elif position == 4:
			self.PF_modifier()
		elif position == 5:
			self.C_modifier()
		# provide bonuses for all-stars
		self.all_star_modifier

def load_players(league_id):
	print "starting player load"
	connection = sqlite3.connect('league.db')
	database = connection.cursor()
	database.execute('''SELECT league_id, team_id, name, age, potential, def_iq, off_iq, decision_making, court_awareness,
			strength, fatigue, stamina, shooting_touch, height, wingspan, vertical,
			speed, passing, dribbling, shot_layup, shot_close, shot_midrange, shot_three, shot_ft, steal,
			rebounding, block, birthday, salary, position, role, Id FROM player_db WHERE league_id = ?''', league_id)

	player_pool = {}
	player_attribute = database.fetchone()
	while player_attribute != None:
		new_player = Player(league_id)
		print "attempting player resurrection"
		new_player.league_id = player_attribute[0]
		new_player.team = player_attribute[1]
		new_player.name = player_attribute[2]
		new_player.age = player_attribute[3]
		new_player.potential = player_attribute[4]
		new_player.def_iq  = player_attribute[5]
		new_player.off_iq = player_attribute[6]
		new_player.decision_making = player_attribute[7]
		new_player.court_awareness = player_attribute[8]
		new_player.strength = player_attribute[9]
		new_player.fatigue = player_attribute[10]
		new_player.stamina = player_attribute[11]
		new_player.shooting_touch = player_attribute[12]
		new_player.height = player_attribute[13]
		new_player.wingspan = player_attribute[14]
		new_player.vertical = player_attribute[15]
		new_player.speed = player_attribute[16]
		new_player.passing = player_attribute[17]
		new_player.dribbling = player_attribute[18]
		new_player.shot_layup = player_attribute[19]
		new_player.shot_close = player_attribute[20]
		new_player.shot_midrange = player_attribute[21]
		new_player.shot_three = player_attribute[22]
		new_player.shot_ft = player_attribute[23]
		new_player.steal = player_attribute[24]
		new_player.rebounding = player_attribute[25]
		new_player.block = player_attribute[26]
		new_player.birthday = player_attribute[27]
		new_player.salary = player_attribute[28]
		new_player.position = player_attribute[29]
		new_player.role = player_attribute[30]
		new_player.db_id = player_attribute[31]
		player_pool[new_player.db_id] = new_player
		print new_player.name, " resurrected"
		player_attribute = database.fetchone()
	connection.commit()
	connection.close()
	return player_pool


text:
<?php

/** */
namespace Core\Entity;

/**
 * Entities implementing this interface are able to provide meta data.
 *
 * This meta data should primarly be used for database interactions.
 *  *
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 * @since 0.27
 */
interface MetaDataProviderInterface
{

    /**
     * Get meta data.
     *
     * Returns the whole meta data array, if no $key is provided.
     * Returns null, if there is no meta data for the provided $key.
     *
     * @param null|string $key
     *
     * @return array|mixed|null
     */
    public function getMetaData($key = null);

    /**
     * Set meta data.
     *
     * @param string $key
     * @param mixed $value
     *
     * @return self
     */
    public function setMetaData($key, $value);

    /**
     * Check if a meta data with a specific key is available.
     *
     * @param string $key
     *
     * @return bool
     */
    public function hasMetaData($key);
}


text:
package gov.nasa.worldwind.render;

import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.util.*;

import javax.media.opengl.GL;
import javax.media.opengl.glu.*;
import java.awt.*;

/**
 * @author dcollins
 * @version $Id: SurfaceConcaveShape.java 12662 2009-09-28 18:19:37Z dcollins $
 */
public abstract class SurfaceConcaveShape extends AbstractSurfaceShape
{
    protected static GLU glu;
    protected static GLUtessellator tess;
    protected WWTexture texture;

    protected SurfaceConcaveShape(ShapeAttributes attributes)
    {
        super(attributes);
    }

    protected SurfaceConcaveShape()
    {
    }

    protected void doRenderInteriorToRegion(DrawContext dc, Sector sector, int x, int y, int width, int height)
    {
        // Concave shape makes no assumptions about the nature or structure of the shape's vertices. The interior is
        // treated as a potentially complex polygon, and this code will do its best to rasterize that polygon. The
        // outline is treated as a simple line loop, regardless of whether the shape's vertices actually define a
        // closed path.

        LatLon shapeCenter = Sector.boundingSector(this.getLocations(dc.getGlobe())).getCentroid();
        getSurfaceShapeSupport().applyInteriorState(dc, this.attributes, this.getTexture(), sector,
            new Rectangle(x, y, width, height), shapeCenter);
        this.drawInterior(dc);
    }

    protected void doRenderOutlineToRegion(DrawContext dc, Sector sector, int x, int y, int width, int height)
    {
        getSurfaceShapeSupport().applyOutlineState(dc, this.attributes);
        this.drawOutline(dc, GL.GL_LINE_LOOP);
    }

    protected void drawInterior(DrawContext dc)
    {
        this.tessellateInterior(dc, new ImmediateModeCallback(dc));
    }

    protected void drawOutline(DrawContext dc, int drawMode)
    {
        getSurfaceShapeSupport().drawLocations(dc, drawMode, this.drawLocations, this.drawLocations.size());
    }

    protected WWTexture getTexture()
    {
        if (this.attributes.getInteriorImageSource() == null)
            return null;

        if (this.texture == null && this.attributes.getInteriorImageSource() != null)
            this.texture = new BasicWWTexture(this.attributes.getInteriorImageSource());

        return this.texture;
    }

    protected static GLU getGLU()
    {
        if (glu == null)
        {
            glu = new GLU();
        }

        return glu;
    }

    protected static GLUtessellator getGLUTessellator()
    {
        if (tess == null)
        {
            tess = glu.gluNewTess();
        }

        return tess;
    }

    //**************************************************************//
    //********************  Interior Tessellation  *****************//
    //**************************************************************//

    protected void tessellateInterior(DrawContext dc, GLUtessellatorCallback callback)
    {
        if (dc == null)
        {
            String message = Logging.getMessage("nullValue.DrawContextIsNull");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }

        GLU glu = new GLU();
        GLUtessellator tess = glu.gluNewTess();
        this.beginTessellation(dc, glu, tess, callback);

        try
        {
            this.doTessellate(dc, glu, tess, callback);
        }
        finally
        {
            this.endTessellation(dc, glu, tess);
            glu.gluDeleteTess(tess);
        }
    }

    @SuppressWarnings({"UnusedDeclaration"})
    protected void beginTessellation(DrawContext dc, GLU glu, GLUtessellator tess, GLUtessellatorCallback callback)
    {
        glu.gluTessNormal(tess, 0.0, 0.0, 1.0);
        glu.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, callback);
        glu.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, callback);
        glu.gluTessCallback(tess, GLU.GLU_TESS_END, callback);
        glu.gluTessCallback(tess, GLU.GLU_TESS_COMBINE, callback);
    }

    @SuppressWarnings({"UnusedDeclaration"})
    protected void endTessellation(DrawContext dc, GLU glu, GLUtessellator tess)
    {
        glu.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, null);
        glu.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, null);
        glu.gluTessCallback(tess, GLU.GLU_TESS_END, null);
        glu.gluTessCallback(tess, GLU.GLU_TESS_COMBINE, null);
    }

    protected void doTessellate(DrawContext dc, GLU glu, GLUtessellator tess, GLUtessellatorCallback callback)
    {
        // Determine the winding order of the shape vertices, and setup the GLU winding rule which corresponds to
        // the shapes winding order.
        //noinspection StringEquality
        int windingRule = (WWMath.computePolygonWindingOrder(this.drawLocations) == AVKey.CLOCKWISE)
            ? GLU.GLU_TESS_WINDING_NEGATIVE : GLU.GLU_TESS_WINDING_POSITIVE;

        glu.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, windingRule);
        glu.gluTessBeginPolygon(tess, null);
        glu.gluTessBeginContour(tess);

        for (LatLon ll : this.drawLocations)
        {
            double[] compArray = new double[3];
            compArray[1] = ll.getLatitude().degrees;
            compArray[0] = ll.getLongitude().degrees;
            glu.gluTessVertex(tess, compArray, 0, compArray);
        }

        glu.gluTessEndContour(tess);
        glu.gluTessEndPolygon(tess);
    }

    protected static class ImmediateModeCallback extends GLUtessellatorCallbackAdapter
    {
        protected final GL gl;

        public ImmediateModeCallback(DrawContext dc)
        {
            if (dc == null)
            {
                String message = Logging.getMessage("nullValue.DrawContextIsNull");
                Logging.logger().severe(message);
                throw new IllegalArgumentException(message);
            }

            this.gl = dc.getGL();
        }

        public void begin(int type)
        {
            this.gl.glBegin(type);
        }

        public void vertex(Object vertexData)
        {
            this.gl.glVertex3dv((double[]) vertexData, 0);
        }

        public void end()
        {
            this.gl.glEnd();
        }

        public void combine(double[] coords, Object[] data, float[] weight, Object[] outData)
        {
            outData[0] = coords;
        }
    }
}


text:
<?xml version="1.0"?>
<doc>
<assembly>
<name>
SykesScreenshotCapture
</name>
</assembly>
<members>
<member name="P:Sykes_Screenshot_Capture.My.Resources.Resources.ResourceManager">
	<summary>
  Returns the cached ResourceManager instance used by this class.
</summary>
</member><member name="P:Sykes_Screenshot_Capture.My.Resources.Resources.Culture">
	<summary>
  Overrides the current thread's CurrentUICulture property for all
  resource lookups using this strongly typed resource class.
</summary>
</member><member name="P:Sykes_Screenshot_Capture.My.Resources.Resources._1401590571_circle_info_more_information_detail_">
	<summary>
  Looks up a localized resource of type System.Drawing.Bitmap.
</summary>
</member><member name="P:Sykes_Screenshot_Capture.My.Resources.Resources._1401590581_device_camera_capture_photo_">
	<summary>
  Looks up a localized resource of type System.Drawing.Bitmap.
</summary>
</member><member name="P:Sykes_Screenshot_Capture.My.Resources.Resources._1401590591_cross5">
	<summary>
  Looks up a localized resource of type System.Drawing.Bitmap.
</summary>
</member><member name="T:Sykes_Screenshot_Capture.My.Resources.Resources">
	<summary>
  A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
</members>
</doc>


text:
package io.druid.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.base.Throwables;
import io.druid.java.util.common.guava.Accumulator;
import io.druid.java.util.common.guava.Sequence;
import io.druid.java.util.common.guava.Yielder;
import org.joda.time.DateTimeZone;

import java.io.IOException;
import java.nio.ByteOrder;
import java.util.TimeZone;

/**
 */
public class DruidDefaultSerializersModule extends SimpleModule
{
  public DruidDefaultSerializersModule()
  {
    super("Druid default serializers");

    JodaStuff.register(this);

    addDeserializer(
        DateTimeZone.class,
        new JsonDeserializer<DateTimeZone>()
        {
          @Override
          public DateTimeZone deserialize(JsonParser jp, DeserializationContext ctxt)
              throws IOException
          {
            String tzId = jp.getText();
            try {
              return DateTimeZone.forID(tzId);
            }
            catch (IllegalArgumentException e) {
              // also support Java timezone strings
              return DateTimeZone.forTimeZone(TimeZone.getTimeZone(tzId));
            }
          }
        }
    );
    addSerializer(
        DateTimeZone.class,
        new JsonSerializer<DateTimeZone>()
        {
          @Override
          public void serialize(
              DateTimeZone dateTimeZone,
              JsonGenerator jsonGenerator,
              SerializerProvider serializerProvider
          )
              throws IOException, JsonProcessingException
          {
            jsonGenerator.writeString(dateTimeZone.getID());
          }
        }
    );
    addSerializer(
        Sequence.class,
        new JsonSerializer<Sequence>()
        {
          @Override
          public void serialize(Sequence value, final JsonGenerator jgen, SerializerProvider provider)
              throws IOException, JsonProcessingException
          {
            jgen.writeStartArray();
            value.accumulate(
                null,
                new Accumulator<Object, Object>()
                {
                  @Override
                  public Object accumulate(Object o, Object o1)
                  {
                    try {
                      jgen.writeObject(o1);
                    }
                    catch (IOException e) {
                      throw Throwables.propagate(e);
                    }
                    return null;
                  }
                }
            );
            jgen.writeEndArray();
          }
        }
    );
    addSerializer(
        Yielder.class,
        new JsonSerializer<Yielder>()
        {
          @Override
          public void serialize(Yielder yielder, final JsonGenerator jgen, SerializerProvider provider)
              throws IOException, JsonProcessingException
          {
            try {
              jgen.writeStartArray();
              while (!yielder.isDone()) {
                final Object o = yielder.get();
                jgen.writeObject(o);
                yielder = yielder.next(null);
              }
              jgen.writeEndArray();
            }
            finally {
              yielder.close();
            }
          }
        }
    );
    addSerializer(ByteOrder.class, ToStringSerializer.instance);
    addDeserializer(
        ByteOrder.class,
        new JsonDeserializer<ByteOrder>()
        {
          @Override
          public ByteOrder deserialize(
              JsonParser jp, DeserializationContext ctxt
          ) throws IOException, JsonProcessingException
          {
            if (ByteOrder.BIG_ENDIAN.toString().equals(jp.getText())) {
              return ByteOrder.BIG_ENDIAN;
            }
            return ByteOrder.LITTLE_ENDIAN;
          }
        }
    );
  }
}


text:
import {Component, Input, Output, EventEmitter, OnChanges} from '@angular/core';

import {Config}                      from '../config';

import {ProblemComponent}            from './problem'

import {User}                        from '../models/user';
import {Submission, Verdict}         from '../models/submission';

import {DatabaseService}             from '../services/database';
import {ProblemService}              from '../services/problem';

import {TimerComponent}              from '../components/timer';

@Component({
  selector: 'uhunt-last-submissions',
  templateUrl: 'app/components/last-submissions.html',
  directives: [
    ProblemComponent,
    TimerComponent,
  ],
})
export class LastSubmissionsComponent implements OnChanges {
  @Input() user: User;
  @Output('world-ranklist') worldRanklistClicked = new EventEmitter<boolean>();

  private last_submissions: Submission[] = [];
  private num_last_subs: number;
  private config = Config;

  constructor(
    private _databaseService: DatabaseService,
    private _problemService: ProblemService) {

    this.num_last_subs =
      this._databaseService.get('uhunt_user_statistics_num_last_subs') || 5;
  }

  ngOnChanges(changes) {
    this._problemService.ready.then(() => this.refresh());
  }

  refresh() {
    var subs = [];
    this.user.each_last_subs(10000, (sub) => subs.push(sub));
    this.last_submissions = subs;
  }

  set_num_last_subs(n) {
    this._databaseService.set('uhunt_user_statistics_num_last_subs',
      this.num_last_subs = n);
  }
}


text:
var $isIE = (window == document && document != window);			// IE是朵奇葩,让IT业繁忙
var $isModernBrowser = (typeof window.screenX === "number");	// IE > 8

// 让IE8支持Array.indexOf
if (!Array.prototype.indexOf){
	Array.prototype.indexOf = function(item, start){
		for (var i = start || 0; i < this.length ; i++){
			if (this[i] === item) return i;
		}
		return -1;
	}
}


text:
<menu>

		Home

		Experience
		Skill
		Contact

</menu>


text:
package com.facebook.react.devsupport;

import javax.annotation.Nullable;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.modules.debug.DeveloperSettings;

/**
 * Helper class for accessing developers settings that should not be accessed outside of the package
 * {@link com.facebook.react.devsupport}. For accessing some of the settings by external modules
 * this class implements an external interface {@link DeveloperSettings}.
 */
@VisibleForTesting
public class DevInternalSettings implements
    DeveloperSettings,
    SharedPreferences.OnSharedPreferenceChangeListener {

  private static final String PREFS_FPS_DEBUG_KEY = "fps_debug";
  private static final String PREFS_JS_DEV_MODE_DEBUG_KEY = "js_dev_mode_debug";
  private static final String PREFS_DEBUG_SERVER_HOST_KEY = "debug_http_host";
  private static final String PREFS_ANIMATIONS_DEBUG_KEY = "animations_debug";
  private static final String PREFS_RELOAD_ON_JS_CHANGE_KEY = "reload_on_js_change";

  private final SharedPreferences mPreferences;
  private final DevSupportManager mDebugManager;

  public DevInternalSettings(
      Context applicationContext,
      DevSupportManager debugManager) {
    mDebugManager = debugManager;
    mPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
    mPreferences.registerOnSharedPreferenceChangeListener(this);
  }

  @Override
  public boolean isFpsDebugEnabled() {
    return mPreferences.getBoolean(PREFS_FPS_DEBUG_KEY, false);
  }

  @Override
  public boolean isAnimationFpsDebugEnabled() {
    return mPreferences.getBoolean(PREFS_ANIMATIONS_DEBUG_KEY, false);
  }

  @Override
  public boolean isJSDevModeEnabled() {
    return mPreferences.getBoolean(PREFS_JS_DEV_MODE_DEBUG_KEY, true);
  }

  public @Nullable String getDebugServerHost() {
    return mPreferences.getString(PREFS_DEBUG_SERVER_HOST_KEY, null);
  }

  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (PREFS_FPS_DEBUG_KEY.equals(key) ||
        PREFS_RELOAD_ON_JS_CHANGE_KEY.equals(key) ||
        PREFS_JS_DEV_MODE_DEBUG_KEY.equals(key)) {
      mDebugManager.reloadSettings();
    }
  }

  public boolean isReloadOnJSChangeEnabled() {
    return mPreferences.getBoolean(PREFS_RELOAD_ON_JS_CHANGE_KEY, false);
  }
}


text:
using System;
using System.Diagnostics;

namespace Microsoft.Scripting.Debugging {
    /// <summary>
    /// Used to provide information about locals/parameters at debug time.
    /// </summary>
    internal sealed class VariableInfo {
        private string _name;
        private Type _type;
        private bool _parameter;    // Indicates whether the symbol represents a local variable or parameter
        private bool _hidden;       // Indicates whether the symbol should be hidden during inspection
        private bool _strongBoxed;  // Indicates whether the lifted value of the variable is exposed through byref or strongbox
        private int _localIndex;    // Index within byref variables list or within strongbox variables list
        private int _globalIndex;   // Index within the combined list

        internal VariableInfo(string name, Type type, bool parameter, bool hidden, bool strongBoxed, int localIndex, int globalIndex) {
            _name = name;
            _type = type;
            _parameter = parameter;
            _hidden = hidden;
            _strongBoxed = strongBoxed;
            _localIndex = localIndex;
            _globalIndex = globalIndex;
        }

        internal VariableInfo(string name, Type type, bool parameter, bool hidden, bool strongBoxed)
            : this(name, type, parameter, hidden, strongBoxed, Int32.MaxValue, Int32.MaxValue) {
            _name = name;
            _type = type;
            _parameter = parameter;
            _hidden = hidden;
            _strongBoxed = strongBoxed;
        }

        internal bool Hidden {
            get { return _hidden; }
        }

        internal bool IsStrongBoxed {
            get { return _strongBoxed; }
        }

        internal int LocalIndex {
            get { Debug.Assert(_localIndex != Int32.MaxValue); return _localIndex; }
        }

        internal int GlobalIndex {
            get { Debug.Assert(_globalIndex != Int32.MaxValue); return _globalIndex; }
        }

        /// <summary>
        /// Type
        /// </summary>
        internal Type VariableType {
            get { return _type; }
        }

        /// <summary>
        /// Name
        /// </summary>
        internal string Name {
            get { return _name; }
        }

        /// <summary>
        /// Parameter
        /// </summary>
        internal bool IsParameter {
            get { return _parameter; }
        }
    }
}


text:
module ShopifyAPI
  class OrderRisk < Base
    init_prefix :order

    cattr_reader :prefix_option_keys do
      [:order_id]
    end

    cattr_reader :mutable_attributes do
      [:cause_cancel, :message, :recommendation, :score, :source]
    end

    self.collection_name = 'risks'
    self.element_name = 'risk'
  end
end


text:
ALTER TABLE VALID_PROTO_ACTION_ACTION ADD
	( CONSTRAINT FK_VALID_PROTO_ACTION_ACTION_2
	FOREIGN KEY(FOLLOWUP_ACTION_CODE)
	REFERENCES PROTOCOL_ACTION_TYPE(PROTOCOL_ACTION_TYPE_CODE)
	);

ALTER TABLE VALID_PROTO_ACTION_ACTION ADD
    ( CONSTRAINT FK_VALID_PROTO_ACTION_ACTION
	FOREIGN KEY(PROTOCOL_ACTION_TYPE_CODE)
	REFERENCES PROTOCOL_ACTION_TYPE(PROTOCOL_ACTION_TYPE_CODE));

ALTER TABLE VALID_PROTO_ACTION_ACTION ADD (
    CONSTRAINT FK_VALID_PROTO_ACTION_ACTION_3
    FOREIGN KEY (COMM_DECISION_MOTION_TYPE_CODE)
    REFERENCES COMM_DECISION_MOTION_TYPE (COMM_DECISION_MOTION_TYPE_CODE)
);


text:
namespace Google.Cloud.Iap.V1.Snippets
{
    // [START iap_v1_generated_IdentityAwareProxyOAuthService_ResetIdentityAwareProxyClientSecret_sync]
    using Google.Cloud.Iap.V1;

    public sealed partial class GeneratedIdentityAwareProxyOAuthServiceClientSnippets
    {
        /// <summary>Snippet for ResetIdentityAwareProxyClientSecret</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ResetIdentityAwareProxyClientSecretRequestObject()
        {
            // Create client
            IdentityAwareProxyOAuthServiceClient identityAwareProxyOAuthServiceClient = IdentityAwareProxyOAuthServiceClient.Create();
            // Initialize request argument(s)
            ResetIdentityAwareProxyClientSecretRequest request = new ResetIdentityAwareProxyClientSecretRequest { Name = "", };
            // Make the request
            IdentityAwareProxyClient response = identityAwareProxyOAuthServiceClient.ResetIdentityAwareProxyClientSecret(request);
        }
    }
    // [END iap_v1_generated_IdentityAwareProxyOAuthService_ResetIdentityAwareProxyClientSecret_sync]
}


text:
package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.ArrayAdapter;

/**
 * Demonstrates how the layout_weight attribute can shrink an element too big
 * to fit on screen.
 */
public class LinearLayout9 extends org.bbs.apklauncher.api.Base_Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linear_layout_9);
        ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, AutoComplete1.COUNTRIES));
    }

}


text:
var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var fs = require('fs');

// load secret key from file
var SUPERSECRETKEY = fs.readFileSync(__dirname + '/../config/secret');
SUPERSECRETKEY = SUPERSECRETKEY.slice(0, SUPERSECRETKEY.length - 1)

var UserSchema = new mongoose.Schema({
  username: {type:String, lowercase: true, unique: true},
  hash: String,
  salt: String
});

UserSchema.methods.setPassword = function(password) {
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};

UserSchema.methods.validPassword = function(password) {
  var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  return this.hash === hash;
};

UserSchema.methods.generateJWT = function() {
  // set expiration to 1 day
  var today = new Date();
  var exp = new Date(today);
  exp.setDate(today.getDate() + 7);

  return jwt.sign({
    username: this.username,
    exp: parseInt(exp.getTime() / 1000)
  }, SUPERSECRETKEY);
};

mongoose.model('User', UserSchema);


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * \class document::ByteFieldValue
 * \ingroup fieldvalue
 *
 * \brief Wrapper for field values of datatype BYTE.
 */
#pragma once

#include "numericfieldvalue.h"
#include <vespa/document/datatype/datatype.h>

namespace document {

class ByteFieldValue final : public NumericFieldValue<int8_t> {
public:
    typedef int8_t Number;

    ByteFieldValue(Number value = 0)
        : NumericFieldValue<Number>(Type::BYTE, value) {}

    void accept(FieldValueVisitor &visitor) override { visitor.visit(*this); }
    void accept(ConstFieldValueVisitor &visitor) const override { visitor.visit(*this); }
    const DataType *getDataType() const override { return DataType::BYTE; }
    ByteFieldValue* clone() const override { return new ByteFieldValue(*this); }

    using NumericFieldValue<Number>::operator=;
    static std::unique_ptr<ByteFieldValue> make(Number value=0) { return std::make_unique<ByteFieldValue>(value); }
};

} // document


text:
package com.thorpora.ezdashing.consumer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@Slf4j
@RestController
@RequestMapping("/api/consumer")
public class ConsumerController {

    private ConsumerRegistry registry;

    @Autowired
    public ConsumerController(ConsumerRegistry registry) {
        this.registry = registry;
    }

    @GetMapping(
            value = "/{queryId}",
            produces = APPLICATION_JSON_VALUE)
    public String getSummary(@PathVariable String queryId, @RequestParam Map<String, String> params) {
        log.debug("GET /api/consumer/{}", queryId);
        Consumer consumer = registry.getConsumer(queryId);
        String consumerResponse = consumer.doQuery(queryId, params);
        log.trace("Response of queryId '{}' : {}", queryId, consumerResponse);
        return consumerResponse;
    }

}


text:
pypicloud.access.base module
============================

.. automodule:: pypicloud.access.base
   :members:
   :undoc-members:
   :show-inheritance:


text:
django-lattice
==============

A reusable application for generating a basic scaffold for a django based CMS


text:
namespace SVI{

	//2011-11-07 masterkeaton27@gmail.com
	//let's pretend be scene can't has a child. (just for now)
	class SVI3DCamera;
	class SVI3DScene {
	public:
		SVI3DScene(SVIGLSurface *surface);
		SVI3DScene(SVIGLSurface *surface, SVIFloat width, SVIFloat height);
		virtual ~SVI3DScene();
	private:
		SVI3DScene(const SVI3DScene& rhs){}
		void operator=(const SVI3DScene& rhs){}
	public:
		void run(float fDeltaTime);

	protected:
		void update(float fDeltaTime);
		void render();

	public:
		void initialize();
		void reset();
		void finalize();

	public:
		void setName(const SVIChar * pstrName);
		void setSize(SVIFloat width, SVIFloat height);
		void setCamera(SVI3DCamera* pCamera);

		// 2011/11/30 rareboy0112@facebook.com
		void addSceneNode(SVISceneNode *sceneNode);

	public:
		SVISceneNode* getRootSceneNode() { return mRootSceneNode; }

	public:
		const SVIChar *		getName(){ return mName;}
		const SVI3DCamera *	getCamera(){ return mCamera; }
		const SVISize		getSize(){ return mSize;}

		void setParent(SVISlide *parentSlide) { mParentSlide = parentSlide; }

	protected:
		void updateCamera();

	private:
		SVISize			mSize;
		SVIChar			mName[64];
		SVI3DCamera *	mCamera;
		SVISceneNode *mRootSceneNode;
		SVISlide *mParentSlide;

		SVIGLSurface *mSVIGLSurface;
	};

}


text:
package org.onosproject.p4tutorial.pipeconf;

import org.onosproject.driver.pipeline.DefaultSingleTablePipeline;
import org.onosproject.net.behaviour.Pipeliner;
import org.onosproject.net.device.PortStatisticsDiscovery;
import org.onosproject.net.pi.model.DefaultPiPipeconf;
import org.onosproject.net.pi.model.PiPipeconf;
import org.onosproject.net.pi.model.PiPipeconfId;
import org.onosproject.net.pi.model.PiPipelineInterpreter;
import org.onosproject.net.pi.model.PiPipelineModel;
import org.onosproject.net.pi.service.PiPipeconfService;
import org.onosproject.p4runtime.model.P4InfoParser;
import org.onosproject.p4runtime.model.P4InfoParserException;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;

import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType.BMV2_JSON;
import static org.onosproject.net.pi.model.PiPipeconf.ExtensionType.P4_INFO_TEXT;

/**
 * Component that produces and registers a pipeconf when loaded.
 */
@Component(immediate = true)
public final class PipeconfFactory {

    private final Logger log = LoggerFactory.getLogger(getClass());

    public static final PiPipeconfId PIPECONF_ID = new PiPipeconfId("p4-tutorial-pipeconf");
    private static final URL P4INFO_URL = PipeconfFactory.class.getResource("/mytunnel_p4info.txt");
    private static final URL BMV2_JSON_URL = PipeconfFactory.class.getResource("/mytunnel.json");

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    private PiPipeconfService piPipeconfService;

    @Activate
    public void activate() {
        // Registers the pipeconf at component activation.
        try {
            piPipeconfService.register(buildPipeconf());
        } catch (P4InfoParserException e) {
            log.error("Fail to register {} - Exception: {} - Cause: {}",
                    PIPECONF_ID, e.getMessage(), e.getCause().getMessage());
        }
    }

    @Deactivate
    public void deactivate() {
        // Unregisters the pipeconf at component deactivation.
        try {
            piPipeconfService.unregister(PIPECONF_ID);
        } catch (IllegalStateException e) {
            log.warn("{} haven't been registered", PIPECONF_ID);
        }
    }

    private PiPipeconf buildPipeconf() throws P4InfoParserException {

        final PiPipelineModel pipelineModel = P4InfoParser.parse(P4INFO_URL);

        return DefaultPiPipeconf.builder()
                .withId(PIPECONF_ID)
                .withPipelineModel(pipelineModel)
                .addBehaviour(PiPipelineInterpreter.class, PipelineInterpreterImpl.class)
                .addBehaviour(PortStatisticsDiscovery.class, PortStatisticsDiscoveryImpl.class)
                // Since mytunnel.p4 defines only 1 table, we re-use the existing single-table pipeliner.
                .addBehaviour(Pipeliner.class, DefaultSingleTablePipeline.class)
                .addExtension(P4_INFO_TEXT, P4INFO_URL)
                .addExtension(BMV2_JSON, BMV2_JSON_URL)
                .build();
    }
}


text:
namespace logs {

bool SoundMgr::accept (QModelIndex const & sourceIndex)
{
	return true;
}

bool SoundMgr::action (QModelIndex const & idx)
{
	bool accepted = true;
	for (int i = 0, ie = m_filters.size(); i < ie; ++i)
	{
		FilterBase * b = m_filters[i];
		if (b->enabled())
		{
			bool const filter_accepted = b->action(idx); // @TODO: short circuit?
			accepted |= filter_accepted;
		}
	}
	return accepted;
}

// @TODO: to base l8r (tag to virtual fn)
void SoundMgr::loadConfig (QString const & path)
{
	QString const fname = path + "/" + g_soundTag + "/" + typeName();
	if (!::loadConfigTemplate(*this, fname))
		defaultConfig();

	recreateFilters();

	for (int i = 0, ie = m_filters.size(); i < ie; ++i)
		m_filters[i]->loadConfig(path);
}

void SoundMgr::saveConfig (QString const & path)
{
	m_currTab = m_tabFilters->currentIndex();
	QString const fname = path + "/" + g_soundTag + "/" + typeName();
	::saveConfigTemplate(*this, fname);

	for (int i = 0, ie = m_filters.size(); i < ie; ++i)
		m_filters[i]->saveConfig(path);
}

FilterBase * SoundMgr::filterFactory (E_FilterType t, QWidget * parent)
{
	switch (t)
	{
		case e_Sound_Mgr: return new SoundMgr (parent);
		case e_Sound_Regex: return new SoundRegex (parent);
		default: return 0;
	}
}

/////////////////// FILTER MGR ///////////////////////////////

SoundMgr::SoundMgr (QWidget * parent)
	: FilterMgr(parent)
{
	m_cache.resize(e_filtertype_max_value);
}

SoundMgr::~SoundMgr ()
{
	qDebug("%s", __FUNCTION__);
}

void SoundMgr::defaultConfig ()
{
	m_filter_order.clear();
	m_filter_order.push_back(g_filterNames[e_Sound_Regex]);
}

/////////////////////////////////////////////////////////////////////

void SoundMgr::initUI ()
{
	FilterMgr::initUI();
	setObjectName(QStringLiteral("SoundWidget"));
	//m_widget->setObjectName(QStringLiteral("FilterWidget"));
}

void SoundMgr::doneUI ()
{
	FilterMgr::doneUI();
}

void SoundMgr::clear ()
{
}

}