text:
ALTER TABLE AM_API  ADD COLUMN API_TIER VARCHAR(256);

CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES (
            ALERT_TYPE_ID INTEGER AUTO_INCREMENT,
            ALERT_TYPE_NAME VARCHAR(256) NOT NULL ,
	    STAKE_HOLDER VARCHAR(100) NOT NULL,
            PRIMARY KEY (ALERT_TYPE_ID)
);

CREATE TABLE IF NOT EXISTS AM_ALERT_TYPES_VALUES (
            ALERT_TYPE_ID INTEGER,
            USER_NAME VARCHAR(256) NOT NULL ,
	    STAKE_HOLDER VARCHAR(100) NOT NULL ,
            PRIMARY KEY (ALERT_TYPE_ID,USER_NAME,STAKE_HOLDER)
);

CREATE TABLE IF NOT EXISTS AM_ALERT_EMAILLIST (
	    EMAIL_LIST_ID INTEGER AUTO_INCREMENT,
            USER_NAME VARCHAR(255) NOT NULL ,
	    STAKE_HOLDER VARCHAR(100) NOT NULL ,
            PRIMARY KEY (EMAIL_LIST_ID,USER_NAME,STAKE_HOLDER)
);

CREATE TABLE IF NOT EXISTS  AM_ALERT_EMAILLIST_DETAILS (
            EMAIL_LIST_ID INTEGER,
	    EMAIL VARCHAR(255),
            PRIMARY KEY (EMAIL_LIST_ID,EMAIL)
);

INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalResponseTime', 'publisher');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalBackendTime', 'publisher');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('abnormalRequestsPerMin', 'subscriber');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('RequestPatternChanged', 'subscriber');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('UnusualIPAccessAlert', 'subscriber');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalRefreshAlert', 'subscriber');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('FrequentTierHittingAlert', 'subscriber');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('AbnormalTierUsage', 'publisher');
INSERT INTO AM_ALERT_TYPES (ALERT_TYPE_NAME, STAKE_HOLDER) VALUES ('healthAvailabilityPerMin', 'publisher');

-- AM Throttling tables --

CREATE TABLE IF NOT EXISTS AM_POLICY_SUBSCRIPTION (
            POLICY_ID INT(11) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(512) NOT NULL,
            DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL,
            TENANT_ID INT(11) NOT NULL,
            DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL,
            QUOTA_TYPE VARCHAR(25) NOT NULL,
            QUOTA INT(11) NOT NULL,
            QUOTA_UNIT VARCHAR(10) NULL,
            UNIT_TIME INT(11) NOT NULL,
            TIME_UNIT VARCHAR(25) NOT NULL,
            RATE_LIMIT_COUNT INT(11) NULL DEFAULT NULL,
            RATE_LIMIT_TIME_UNIT VARCHAR(25) NULL DEFAULT NULL,
            IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0,
			      CUSTOM_ATTRIBUTES BLOB DEFAULT NULL,
            STOP_ON_QUOTA_REACH BOOLEAN NOT NULL DEFAULT 0,
            BILLING_PLAN VARCHAR(20) NOT NULL,
            PRIMARY KEY (POLICY_ID),
            UNIQUE INDEX AM_POLICY_SUBSCRIPTION_NAME_TENANT (NAME, TENANT_ID)
);

CREATE TABLE IF NOT EXISTS AM_POLICY_APPLICATION (
            POLICY_ID INT(11) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(512) NOT NULL,
            DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL,
            TENANT_ID INT(11) NOT NULL,
            DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL,
            QUOTA_TYPE VARCHAR(25) NOT NULL,
            QUOTA INT(11) NOT NULL,
            QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL,
            UNIT_TIME INT(11) NOT NULL,
            TIME_UNIT VARCHAR(25) NOT NULL,
            IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0,
			CUSTOM_ATTRIBUTES BLOB DEFAULT NULL,
            PRIMARY KEY (POLICY_ID),
            UNIQUE INDEX APP_NAME_TENANT (NAME, TENANT_ID)
);

CREATE TABLE IF NOT EXISTS AM_POLICY_HARD_THROTTLING (
            POLICY_ID INT(11) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(512) NOT NULL,
            TENANT_ID INT(11) NOT NULL,
            DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL,
            QUOTA_TYPE VARCHAR(25) NOT NULL,
            QUOTA INT(11) NOT NULL,
            QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL,
            UNIT_TIME INT(11) NOT NULL,
            TIME_UNIT VARCHAR(25) NOT NULL,
            IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0,
            PRIMARY KEY (POLICY_ID),
            UNIQUE INDEX POLICY_HARD_NAME_TENANT (NAME, TENANT_ID)
);

CREATE TABLE IF NOT EXISTS AM_API_THROTTLE_POLICY (
            POLICY_ID INT(11) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(512) NOT NULL,
            DISPLAY_NAME VARCHAR(512) NULL DEFAULT NULL,
            TENANT_ID INT(11) NOT NULL,
            DESCRIPTION VARCHAR (1024),
            DEFAULT_QUOTA_TYPE VARCHAR(25) NOT NULL,
            DEFAULT_QUOTA INTEGER NOT NULL,
            DEFAULT_QUOTA_UNIT VARCHAR(10) NULL,
            DEFAULT_UNIT_TIME INTEGER NOT NULL,
            DEFAULT_TIME_UNIT VARCHAR(25) NOT NULL,
            APPLICABLE_LEVEL VARCHAR(25) NOT NULL,
            IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0,
            PRIMARY KEY (POLICY_ID),
            UNIQUE INDEX API_NAME_TENANT (NAME, TENANT_ID)
);

CREATE TABLE IF NOT EXISTS AM_CONDITION_GROUP (
            CONDITION_GROUP_ID INTEGER NOT NULL AUTO_INCREMENT,
            POLICY_ID INTEGER NOT NULL,
            QUOTA_TYPE VARCHAR(25),
            QUOTA INTEGER NOT NULL,
            QUOTA_UNIT VARCHAR(10) NULL DEFAULT NULL,
            UNIT_TIME INTEGER NOT NULL,
            TIME_UNIT VARCHAR(25) NOT NULL,
            DESCRIPTION VARCHAR (1024) NULL DEFAULT NULL,
            PRIMARY KEY (CONDITION_GROUP_ID),
            FOREIGN KEY (POLICY_ID) REFERENCES AM_API_THROTTLE_POLICY(POLICY_ID) ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS AM_QUERY_PARAMETER_CONDITION (
            QUERY_PARAMETER_ID INTEGER NOT NULL AUTO_INCREMENT,
            CONDITION_GROUP_ID INTEGER NOT NULL,
            PARAMETER_NAME VARCHAR(255) DEFAULT NULL,
            PARAMETER_VALUE VARCHAR(255) DEFAULT NULL,
	    	IS_PARAM_MAPPING BOOLEAN DEFAULT 1,
            PRIMARY KEY (QUERY_PARAMETER_ID),
            FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS AM_HEADER_FIELD_CONDITION (
            HEADER_FIELD_ID INTEGER NOT NULL AUTO_INCREMENT,
            CONDITION_GROUP_ID INTEGER NOT NULL,
            HEADER_FIELD_NAME VARCHAR(255) DEFAULT NULL,
            HEADER_FIELD_VALUE VARCHAR(255) DEFAULT NULL,
	    	IS_HEADER_FIELD_MAPPING BOOLEAN DEFAULT 1,
            PRIMARY KEY (HEADER_FIELD_ID),
            FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS AM_JWT_CLAIM_CONDITION (
            JWT_CLAIM_ID INTEGER NOT NULL AUTO_INCREMENT,
            CONDITION_GROUP_ID INTEGER NOT NULL,
            CLAIM_URI VARCHAR(512) DEFAULT NULL,
            CLAIM_ATTRIB VARCHAR(1024) DEFAULT NULL,
	    IS_CLAIM_MAPPING BOOLEAN DEFAULT 1,
            PRIMARY KEY (JWT_CLAIM_ID),
            FOREIGN KEY (CONDITION_GROUP_ID) REFERENCES AM_CONDITION_GROUP(CONDITION_GROUP_ID) ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS AM_IP_CONDITION (
  AM_IP_CONDITION_ID INT NOT NULL AUTO_INCREMENT,
  STARTING_IP VARCHAR(45) NULL,
  ENDING_IP VARCHAR(45) NULL,
  SPECIFIC_IP VARCHAR(45) NULL,
  WITHIN_IP_RANGE BOOLEAN DEFAULT 1,
  CONDITION_GROUP_ID INT NULL,
  PRIMARY KEY (AM_IP_CONDITION_ID),
   FOREIGN KEY (CONDITION_GROUP_ID)    REFERENCES AM_CONDITION_GROUP (CONDITION_GROUP_ID)  ON DELETE CASCADE ON UPDATE CASCADE);

CREATE TABLE IF NOT EXISTS AM_POLICY_GLOBAL (
            POLICY_ID INT(11) NOT NULL AUTO_INCREMENT,
            NAME VARCHAR(512) NOT NULL,
            KEY_TEMPLATE VARCHAR(512) NOT NULL,
            TENANT_ID INT(11) NOT NULL,
            DESCRIPTION VARCHAR(1024) NULL DEFAULT NULL,
            SIDDHI_QUERY BLOB DEFAULT NULL,
            IS_DEPLOYED TINYINT(1) NOT NULL DEFAULT 0,
            PRIMARY KEY (POLICY_ID)
);

CREATE TABLE IF NOT EXISTS AM_THROTTLE_TIER_PERMISSIONS (
  THROTTLE_TIER_PERMISSIONS_ID INT NOT NULL AUTO_INCREMENT,
  TIER VARCHAR(50) NULL,
  PERMISSIONS_TYPE VARCHAR(50) NULL,
  ROLES VARCHAR(512) NULL,
  TENANT_ID INT(11) NULL,
  PRIMARY KEY (THROTTLE_TIER_PERMISSIONS_ID));

CREATE TABLE `AM_BLOCK_CONDITIONS` (
  `CONDITION_ID` int(11) NOT NULL AUTO_INCREMENT,
  `TYPE` varchar(45) DEFAULT NULL,
  `VALUE` varchar(45) DEFAULT NULL,
  `ENABLED` varchar(45) DEFAULT NULL,
  `DOMAIN` varchar(45) DEFAULT NULL,
  `UUID` VARCHAR(256),
  PRIMARY KEY (`CONDITION_ID`),
  UNIQUE (UUID)
);

-- End of API-MGT Tables --


text:
layout: post
title: "Congrats to Serena!"
date: 2018-04-30T15:04:18-07:00
categories: posts
---
Time to break the update hiatus with some good news. Serena, one of the first members to join the Visger lab, was just the Biology Laureates Endowed Scholarship.

Great job Serena!

"The Biology Laureates Endowed Scholarship Program is a renewable scholarship program for students in the Biological Sciences.  The award will cover tuition and fees for up to four years (three years for transfer students) as long as students continue to meet the renewal criteria (see below).  We are looking for students who plan to pursue a career in STEM disciplines and have the potential to be an important contributor to the community through service, leadership, and/or research."

redpajama_set_name: RedPajamaGithub


text:
import sortBy from 'lodash/sortBy';
import React, { ChangeEvent, useState } from 'react';
import Button from '../common/Button';
import HorizontalFormItem from '../common/HorizontalFormItem';
import Input from '../common/Input';
import message from '../common/message';
import Select from '../common/Select';
import { ConnectionAccess } from '../types';
import { api } from '../utilities/api';

type Edits = {
  connectionId?: string;
  userId?: string;
  duration?: string;
};

interface UserSummary {
  id: string;
  name?: string;
  email?: string;
  ldapId?: string;
}

interface Props {
  onConnectionAccessSaved: (connectionAccess: ConnectionAccess) => void;
}

function ConnectionAccessForm({ onConnectionAccessSaved }: Props) {
  const [connectionAccessEdits, setConnectionAccessEdits] = useState<Edits>({});
  const [creating, setCreating] = useState(false);

  let { data: apiConnections } = api.useConnections();
  const connections = [
    {
      id: '__EVERY_CONNECTION__',
      name: 'Every Connection',
    },
  ].concat(apiConnections || []);

  let { data: apiUsers } = api.useUsers();

  const users: UserSummary[] = [
    {
      id: '__EVERYONE__',
      email: 'Everyone',
    },
  ];

  if (apiUsers) {
    apiUsers.forEach((user) => {
      users.push({
        id: user.id,
        email: user.email,
        name: user.name,
        ldapId: user.ldapId,
      });
    });
  }

  const setConnectionAccessValue = (key: keyof Edits, value: string) => {
    setConnectionAccessEdits((prev) => ({ ...prev, [key]: value }));
  };

  const createConnectionAccess = async (event: any) => {
    // prevent the browsers default handling of submit.
    // otherwise it will bake a get request to the url of the form with the fields as params.
    event.preventDefault();

    if (creating) {
      return;
    }

    setCreating(true);
    const json = await api.post(
      '/api/connection-accesses',
      connectionAccessEdits
    );
    if (json.error) {
      setCreating(false);
      return message.error(json.error);
    }
    return onConnectionAccessSaved(json.data);
  };

  const {
    connectionId = '',
    userId = '',
    duration = '',
  } = connectionAccessEdits;

  const connectionSelectOptions = [<option key="none" value="" />];

  if (!connections.length) {
    connectionSelectOptions.push(
      <option key="loading" value="">
        Loading...
      </option>
    );
  } else {
    sortBy(connections, ['name']).forEach((connection) =>
      connectionSelectOptions.push(
        <option key={connection.id} value={connection.id}>
          {connection.name}
        </option>
      )
    );
  }

  const userSelectOptions = [<option key="none" value="" />];

  if (!users.length) {
    userSelectOptions.push(
      <option key="loading" value="">
        Loading...
      </option>
    );
  } else {
    sortBy(users, ['email']).forEach((user) =>
      userSelectOptions.push(
        <option key={user.id} value={user.id}>
          {user.email || user.name || user.ldapId}
        </option>
      )
    );
  }

  return (

      <form
        onSubmit={createConnectionAccess}
        autoComplete="off"
        style={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
        }}
      >
        <HorizontalFormItem label="Connection">
          <Select
            name="connectionId"
            value={connectionId}
            error={!connectionId}
            onChange={(event: ChangeEvent<HTMLSelectElement>) =>
              setConnectionAccessValue('connectionId', event.target.value)
            }
          >
            {connectionSelectOptions}
          </Select>
        </HorizontalFormItem>
        <HorizontalFormItem label="User">
          <Select
            name="userId"
            value={userId}
            error={!userId}
            onChange={(event: ChangeEvent<HTMLSelectElement>) =>
              setConnectionAccessValue('userId', event.target.value)
            }
          >
            {userSelectOptions}
          </Select>
        </HorizontalFormItem>
        <HorizontalFormItem label="Duration in seconds (optional)">
          <Input
            name="duration"
            value={duration}
            onChange={(e: ChangeEvent<HTMLInputElement>) =>
              setConnectionAccessValue('duration', e.target.value)
            }
          />
        </HorizontalFormItem>

          <Button
            htmlType="submit"
            style={{ width: 120 }}
            variant="primary"
            disabled={creating}
          >
            {creating ? 'Creating...' : 'Create'}
          </Button>{' '}

      </form>

  );
}

export default ConnectionAccessForm;


text:
<?php

/**
 * BaseaEvent
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 *
 * @package    asturiana
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseaEvent extends aBlogItem
{
    public function setUp()
    {
        parent::setUp();

    }
}


text:
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.stardroid.control;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.util.Log;

import com.google.android.stardroid.util.MiscUtil;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Aggregates the RealMagneticDeclinationCalculator and the
 * ZeroMagneticDeclinationCalculator and switches them in the AstronomerModel.
 *
 * @author John Taylor
 */
// TODO(johntaylor): add a unit test once we've reworked the tests to use
// the Android environment (so we can access SharePreferences).
public class MagneticDeclinationCalculatorSwitcher implements OnSharedPreferenceChangeListener {
  private static final String KEY = "use_magnetic_correction";
  private static final String TAG = MiscUtil.getTag(MagneticDeclinationCalculatorSwitcher.class);

  private MagneticDeclinationCalculator realCalculator;
  private MagneticDeclinationCalculator zeroCalculator;
  private AstronomerModel model;

  /**
   * Constructs a new MagneticDeclinationCalculatorSwitcher.
   *
   * @param model the object in which to swap the calculator
   * @param preferences a SharedPreferences object which will indicate which
   * calculator to use.
   */
  @Inject
  public MagneticDeclinationCalculatorSwitcher(
      AstronomerModel model,
      SharedPreferences preferences,
      @Named("zero") MagneticDeclinationCalculator zeroCalculator,
      @Named("real") MagneticDeclinationCalculator realCalculator) {
    this.zeroCalculator = zeroCalculator;
    this.realCalculator = realCalculator;
    this.model = model;
    preferences.registerOnSharedPreferenceChangeListener(this);
    setTheModelsCalculator(preferences);
  }

  private void setTheModelsCalculator(SharedPreferences preferences) {
    boolean useRealCalculator = preferences.getBoolean(KEY, true);
    if (useRealCalculator) {
      model.setMagneticDeclinationCalculator(realCalculator);
    } else {
      model.setMagneticDeclinationCalculator(zeroCalculator);
    }
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    // TODO(johntaylor): investigate the preferences API - currently we have too
    // many classes all hanging off SharedPreferences.
    if (KEY.equals(key)) {
      Log.i(TAG, "Magnetic declination preference changed");
      setTheModelsCalculator(sharedPreferences);
    }

  }
}


text:
import pytest
import imp

from pyhocon import ConfigFactory

from context import ModelLoader, ModelValidator, ValidationError, Precision, RandomDistribution

@pytest.fixture
def internal_conf():
    return ConfigFactory.parse_file('csaopt/internal/csaopt-internal.conf')

@pytest.fixture
def conf():
    return ConfigFactory.parse_string("""
        {
            model {
                name = testopt
                path = examples/langermann/langermann_opt.py
                skip_typecheck = True
                dimensions = 2
            }
        }
        """)

def test_build_model(conf, internal_conf, mocker):
    validator = ModelValidator()
    validator.validate_functions = mocker.stub(name='validate_functions_stub')
    loader = ModelLoader(conf, internal_conf, validator)
    model = loader.get_model()

    assert model is not None
    assert len(model.functions) == 6
    validator.validate_functions.assert_called_once()

def test_validator_has_errors(conf, internal_conf, mocker):
    validator = ModelValidator()
    validator.validate_functions = mocker.Mock(return_value=[ValidationError('this is a test error')])
    loader = ModelLoader(conf, internal_conf, validator)
    model = loader.get_model()

    assert model is None
    assert len(loader.errors) == 1

def test_should_run_type_check(conf, internal_conf, mocker):
    conf['model']['skip_typecheck'] = False

    validator = ModelValidator()
    validator.validate_functions = mocker.stub(name='validate_functions_stub')
    validator.validate_typing = mocker.stub(name='validate_typing_stub')

    ModelLoader(conf, internal_conf, validator)
    validator.validate_functions.assert_called_once()
    validator.validate_typing.assert_called_once()

def test_loading_py_model_failed(conf, internal_conf, mocker):
    mocker.patch('imp.load_source', return_value=None)

    validator = ModelValidator()
    validator.validate_functions = mocker.stub(name='validate_functions_stub')

    with pytest.raises(AssertionError):
        ModelLoader(conf, internal_conf, validator)

    imp.load_source.assert_called_once_with('testopt', 'examples/langermann/langermann_opt.py')

def test_globals(conf, internal_conf, mocker):
    validator = ModelValidator()
    validator.validate_functions = mocker.stub(name='validate_functions_stub')
    validator.validate_typing = mocker.stub(name='validate_typing_stub')

    loader = ModelLoader(conf, internal_conf, validator)
    validator.validate_functions.assert_called_once()

    model = loader.get_model()
    assert 'm = 5' in model.globals
    assert 'c = (1, 2, 5, 2, 3)' in model.globals
    assert 'A = ((3, 5), (5, 2), (2, 1), (1, 4), (7, 9))' in model.globals

    assert 'from math import pi' not in model.globals

def test_model_params(conf, internal_conf, mocker):
    validator = ModelValidator()
    validator.validate_functions = mocker.stub(name='validate_functions_stub')
    validator.validate_typing = mocker.stub(name='validate_typing_stub')

    loader = ModelLoader(conf, internal_conf, validator)
    validator.validate_functions.assert_called_once()

    model = loader.get_model()
    assert Precision.Float32 == model.precision
    assert RandomDistribution.Uniform == model.distribution
    assert 2 == model.dimensions


text:
require "feature_system/engine"
require "feature_system/provides"

module FeatureSystem
end


text:
PROJECT = 'openstack_fabric_enabler'

VERSION = '1.0'

from setuptools import setup, find_packages

try:
    long_description = open('README.txt', 'rt').read()
except IOError:
    long_description = ''

with open('requirements.txt', 'r') as f:
    requires = [x.strip() for x in f if not x.startswith('#') and x.strip()]

setup(
    name=PROJECT,
    version=VERSION,
    description='Fabric enabler for openstack',
    long_description=long_description,
    platforms=['Any'],
    scripts=[],
    provides=[],
    namespace_packages=[],
    packages=find_packages(exclude=['tests']),
    include_package_data=True,
    install_requires=requires,
    data_files=[('/etc/saf', ['enabler_conf.ini'])],
    entry_points={
        'console_scripts': [
            'fabric-enabler-server = dfa.dfa_enabler_server:dfa_server',
            'fabric-enabler-agent = dfa.dfa_enabler_agent:dfa_agent',
            'fabric-enabler-cli = dfa.dfa_cli:dfa_cli',
        ],
        'services.firewall.native.drivers': [
            'phy_asa = dfa.server.services.firewall.native.drivers.phy_asa:PhyAsa',
            'native = dfa.server.services.firewall.native.drivers.native:NativeFw',
        ]
    },
    zip_safe=False,
)


text:
import bisect
from hashlib import md5
from pygments.token import Token
from ni.actions.base import EditAction

# Basically a view wraps a document and remembers stuff like the scrolling
# position, the cursor position, the selection and so on. That's so that some
# editors can do stuff like have multiple views open on the same document.
# This is just an interface and actual editors should inherit from View.

# TODO: these should probably be pluggable per mode
OPEN_BRACKETS = {
    u'{': u'}',
    u'(': u')',
    u'[': u']',
}
CLOSE_BRACKETS = {
    u'}': u'{',
    u')': u'(',
    u']': u'[',
}

def find_bracket_in_token(tvalue, token_offset, cursor_offset):
    """
    Find the position of the bracket character in the multi-char punctuation
    token that's at the cursor position.
    """

    brackets = set(OPEN_BRACKETS.keys()+CLOSE_BRACKETS.keys())
    for i, char in enumerate(tvalue):
        if token_offset+i == cursor_offset-1:
            if char in brackets:
                return char, i
    return None

def fake_punc_tokens(tokens, index, char_offset):
    """
    A generator that returns the tokens from pos onwards. It turns multi-
    character punctuation tokens into 'fake' one-char tokens and sets offset
    for the position inside that token. It skips the first offset chars of the
    first multi-char punctuation token or the first token, because that one was
    the one that matched (the opening bracket).
    """

    total_tokens = len(tokens)
    is_first = True

    while index < total_tokens:
        ttype, tvalue = tokens[index]
        if ttype is Token.Punctuation:
            for i, char in enumerate(tvalue):
                if not is_first or i > char_offset:
                    yield ttype, char, index, i

        else:
            if not is_first:
                yield ttype, tvalue, index, 0

        is_first = False
        index += 1

def fake_punc_tokens_reverse(tokens, index, char_offset):
    """
    Similar to fake_punc_tokens, but in reverse (for closing brackets)
    """

    is_first = True

    while index >= 0:
        ttype, tvalue = tokens[index]
        if ttype is Token.Punctuation:
            for i, char in reversed(list(enumerate(tvalue))):
                if not is_first or i < char_offset:
                    yield ttype, char, index, i

        else:
            if not is_first:
                yield ttype, tvalue, index, 0

        is_first = False
        index -= 1

class View(object):
    def __init__(self, editor, document):
        self.editor = editor
        self.document = document
        self.cursor_pos = (0, 0) # or should this change to offset?
        self.scroll_pos = (0, 0)
        self.last_x_pos = 0 # This is not the index into the line, but the
                            # position on screen after tabs are taken into
                            # account so that we can get the cursor as close
                            # to it as possible when we navigate around.
        self.selection = None

        self.previous_action = None

    def invalidate(self):
        raise NotImplemented

    def _get_textbox_dimensions(self):
        raise NotImplemented
    textbox_dimensions = property(_get_textbox_dimensions)

    def _get_page_size(self):
        raise NotImplemented
    page_size = property(_get_page_size)

    def calculate_brackets(self):
        """
        Set self.brackets to the (x, y) position of the matching bracket.

        (Actually self.brackets is a sequence of all the positions to hilight,
         but for now it is always zero length)
        """

        # clear brackets so that if we short-circuit later it is safe
        self.brackets = []

        cy, cx = self.cursor_pos

        if cx == 0:
            return # start of the line guaranteed not to match

        # cache some lookups
        cursor_pos = self.cursor_pos
        doc = self.document
        tokenizer = doc.tokenizer
        tokens = tokenizer.tokens
        offsets = tokenizer.offsets

        def find_offset(offsets, offset):
            pos = bisect.bisect_left(offsets, offset)
            if pos >= len(offsets):
                # bisect_left might return an index outside of the list
                pos = len(offsets)-1
            elif offsets[pos] > offset:
                # if the offset of the line index bist_left returns is after the
                # offset we're looking for, use the previous line
                pos -= 1
            return pos

        # find the index in offsets that refers to the token that contains the
        # character under the cursor
        cursor_offset = doc.cursor_pos_to_offset(cursor_pos)
        index = find_offset(offsets, cursor_offset)
        # we look at the previous token to find the relevant bracket
        index -= 1
        ttype, tvalue = tokens[index]
        if not ttype is Token.Punctuation:
            return

        # sometimes the tokenizer will return adjacent punctuation tokens
        # grouped into one, so we have to find the token inside that
        token_offset = offsets[index]
        r = find_bracket_in_token(tvalue, token_offset, cursor_offset)
        if not r:
            # shouldn't realistically happen, but you never know
            # what any of the many lexers out there will do..
            return
        bracket, char_offset = r

        if OPEN_BRACKETS.has_key(bracket):
            matching = OPEN_BRACKETS[bracket]

            # For now we lex to the end so that we know that everything
            # is there to be checked.
            # TODO: This should be easy to optimise..
            doc.update_tokens(self.scroll_pos,
                              self.textbox_dimensions,
                              to_end=True)

            stack = 0
            for r in fake_punc_tokens(tokens, index, char_offset):
                ttype, tvalue, index, char_offset = r
                if ttype is Token.Punctuation:
                    if tvalue == bracket:
                        stack += 1
                    elif tvalue == matching:
                        if stack > 0:
                            stack -= 1
                        else:
                            token_offset = offsets[index]
                            if token_offset:
                                bracket_offset = token_offset+char_offset
                            self.brackets = (bracket_offset,)
                            return

        elif CLOSE_BRACKETS.has_key(bracket):
            matching = CLOSE_BRACKETS[bracket]

            stack = 0
            for r in fake_punc_tokens_reverse(tokens, index, char_offset):
                ttype, tvalue, index, char_offset = r
                if ttype is Token.Punctuation:
                    if tvalue == bracket:
                        stack += 1
                    elif tvalue == matching:
                        if stack > 0:
                            stack -= 1
                        else:
                            token_offset = offsets[index]
                            if token_offset:
                                bracket_offset = token_offset+char_offset
                            self.brackets = (bracket_offset,)
                            return

        else:
            return

    def check_cursor(self):
        """
        Make sure the cursor is on the screen and scroll if necessary.
        """

        doc = self.document

        maxcol, maxrow = self.textbox_dimensions
        y, x = self.cursor_pos
        topy, topx = self.scroll_pos

        # sanity checks
        if x < 0:
            x = 0
        if y < 0:
            y = 0
        if topx < 0:
            topx = 0
        if topy < 0:
            topy = 0

        if x < topx:
            topx = x
        if y < topy:
            topy = y
        if x >= (topx+maxcol-1):
            topx = x - maxcol + 2
        if y >= (topy+maxrow-1):
            topy = y - maxrow + 2

        # don't scroll too far:
        if topy > doc.num_lines-maxrow+2:
            topy = doc.num_lines-maxrow+2

        if topx < 0:
            topx = 0

        if topy < 0:
            topy = 0

        line = doc.get_line(y)
        if len(line) < maxcol:
            topx = 0

        self.cursor_pos = y, x
        self.scroll_pos = topy, topx

    def execute_action(self, action):
        """
        Common code for executing an action. Actual editors will almost
        certainly do stuff before and after calling this.
        """

        # group similar actions so that we can undo/redo them together
        # TODO: is hash() safe in this context?
        if isinstance(action, type(self.previous_action)):
            if self.previous_action.grouped:
                action.grouped = hash(self.previous_action.grouped)
            else:
                self.previous_action.grouped = hash(self.previous_action)
                action.grouped = hash(self.previous_action)

        action.execute()
        if isinstance(action, EditAction):
            self.document.undo_stack.push(action)
            self.document.redo_stack.clear()

        self.previous_action = action

        self.check_cursor()


text:
namespace StarTrek {

StarTrek::Game::Game() : e_(10000), t_(8) {
}

void Game::fireWeapon(Untouchables::WebGadget* wg) {
	if (wg->parameter("command") == "phaser") {
		int amount = atoi(wg->parameter("amount").c_str());
		Klingon* enemy = (Klingon*)wg->variable("target");
		if (e_ >= amount) {
			int distance = enemy->distance();
			if (distance > 4000) {
				stringstream message;
				message << "Klingon out of range of phasers at " << distance << " sectors...";
				wg->writeLine(message.str());
			} else {
				int damage = amount - (((amount /20)* distance /200) + rnd(200));
				if (damage < 1)
					damage = 1;
				stringstream message;
				message << "Phasers hit Klingon at " << distance << " sectors with " << damage << " units";
				wg->writeLine(message.str());
				if (damage < enemy->energy()) {
					enemy->energy(enemy->energy() - damage);
					stringstream message;
					message << "Klingon has " << enemy->energy() << " remaining";
					wg->writeLine(message.str());
				} else {
					wg->writeLine("Klingon destroyed!");
					enemy->destroy();
				}
			}
			e_ -= amount;

		} else {
			wg->writeLine("Insufficient energy to fire phasers!");
		}

	} else if (wg->parameter("command") == "photon") {
		Klingon* enemy = (Klingon*)wg->variable("target");
		if (t_ > 0) {
			int distance = enemy->distance();
			if ((rnd(4) + ((distance / 500) + 1) > 7)) {
				stringstream message;
				message << "Torpedo missed Klingon at " << distance << " sectors...";
				wg->writeLine(message.str());
			} else {
				int damage = 800 + rnd(50);
				stringstream message;
				message << "Photons hit Klingon at " << distance << " sectors with " << damage << " units";
				wg->writeLine(message.str());

				if (damage < enemy->energy()) {
					enemy->energy(enemy->energy() - damage);
					stringstream message;
					message << "Klingon has " << enemy->energy() << " remaining";
					wg->writeLine(message.str());
				} else {
					wg->writeLine("Klingon destroyed!");
					enemy->destroy();
				}
			}
			t_--;

		} else {
			wg->writeLine("No more photon torpedoes!");
		}
	}
}
}


text:
package nl.stokpop.lograter.processor.latency;

import nl.stokpop.lograter.counter.CounterKey;
import nl.stokpop.lograter.logentry.LatencyLogEntry;
import nl.stokpop.lograter.processor.CounterKeyCreator;
import nl.stokpop.lograter.util.linemapper.LineMap;

import java.util.List;

public class LatencyCounterKeyCreator implements CounterKeyCreator<LatencyLogEntry> {

    private final List<String> groupByFields;

    public LatencyCounterKeyCreator(final List<String> groupByFields) {
        this.groupByFields = groupByFields;
    }

    @Override
    public final CounterKey createCounterKey(final LatencyLogEntry entry) {
        return createCounterKey(entry, counterKeyBaseName(entry));
    }

    @Override
    public final CounterKey createCounterKey(final LatencyLogEntry entry, final LineMap lineMap) {
        return createCounterKey(entry, counterKeyBaseName(entry, lineMap));
    }

    @Override
    public final CounterKey createCounterKey(final LatencyLogEntry entry, final String baseName) {
        return constructCounterKey(entry, baseName, groupByFields);
    }

    public String counterKeyBaseName(LatencyLogEntry entry) {
        return entry.getMessage();
    }

    private String counterKeyBaseName(LatencyLogEntry entry, LineMap lineMap) {
        return lineMap.getNameWithReplacementsFromLine(entry.getMessage());
    }

}


text:
/* eslint-disable no-unused-vars, func-names */

const FileUploadSignatureResult = `
  type FileUploadSignatureResult {
    url: String!
  }
`;

const FileToUpload = `
  input FileToUpload {
    collectionId: String!
    collectionName: String!
    fileName: String!
    contentType: String!
  }
`;

const FileUploadSignatureQuery = `
  extend type Query {
    fileUploadSignature(input: FileToUpload!): FileUploadSignatureResult
  }
`;

module.exports = function () {
  return [FileUploadSignatureResult, FileToUpload, FileUploadSignatureQuery];
};


text:
package org.apache.ambari.server.controller;

/**
 * RootComponent is an enumeration of root-level components.
 */
public enum RootComponent {
  AMBARI_SERVER,
  AMBARI_AGENT
}


text:
package io.github.resilience4j.bulkhead.autoconfigure;

import io.github.resilience4j.TestUtils;
import io.github.resilience4j.bulkhead.BulkheadRegistry;
import io.github.resilience4j.bulkhead.ThreadPoolBulkheadRegistry;
import io.github.resilience4j.bulkhead.configure.BulkheadAspect;
import io.github.resilience4j.bulkhead.configure.BulkheadAspectExt;
import io.github.resilience4j.bulkhead.configure.BulkheadConfiguration;
import io.github.resilience4j.bulkhead.event.BulkheadEvent;
import io.github.resilience4j.consumer.DefaultEventConsumerRegistry;
import io.github.resilience4j.consumer.EventConsumerRegistry;
import io.github.resilience4j.fallback.FallbackExecutor;
import io.github.resilience4j.spelresolver.SpelResolver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import static org.junit.Assert.assertEquals;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
    BulkheadConfigurationOnMissingBeanTest.ConfigWithOverrides.class,
    BulkheadAutoConfiguration.class,
    BulkheadConfigurationOnMissingBean.class
})
@EnableConfigurationProperties(BulkheadProperties.class)
public class BulkheadConfigurationOnMissingBeanTest {

    @Autowired
    private ConfigWithOverrides configWithOverrides;

    @Autowired
    private BulkheadRegistry bulkheadRegistry;

    @Autowired
    private BulkheadAspect bulkheadAspect;

    @Autowired
    private EventConsumerRegistry<BulkheadEvent> bulkheadEventEventConsumerRegistry;

    @Test
    public void testAllBeansFromBulkHeadHasOnMissingBean() throws NoSuchMethodException {
        final Class<BulkheadConfiguration> originalClass = BulkheadConfiguration.class;
        final Class<BulkheadConfigurationOnMissingBean> onMissingBeanClass = BulkheadConfigurationOnMissingBean.class;
        TestUtils.assertAnnotations(originalClass, onMissingBeanClass);
    }

    @Test
    public void testAllBulkHeadConfigurationBeansOverridden() {
        assertEquals(bulkheadRegistry, configWithOverrides.bulkheadRegistry);
        assertEquals(bulkheadAspect, configWithOverrides.bulkheadAspect);
        assertEquals(bulkheadEventEventConsumerRegistry,
            configWithOverrides.bulkheadEventEventConsumerRegistry);
    }

    @Configuration
    public static class ConfigWithOverrides {

        private BulkheadRegistry bulkheadRegistry;

        private BulkheadAspect bulkheadAspect;

        private EventConsumerRegistry<BulkheadEvent> bulkheadEventEventConsumerRegistry;

        @Bean
        public BulkheadRegistry bulkheadRegistry() {
            bulkheadRegistry = BulkheadRegistry.ofDefaults();
            return bulkheadRegistry;
        }

        @Bean
        public BulkheadAspect bulkheadAspect(
            BulkheadRegistry bulkheadRegistry,
            ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry,
            @Autowired(required = false) List<BulkheadAspectExt> bulkheadAspectExts,
            FallbackExecutor fallbackExecutor,
            SpelResolver spelResolver
        ) {
            bulkheadAspect = new BulkheadAspect(new BulkheadProperties(),
                threadPoolBulkheadRegistry, bulkheadRegistry, bulkheadAspectExts,
                fallbackExecutor, spelResolver);
            return bulkheadAspect;
        }

        @Bean
        public EventConsumerRegistry<BulkheadEvent> bulkheadEventConsumerRegistry() {
            bulkheadEventEventConsumerRegistry = new DefaultEventConsumerRegistry<>();
            return bulkheadEventEventConsumerRegistry;
        }
    }
}


text:
var porta = 3000,
    uri = "http://localhost:" + porta;

function startLoadingActivity(elementId) {
    document.getElementById(elementId).innerHTML = '
' +
        '
' +
        '
' +
        '

' +
        '
' +
        '

' +
        '
' +
        '

';
}

function stopLoadingActivity(elementId) {
    document.getElementById(elementId).innerHTML = '';
}

function timestampSort(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = i; j < arr.length; j++) {
            if (arr[i]['timestamp'] > arr[j]['timestamp']) {
                var aux = arr[i];
                arr[i] = arr[j];
                arr[j] = aux;
            }
        }
    }
    return arr;
}

function insertBloco(obj, cont) {
    var lista = obj["$class"].split(".");
    var content = "

#" + cont + "

" + lista[lista.length - 1] + "

";
    $(".tRow").prepend(content);
}

function getBlockchain() {
    $(".blockchain").css("padding-left", "0px");
    $("#erroBlockchain").addClass("hide");
    $("#erroBlockchain").removeClass("animated flash");
    $("#loaderBlockchain").removeClass("hide");
    $("#overBlockchain").removeClass("hide");
    $(".table").addClass("hide");
    startLoadingActivity("loaderBlockchain");
    $(".tRow").html("");
    $.ajax({
        url: uri + "/api/system/transactions",
        error: function () {
            stopLoadingActivity("loaderBlockchain");
            $("#loaderBlockchain").addClass("hide");
            $("#erroBlockchain").removeClass("hide");
            $("#erroBlockchain").addClass("animated flash");
        },
        success: function (data) {
            stopLoadingActivity("loaderBlockchain");
            $("#loaderBlockchain").addClass("hide");
            $("#overBlockchain").addClass("hide");
            $(".blockchain").css("padding-left", "75px");
            $(".table").removeClass("hide");
            data = timestampSort(data);
            for (var i in data) {
                insertBloco(data[i], i);
            }
        },
        timeout: 5000
    })
}

function getBloco(elem) {
    var id = $(elem).attr("idBloco"),
    cont = $($(elem).children()[0]).attr("numBloco");
    $("#numBloco").addClass("hide");
    $("#informacoes").addClass("hide");
    $("#loaderBloco").removeClass("hide");
    startLoadingActivity("loaderBloco");
    $.ajax({
        url: uri + "/api/system/transactions/" + id,
        error: function () {
            stopLoadingActivity("loaderBloco");
            $("#loaderBloco").addClass("hide");
            $("#erroBloco").removeClass("hide");
            $("#erroBloco").addClass("animated flash");
            setTimeout(function () {
                $("#erroBloco").removeClass("animated flash");
                $("#erroBloco").addClass("hide");
                $("#numBloco").removeClass("hide");
                $("#informacoes").removeClass("hide");
            }, 4000)
        },
        success: function (data) {
            $("#numBloco").html("
" + cont + "
");
            var content = "
{
";
            var keys = Object.keys(data);
            for (var i of keys) {
                if (typeof data[i] == 'object') {
                    if (data[i].constructor === Array) {
                        content += "
" + i + " : [
";
                        content += "
";
                        for (var j of data[i]) {
                            if (typeof data[i] == 'object') {
                                content += "{
"
                                keys3 = Object.keys(j);
                                for(var l of keys3){
                                    content += "
" + l + " : "+j[l]+"
";
                                }
                                content += "
},"
                            } else {
                                content += j+", ";
                            }
                        }
                        content+="

],
";
                    } else {
                        var keys2 = Object.keys(data[i])
                        content += "
{
"
                        for(var j of keys2){
                            content += "
" + i + " : " + data[i][j] + ",
"
                        }
                        content += "
},
"
                    }
                } else {
                    content += "
" + i + " : " + data[i] + ",
";
                }
            }
            content += "
}
"
            stopLoadingActivity("loaderBloco");
            $("#loaderBloco").addClass("hide");
            $("#informacoes").html(content);
            $("#numBloco").removeClass("hide");
            $("#informacoes").removeClass("hide");
        },
        timeout: 5000
    })
}

function getCargos() {
    $("select").prop("disabled", null);
    $("select").html("<option value='' disabled selected>Carregando Cargos...</option>");
    $.ajax({
        url: uri + "/api/Cargo",
        error: function () {
            $("select").html("<option value='' disabled selected>Erro ao carregar cargos, atualize a pagina</option>");
            $('select').material_select();
        },
        success: function (data) {
            var content = "<option value='' disabled selected>Selecione um cargo</option>";
            for (var i of data) {
                content += "<option value='" + i.cargoId + "'>" + i.DescCargo + "</option>";
            }
            $("select").html(content);
            $('select').material_select();
        },
        timeout: 5000
    })
}

function apurar(id) {
    var timestamp = new Date(Date.now()),
        apuracao = {
            "$class": "org.acme.model.Apuracao",
            "cargo": id,
            "timestamp": timestamp
        };
    $("#resultado").addClass("hide");
    $("#loaderApur").removeClass("hide");
    startLoadingActivity("loaderApur");

    $.ajax({
        url: uri + "/api/Apuracao",
        data: apuracao,
        method: "POST",
        error: function () {
            $("#loaderApur").addClass("hide");
            stopLoadingActivity("loaderApur");
            $("#infoErroApur").html("Erro ao realizar apuração");
            $("#erroApur").removeClass("hide");
            $("#errorApur").addClass("animated flash");
            setTimeout(function () {
                $("#erroApur").removeClass("animated flash");
                $("#erroApur").addClass("hide");
                $("#numBloco").removeClass("hide");
                $("#informacoes").removeClass("hide");
            }, 4000)
        },
        success: function (data) {
            $.ajax({
                url: uri + "/api/Cargo/" + id,
                error: function () {
                    $("#loaderApur").addClass("hide");
                    stopLoadingActivity("loaderApur");
                    $("#infoErroApur").html("Erro ao encontrar eleito");
                    $("#erroApur").removeClass("hide");
                    $("#errorApur").addClass("animated flash");
                    setTimeout(function () {
                        $("#erroApur").removeClass("animated flash");
                        $("#erroApur").addClass("hide");
                        $("#numBloco").removeClass("hide");
                        $("#informacoes").removeClass("hide");
                    }, 4000)
                },
                success: function (data2) {
                    $("#loaderApur").addClass("hide");
                    stopLoadingActivity("loaderApur");
                    $("#ganhador").text(data2.eleitos[0].split("#")[1]);
                    $("#resultado").removeClass("hide");
                },
                timeout: 5000
            })
        },
        timeout: 7000
    })
}

$(document).ready(function () {
    getCargos();
    getBlockchain();
    $('select').material_select();
    $("#botaoRefresh").click(function () {
        getBlockchain();
    });
    $(".btnEnviar").click(function () {
        apurar($("select").val());
    })
})


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package Bio::EnsEMBL::Production::Pipeline::PipeConfig::Flatfile_conf;

use strict;
use warnings;

use base ('Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf');

use Bio::EnsEMBL::ApiVersion qw/software_version/;

sub default_options {
    my ($self) = @_;

    return {
      # inherit other stuff from the base class
      %{ $self->SUPER::default_options() },

      ### OVERRIDE

      #'registry' => 'Reg.pm', # default option to refer to Reg.pm, should be full path
      #'base_path' => '', #where do you want your files

      ### Optional overrides
      species => [],

      release => software_version(),

      types => [],

      ### Defaults

      pipeline_name => 'flatfile_dump_'.$self->o('release'),

      email => $self->o('ENV', 'USER').'@sanger.ac.uk',

    };
}

sub pipeline_create_commands {
    my ($self) = @_;
    return [
      # inheriting database and hive tables' creation
      @{$self->SUPER::pipeline_create_commands},
    ];
}

## See diagram for pipeline structure
sub pipeline_analyses {
    my ($self) = @_;

    return [

      {
        -logic_name => 'ScheduleSpecies',
        -module     => 'Bio::EnsEMBL::Production::Pipeline::SpeciesFactory',
        -parameters => {
          species => $self->o('species'),
          randomize => 1,
        },
        -input_ids  => [ {} ],
        -flow_into  => {
          1 => 'Notify',
          2 => ['DumpTypeFactory'],
        },
      },

      ######### DUMPING DATA

      {
        -logic_name => 'DumpTypeFactory',
        -module     => 'Bio::EnsEMBL::Production::Pipeline::Flatfile::DumpTypeFactory',
        -parameters => {
          types => $self->o('types'),
        },
        -flow_into  => {
          2 => { 'DumpFlatfile' => { species => "#species#", type => "#type#" },
		 'CheckFlatfile' => { species => "#species#", type => "#type#" },
                 'ChecksumGenerator' => { species => "#species#", type => "#type#" },
          },
        },
      },

      {
        -logic_name => 'DumpFlatfile',
        -module     => 'Bio::EnsEMBL::Production::Pipeline::Flatfile::DumpFile',
        -max_retry_count  => 1,
        -analysis_capacity => 10,
        -rc_name => 'dump',
      },

      ####### CHECK

      {
       -logic_name => 'CheckFlatfile',
       -module     => 'Bio::EnsEMBL::Production::Pipeline::Flatfile::CheckFlatfile',
       -wait_for   => [qw/DumpFlatfile/],
       -analysis_capacity => 15,
       -rc_name => 'check',
      },

      {
        -logic_name => 'ChecksumGenerator',
        -module     => 'Bio::EnsEMBL::Production::Pipeline::Flatfile::ChecksumGenerator',
        -wait_for   => [qw/DumpFlatfile/],
        -analysis_capacity => 10,
      },

      ####### NOTIFICATION

      {
        -logic_name => 'Notify',
        -module     => 'Bio::EnsEMBL::Hive::RunnableDB::NotifyByEmail',
        -parameters => {
          email   => $self->o('email'),
          subject => $self->o('pipeline_name').' has finished',
          text    => 'Your pipeline has finished. Please consult the hive output'
        },
        -wait_for   => [qw/ CheckFlatfile ChecksumGenerator /],
      }

    ];
}

sub pipeline_wide_parameters {
    my ($self) = @_;

    return {
        %{ $self->SUPER::pipeline_wide_parameters() },  # inherit other stuff from the base class
        base_path => $self->o('base_path'),
        release => $self->o('release'),
    };
}

# override the default method, to force an automatic loading of the registry in all workers
sub beekeeper_extra_cmdline_options {
    my $self = shift;
    return "-reg_conf ".$self->o("registry");
}

sub resource_classes {
    my $self = shift;
    return {
      %{$self->SUPER::resource_classes()},
      dump => { 'LSF' => '-q normal -M1500 -R"select[mem>1500] rusage[mem=1500]"'},
      check => { 'LSF' => '-q normal -M500 -R"select[mem>500] rusage[mem=500]"'},
    }
}

1;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Warnings on Admin Page — ownCloud Server Administration Manual 8.1 documentation</title>

    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />

    <link rel="top" title="ownCloud Server Administration Manual 8.1 documentation" href="../index.html" />
    <link rel="up" title="ownCloud Server Configuration" href="index.html" />
    <link rel="next" title="Using the occ Command" href="occ_command.html" />
    <link rel="prev" title="ownCloud Server Configuration" href="index.html" />

ownCloud Server Administration Manual

Table of Contents

ownCloud 8.1 Server Administration Manual Introduction

ownCloud 8.1 Release Notes

What’s New for Admins in ownCloud 8

Installation

User Management

File Sharing and Management

ownCloud Server Configuration

Warnings on Admin Page

Cache Warnings

You are accessing this site via HTTP

Using the occ Command

Configuring the Activity App

Configuring the ClamAV Antivirus Scanner

Automatic Configuration Setup

Defining Background Jobs

Config.php Parameters

Email Configuration

Linking External Sites

JavaScript and CSS Asset Management

Knowledge Base Configuration

Language Configuration

Logging Configuration

Hardening and Security Guidance

Server Tuning & Performance Tips

Reverse Proxy Configuration

Enabling Full-Text Search

Using Third Party PHP Components

Database Configuration

Maintenance

Operations

Issues and Troubleshooting

ownCloud Videos

Enterprise Subscription Installation (ES Only)

Creating Branded ownCloud Clients (ES only)

External Storage (ES only)

User Management (ES only)

Enabling Anonymous Uploads with Files Drop (ES Only)

Warnings on Admin Page¶

Your ownCloud server has a built-in configuration checker, and it reports its
findings at the top of your Admin page. These are some of the warnings you
might see, and what to do about them.

Cache Warnings¶

“No memory cache has been configured. To enhance your performance please
configure a memcache if available.” ownCloud supports multiple php caching
extentions:

APC

APCu (minimum required php extension version: 4.0.6)

Memcached

Redis (minimum required php extension version: 2.2.5)

Xcache

You will see this warning if you have no caches installed or if your cache
does not have the required minimum version installed; older versions are
disabled because of performance problems.

If you see “{Cache} below version {Version} is installed. for stability and
performance reasons we recommend to update to a newer {Cache} version” then
you need to upgrade, or, if you’re not using it, remove it.

It is not required to use any caches, but caches improve server performance. See
Server Tuning & Performance Tips for more information on installing and using caches.

You are accessing this site via HTTP¶

“You are accessing this site via HTTP. We strongly suggest you configure your
server to require using HTTPS instead.” Please take this warning seriously;
using HTTPS is a fundamental security measure. You must configure your Web
server to support it, and then there are some settings in the Security
section of your ownCloud Admin page to enable. The following manual pages
describe how to enable HTTPS on the Apache and Nginx Web servers.

Enabling SSL (on Apache)

Use HTTPS

Nginx
Configuration


text:
package datasource

import (
	"github.com/zupzup/calories/model"
)

// DataSource is the interface to the data layer
type DataSource interface {
	Setup(connection string) (func() error, error)
	SetConfig(*model.Config) error
	FetchConfig() (*model.Config, error)
	AddWeight(weight float64) error
	CurrentWeight() (*model.Weight, error)
	FetchWeights() ([]model.Weight, error)
	AddEntry(entryDate string, calories int, food string) error
	FetchEntries(entryDate string) (model.Entries, error)
	FetchAllEntries() (model.Entries, error)
	RemoveEntries(entryDate string) error
	RemoveEntry(entryDate string, id int) error
	Import(data *model.ImpEx) error
	Export() (*model.ImpEx, error)
}


text:
FULLCALENDAR_FILE_PATH = Rails.root.join('config', 'fullcalendar.yml')
config = File.exists?(FULLCALENDAR_FILE_PATH) ? YAML.load_file(FULLCALENDAR_FILE_PATH) || {} : {}
FullcalendarEngine::Configuration = {
  'editable'    => true,
  'header'      => {
    left: 'prev,next today',
    center: 'title',
    right: 'month,agendaWeek,agendaDay'
  },
  'defaultView' => 'agendaWeek',
  'height'      => 500,
  'slotMinutes' => 15,
  'dragOpacity' => 0.5,
  'selectable'  => true,
  'timeFormat'  => "h:mm t{ - h:mm t}"
}
FullcalendarEngine::Configuration.merge!(config)
FullcalendarEngine::Configuration['events'] = "#{FullcalendarEngine::Configuration['mount_path']}/events/get_events"


text:
#include <string>
#include <exception>
#include <stdexcept>

#include "cashka-cli.h"

using std::string;
using std::invalid_argument;

namespace cashka_cli
{
	/**
	 * Сгенерировать исключение
	 *
	 * @param string type
	 * @param string message
	 * @return void
	 */
	void err (string message, string type)
	{
		if (type == "default")
		{

		}
		else if (type == "cli")
		{
			message = (string)"Командная строка. " + message;
		}
		else if (type == "config")
		{
			message = (string)"Конфигурационный файл. " + message;
		}

		throw invalid_argument (message);
	}
}


text:
package patterns.creational.singleton.example4;

public class Singleton {

    private Singleton() {}

    private static class SingletonHelper {

        //Nested class is referenced after getCaptain() is called
        private static final Singleton SINGLETON = new Singleton();

    }

    public static Singleton getINSTANCE() {
        return SingletonHelper.SINGLETON;
    }

}


text:
BUILD=	alloc.html bigfile.html conflict.html disk.html getswap.html \
	gettype.html intro.html memp_fget.html rpc.html shared.html \
	toc.html txn_prepare.html

all: ${BUILD}


text:
package com.yjz.microweb.session;

import java.util.Set;

public interface Session {

	public String getSid();

	public long getCreationTime();

	public long getLastAccessedTime();

	public long getMaxActiveTime();

	public void setMaxActiveTime(long maxActiveTime);

	public Object getAttribute(String name);

	public Session setAttribute(String name, Object value);

	public Session removeAttribute(String name);

	public Set<String> getAttributeNames();

	public void invalidate();

	public boolean isNew();

	public boolean update();

}


text:
#ifndef  COCO_ERRORPOOL_H
#define  COCO_ERRORPOOL_H

#ifndef   COCO_CDEFS_H
#include  "CDefs.h"
#endif

EXTC_BEGIN

struct CcsLocation_s {
    const char * fname;
    int line;
    int col;
};

struct CcsErrorPool_s {
    FILE * fp;
    int    warningCount;
    int    errorCount;
};

CcsErrorPool_t * CcsErrorPool(CcsErrorPool_t * self, FILE * fp);
void CcsErrorPool_Destruct(CcsErrorPool_t * self);

void CcsErrorPool_Info(CcsErrorPool_t *, const char * format, ...);
/* token == NULL is permitted. */
void CcsErrorPool_Warning(CcsErrorPool_t * self, const CcsLocation_t * token,
			  const char * format, ...);
void CcsErrorPool_VWarning(CcsErrorPool_t * self, const CcsLocation_t * token,
			   const char * format, va_list ap);
void CcsErrorPool_Error(CcsErrorPool_t * self, const CcsLocation_t * token,
			const char * format, ...);
void CcsErrorPool_VError(CcsErrorPool_t * self, const CcsLocation_t * token,
			 const char * format, va_list ap);
void CcsErrorPool_Fatal(CcsErrorPool_t * self, const CcsLocation_t * token,
			const char * format, ...);
void CcsErrorPool_VFatal(CcsErrorPool_t * self, const CcsLocation_t * token,
			 const char * format, va_list ap);
EXTC_END

#endif /* COCO_ERRORPOOL_H */


text:
from django.core.management.base import BaseCommand

import olympia.core.logger

from olympia import amo
from olympia.reviewers.models import AutoApprovalSummary

log = olympia.core.logger.getLogger('z.reviewers.recalculate_weights')

class Command(BaseCommand):
    help = 'Recalculate post-review weights for unconfirmed auto-approvals.'

    def handle(self, *args, **options):
        qs = AutoApprovalSummary.objects.filter(
            confirmed=False, verdict=amo.AUTO_APPROVED)
        for summary in qs:
            log.info('Recalculating weight for %s', summary)
            old_weight = summary.weight
            summary.calculate_weight()
            if summary.weight != old_weight:
                log.info('Saving weight change (from %d to %d) for %s',
                         old_weight, summary.weight, summary)
                summary.save()


text:
using System.Collections.Generic;
using System.Runtime.Serialization;
using Crossroads.Web.Common.MinistryPlatform;
using MinistryPlatform.Translation.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MinistryPlatform.Translation.Models.DTO
{
    [MpRestApiTable(Name = "Event_Groups")]
    public class MpEventGroupDto : MpBaseDto
    {
        [MpRestApiPrimaryKey("Event_Group_ID")]
        [JsonProperty("Event_Group_ID")]
        public int Id { get; set; }
        [JsonIgnore]
        public MpEventDto Event { get; set; } = new MpEventDto();
        [JsonIgnore]
        public MpGroupDto Group { get; set; } = new MpGroupDto();
        [JsonIgnore]
        public MpEventRoomDto RoomReservation { get; set; } = new MpEventRoomDto();

        [JsonProperty("Event_ID")]
        public int EventId
        {
            get { return Event.EventId; }
            set { Event.EventId = value; RoomReservation.EventId = value; }
        }

        [JsonProperty("Group_ID")]
        public int GroupId
        {
            get { return Group.Id; }
            set { Group.Id = value; }
        }

        [JsonProperty("Event_Room_ID")]
        public int? RoomReservationId
        {
            get { return RoomReservation.EventRoomId; }
            set { RoomReservation.EventRoomId = value; }
        }

        [JsonProperty("Room_ID", NullValueHandling = NullValueHandling.Ignore)]
        public int? RoomId
        {
            get { return RoomReservation.RoomId == 0 ? (int?)null : RoomReservation.RoomId; }
            set { RoomReservation.RoomId = value ?? 0; }
        }

        [JsonProperty("Signed_In", NullValueHandling = NullValueHandling.Ignore)]
        public int? SignedIn
        {
            get { return RoomReservation.SignedIn == 0 ? (int?)null : RoomReservation.SignedIn; }
            set { RoomReservation.SignedIn = value ?? 0; }
        }

        [JsonProperty("Checked_In", NullValueHandling = NullValueHandling.Ignore)]
        public int? CheckedIn
        {
            get { return RoomReservation.CheckedIn == 0 ? (int?)null : RoomReservation.CheckedIn; }
            set { RoomReservation.CheckedIn = value ?? 0; }
        }

        public bool HasRoomReservation()
        {
            return RoomReservation != null && RoomReservation.RoomId > 0;
        }

        protected override void ProcessUnmappedData(IDictionary<string, JToken> unmappedData, StreamingContext context)
        {
            RoomReservation.Label = unmappedData.GetUnmappedDataField<string>("Label");
            RoomReservation.AllowSignIn = unmappedData.GetUnmappedDataField<bool>("Allow_Checkin");
            RoomReservation.Capacity = unmappedData.GetUnmappedDataField<int>("Capacity");
            RoomReservation.Volunteers = unmappedData.GetUnmappedDataField<int>("Volunteers");
        }
    }
}


text:
namespace rclcpp
{

GuardCondition::GuardCondition(
  rclcpp::Context::SharedPtr context,
  rcl_guard_condition_options_t guard_condition_options)
: context_(context), rcl_guard_condition_{rcl_get_zero_initialized_guard_condition()}
{
  if (!context_) {
    throw std::invalid_argument("context argument unexpectedly nullptr");
  }
  rcl_ret_t ret = rcl_guard_condition_init(
    &this->rcl_guard_condition_,
    context_->get_rcl_context().get(),
    guard_condition_options);
  if (RCL_RET_OK != ret) {
    rclcpp::exceptions::throw_from_rcl_error(ret, "failed to create guard condition");
  }
}

GuardCondition::~GuardCondition()
{
  rcl_ret_t ret = rcl_guard_condition_fini(&this->rcl_guard_condition_);
  if (RCL_RET_OK != ret) {
    try {
      rclcpp::exceptions::throw_from_rcl_error(ret);
    } catch (const std::exception & exception) {
      RCLCPP_ERROR(
        rclcpp::get_logger("rclcpp"),
        "failed to finalize guard condition: %s", exception.what());
    }
  }
}

rclcpp::Context::SharedPtr
GuardCondition::get_context() const
{
  return context_;
}

rcl_guard_condition_t &
GuardCondition::get_rcl_guard_condition()
{
  return rcl_guard_condition_;
}

const rcl_guard_condition_t &
GuardCondition::get_rcl_guard_condition() const
{
  return rcl_guard_condition_;
}

void
GuardCondition::trigger()
{
  rcl_ret_t ret = rcl_trigger_guard_condition(&rcl_guard_condition_);
  if (RCL_RET_OK != ret) {
    rclcpp::exceptions::throw_from_rcl_error(ret);
  }

  {
    std::lock_guard<std::recursive_mutex> lock(reentrant_mutex_);

    if (on_trigger_callback_) {
      on_trigger_callback_(1);
    } else {
      unread_count_++;
    }
  }
}

bool
GuardCondition::exchange_in_use_by_wait_set_state(bool in_use_state)
{
  return in_use_by_wait_set_.exchange(in_use_state);
}

void
GuardCondition::add_to_wait_set(rcl_wait_set_t * wait_set)
{
  std::lock_guard<std::recursive_mutex> lock(reentrant_mutex_);

  if (exchange_in_use_by_wait_set_state(true)) {
    if (wait_set != wait_set_) {
      throw std::runtime_error("guard condition has already been added to a wait set.");
    }
  } else {
    wait_set_ = wait_set;
  }

  rcl_ret_t ret = rcl_wait_set_add_guard_condition(wait_set, &this->rcl_guard_condition_, NULL);
  if (RCL_RET_OK != ret) {
    rclcpp::exceptions::throw_from_rcl_error(
      ret, "failed to add guard condition to wait set");
  }
}

void
GuardCondition::set_on_trigger_callback(std::function<void(size_t)> callback)
{
  std::lock_guard<std::recursive_mutex> lock(reentrant_mutex_);

  if (callback) {
    on_trigger_callback_ = callback;

    if (unread_count_) {
      callback(unread_count_);
      unread_count_ = 0;
    }
  } else {
    on_trigger_callback_ = nullptr;
  }
}

}  // namespace rclcpp


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package agent.dbgeng.manager.cmd;

import agent.dbgeng.dbgeng.DebugSessionId;
import agent.dbgeng.manager.DbgSession;
import agent.dbgeng.manager.impl.DbgManagerImpl;

public class DbgSetActiveSessionCommand extends AbstractDbgCommand<Void> {
	private DbgSession session;

	/**
	 * Set the active session
	 *
	 * @param manager the manager to execute the command
	 * @param process the desired process
	 */
	public DbgSetActiveSessionCommand(DbgManagerImpl manager, DbgSession session) {
		super(manager);
		this.session = session;
	}

	@Override
	public void invoke() {
		if (session != null) {
			DebugSessionId id = session.getId();
			if (id != null) {
				manager.getSystemObjects().setCurrentSystemId(id);
			}
		}
	}
}


text:
namespace rx
{
static gl::ImageIndex GetImageIndex(GLenum target, size_t mip, size_t layer)
{
    if (target == GL_TEXTURE_3D)
    {
        return gl::ImageIndex::Make3D(static_cast<GLint>(mip), static_cast<GLint>(layer));
    }
    else
    {
        ASSERT(layer == 0);
        return gl::ImageIndex::MakeGeneric(target, static_cast<GLint>(mip));
    }
}

EGLImageD3D::EGLImageD3D(RendererD3D *renderer,
                         EGLenum target,
                         egl::ImageSibling *buffer,
                         const egl::AttributeMap &attribs)
    : mRenderer(renderer), mBuffer(buffer), mAttachmentBuffer(nullptr), mRenderTarget(nullptr)
{
    ASSERT(renderer != nullptr);
    ASSERT(buffer != nullptr);

    if (egl::IsTextureTarget(target))
    {
        mAttachmentBuffer = GetImplAs<TextureD3D>(GetAs<gl::Texture>(buffer));
        mAttachmentTarget = gl::FramebufferAttachment::Target(
            GL_NONE, GetImageIndex(egl_gl::EGLImageTargetToGLTextureTarget(target),
                                   attribs.get(EGL_GL_TEXTURE_LEVEL_KHR, 0),
                                   attribs.get(EGL_GL_TEXTURE_ZOFFSET_KHR, 0)));
    }
    else if (egl::IsRenderbufferTarget(target))
    {
        mAttachmentBuffer = GetImplAs<RenderbufferD3D>(GetAs<gl::Renderbuffer>(buffer));
        mAttachmentTarget =
            gl::FramebufferAttachment::Target(GL_NONE, gl::ImageIndex::MakeInvalid());
    }
    else
    {
        UNREACHABLE();
    }
}

EGLImageD3D::~EGLImageD3D()
{
    SafeDelete(mRenderTarget);
}

egl::Error EGLImageD3D::initialize()
{
    return egl::Error(EGL_SUCCESS);
}

gl::Error EGLImageD3D::orphan(egl::ImageSibling *sibling)
{
    if (sibling == mBuffer)
    {
        gl::Error error = copyToLocalRendertarget();
        if (error.isError())
        {
            return error;
        }
    }

    return gl::Error(GL_NO_ERROR);
}

gl::Error EGLImageD3D::getRenderTarget(RenderTargetD3D **outRT) const
{
    if (mAttachmentBuffer)
    {
        FramebufferAttachmentRenderTarget *rt = nullptr;
        gl::Error error = mAttachmentBuffer->getAttachmentRenderTarget(mAttachmentTarget, &rt);
        if (error.isError())
        {
            return error;
        }

        *outRT = static_cast<RenderTargetD3D *>(rt);
        return gl::Error(GL_NO_ERROR);
    }
    else
    {
        ASSERT(mRenderTarget);
        *outRT = mRenderTarget;
        return gl::Error(GL_NO_ERROR);
    }
}

gl::Error EGLImageD3D::copyToLocalRendertarget()
{
    ASSERT(mBuffer != nullptr);
    ASSERT(mAttachmentBuffer != nullptr);
    ASSERT(mRenderTarget == nullptr);

    RenderTargetD3D *curRenderTarget = nullptr;
    gl::Error error = getRenderTarget(&curRenderTarget);
    if (error.isError())
    {
        return error;
    }

    // Clear the source image buffers
    mBuffer           = nullptr;
    mAttachmentBuffer = nullptr;

    return mRenderer->createRenderTargetCopy(curRenderTarget, &mRenderTarget);
}
}


text:
<?php

namespace Symfony\Component\Mime\Encoder;

/**
 * @author Chris Corbyn
 *
 * @experimental in 4.3
 */
class Base64Encoder implements EncoderInterface
{
    /**
     * Takes an unencoded string and produces a Base64 encoded string from it.
     *
     * Base64 encoded strings have a maximum line length of 76 characters.
     * If the first line needs to be shorter, indicate the difference with
     * $firstLineOffset.
     */
    public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string
    {
        if (0 >= $maxLineLength || 76 < $maxLineLength) {
            $maxLineLength = 76;
        }

        $encodedString = base64_encode($string);
        $firstLine = '';
        if (0 !== $firstLineOffset) {
            $firstLine = substr($encodedString, 0, $maxLineLength - $firstLineOffset)."\r\n";
            $encodedString = substr($encodedString, $maxLineLength - $firstLineOffset);
        }

        return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n"));
    }
}


text:
package scalaz.stream.actor

object actors
  extends QueueActor
          with RefActor with TopicActor


text:
      Department
      master data

 Home

Master Data

         Tambah Data

              No
              Kode
              Nama
              Aksi

            <?php $i=1; foreach ($department->result() as $dt): ?>

              <?=$i?>
              <?=$dt->d_kode?>
              <?=$dt->d_nama?>

                <a href="<?=base_url('master/department_delete/').$dt->id_department;?>" class="btn btn-danger btn-sm btn-flat" title="Hapus" onclick="return confirm('Delete <?=$dt->d_nama;?> ?')">

                <a data-toggle="modal" href='#edit-<?=$dt->id_department?>' class="btn btn-info btn-sm btn-flat" title="Edit">

            <?php $i++; endforeach ?>

              No
              Kode
              Nama
              Aksi

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Tambah Data

      <form action="<?=base_url('master/department_add');?>" method="post">

            Kode
            <input type="text" name="d_kode" value="" placeholder="" class="form-control">

            Nama
            <input type="text" name="d_nama" value="" placeholder="" class="form-control">

          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Simpan</button>

      </form>

<?php foreach ($department->result() as $dt): ?>
<div class="modal fade" id="edit-<?=$dt->id_department?>">

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Tambah Data

      <form action="<?=base_url('master/department_edit/').$dt->id_department;?>" method="post">

            Kode
            <input type="text" name="d_kode" value="<?=$dt->d_kode?>" placeholder="" class="form-control">

            Nama
            <input type="text" name="d_nama" value="<?=$dt->d_nama?>" placeholder="" class="form-control">

          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Simpan</button>

      </form>

<?php endforeach ?>


text:
AppLauncherPlugin::AppLauncherPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){
  QVBoxLayout *lay = new QVBoxLayout();
  this->setLayout(lay);
    lay->setContentsMargins(0,0,0,0);
  button = new QToolButton(this);
    button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    button->setAutoRaise(true);
    button->setText("...\n..."); //Need to set something here so that initial sizing works properly

  lay->addWidget(button, 0, Qt::AlignCenter);
	connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()) );
  menu = new QMenu(this);
  int icosize = this->readSetting("iconsize",-1).toInt();
  if(icosize <1){
    icosize = LSession::handle()->sessionSettings()->value("DefaultIconSize",64).toInt();
    this->saveSetting("iconsize",icosize);
  }
  button->setIconSize(QSize(icosize,icosize));
  this->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(openContextMenu()) );
  watcher = new QFileSystemWatcher(this);
	connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT( loadButton()) );
  //Calculate the initial size of the button
  //qDebug() << "Button Size:" << button->size();
  //qDebug() << "Calculated:" << icosize+4 << icosize+8+qRound(2.15*button->fontMetrics().height());
  //qDebug() << "Preferred Size:" << button->sizeHint();
  QSize sz(qRound(1.1*icosize), icosize+qRound(2.7*button->fontMetrics().height()) );
  button->setFixedSize(sz); //make sure to adjust the button on first show.
  this->setInitialSize(this->sizeHint().width()+2, this->sizeHint().height()+2); //give the container a bit of a buffer
  QTimer::singleShot(100,this, SLOT(loadButton()) );
}

void AppLauncherPlugin::Cleanup(){
  //This is run only when the plugin was forcibly closed/removed
  if(QFile::exists(button->whatsThis()) && button->whatsThis().startsWith(QDir::homePath()+"/Desktop") ){
    deleteFile();
  }
}

void AppLauncherPlugin::loadButton(bool onchange){
  QString def = this->ID().section("::",1,50).section("---",0,0).simplified();
  QString path = this->readSetting("applicationpath",def).toString(); //use the default if necessary
  //qDebug() << "Default Application Launcher:" << def << path;
  bool ok = QFile::exists(path);
  QString txt;
  if(path.endsWith(".desktop") && ok){
    XDGDesktop file = LXDG::loadDesktopFile(path, ok);
    if(path.isEmpty() || !QFile::exists(path) || !ok){
      button->setWhatsThis("");
      button->setIcon( LXDG::findIcon("quickopen-file","") );
      txt = tr("Click to Set");
      if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
    }else{
      button->setWhatsThis(file.filePath);
      button->setIcon( LXDG::findIcon(file.icon,"quickopen") );
      txt = file.name;
      if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
      watcher->addPath(file.filePath); //make sure to update this shortcut if the file changes
    }
  }else if(ok){
    QFileInfo info(path);
    button->setWhatsThis(info.absoluteFilePath());
    if(info.isDir()){
	button->setIcon( LXDG::findIcon("folder","") );
    }else if(LUtils::imageExtensions().contains(info.suffix().toLower()) ){
      button->setIcon( QIcon(QPixmap(path).scaled(256,256)) ); //max size for thumbnails in memory
    }else{
      button->setIcon( LXDG::findMimeIcon(path) );
    }
    txt = info.fileName();
    if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
    watcher->addPath(path); //make sure to update this shortcut if the file changes
  }else{
    //InValid File
    button->setWhatsThis("");
    button->setIcon( LXDG::findIcon("quickopen","") );
    button->setText( tr("Click to Set") );
    if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
  }
  //Now adjust the visible text as necessary based on font/grid sizing
  button->setToolTip(txt);
  int icosize = this->readSetting("iconsize",64).toInt();
  int bwid = qRound(1.1*icosize);
  this->setFixedSize(bwid, icosize+qRound(2.5*button->fontMetrics().height()) ); //make sure to adjust the button on first show.
  if(onchange){ this->adjustSize( bwid+4, icosize+8+qRound(2.5*button->fontMetrics().height())); }
    //qDebug() << "Initial Button Text:" << txt << icosize;
    if(button->fontMetrics().width(txt) > (bwid-2) ){
      //int dash = this->fontMetrics().width("-");
      //Text too long, try to show it on two lines
      txt = txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks
      if(txt.contains("\n")){
        //need to check each line
	QStringList txtL = txt.split("\n");
	for(int i=0; i<txtL.length(); i++){
	  if(i>1){ txtL.removeAt(i); i--; } //Only take the first two lines
	  else{ txtL[i] = button->fontMetrics().elidedText(txtL[i], Qt::ElideRight, bwid-2);  }
	}
	txt = txtL.join("\n");
      }else{
        txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*bwid -4);
        //Now split the line in half for the two lines
        txt.insert( (txt.count()/2), "\n");
      }
    }
    if(!txt.contains("\n")){ txt.append("\n "); } //always use two lines
    //qDebug() << " - Setting Button Text:" << txt;
    button->setText(txt);
  //Now setup the menu again
  menu->clear();
  menu->addAction(LXDG::findIcon("zoom-in",""), tr("Increase Size"), this, SLOT(increaseIconSize()));
  menu->addAction(LXDG::findIcon("zoom-out",""), tr("Decrease Size"), this, SLOT(decreaseIconSize()));
  if( !button->whatsThis().isEmpty() && button->whatsThis().startsWith(QDir::homePath()+"/Desktop") ){
    menu->addAction(LXDG::findIcon("list-remove",""), tr("Delete File"), this, SLOT(deleteFile()) );
  }

  QTimer::singleShot(100, this, SLOT(update()) ); //Make sure to re-draw the image in a moment
}

void AppLauncherPlugin::buttonClicked(){
  QString path = button->whatsThis();
  if(path.isEmpty() || !QFile::exists(path) ){
    //prompt for the user to select an application
    QList<XDGDesktop> apps = LXDG::sortDesktopNames( LXDG::systemDesktopFiles() );
    QStringList names;
    for(int i=0; i<apps.length(); i++){ names << apps[i].name; }
    bool ok = false;
    QString app = QInputDialog::getItem(this, tr("Select Application"), tr("Name:"), names, 0, false, &ok);
    if(!ok || names.indexOf(app)<0){ return; } //cancelled
    this->saveSetting("applicationpath", apps[ names.indexOf(app) ].filePath);
    QTimer::singleShot(0,this, SLOT(loadButton()));
  }else{
    LSession::LaunchApplication("lumina-open \""+path+"\"");
  }

}

void AppLauncherPlugin::openContextMenu(){
  if(button->underMouse()){
    menu->popup(QCursor::pos());
  }else{
    emit OpenDesktopMenu();
  }
}

void AppLauncherPlugin::increaseIconSize(){
  int icosize = this->readSetting("iconsize",64).toInt();
  icosize += 16;
  button->setIconSize(QSize(icosize,icosize));
  this->saveSetting("iconsize",icosize);
  this->loadButton(true); //redo size calculations

}

void AppLauncherPlugin::decreaseIconSize(){
  int icosize = this->readSetting("iconsize",64).toInt();
  if(icosize < 20){ return; } //cannot get smaller
  icosize -= 16;
  button->setIconSize(QSize(icosize,icosize));
  this->saveSetting("iconsize",icosize);
  this->loadButton(true); //redo size calculations
}

void AppLauncherPlugin::deleteFile(){
  if(QFileInfo(button->whatsThis()).isDir()){
    QProcess::startDetached("rm -r \""+button->whatsThis()+"\"");
  }else{
    QFile::remove(button->whatsThis());
  }
}


text:
// -------------------------------------------------------------------
//
// basho_metrics:  fast performance metrics for Erlang.
//
// inspired and partially derived from Coda Hale's 'metrics'
// Copyright (c) 2010-2001 Coda Hale
// https://github.com/codahale/metrics/blob/development/LICENSE.md
//
// Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.  You may obtain
// a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------
#ifndef EWMA_HPP_
#define EWMA_HPP_

#include <cmath>

/**
 * An exponentially-weighted moving average.
 *
 * UNIX Load Average Part 1: How It Works: http://www.teamquest.com/pdfs/whitepaper/ldavg1.pdf
 *
 * UNIX Load Average Part 2: Not Your Average Average: http://www.teamquest.com/pdfs/whitepaper/ldavg2.pdf
 */
class ewma
{
    static const double MICRO = 1000000.0;
public:
    explicit ewma(double alpha, unsigned int interval)
        : rate_(0.0),
          uncounted_(0),
          alpha_(alpha),
          interval_(interval * MICRO / 1000), // ms
          initialized_(false) { }

    /**
     * Update the moving average with a new value.
     */
    void update(long n)
    {
        uncounted_ += n;
    }

    /**
     * Mark the passage of time and decay the current rate accordingly.
     */
    void tick()
    {
        std::size_t count = uncounted_;
        uncounted_ = 0;
        double instant_rate = count / interval_;
        if (initialized_)
            rate_ += (alpha_ * (instant_rate - rate_));
        else
        {
            rate_ = instant_rate;
            initialized_ = true;
        }
    }

    double rate() const
    {
        return rate_ * (double)MICRO;
    }

private:
    double rate_;
    unsigned long uncounted_;
    double alpha_;
    double interval_;
    bool initialized_;
};

inline double alpha_one()
{
    return 1.0 - std::exp(-5.0 / 60.0);
}

inline double alpha_five()
{
    return 1.0 - std::exp(-5.0 / 60.0 / 5.0);
}

inline double alpha_fifteen()
{
    return 1.0 - std::exp(-5.0 / 60.0 / 15.0);
}

#endif // include guard


text:
package org.elasticsearch.index.mapper;

public class VersionFieldTypeTests extends FieldTypeTestCase<MappedFieldType> {
    @Override
    protected MappedFieldType createDefaultFieldType() {
        return new VersionFieldMapper.VersionFieldType();
    }
}


text:
exports.route = function(handle, pathname, request, response) {
  if(typeof handle[pathname] === 'function') {
    handle[pathname](request, response);
  } else {
    response.writeHead(404, {'Content-Type' : 'text/plain'});
    response.write('404 NOT FOUNO');
    response.end();
  }
}


text:
<?php

error_reporting(E_STRICT | E_ALL);

// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';

try {
  // Get DfpUser from credentials in "../auth.ini"
  // relative to the DfpUser.php file's directory.
  $user = new DfpUser();

  // Log SOAP XML request and response.
  $user->LogDefaults();

  // Get the ContactService.
  $contactService = $user->GetService('ContactService', 'v201311');

  // Statement parts to help build a statement to select all contacts.
  $pqlTemplate = 'ORDER BY id LIMIT %d OFFSET %d';
  $SUGGESTED_PAGE_LIMIT = 500;
  $offset = 0;

  $page = new ContactPage();

  do {
    // Get contacts by statement.
    $page = $contactService->getContactsByStatement(new Statement(
        sprintf($pqlTemplate, $SUGGESTED_PAGE_LIMIT, $offset)));

    // Display results.
    if (isset($page->results)) {
      $i = $page->startIndex;
      foreach ($page->results as $contact) {
        printf("%d) Contact with ID \"%d\" and name \"%s\" was found.\n", $i++,
            $contact->id, $contact->name);
      }
    }

    $offset += $SUGGESTED_PAGE_LIMIT;
  } while ($offset < $page->totalResultSetSize);

  printf("Number of results found: %d\n", $page->totalResultSetSize);
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
  printf("%s\n", $e->getMessage());
}


text:
package pivot

import (
	"io/ioutil"
	"path"

	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"

	"github.com/openshift/origin/pkg/oc/clusterup/componentinstall"
	"github.com/openshift/origin/pkg/oc/clusterup/docker/dockerhelper"
)

type Component interface {
	Name() string
	Install(dockerClient dockerhelper.Interface) error
}

type KubeAPIServerContent struct {
	InstallContext componentinstall.Context
}

func (k *KubeAPIServerContent) Name() string {
	return "KubeAPIServerContent"
}

// this ia list of all the secrets and configmaps we need to create
const (
	namespace = "openshift-kube-apiserver"

	// saTokenSigningCerts contains certificates corresponding to the valid keys that are and were used to sign SA tokens
	saTokenSigningCerts = "sa-token-signing-certs"
	// aggregatorClientCABundle is the ca-bundle to use to verify that the aggregator is proxying to your apiserver
	aggregatorClientCABundle = "aggregator-client-ca"
	// aggregatorClientCertKeyPair is the client cert/key pair used by the aggregator when proxying
	aggregatorClientCertKeyPair = "aggregator-client"
	// kubeletClientCertKeyPair is the client cert/key used by the kube-apiserver when communicating with the kubelet
	kubeletClientCertKeyPair = "kubelet-client"
	// kubeletServingCABundle is the ca-bundle to use to verify connections to the kubelet
	kubeletServingCABundle = "kubelet-serving-ca"
	// apiserverServingCertKeyPair is the serving cert/key used by the kube-apiserver to secure its https server
	apiserverServingCertKeyPair = "serving-cert"
	// apiserverClientCABundle is the ca-bundle used to identify users from incoming connections to the kube-apiserver
	apiserverClientCABundle = "client-ca"
	// etcdClientCertKeyPair is the client cert/key pair used by the kube-apiserver when communicating with etcd
	etcdClientCertKeyPair = "etcd-client"
	// etcdServingCABundle is the ca-bundle to use to verify connections to etcd
	etcdServingCABundle = "etcd-serving-ca"
)

func (c *KubeAPIServerContent) Install(dockerClient dockerhelper.Interface) error {
	kubAPIServerConfigDir := path.Join(c.InstallContext.BaseDir(), "kube-apiserver")
	kubeClient, err := kubernetes.NewForConfig(c.InstallContext.ClusterAdminClientConfig())
	if err != nil {
		return err
	}

	_, err = kubeClient.CoreV1().Namespaces().Create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace, Labels: map[string]string{"openshift.io/run-level": "0"}}})
	if err != nil && !apierrors.IsAlreadyExists(err) {
		return err
	}

	if err := ensureCABundle(kubeClient, kubAPIServerConfigDir, saTokenSigningCerts, "serviceaccounts.public.key"); err != nil {
		return err
	}
	if err := ensureCABundle(kubeClient, kubAPIServerConfigDir, aggregatorClientCABundle, "frontproxy-ca.crt"); err != nil {
		return err
	}
	if err := ensureCABundle(kubeClient, kubAPIServerConfigDir, kubeletServingCABundle, "ca.crt"); err != nil {
		return err
	}
	if err := ensureCABundle(kubeClient, kubAPIServerConfigDir, apiserverClientCABundle, "ca.crt"); err != nil {
		return err
	}
	if err := ensureCABundle(kubeClient, kubAPIServerConfigDir, etcdServingCABundle, "ca.crt"); err != nil {
		return err
	}

	if err := ensureCertKeyPair(kubeClient, kubAPIServerConfigDir, aggregatorClientCertKeyPair, "openshift-aggregator"); err != nil {
		return err
	}
	if err := ensureCertKeyPair(kubeClient, kubAPIServerConfigDir, kubeletClientCertKeyPair, "master.kubelet-client"); err != nil {
		return err
	}
	if err := ensureCertKeyPair(kubeClient, kubAPIServerConfigDir, apiserverServingCertKeyPair, "master.server"); err != nil {
		return err
	}
	if err := ensureCertKeyPair(kubeClient, kubAPIServerConfigDir, etcdClientCertKeyPair, "master.etcd-client"); err != nil {
		return err
	}

	return nil
}

func ensureConfigMap(kubeClient kubernetes.Interface, obj *corev1.ConfigMap) error {
	_, err := kubeClient.CoreV1().ConfigMaps(obj.Namespace).Get(obj.Name, metav1.GetOptions{})
	if err == nil || !apierrors.IsNotFound(err) {
		return err
	}

	_, err = kubeClient.CoreV1().ConfigMaps(obj.Namespace).Create(obj)
	return err
}

func ensureSecret(kubeClient kubernetes.Interface, obj *corev1.Secret) error {
	_, err := kubeClient.CoreV1().Secrets(obj.Namespace).Get(obj.Name, metav1.GetOptions{})
	if err == nil || !apierrors.IsNotFound(err) {
		return err
	}

	_, err = kubeClient.CoreV1().Secrets(obj.Namespace).Create(obj)
	return err
}

func ensureCABundle(kubeClient kubernetes.Interface, kubeAPIServerDir, name, filename string) error {
	content, err := ioutil.ReadFile(path.Join(kubeAPIServerDir, filename))
	if err != nil {
		return err
	}
	obj := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name},
		Data: map[string]string{
			"ca-bundle.crt": string(content),
		}}
	return ensureConfigMap(kubeClient, obj)
}

func ensureCertKeyPair(kubeClient kubernetes.Interface, kubeAPIServerDir, name, baseFilename string) error {
	cert, err := ioutil.ReadFile(path.Join(kubeAPIServerDir, baseFilename+".crt"))
	if err != nil {
		return err
	}
	key, err := ioutil.ReadFile(path.Join(kubeAPIServerDir, baseFilename+".key"))
	if err != nil {
		return err
	}
	obj := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name},
		Data: map[string][]byte{
			"tls.crt": cert,
			"tls.key": key,
		}}
	return ensureSecret(kubeClient, obj)
}


text:
<readable><title>2751602672_ca5e1f6447</title><content>
A bald man demonstarting how high his brown and black dog can jump .
a bald man in grey is holding out a stick whilst a black and brown dog jumps up to catch it .
A man holds a stick above a jumping dog .
A medium sized dog is jumping to get a stick .
Man holding a stick while a dog jumps up to grab it
</content></readable>