text:
package in.edureka.mapreduce;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.fs.Path;

public class word_position_count {

	public static class Map extends Mapper<LongWritable,Text,Text,IntWritable>{

		public void map(LongWritable key, Text value,
				Context context)
				throws IOException,InterruptedException
		{

			Configuration conf = context.getConfiguration();
			String K = conf.get("k");

			int k = Integer.parseInt(K);

			String line = value.toString();
			StringTokenizer tokenizer = new StringTokenizer(line);

			//int k=1;			// set K : K is the position in a sentence =>  1=< K <= N
								// N is the max size of sentence in Corpus
								// N is set to the last row column 1 value of the SentenceWordCount job

			for(int i=0;i<k-1;i++)
				tokenizer.nextToken();

			while (tokenizer.hasMoreTokens())
			{
				value.set(tokenizer.nextToken());
				context.write(value, new IntWritable(1));
				break;
			}

		}

	}
	public static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable>{

		public void reduce(Text key, Iterable<IntWritable> values,
				Context context)
				throws IOException,InterruptedException {
			int sum=0;
			// TODO Auto-generated method stub
			for(IntWritable x: values)
			{
				sum+=x.get();
			}
			context.write(key, new IntWritable(sum));

		}

	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		//JobConf conf = new JobConf(WordCount.class);
		Configuration conf= new Configuration();

		conf.set("k", args[2]);  ///  pass k as argument

		//conf.setJobName("mywc");
		Job job = new Job(conf,"mywc");

		job.setJarByClass(word_position_count.class);
		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);

		//conf.setMapperClass(Map.class);
		//conf.setReducerClass(Reduce.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);

		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);

		Path outputPath = new Path(args[1]);

	        //Configuring the input/output path from the filesystem into the job

	    FileInputFormat.addInputPath(job, new Path(args[0]));
	    FileOutputFormat.setOutputPath(job, new Path(args[1]));

	    //Configuration config= new Configuration();

	    //FileOutputFormat.setOutputPath(job, new Path(args[2]));
			//deleting the output path automatically from hdfs so that we don't have delete it explicitly

		outputPath.getFileSystem(conf).delete(outputPath);

			//exiting the job only if the flag value becomes false

		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}


text:
//
//  CellToolbarView.m
//  KYPFanfou
//
//  Created by trainer on 8/2/16.
//  Copyright © 2016 trainer. All rights reserved.
//

#import "CellToolbarView.h"

@implementation CellToolbarView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

redpajama_set_name: RedPajamaGithub


text:
#ifndef SQLCOMP_HDR
#define SQLCOMP_HDR

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

#include "ComOptIncludes.h"
#include "CmpCommon.h"
#include "SchemaDB.h"
#include "opt_error.h"

#endif // SQLCOMP_HDR


text:
namespace blink {

MutableStylePropertySet* SVGElementRareData::ensureAnimatedSMILStyleProperties()
{
    if (!m_animatedSMILStyleProperties)
        m_animatedSMILStyleProperties = MutableStylePropertySet::create(SVGAttributeMode);
    return m_animatedSMILStyleProperties.get();
}

ComputedStyle* SVGElementRareData::overrideComputedStyle(Element* element, const ComputedStyle* parentStyle)
{
    ASSERT(element);
    if (!m_useOverrideComputedStyle)
        return nullptr;
    if (!m_overrideComputedStyle || m_needsOverrideComputedStyleUpdate) {
        // The style computed here contains no CSS Animations/Transitions or SMIL induced rules - this is needed to compute the "base value" for the SMIL animation sandwhich model.
        m_overrideComputedStyle = element->document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
        m_needsOverrideComputedStyleUpdate = false;
    }
    ASSERT(m_overrideComputedStyle);
    return m_overrideComputedStyle.get();
}

DEFINE_TRACE(SVGElementRareData)
{
#if ENABLE(OILPAN)
    visitor->trace(m_outgoingReferences);
    visitor->trace(m_incomingReferences);
    visitor->trace(m_animatedSMILStyleProperties);
    visitor->trace(m_elementInstances);
    visitor->trace(m_correspondingElement);
    visitor->trace(m_owner);
    visitor->template registerWeakMembers<SVGElementRareData, &SVGElementRareData::processWeakMembers>(this);
#endif
}

void SVGElementRareData::processWeakMembers(Visitor* visitor)
{
#if ENABLE(OILPAN)
        ASSERT(m_owner);
        if (!Heap::isHeapObjectAlive(m_cursorElement))
            m_cursorElement = nullptr;

        if (!Heap::isHeapObjectAlive(m_cursorImageValue)) {
            // The owning SVGElement is still alive and if it is pointing to an SVGCursorElement
            // we unregister it when the CSSCursorImageValue dies.
            if (m_cursorElement) {
                m_cursorElement->removeReferencedElement(m_owner);
                m_cursorElement = nullptr;
            }
            m_cursorImageValue = nullptr;
        }
        ASSERT(!m_cursorElement || Heap::isHeapObjectAlive(m_cursorElement));
        ASSERT(!m_cursorImageValue || Heap::isHeapObjectAlive(m_cursorImageValue));
#endif
}

AffineTransform* SVGElementRareData::animateMotionTransform()
{
    if (!m_animateMotionTransform)
        m_animateMotionTransform = adoptPtr(new AffineTransform);
    return m_animateMotionTransform.get();
}

}


text:
class EnvironmentsController < ApplicationController
  before_filter :find_project
  before_filter :find_environment, only: :update
  before_filter :admin_login_required, only: :update

  respond_to :json

  # Edits an Environment. Only the Project owner or an admin can modify an
  # Environment.
  #
  # Routes
  # ------
  #
  # * `PATCH /projects/:project_id/environments/:id.json`
  #
  # Path Parameters
  # ---------------
  #
  # |      |                         |
  # |:-----|:------------------------|
  # | `id` | The Environment's name. |
  #
  # Body Parameters
  # ---------------
  #
  # The body can be JSON- or form URL-encoded.
  #
  # |               |                                           |
  # |:--------------|:------------------------------------------|
  # | `environment` | Parameterized hash of Environment fields. |

  def update
    @environment.update_attributes environment_params
    respond_with @environment, location: project_url(@project)
  end

  private

  def find_environment
    @environment = @project.environments.find_by_name!(params[:id])
  end

  def environment_params
    params.require(:environment).permit(:sends_emails, :notifies_pagerduty)
  end
end


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
    [Collection(nameof(SharedIntegrationHostFixture))]
    public class BasicSquigglesNetCore : BasicSquigglesCommon
    {
        public BasicSquigglesNetCore(VisualStudioInstanceFactory instanceFactory)
            : base(instanceFactory, WellKnownProjectTemplates.VisualBasicNetCoreClassLibrary)
        {
        }

        [WorkItem(1825, "https://github.com/dotnet/roslyn-project-system/issues/1825")]
        [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
        [Trait(Traits.Feature, Traits.Features.NetCore)]
        public override void VerifySyntaxErrorSquiggles()
        {
            base.VerifySyntaxErrorSquiggles();
        }

        [WorkItem(1825, "https://github.com/dotnet/roslyn-project-system/issues/1825")]
        [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
        [Trait(Traits.Feature, Traits.Features.NetCore)]
        public override void VerifySemanticErrorSquiggles()
        {
            base.VerifySemanticErrorSquiggles();
        }
    }
}


text:
'use strict';

module.exports = function(shariff) {

    var url = encodeURIComponent(shariff.options.flattrurl),
		id = '';
	if (typeof shariff.options.flattrid !== 'undefined') {
		id = '&user_id=' + shariff.options.flattrid;
	}

    return {
		blank: true,
        shareText: {
            'en': 'flattr',
        },
        name: 'flattr',
        faName: 'fa-money',
        title: {
            'de': 'Mit Flattr spenden',
            'en': 'spend with Flattr',
        },
        shareUrl: 'https://flattr.com/submit/auto?url=' + url + id
    };
};


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
	<title></title>

	<link rel="stylesheet" href="https://defunsm.github.io/css/style.css" />
	<link rel="stylesheet" href="https://defunsm.github.io/css/font-awesome.min.css" />
	<link type="text/css" rel="stylesheet" href="https://defunsm.github.io/featherlight.css" />
        <link rel="stylesheet" href="https://defunsm.github.io/css/screen.css" />
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.1/styles/default.min.css">

	<link rel="shortcut icon" href="images/favicon.png">

     <ul3 class="nav-two">
  <li3 class="three">Home </li3>
  <li3 class="fourl">About </li3>
  <li3 class="onel">GitHub </li3>
  <li3 class="twol">Blog </li3>
  </ul3>

			      Home

						About

						Github

						Blog

Categories :

                Computers

                Physics

                Python

                Computer

                Graphics

                Pathfinding

                Clojure Guide Code

                Blog

                Clojure

                ClojureScript

                Haskell

                Graphing

                Racket

                Code

                Machine Learning

                Terminals

                Guide

© 2016 Salman Hossain

				Top


text:
namespace Google.Cloud.ApigeeRegistry.V1.Snippets
{
    // [START apigeeregistry_v1_generated_Registry_DeleteApi_async_flattened_resourceNames]
    using Google.Cloud.ApigeeRegistry.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedRegistryClientSnippets
    {
        /// <summary>Snippet for DeleteApiAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task DeleteApiResourceNamesAsync()
        {
            // Create client
            RegistryClient registryClient = await RegistryClient.CreateAsync();
            // Initialize request argument(s)
            ApiName name = ApiName.FromProjectLocationApi("[PROJECT]", "[LOCATION]", "[API]");
            // Make the request
            await registryClient.DeleteApiAsync(name);
        }
    }
    // [END apigeeregistry_v1_generated_Registry_DeleteApi_async_flattened_resourceNames]
}


text:
from __future__ import unicode_literals
from sys import stdout

class EventNotRegisteredException(Exception):
    pass

class EventMalformedException(Exception):
    pass

class EventHandler(object):

    def __init__(self):
        pass

    def handle_event(self, event, kwargs):
        raise NotImplementedError("Please implement")

class EventManager(object):

    def __init__(self, limit_output=False, *handlers):
        self._registered_events = dict()
        self._handlers = list(handlers) or []
        self._last_event = None
        self._limit_output = limit_output

    def event_report(self):
        for event, parameters in self._registered_events.iteritems():
            print '-'*80
            print 'Event: {}'.format(event)
            if parameters:
                print 'Parameters:'
                for parameter in parameters:
                    print '* {}'.format(parameter)

    def add_handler(self, event_handler):
        self._handlers.append(event_handler)

    def register_event(self, name, parameters=[]):
        self._registered_events[name] = parameters

    def emit(self, event, sender=None, level='info', formatted='', data={}):
        if not sender:
            raise ArgumentError('Event needs a sender!')

        levels = ['info', 'warning', 'error', 'critical', 'debug']
        if not level in levels:
            raise ArgumentError('Event level needs to be in: {}'.format(levels))

        if event not in self._registered_events:
            raise EventNotRegisteredException("Event %s not registered..." % event)

        if self._limit_output:
            if (event == self._last_event) and (event in ["moving_to_fort", "moving_to_lured_fort", "position_update"]):
                stdout.write("\033[1A\033[0K\r")
                stdout.flush()

            if level == "info" and formatted:
                self._last_event = event

        # verify params match event
        parameters = self._registered_events[event]
        if parameters:
            for k, v in data.iteritems():
                if k not in parameters:
                    raise EventMalformedException("Event %s does not require parameter %s" % (event, k))

        formatted_msg = formatted.format(**data)

        # send off to the handlers
        for handler in self._handlers:
            handler.handle_event(event, sender, level, formatted_msg, data)


text:
.FlatView {
    font-size: 14px;
}

.FlatView input[type="search"].search {
    width: 100%;
    color: white;
    font-family: inherit;
    font-size: 0.9em;
    background-color: transparent;
    border-bottom: 2px solid transparent;
    transition: border .25s ease-in-out;
}
.FlatView input[type="search"].search::placeholder {
    color: #CCC;
}

.FlatView ul {
    padding: 0;
    margin: 0;
    list-style: none;
    user-select: none;
}

.FlatView li:not(.disabled) {
    cursor: pointer;
}

.FlatView li .item {
    display: block;
    transition: all 0.25s ease-in-out;
}

.FlatView li:not(.category) > .item {
    padding: 5px 0px;
}

.FlatView li.category > .item {
    background: white;
    color: black;
    padding: 5px 15px;
    font-weight: bold;
}
.FlatView li.selected > .item {
    color: white;
    background-color: #f44336;
}
.FlatView li:not(.category):not(.selected).disabled > .item {
    background: #CCC;
    color: #888;
}

.FlatView li:not(.disabled):not(.selected) > .item:hover {
    color: #f44336;
}
.FlatView li.selected > .item:hover {
    color: rgb(224, 224, 224);
}

.FlatView li.category > .item span.icons {
    position: absolute;
    right: 15px;
}

.FlatView li.category > .item {
    cursor: pointer;
}
.FlatView li.category > .item:hover  {
    color: #f44336;
}


text:
package com.dm.ycm.model.dao;

import java.util.Map;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;

import com.dm.ycm.model.entity.MentionEntity;

import com.dm.ycm.model.dao.MentionEntityDao;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.

/**
 * {@inheritDoc}
 *
 * @see org.greenrobot.greendao.AbstractDaoSession
 */
public class DaoSession extends AbstractDaoSession {

    private final DaoConfig mentionEntityDaoConfig;

    private final MentionEntityDao mentionEntityDao;

    public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
            daoConfigMap) {
        super(db);

        mentionEntityDaoConfig = daoConfigMap.get(MentionEntityDao.class).clone();
        mentionEntityDaoConfig.initIdentityScope(type);

        mentionEntityDao = new MentionEntityDao(mentionEntityDaoConfig, this);

        registerDao(MentionEntity.class, mentionEntityDao);
    }

    public void clear() {
        mentionEntityDaoConfig.clearIdentityScope();
    }

    public MentionEntityDao getMentionEntityDao() {
        return mentionEntityDao;
    }

}


text:
======
Logjam
======

logjam 0.0.4

Released: 14-May-2015

.. image:: https://travis-ci.org/hblanks/logjam.png?branch=develop
        :target: https://travis-ci.org/hblanks/logjam

Logjam handles the (relatively) simple problem of compressing and archiving
ISO8601 logfiles. It works like this:

    1. Write all your logs into hourly files with an ISO8601 in their filenames.
    2. Run **logjam-compress** and **logjam-upload** on your log directories,
       either via cron or as a daemon.
    3. Your completed logfiles will automatically be compressed and uploaded to S3.

How to use it
-------------

the logfile format
~~~~~~~~~~~~~~~~~~

Your logfiles need two things:

	#. They must contain an **UTC ISO8601 timestamp**. In
	   ``haproxy-20130704T0000Z-us-west-2-i-ae23fega.log``, for instance,
	   the timestamp is ``20130704T0000Z``.
	#. They need to be written hourly or more frequent than hourly. Not daily.

If you use *rsyslog* or *syslog-ng*, then chances are you already use hourly
files. If not, they're very easy to configure.

logjam-compress
~~~~~~~~~~~~~~~

Sample entry in ``/etc/cron.d/``::

	10 * * * * * root logjam-compress --once /var/log/my-log-dir/

Sample command to put in an **upstart** config file or **runit** run script::

	logjam-compress /var/log/my-log-dir

logjam-upload
~~~~~~~~~~~~~~~

Sample entry in ``/etc/cron.d/``::

	10 * * * * * root logjam-upload --once /var/log/my-log-dir/archive/ s3://YOUR_BUCKET/{prefix}/{year}/{month}{/{day}/{filename}

Sample command to put in an **upstart** config file or **runit** run script::

	 logjam-upload /var/log/my-log-dir/archive/ s3://YOUR_BUCKET/{prefix}/{year}/{month}{/{day}/{filename}

**A note on authentication** ``logjam-upload`` looks for the standard boto
environment variables **$AWS_ACCESS_KEY_ID**, **AWS_SECRET_ACCESS_KEY**, plus
**$AWS_DEFAULT_REGION** to figure out which S3 region to use, and what creds
to use when connecting.

If those variables are not present, and you happen to be running
``logjam-upload`` from an instance with an IAM role, ``logjam-upload``
will parse its AWS credential from that, and connect to the local S3
region unless told otherwise with **$AWS_DEFAULT_REGION**.

What you need to get started
----------------------------

Just boto, and a bucket in S3.

Why is this useful?
-------------------

You may be right to think that don't need this, because if you have any
significant amount of logs, you're going to want some sort of online log
aggregation system, such as Logstash.

And if you have a really significant amount of logs, you're going to want
a really robust, distributed system for collecting *and* storing logs, such as
Scribe.

If you're big enough to need the latter, then this is not the tool for you.

But, if you're small enough that don't want to maintain your own distributed
system for storing logs, then you have two choices:

    1. Implement the online log aggregation solution, and then deal with log
       persistence, probably by setting up some sort S3 output to run on
       your log aggregation server. This will work, although you will have a
       SPOF where you can lose all your logs for a given time period.

    2. Implement a log persistence solution whose primary machinism is
       decoupled from your log aggregation solution.

In the second case, you no longer have a SPOF that can lose all your logs for a
given time, although when you lose an individual server, you *will lose its logs
from its last, partial hour.*

I've been very happy with the second case, and indeed when I have to
choose which to have first, I always choose persistence over
aggregation. Unfortunately, I'm always writing code to take care of the
persistence -- i.e. of compressing and uploading logfiles. So, finally,
here's a small, open source tool for it.

Running tests
-------------

Unit tests run with::

    python setup.py test

Integration tests run with:

    export SENTRY_DSN="https:// SOME SENTRY DSN"
    python tests/integration/test_all.py

Or run them all with:

    ./test_all.sh


text:
Billbo
==============
[![Build Status](https://secure.travis-ci.org/piesync/billbo.png?branch=master)](http://travis-ci.org/piesync/billbo)
[![Test Coverage](https://codeclimate.com/github/piesync/billbo/coverage.png)](https://codeclimate.com/github/piesync/billbo)

About
-----

Billbo is an easy to use billing service including VAT support written in Ruby that is designed and built around the [Stripe] API. It decouples billing functionality from your application's core functionality and centralizes billing and invoicing logic into a stable workflow.

Billbo uses the Stripe invoicing system and adds VAT information/charges following legal regulations. As soon as a Stripe invoice charge succeeds, an internal invoice is created, generated in pdf and emailed to the customer.

It's currently designed to support billing from EU based countries.

[Stripe]: https://stripe.com/

Features
--------

* Automatic VAT addition according to legal regulations (incl 2015 VAT update)
* VAT number validation and owner details using VIES service (company name, address)
* Automatic and consistent invoice numbering (configurable)
* Revenue analytics with [Segment.io](https://segment.io/) (optional)
* Error Tracking with [Getsentry](https://getsentry.com/) (optional)
* Automatic and legally correct pdf invoice generation ([download example pdf](https://github.com/piesync/billbo/blob/master/assets/example.pdf?raw=true))
* Battle-tested at [PieSync](http://www.piesync.com)
* Works in various situations like prorations, discount ([examples](https://github.com/piesync/billbo/tree/master/spec/visual))
* Works with refunds
* Invoice storage: choice between local or or Amazon S3

How it Works with Stripe
------------------------

Subscriptions are created through Billbo instead of through the Stripe API directly. When the subscription is being created, Billbo calculated the correct VAT rate that should be applied to this subscription based on the customer metadata. This VAT rate is then passed to Stripe as `tax_percent`.

When we receive a `invoice.payment_succeeded` event from Stripe, we finalize and assign an invoice number to the associated invoice in the Billbo database.

Deployment and configuration
----------

The easiest way to get Billbo online to use it for production is Heroku. The `deploy-heroku` script in the root directory helps you with that. It provisions a Heroku instance with a Postgres database and all the right settings.

The fastest path we can offer you:

**Deploy to Heroku**

```
git clone git@github.com:piesync/billbo.git && cd billbo
bundle install
./deploy-heroku [HEROKU_APP_NAME] -s [SECRET_STRIPE_KEY]
```

The deploy script takes lots of additional options to customize your Billbo instance. Just run `./deploy-heroku` to see usage details.

**Configure Stripe Webhook**

Add a Webhook to Stripe that points to `https://HEROKU_APP_NAME.herokuapp.com/hook`

**Configuration**

TK list env vars

**Generating invoices**

TK CRON JOB

Basic Usage
-----------
Billbo works with all different types of Stripe invoicing workflows, the only specifics you need are customer related.

**Creating Stripe Customers**

Create Stripe customers with the following required metadata.

Example using Ruby ([or using Curl](https://stripe.com/docs/api/curl#create_customer)):
```ruby
Stripe::Customer.create(
  card: "tok_14JuLq2nHroS7mLXZ5uxDRqs" # obtained with Stripe.js
  metadata: {
    country_code: 'US', # required - ISO 3166-1 alpha-2 standard
    vat_registered: true, # required
    name: 'John Doe', # optional
    company_name: 'DoeComp', # optional, VIES value if not provided and vat_number is provided
    address: 'Doestreet 1, 1111 Doeville', # optional, VIES value if not provided and vat_number is provided
    vat_number: 'DOE1234', # optional
    accounting_id: '8723648', # optional
    ... # optional extra metadata
  }
)
```
This data and any extra metadata of your customers will be copied into the metadata of your Stripe invoices.
This way you can make your invoices immutable containing all their needed info taken at a certain point in time.

**Creating Subscriptions**

To use Billbo in the correct way, instead of creating subscriptions using the Stripe API, create your subscriptions using Billbo.

Example using the `billbo` Ruby Gem:
```ruby
Billbo.create_subscription(
  plan: 'basic',
  customer: 'cus_4XWKfwBrWLHvf8',
  ... # other Stripe compatible options
)
# => A Stripe::Subscription object
```

Or using Curl:
```
curl https://HOST/subscriptions \
   -u X:BILLBO_TOKEN \
   -d plan=large
```

You can pass all options supported in the Stripe [create subscription](https://stripe.com/docs/api#create_subscription) call. The returned `Stripe::Subscription` or raised errors are 100% compatible with the [Stripe Ruby Gem](https://github.com/stripe/stripe-ruby).

Help and Discussion
-------------------

If you need help you can contact us by sending a message to:
[oss@piesync.com][mail].

[mail]:   mailto:oss@piesync.com

If you believe you've found a bug, please report it at:
https://github.com/piesync/billbo/issues

Contributing to Billbo
----------------------

* Please fork Billbo on github
* Make your changes and send us a pull request with a brief description of your addition
* We will review all pull requests and merge them upon approval

Copyright
---------

Copyright (c) 2014 PieSync.


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

module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        'watch': {
            lang: {
                files: ['lucy/dev/lang/*.js'],
                tasks: ['copy:skulpt'],
                options: {
                    interrupt: true
                }
            },

            game: {
                files: ['lucy/dev/game/**/*.ts'],
                tasks: ['ts:game'],
                options: {
                    interrupt: true
                }
            },

            app: {
                files: ['lucy/dev/app/**/module.js', 'lucy/dev/app/**/*.js'],
                tasks: ['concat:app'],
                options: {
                    interrupt: true
                }
            },

            md: {
                files: ['lucy/dev/game/assets/levels/**/*.md'],
                tasks: ['md'],
                options: {
                    interrupt: true
                }
            }

        },

        //
        // Typescript task. Compiles changes made to the game code
        //
        'ts': {
            options: {

            },
            game: {
                src: ['lucy/dev/game/**/*.ts'],
                out: 'lucy/dist/game.js'
            }
        },

        //
        // Copy task to copy skulpt changes from dev/ to dist/
        //
        'copy': {
            skulpt : {
                files : [
                    {expand:true, src:['lucy/dev/lang/*.js'], dest:'lucy/dist/', flatten:true}
                ]
            }
        },

        //
        // Concat task to join all Angular Modules into one file
        //
        'concat': {
            options: {
                process: function(src, filepath) {
                  return '//\n// ' + filepath + '\n//\n' + src;
                }
            },
            app: {
                src: ['lucy/dev/app/**/module.js', 'lucy/dev/app/**/*.js'],
                dest: 'lucy/dist/app.js'
            }
        },

        //
        // Starts the HTTP Server for local testing
        //
        'http-server' : {
            dev : {
                root: './',
                port: 8081
            }
        },

        //
        // Runs tasks concurrently
        //
        'concurrent' : {
            dev : {
                tasks: ['http-server', 'watch:lang', 'watch:game', 'watch:app'],
                options: {
                    logConcurrentOutput:true
                }
            }
        }

    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-http-server');
    grunt.loadNpmTasks('grunt-concurrent');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-ts');

    grunt.registerTask('dev', ['concurrent:dev'])

    grunt.registerTask('md', 'Parse markdown files', function() {
        function getDirectories(srcpath) {
          return fs.readdirSync(srcpath).filter(function(file) {
            return fs.statSync(path.join(srcpath, file)).isDirectory();
          });
        }

        function writeParsedHtml(dir, filename) {
            grunt.log.writeln('Reading: ' + filename);
            var mdString = fs.readFileSync(dir+filename, 'utf8');
            var htmlString = marked(mdString);
            var baseName = path.basename(filename, '.md'); // filename without ext
            var newfile = dir+baseName+'.html'
            fs.writeFileSync(newfile, htmlString);
            grunt.log.writeln('Finished writing :' + newfile);
        }

        var levelsDir = './lucy/dev/game/assets/levels/';
        var folders = getDirectories(levelsDir);
        for (var folder in folders) {
            var fullpath = levelsDir + folders[folder] + '/';
            var files = fs.readdirSync(fullpath);
            for (var file in files) {
                if (path.extname(files[file]) === '.md') {
                    var filename = files[file];
                    writeParsedHtml(fullpath, filename);
                }
           }
        }

        grunt.log.writeln('finished')
    });
};


text:
package session.redis.explorer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import session.redis.explorer.repository.ExpirationSessionRepository;
import session.redis.explorer.repository.MapSessionRepository;

/**
 *
 */
@Controller
@RequestMapping("")
public class RootController {

    private MapSessionRepository mapSessionRepository;

    private ExpirationSessionRepository expirationSessionRepository;

    @Autowired
    public RootController(MapSessionRepository mapSessionRepository,
                          ExpirationSessionRepository expirationSessionRepository) {
        this.mapSessionRepository = mapSessionRepository;
        this.expirationSessionRepository = expirationSessionRepository;
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String getIndex(Model model) {
        model.addAttribute("mapSessionList", mapSessionRepository.getAll());
        model.addAttribute("expirationSessionList", expirationSessionRepository.getAll());

        return "index";
    }
}


text:
package com.meizu.smartbar.tab;

import com.meizu.smartbar.R;
import com.meizu.smartbar.SmartBarUtils;

import java.sql.BatchUpdateException;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.TabHost;

/**
 * 使用 ActionBar Tab 与 TabHost 实现 SmartBar tab 界面。
 */
public class ActionBarTabAndTabHost extends TabActivity implements ActionBar.TabListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		boolean findMethod = findActionBarTabsShowAtBottom();
		if (!findMethod) {
		    // 取消ActionBar拆分,换用TabHost
		    getWindow().setUiOptions(0);
		}

		setContentView(R.layout.tab_content);

		final TabHost tabHost = getTabHost();
		tabHost.addTab(tabHost.newTabSpec("recent")
		        .setIndicator(null, getResources().getDrawable(R.drawable.ic_tab_recent))
				.setContent(new Intent(this, RecentActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("contacts")
		        .setIndicator(null, getResources().getDrawable(R.drawable.ic_tab_contacts))
				.setContent(new Intent(this, ContactsActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("dialer")
		        .setIndicator(null, getResources().getDrawable(R.drawable.ic_tab_dialer))
				.setContent(new Intent(this, DialerActivity.class)));

		if (findMethod) {
		    getTabWidget().setVisibility(View.GONE);

	        final ActionBar bar = getActionBar();
	        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

	        bar.addTab(bar.newTab().setIcon(R.drawable.ic_tab_recent).setTabListener(this));
	        bar.addTab(bar.newTab().setIcon(R.drawable.ic_tab_contacts).setTabListener(this));
	        bar.addTab(bar.newTab().setIcon(R.drawable.ic_tab_dialer).setTabListener(this));

//	         如果是用户自定义的View,可以像下面这样操作
//	        bar.addTab(bar.newTab().setTabListener(this).setCustomView(R.layout.tab_widget_indicator).setTabListener(this));

	        // 设置ActionBar Tab显示在底栏
	        SmartBarUtils.setActionBarTabsShowAtBottom(bar, true);
		}
	}

	// 查找设置ActionBar Tab显示在底栏的方法,找不到method则返回false。
	private boolean findActionBarTabsShowAtBottom() {
        try {
            Class.forName("android.app.ActionBar")
                    .getMethod("setTabsShowAtBottom", new Class[] { boolean.class });
        } catch (Exception e) {
            return false;
        }

        return true;
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_settings, menu);
		return true;
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {

	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		if (tab != null) {
			getTabHost().setCurrentTab(tab.getPosition());
		}
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {

	}
}


text:
from unittest import TestCase
from tulip import *
import tulippaths as tp

class TestPathFinderWrapper(TestCase):

    def test_findRegexConstrainedPaths(self):
        graphFile = '../data/test_one.tlp'
        graph = tlp.loadGraph(graphFile)

        edgeConstraints = ["Ribbon Synapse", "Adherens"]
        nodeConstraints = ["CBb3-4i", "GC ON", "CBb4w"]

        pathFinderWrapper = tp.PathFinderWrapper(graph)

        paths = pathFinderWrapper.findRegexConstrainedPaths(nodeConstraints, edgeConstraints)

        path = paths[0]

        self.assertTrue(path.toStringOfTypes() == "CBb3-4i, Ribbon Synapse, GC ON, Adherens, CBb4w")
        self.assertTrue(path.toStringOfIds() == "176, (53563 -> 53564    53563 -> 53564), 606, (54048 -> 54049    54050 -> 54051    82555 -> 80970    82684 -> 77469    82882 -> 81107    82885 -> 81135), 5530")


text:
/**
 * @license Use of this source code is governed by an MIT-style license that
 * can be found in the LICENSE file at https://github.com/cartant/rxjs-tslint-rules
 */

import { tsquery } from "@phenomnomnominal/tsquery";
import * as Lint from "tslint";
import * as ts from "typescript";
import * as peer from "../support/peer";

export class Rule extends Lint.Rules.TypedRule {
  public static metadata: Lint.IRuleMetadata = {
    deprecationMessage: peer.v5 ? peer.v5NotSupportedMessage : undefined,
    description:
      "Disallows implicit `any` error parameters in `catchError` operators.",
    options: {
      properties: {
        allowExplicitAny: { type: "boolean" },
      },
      type: "object",
    },
    optionsDescription: Lint.Utils.dedent`
      An optional object with an optional \`allowExplicitAny\` property.`,
    requiresTypeInfo: true,
    ruleName: "rxjs-no-implicit-any-catch",
    type: "functionality",
    typescriptOnly: true,
  };

  public static EXPLICIT_ANY = "Explicit any in catchError";
  public static IMPLICIT_ANY = "Implicit any in catchError";
  public static NARROWED = "Error type must be unknown or any";

  public applyWithProgram(
    sourceFile: ts.SourceFile,
    program: ts.Program
  ): Lint.RuleFailure[] {
    const {
      ruleArguments: [options],
    } = this.getOptions();
    const allowExplicitAny =
      options && options.hasOwnProperty("allowExplicitAny")
        ? options.allowExplicitAny
        : false;
    const failures: Lint.RuleFailure[] = [];

    const callExpressions = tsquery(
      sourceFile,
      `CallExpression[expression.text="catchError"]`
    ) as ts.CallExpression[];

    callExpressions.forEach((callExpression) => {
      const [arg] = callExpression.arguments;
      if (!arg) {
        return;
      }
      if (ts.isArrowFunction(arg) || ts.isFunctionExpression(arg)) {
        const [parameter] = arg.parameters;
        if (!parameter) {
          return;
        }
        if (parameter.type) {
          if (parameter.type.kind === ts.SyntaxKind.AnyKeyword) {
            if (allowExplicitAny) {
              return;
            }
            failures.push(
              new Lint.RuleFailure(
                sourceFile,
                parameter.getStart(),
                parameter.getStart() + parameter.getWidth(),
                Rule.EXPLICIT_ANY,
                this.ruleName,
                Lint.Replacement.replaceNode(parameter.type, "unknown")
              )
            );
          } else if (parameter.type.kind !== ts.SyntaxKind.UnknownKeyword) {
            failures.push(
              new Lint.RuleFailure(
                sourceFile,
                parameter.getStart(),
                parameter.getStart() + parameter.getWidth(),
                Rule.NARROWED,
                this.ruleName
              )
            );
          }
        } else {
          failures.push(
            new Lint.RuleFailure(
              sourceFile,
              parameter.getStart(),
              parameter.getStart() + parameter.getWidth(),
              Rule.IMPLICIT_ANY,
              this.ruleName,
              Lint.Replacement.appendText(
                parameter.getStart() + parameter.getWidth(),
                ": unknown"
              )
            )
          );
        }
      }
    });
    return failures;
  }
}


text:
.locationWidget {
    white-space: nowrap;
}

.locationWidget .tc {
    width: 310px;
}

.locationWidget .tab {
    height: 65px;
}

.locationWidget .label {
    width: 80px;
    font-weight: bold;
    display: inline-block;
    padding-top: 2px;
}

.locationWidget .inputMGRS {
    width: 134px;
    display: inline-block;
    vertical-align: middle;
}

.locationWidget .selectLatLonFormat {
    width: 211px;
    display: inline-block;
    vertical-align: middle;
}

.locationWidget .inputDD {
    width: 135px;
    display: inline-block;
    vertical-align: middle;
}

.locationWidget .inputDMS {
    width: 35px;
    display: inline-block;
    vertical-align: middle;
}

.locationWidget .selectHemi {
    width: 60px;
    display: inline-block;
    vertical-align: middle;
}

.locationWidget .inputw3w {
    width: 200px;
    display: inline-block;
    vertical-align: middle;
}

.locationWidget .smallText {
    font-weight: normal;
    font-size: 7px;
}


text:
class AddFeedNameToNeuigkeiten < ActiveRecord::Migration
  def change
    add_column :neuigkeitens, :feed_name, :string
  end
end


text:
package org.bbs.felix.activity.bundlemanager;

import java.util.Date;

import org.bbs.felix.util.OsgiUtil;
import org.bbs.felixonandroid.R;
import org.osgi.framework.BundleException;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class BundleDetailFragment extends Fragment {
	public static final String EXTRA_BUNDLE_ID = "extra.bundle.id";
	private ViewPager mViewPager;
	private Adapter mAdapter;
	private org.osgi.framework.Bundle[] mBundles;

	public BundleDetailFragment(){
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_bundle_detail, null);
		long bId = getActivity().getIntent().getLongExtra(EXTRA_BUNDLE_ID, -1);

		mAdapter = new Adapter();
		mBundles = BundleListActivity.BundleList.getInstance().getBundles();
		mViewPager = (ViewPager)v.findViewById(R.id.viewpager);
		mViewPager.setAdapter(mAdapter);

		int index = 0;
		for (org.osgi.framework.Bundle b : mBundles) {
			if (bId == b.getBundleId()){
				mViewPager.setCurrentItem(index);
				break;
			}
			index++;
		}
		return v;
	}

	public static CharSequence toString(org.osgi.framework.Bundle b) {
		String str = ""
				 + "id: " + b.getBundleId() + "\n"
				 + "version: " + b.getVersion() + "\n"
				 + "location: " + b.getLocation() + "\n"
				 + "state: " + OsgiUtil.bundleState2Str(b.getState()) + "\n"
				 + "lastModified: " + new Date(b.getLastModified()) + "\n"
				 + "headers: \n" + getHeader(b) + "\n"
				;
		return str;
	}

	public static String getHeader(org.osgi.framework.Bundle b) {
		return OsgiUtil.getHeader(b, OsgiUtil.HEADER_OSGI);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu,  MenuInflater inflater) {
		// Inflate the menu; this adds items to the action bar if it is present.
		inflater.inflate(R.menu.menu_bundle_detail, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			int position = mViewPager.getCurrentItem();
			org.osgi.framework.Bundle b = mBundles[position];
			int itemId = item.getItemId();
			if (itemId == R.id.action_start) {
				b.start();
			} else if (itemId == R.id.action_stop) {
				b.stop();
			} else if (itemId == R.id.action_uninstall) {
				b.uninstall();
			} else {
			}

			mAdapter.notifyDataChanged(position);
		} catch (BundleException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.onOptionsItemSelected(item);
	}

	class Adapter extends PagerAdapter {
		private int mPendingUpdatePositon;

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			org.osgi.framework.Bundle b = mBundles[position];
			TextView text = new TextView(getActivity());
			text.setText(BundleDetailFragment.toString(b));
			text.setTag(position);
			text.setMovementMethod(new ScrollingMovementMethod());

			container.addView(text);
			return text;
		}

		@Override
		public void destroyItem(ViewGroup container, int position,
				Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return "id: " + mBundles[position].getBundleId();
		}

		@Override
		public int getCount() {
			return mBundles.length;
		}

		// viewpager bug.
		public int getItemPosition(Object object) {
			int position = (Integer) ((View)object).getTag();
			if (position == mPendingUpdatePositon) {
				mPendingUpdatePositon = -1;
				return POSITION_NONE;
			}
			return super.getItemPosition(object);
		}
		public void notifyDataChanged(int position){
			mPendingUpdatePositon = position;
			notifyDataSetChanged();
		}
	}

}


text:
'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.createTable('items',
    {
      id: {
        type: Sequelize.INTEGER.UNSIGNED,
        primaryKey: true,
        autoIncrement: true
      },
      title: {
        type: Sequelize.STRING
      },
      body: {
        type: Sequelize.TEXT
      },
      status: {
        type: Sequelize.BOOLEAN
      },
      createdAt: {
        type: Sequelize.DATE
      },
      updatedAt: {
        type: Sequelize.DATE
      }
    });
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.dropTable('items');
  }
};


text:
class Golden::Setting::SettingsController < ApplicationController
  if Golden::Setting.before_actions.blank?
    raise "Please set config.before_actions like `authenticate_user!` for security."
  end
  Golden::Setting.before_actions.each do |action|
    before_filter action.to_sym
  end
  before_filter :load_setting_class, only: [:index, :create, :list, :batch_update]
  before_filter :new_setting, only: [:create]
  load_and_authorize_resource :setting, class: Golden::Setting.setting_class, parent: false

  respond_to :html

  def index
    @default_tab = Golden::Setting.default_tab
    respond_with @settings
  end

  def show
    respond_with @setting
  end

  def new
    respond_with @setting
  end

  def edit
  end

  def create
    @setting.save
    respond_with @setting, location: setting_path(@setting)
  end

  def update
    value = params[:setting].delete :value
    @setting.value = value
    @setting.update_attributes setting_params
    respond_with @setting, location: setting_path(@setting)
  end

  def destroy
    @setting.destroy
    respond_with @setting, location: settings_path
  end

  def list
    @settings = @settings.paginate page: params[:page]
    respond_with @settings
  end

  def batch_update
    params[:setting].each do |setting, value|
      @setting_class.send "#{setting}=", value
    end if params[:setting]
    redirect_to action: :index
  end

  protected

  def load_setting_class
    @setting_class = Golden::Setting.setting_class.constantize
  end

  def new_setting
    value = params[:setting].delete :value
    @setting = @setting_class.new setting_params
    @setting.value = value
  end

  def setting_params
    if params.respond_to? :permit
      params.require(:setting).permit(Golden::Setting.permitted_fields)
    else
      params[:setting]
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Extensions.Configuration;

namespace HostBox.Configuration
{
    public class ComponentConfigurationSection : Borderline.IConfiguration
    {
        private readonly IConfigurationSection innerSection;

        internal ComponentConfigurationSection(IConfigurationSection innerSection)
        {
            this.innerSection = innerSection;
        }

        /// <inheritdoc />
        public string Key => this.innerSection.Key;

        /// <inheritdoc />
        public string Path => this.innerSection.Path;

        /// <inheritdoc />
        public string Value => this.innerSection.Value;

        /// <inheritdoc />
        public string this[string key] => this.innerSection[key];

        /// <inheritdoc />
        public T BindSection<T>(string path) where T : new()
        {
            return this.innerSection.GetSection(path).Get<T>();
        }

        /// <inheritdoc />
        public IEnumerable<Borderline.IConfiguration> GetChildren()
        {
            return this.innerSection
                .GetChildren()
                .Select(s => new ComponentConfigurationSection(s));
        }

        /// <inheritdoc />
        public Borderline.IConfiguration GetSection(string path)
        {
            return new ComponentConfigurationSection(this.innerSection.GetSection(path));
        }

        /// <inheritdoc />
        public void OnReload(Action<Borderline.IConfiguration> callback)
            => innerSection.OnChange(this, callback);
    }
}


text:
class Hero
  def initialize id
    @id = id
    @name = "UnknownHero#{@id}"
  end

end


text:
title: 'Tie- ja Meriliikenteen siirto AWS-pilvipalveluun on valmistunut'
categories: Tiedotteet
image:
lang: fi
published: true
ref: 2018-11-12-road-marine-now-in-aws
traffictypes:
  - Tieliikenne
  - Meriliikenne
tags:
  - Rajapinnat
  - Ylläpito
---

Digitrafficin tie- ja meriliikenteen palvelut ovat siirtyneet AWS-pilvipalveluun.

Merkillepantavaa muutoksessa ovat seuraavat asiat:

* Ennen muutosta aikaleimat olivat Suomen paikallista aikaa. Muutoksen jälkeen ajat ilmoitetaan [koordinoidussa yleisajassa (UTC)](https://fi.wikipedia.org/wiki/ISO_8601#Aika).
Lisäksi aikaleimojen formaatti vaihtui: Ennen muutosta aikaleiman perään merkittiin ero koordinoituun yleisaikaan (UTC). Muutoksen
jälkeen käytetään koordinoidun yleisajan lyhennettä Z.
Ennen muutosta ajat ilmoitettiin esimerkiksi muodossa
`2018-11-06T15:51:00+03:00`
Uusi formaatti samalle aikaleimalle on:
`2018-11-06T12:51:00Z`
Lisätietoja: [2018-11-12-timestamp-change](http://www.digitraffic.fi/tiedotteet/2018/11/12/timestamp-change.html)
* Uudessa ympäristössä tietokantamoottori vaihtuu Postgres:iin, joten on mahdollista, että
joissakin tulosjoukoissa vastausten järjestys hieman muuttuu.

Muilta osin ympäristöjen pitäisi toimia identtisesti.

Lue myös tiedote  Websocket-rajapintojen muutoksista
[2018-10-12-ws-legacy-marine](http://www.digitraffic.fi/tiedotteet/2018/10/12/ws-legacy-marine.html)
sivulla.


text:
stylus Muse.styl -o muse.css
stylus Mist.styl -o mist.css
stylus Pisces.styl -o pisces.css


text:
//========================================================================
//$Id: Jetty6RunWar.java 3591 2008-09-03 21:31:12Z jesse $
//Copyright 2000-2004 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package org.mortbay.jetty.plugin;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.mortbay.util.Scanner;

/**
 *

 *  This goal is used to assemble your webapp into a war and automatically deploy it to Jetty.
 *

 *

 *  Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and to the
 *  war file and automatically performing a
 *  hot redeploy when necessary.
 *

 *

 *  You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
 *  This can be used, for example, to deploy a static webapp that is not part of your maven build.
 *

 *

 *  There is a reference guide to the configuration parameters for this plugin, and more detailed information
 *  with examples in the Configuration Guide.
 *

 *
 * @goal run-war
 * @requiresDependencyResolution runtime
 * @execute phase="package"
 * @description Runs jetty6 on a war file
 *
 */
public class Jetty6RunWar extends AbstractJetty6Mojo
{

    /**
     * The location of the war file.
     * @parameter expression="${project.build.directory}/${project.build.finalName}.war"
     * @required
     */
    private File webApp;

    /**
     * @see org.apache.maven.plugin.Mojo#execute()
     */
    public void execute() throws MojoExecutionException, MojoFailureException
    {
        super.execute();
    }

    public void configureWebApplication () throws Exception
    {
        super.configureWebApplication();

        webAppConfig.setWar(webApp.getCanonicalPath());
        webAppConfig.configure();
    }

    /**
     * @see org.mortbay.jetty.plugin.AbstractJettyMojo#checkPomConfiguration()
     */
    public void checkPomConfiguration() throws MojoExecutionException
    {
       return;
    }

    /* (non-Javadoc)
     * @see org.mortbay.jetty.plugin.util.AbstractJettyMojo#configureScanner()
     */
    public void configureScanner() throws MojoExecutionException
    {
        final ArrayList scanList = new ArrayList();
        scanList.add(getProject().getFile());
        scanList.add(webApp);
        setScanList(scanList);

        ArrayList listeners = new ArrayList();
        listeners.add(new Scanner.BulkListener()
        {
            public void filesChanged(List changes)
            {
                try
                {
                    boolean reconfigure = changes.contains(getProject().getFile().getCanonicalPath());
                    restartWebApp(reconfigure);
                }
                catch (Exception e)
                {
                    getLog().error("Error reconfiguring/restarting webapp after change in watched files",e);
                }
            }
        });
        setScannerListeners(listeners);

    }

    public void restartWebApp(boolean reconfigureScanner) throws Exception
    {
        getLog().info("Restarting webapp ...");
        getLog().debug("Stopping webapp ...");
        webAppConfig.stop();
        getLog().debug("Reconfiguring webapp ...");

        checkPomConfiguration();

        // check if we need to reconfigure the scanner,
        // which is if the pom changes
        if (reconfigureScanner)
        {
            getLog().info("Reconfiguring scanner after change to pom.xml ...");
            ArrayList scanList = getScanList();
            scanList.clear();
            scanList.add(getProject().getFile());
            scanList.add(webApp);
            setScanList(scanList);
            getScanner().setScanDirs(scanList);
        }

        getLog().debug("Restarting webapp ...");
        webAppConfig.start();
        getLog().info("Restart completed.");
    }

    /**
     * @see org.mortbay.jetty.plugin.AbstractJettyMojo#finishConfigurationBeforeStart()
     */
    public void finishConfigurationBeforeStart()
    {
        return;
    }

}


text:
# jquery-bemhelpers

BEM helpers for jQuery

## Why you might need it

[BEM](http://getbem.com) (Block, Element, Modifier) is a popular front-end methodology that introduces unified semantic entities across different frontend technologies such as CSS, HTML, JavaScript and templates.

BEM is not tied to any particular implementation or framework. This jQuery plugin provides basic support for working with modifiers and setting up callbacks based on modifier change.

## Naming convention

This plugin supports multiple BEM naming conventions.

By default, it uses BEM naming convention introduced by [Yandex](http://yandex.com):

  * CSS class names are used to denote BEM entities
  * Blocks with and without prefix are supported
  * Elements: block__element
  * Boolean modifiers: block_mod, block__element_mod
  * Key/value modifiers: block_modname_modval, block__element_modname_modval

You can set alternative naming conventions by calling the `$.BEMsyntax` method:

```javascript
// to read the existing syntax
var currentSyntax = $.BEMsyntax();

// to set a new syntax
var newSyntax = $.BEMsyntax({
    elem: '__',  // separator between block and element name
    modBefore: '--',  // separator between block/element and modifier name
    modKeyVal: '_'  // separator between modifier key and modifier value
});
```

You can omit some properties if you inherit them from a previously defined scheme or default Yandex scheme.
Changes are effective immediately and persist until you change them again.

`newSyntax` contains an object describing the new syntax (all fields).

## setMod

`.setMod` sets a block modifier on each element of a jQuery collection, and returns the same collection.

### Set a boolean modifier on a block:

`.setMod(blockName, modName, true|false)`

Sets a boolean modifier `modName` for each block `blockName` in a provided jQuery collection.
Third argument is the modifier value: `true` adds a modifier, `false` removes it.

According to BEM, the DOM element that receives a modifier also needs the original block or element CSS class to be assigned (so, modifier classes are never used standalone). Currently, the library does not check or enforce this rule, but might start doing that in any future release.

Example usage:
```javascript
// Add 'hidden' boolean modifier to the 'b-widget' block
$('.b-widget').setMod('b-widget', 'hidden', true);

// Remove 'hidden' boolean modifier from the 'b-widget' block
$('.b-widget').setMod('b-widget', 'hidden', false);
```

### Set a boolean modifier on an element:

`.setMod(blockName, elemName, modName, true|false)`

Same as above, but the second argument is an element name.

### Set a key/value modifier on a block:

Key/value modifiers are different from boolean modifiers in that they have distinct string values. Values follow the same limitations as modifier names do; namely, they cannot contain underscores and should comply with general limitations of CSS class names.

`.setMod(blockName, modName, modVal)`

*modVal* should not be a boolean value, otherwise it will be treated as a boolean modifier.

If you also set *modVal* to an empty `String` `''`, the modifier will be removed.

Example usage:
```javascript
// Add 'theme' key/value modifier to the 'b-widget' block
$('.b-widget').setMod('b-widget', 'theme', 'light');

// Remove 'theme' key/value modifier from the 'b-widget' block
$('.b-widget').setMod('b-widget', 'theme', '');
```

### Set a key/value modifier on an element:

`.setMod(blockName, elemName, modName, modVal)`

Same as above, but the second argument is an element name. *modVal* should not also be a boolean value.

## getMod

This is a simple API to read modifier values. It only reads the *first* element in a jQuery collection, ignoring all the rest, and returns a primitive value based on what it finds.

For blocks:

`.getMod(blockName, modName)`

For elements:

`.getMod(blockName, elemName, modName)`

It returns boolean `true` for a boolean modifier that exists, a `String` modifier value for a key/value modifier that exists, and boolean `false` for a modifier that was not found (as it is not there, there is no way to determine whether we're dealing with a boolean or key/value modifier).

For an empty jQuery collection, the method would return `undefined`. This might be an inconsistency; I may change it later.

## hasMod

`.hasMod` checks whether the first item in a jQuery collection has a modifier set on a specified block/element.

Returns a boolean value. For key/value modifiers, return `true` if any modifier value is present, regardless of the actual value.

For blocks:

```javascript
var hasMod = $('.b-block').hasMod('b-block', 'expanded');
```

For elements:

```javascript
var hasMod = $('.b-block__elem').hasMod('b-block', 'elem', 'expanded');
```

## Event handlers

For each modifier being set, a jQuery `setMod` event is being triggered that propagates up the DOM tree. It also contains metadata that lets you get additional information. This allows for callbacks being assigned to modifier changes.

### Subscribing to setMod events

For each modifier being set, a custom jQuery event fires which unique name is formed according to a pattern that is described below. The event also contains metadata you can read from the second argument of an event handler.

For all modifiers (both boolean and key/value pairs), the custom event is formed like this:

For blocks: `setMod:block_modName_*`
For elements: `setMod:block__elem_modName_*`

**NOTE**: If you define a custom BEM syntax with `$.BEMsyntax()` method, you should adjust your event name patterns accordingly. Events being triggered always use the current syntax.

```javascript
$(document).on('setMod:widget_init_*', function(e, data) {
    console.log('Block name:', data.block);
    console.log('Element name:', data.elem);  // undefined, as it's a block-level modifier
    console.log('Modifier name:', data.modName);
    console.log('Modifier value:', data.modVal);
});

$('div.widget').setMod('widget', 'init', true);
/* Console output:

>  Block name: widget
>  Element name: undefined
>  Modifier name: init
>  Modifier value: true

*/
```

An asterisk `*` at the end of an event name means it's triggered for all modifier values. An object passed as a second argument to an event handler contains additional keys:

   * `block` — block name
   * `elem` — element name (`undefined` if modifier is set on a block level)
   * `modName` — modifier name
   * `modVal` — modifier value that is set: a boolean `true`/`false` for boolean modifiers, a `String` value for key/value modifiers

**TIP**: For key/value modifier *only*, an *additional* event is triggered which is specific to a modifier value being set. Its custom name is formed like this:

For blocks: `setMod:block_modName_modVal`
For elements: `setMod:block__elem_modName_modVal`

```javascript
$(document).on('setMod:widget_theme_light', function(e, data) {
    console.log('Block name:', data.block);
    console.log('Element name:', data.elem);  // undefined, as it's a block-level modifier
    console.log('Modifier name:', data.modName);
    console.log('Modifier value:', data.modVal);
});

$('div.widget').setMod('widget', 'theme', 'light');
/* Console output:

>  Block name: widget
>  Element name: undefined
>  Modifier name: theme
>  Modifier value: light

*/
```

So as an example if you set `setMod:widget_theme_light` event listener, then it will be triggered *only* if you set the `theme` key/value modifier's value to `light`. Any other values won't trigger the event listener.

**NOTE**: Please also note that if you have removed the string modifier value by setting it to an empty `String`, `$('div.widget').setMod('widget', 'theme', '');` then the specific event listener won't again be triggered obviously! In such cases you might consider setting the wild-card event listener, just like how you set it for boolean modifiers: `setMod:widget_theme_*`.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of ReadFloatArray</title>
  <meta name="keywords" content="ReadFloatArray">
  <meta name="description" content="">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../../../m2html.css">

Home >  .. > SMASHtoolbox > +SMASH > +FileAccess > @PFFfile > private > ReadFloatArray.m

ReadFloatArray

PURPOSE

SYNOPSIS

function result=ReadFloatArray(fid)

DESCRIPTION

CROSS-REFERENCE INFORMATION

This function calls:

ReadFloat

ReadLong

ReadWord

This function is called by:

readPFTIFL

readPFTNF3

readPFTNG3

readPFTNGD

readPFTNI3

readPFTNV3

readPFTUF1

readPFTUF3

readPFTVTX

SOURCE CODE

0001 function result=ReadFloatArray(fid)
0002
0003
0004 first=ReadWord(fid);
0005 if first==-6 % full float precision
0006     FOFF10=ReadWord(fid); %#ok<NASGU>
0007     LENGTH=ReadLong(fid);
0008     result=fread(fid,LENGTH,'single');
0009 else % reduced float precision
0010     fseek(fid,-2,'cof');
0011     OFFSET=ReadFloat(fid);
0012     SCALE=ReadFloat(fid);
0013     LENGTH=ReadLong(fid);
0014     result=ReadWord(fid,LENGTH);
0015     result=OFFSET+SCALE*result;
0016 end
0017
0018 end

<address>Generated on Tue 10-Nov-2020 17:53:50 by m2html © 2005</address>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2013, The Sporting Exchange Limited
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cougar-test</artifactId>
        <groupId>com.betfair.cougar</groupId>
        <version>3.3-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cougar-client-code-tests</artifactId>
    <name>${project.artifactId}</name>

    <profiles>
        <profile>
            <id>default</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <skipTests>true</skipTests>
                <failIfNoTests>false</failIfNoTests>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.14.1</version>
                        <executions>
                            <execution>
                                <id>unit-test</id>
                                <configuration>
                                    <skipTests>true</skipTests>
                                    <failIfNoTests>false</failIfNoTests>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>run-integration-tests</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <properties>
                <skipTests>false</skipTests>
                <failIfNoTests>true</failIfNoTests>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.14.1</version>
                        <executions>
                            <execution>
                                <id>unit-test</id>
                                <configuration>
                                    <skipTests>false</skipTests>
                                    <failIfNoTests>true</failIfNoTests>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencies>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${json.version}</version>
        </dependency>

        <dependency>
            <groupId>com.betfair.cougar</groupId>
            <artifactId>client-app</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>cougar-test-utils</artifactId>
            <version>${project.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.sun</groupId>
                    <artifactId>tools</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.sun</groupId>
            <artifactId>tools</artifactId>
            <scope>system</scope>
            <systemPath>${java.home}/../lib/tools.jar</systemPath>
            <version>${java.version}</version>
        </dependency>

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>cougar-ci-test-listener</artifactId>
            <version>${project.version}</version>
        </dependency>

	</dependencies>

</project>


text:
.class public abstract Landroid/media/DrmInitData;
.super Ljava/lang/Object;
.source "DrmInitData.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/media/DrmInitData$SchemeInitData;
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public abstract get(Ljava/util/UUID;)Landroid/media/DrmInitData$SchemeInitData;
.end method


text:
     NAME
	  glPushName, glPopName	- push and pop the name	stack

     C SPECIFICATION
	  void glPushName( GLuint name )

     PARAMETERS
	  name	Specifies a name that will be pushed onto the name
		stack.

     C SPECIFICATION
	  void glPopName( void )

     DESCRIPTION
	  The name stack is used during	selection mode to allow	sets
	  of rendering commands	to be uniquely identified.  It
	  consists of an ordered set of	unsigned integers and is
	  initially empty.

	  glPushName causes name to be pushed onto the name stack.
	  glPopName pops one name off the top of the stack.

	  The maximum name stack depth is implementation-dependent;
	  call GL_MAX_NAME_STACK_DEPTH to find out the value for a
	  particular implementation. It	is an error to push a name
	  onto a full stack, or	to pop a name off an empty stack.  It
	  is also an error to manipulate the name stack	between	the
	  execution of glBegin and the corresponding execution of
	  glEnd.  In any of these cases, the error flag	is set and no
	  other	change is made to GL state.

	  The name stack is always empty while the render mode is not
	  GL_SELECT.  Calls to glPushName or glPopName while the
	  render mode is not GL_SELECT are ignored.

     ERRORS
	  GL_STACK_OVERFLOW is generated if glPushName is called while
	  the name stack is full.

	  GL_STACK_UNDERFLOW is	generated if glPopName is called while
	  the name stack is empty.

	  GL_INVALID_OPERATION is generated if glPushName or glPopName
	  is executed between a	call to	glBegin	and the	corresponding
	  call to glEnd.

     ASSOCIATED	GETS
	  glGet	with argument GL_NAME_STACK_DEPTH
	  glGet	with argument GL_MAX_NAME_STACK_DEPTH
     SEE ALSO
	  glInitNames, glLoadName, glRenderMode, glSelectBuffer


text:
module Effective
  module Generators
    class FormGenerator < Rails::Generators::NamedBase
      include Helpers

      source_root File.expand_path(('../' * 4) + 'lib/scaffolds', __FILE__)

      desc 'Creates a _form.html.haml in your app/views/model/ folder.'

      argument :attributes, type: :array, default: [], banner: 'field[:type] field[:type]'
      class_option :tabbed, type: :string, default: 'true'

      def validate_resource
        exit unless resource_valid?
      end

      def assign_attributes
        @attributes = invoked_attributes.presence || resource_attributes
        self.class.send(:attr_reader, :attributes)
      end

      def invoke_form
        say_status :invoke, :form, :white
      end

      def create_flat_form
        with_resource_tenant do
          if options[:tabbed] == 'false'
            template 'forms/flat/_form.html.haml', resource.view_file('form', partial: true)
          end
        end
      end

      def create_tabbed_form
        with_resource_tenant do
          if options[:tabbed] == 'true'
            template 'forms/tabbed/_form.html.haml', resource.view_file('form', partial: true)
            template 'forms/tabbed/_form_resource.html.haml', resource.view_file("form_#{resource.name}", partial: true)
          end
        end
      end

      protected

      def form_for
        if resource.namespaces.blank?
          resource.name
        else
          '[' + resource.namespaces.map { |ns| ':' + ns }.join(', ') + ', ' + resource.name + ']'
        end
      end

      def render_field(attribute, depth: 0)
        b = binding

        b.local_variable_set(:resource, resource)

        partial = case attribute
        when (ActiveRecord::Reflection::BelongsToReflection rescue false)
          b.local_variable_set(:reference, attribute)
          'belongs_to'
        when (ActiveRecord::Reflection::HasManyReflection rescue false)
          b.local_variable_set(:nested_resource, attribute)
          'nested_resource'
        when Effective::Resource
          b.local_variable_set(:nested_resource, attribute)
          'nested_resource'
        else # [:name, [:string]]
          name = attribute.first.to_s
          datatype = ((attribute.last || []).first || :string).to_s

          b.local_variable_set(:attribute, name)

          if datatype == 'string' && (resource.klass || NilClass).const_defined?(name.pluralize.upcase)
            attribute_constant = "#{resource.klass.name}::#{name.pluralize.upcase}"
            b.local_variable_set(:attribute_constant, attribute_constant)

            'select_constant'
          elsif datatype == :string && (resource.klass || NilClass).const_defined?(name.singularize.upcase)
            attribute_constant = "#{resource.klass.name}::#{name.singularize.upcase}"
            b.local_variable_set(:attribute_constant, attribute_constant)

            'select_constant'
          elsif name.include?('price')
            'price'
          elsif name.include?('_url')
            'url'
          elsif name.include?('email')
            'email'
          else
            datatype
          end
        end

        html = ERB.new(
          File.read("#{File.dirname(__FILE__)}/../../scaffolds/forms/fields/_field_#{partial}.html.haml")
        ).result(b).split("\n").map { |line| ('  ' * depth) + line }

        html.length > 1 ? (html.join("\n") + "\n") : html.join
      end

    end
  end
end


text:
using System.Numerics;
using ImGuiNET;
using OpenSage.Data.Apt.Characters;
using OpenSage.Diagnostics.Util;
using OpenSage.Gui.Apt;
using OpenSage.Gui.Apt.ActionScript;

namespace OpenSage.Diagnostics
{
    internal sealed class AptView : DiagnosticView
    {
        public override string DisplayName { get; } = "APT Windows";
        private DisplayItem _selectedItem;
        private int? _currentClipDepth;

        public AptView(DiagnosticViewContext context)
            : base(context)
        {

        }

        private object CreateObject(Value value)
        {
            switch (value.Type)
            {
                case ValueType.String:
                    return value.ToString();
                case ValueType.Boolean:
                    return value.ToBoolean();
                case ValueType.Short:
                case ValueType.Integer:
                    return value.ToInteger();
                case ValueType.Float:
                    return value.ToFloat();
                case ValueType.Object:
                    return "[OBJECT]";
                case ValueType.Function:
                    return "[FUNCTION]";
                case ValueType.Array:
                    return "[ARRAY]";
                case ValueType.Undefined:
                    return "[UNDEFINED]";
            }

            return null;
        }

        protected override void DrawOverride(ref bool isGameViewFocused)
        {
            foreach (var aptWindow in Game.Scene2D.AptWindowManager.WindowStack)
            {
                ImGui.BeginChild("DisplayLists", new Vector2(400, 0), true, ImGuiWindowFlags.HorizontalScrollbar);

                if (ImGui.TreeNodeEx(aptWindow.Name, ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.OpenOnArrow))
                {
                    DrawDisplayListRecursive(0, aptWindow.Root);
                    ImGui.TreePop();
                }
                ImGui.EndChild();

                ImGui.SameLine();
                ImGui.BeginChild("ScriptObject");
                if (_selectedItem != null)
                {
                    ImGuiUtility.BeginPropertyList();
                    ImGuiUtility.PropertyRow("Type", _selectedItem.Character.GetType());
                    ImGuiUtility.PropertyRow("ClipDepth", _selectedItem.ClipDepth);
                    ImGuiUtility.PropertyRow("Visible", _selectedItem.Visible);

                    ImGuiUtility.EndPropertyList();

                    switch (_selectedItem)
                    {
                        case SpriteItem si:
                            ImGuiUtility.BeginPropertyList();
                            // CurrentFrame shows the next frame that should be played
                            ImGuiUtility.PropertyRow("CurrentFrame", si.CurrentFrame - 1);
                            ImGuiUtility.PropertyRow("State", si.State);
                            ImGuiUtility.EndPropertyList();

                            if (ImGui.CollapsingHeader("FrameLabels", ImGuiTreeNodeFlags.DefaultOpen))
                            {
                                ImGuiUtility.BeginPropertyList();
                                foreach (var frameLabels in si.FrameLabels)
                                {
                                    ImGuiUtility.PropertyRow(frameLabels.Key, frameLabels.Value);
                                }
                                ImGuiUtility.EndPropertyList();
                            }
                            break;
                        case RenderItem ri:
                            if (_selectedItem.Character is Text)
                            {
                                var text = _selectedItem.Character as Text;
                                ImGuiUtility.BeginPropertyList();
                                ImGuiUtility.PropertyRow("Content", ri.TextValue?.Original ?? "null");
                                ImGuiUtility.PropertyRow("LocalizedContent", ri.TextValue?.Localized ?? "null");
                                ImGuiUtility.PropertyRow("InitialContent", text.Content);
                                ImGuiUtility.PropertyRow("InitialValue", text.Value);
                                ImGuiUtility.PropertyRow("Color", text.Color.ToString());
                                ImGuiUtility.PropertyRow("Multiline", text.Multiline);
                                ImGuiUtility.PropertyRow("Wordwrap", text.WordWrap);
                                ImGuiUtility.EndPropertyList();
                            }
                            else if (_selectedItem.Character is Shape)
                            {
                                var shape = _selectedItem.Character as Shape;
                                ImGuiUtility.BeginPropertyList();
                                ImGuiUtility.PropertyRow("GeometryID", shape.Geometry);
                                ImGuiUtility.EndPropertyList();
                            }
                            break;
                    }

                    if (ImGui.CollapsingHeader("Variables", ImGuiTreeNodeFlags.DefaultOpen))
                    {
                        ImGuiUtility.BeginPropertyList();
                        if (_selectedItem.ScriptObject != null)
                        {
                            foreach (var variable in _selectedItem.ScriptObject.Variables)
                            {
                                ImGuiUtility.PropertyRow(variable.Key, CreateObject(variable.Value));
                            }
                        }
                        ImGuiUtility.EndPropertyList();
                    }

                    if (ImGui.CollapsingHeader("Constants", ImGuiTreeNodeFlags.DefaultOpen))
                    {
                        ImGuiUtility.BeginPropertyList();
                        int index = 0;
                        if (_selectedItem.ScriptObject != null)
                        {
                            foreach (var variable in _selectedItem.ScriptObject?.Constants)
                            {
                                ImGuiUtility.PropertyRow($"{index++}", CreateObject(variable));
                            }
                        }
                        ImGuiUtility.EndPropertyList();
                    }
                }
                ImGui.EndChild();
            }
        }

        private void DrawDisplayListRecursive(int depth, DisplayItem item)
        {
            var treeNodeFlags = ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.OpenOnDoubleClick;

            // workaround for Apt Editor
            var type = item.GetType();
            if (type.FullName == "OpenSage.Tools.AptEditor.Apt.WrappedDisplayItem")
            {
                item = (DisplayItem) type.GetProperty("Item").GetValue(item);
            }

            if (_currentClipDepth.HasValue && (depth > _currentClipDepth.Value))
            {
                _currentClipDepth = null;
            }

            if (item.ClipDepth.HasValue)
            {
                _currentClipDepth = item.ClipDepth;
            }

            if (!(item is SpriteItem))
            {
                treeNodeFlags = ImGuiTreeNodeFlags.Leaf;
            }

            if (item == _selectedItem)
            {
                treeNodeFlags |= ImGuiTreeNodeFlags.Selected;
            }

            if (item.ClipDepth.HasValue)
            {
                ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.5f, 1.0f, 0.5f, 1.0f));
            }
            else if (_currentClipDepth.HasValue)
            {
                ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.5f, 0.5f, 0.5f, 1.0f));
            }

            bool hasRenderCallback = false;
            if (item is RenderItem renderItem && renderItem.RenderCallback != null)
            {
                hasRenderCallback = true;
                ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1.0f, 0.5f, 0.5f, 1.0f));
            }

            var opened = ImGui.TreeNodeEx($"[{depth}] {item.Name}", treeNodeFlags);

            if (hasRenderCallback)
            {
                ImGui.PopStyleColor();
            }

            if (_currentClipDepth.HasValue)
            {
                ImGui.PopStyleColor();
            }

            ImGuiUtility.DisplayTooltipOnHover("MovieClip: " + item.Character.Container.MovieName);

            if (ImGuiNative.igIsItemClicked(0) > 0)
            {
                SelectDisplayItem(item);
            }

            if (opened)
            {
                if (item is SpriteItem)
                {
                    var spriteItem = item as SpriteItem;
                    foreach (var pair in spriteItem.Content.Items)
                    {
                        DrawDisplayListRecursive(pair.Key, pair.Value);
                    }
                }

                ImGui.TreePop();
            }
        }

        private void SelectDisplayItem(DisplayItem item)
        {
            if (_selectedItem != null)
            {
                _selectedItem.Highlight = false;
                _selectedItem = null;
            }
            _selectedItem = item;
            _selectedItem.Highlight = true;
            Context.SelectedAptWindow = _selectedItem.Context.Window;
        }
    }
}


text:
package org.lesie.kernel.impl;

import org.lesie.dto.request.LesieRequestDTO;
import org.lesie.dto.response.LesieResponseDTO;
import org.lesie.kernel.SwitchBoard;
import org.lesie.queue.manager.QueueManager;

import java.util.Map;

public class SwitchBoardImpl implements SwitchBoard {

    private QueueManager queueManager;

    public SwitchBoardImpl(){};

    @Override
    public LesieResponseDTO command(String commandName,Map<String,String> parameters){
        LesieRequestDTO requestObj = new LesieRequestDTO(commandName,parameters);
        String requestToken = queueManager.queueRequest(requestObj);
        LesieResponseDTO responseObject = queueManager.queueResponse(requestToken);
        return responseObject;
    };

    public QueueManager getQueueManager() {
        return queueManager;
    }

    public void setQueueManager(QueueManager queueManager) {
        this.queueManager = queueManager;
    }
}


text:
import gulp from 'gulp';
import gcleanCss from 'gulp-clean-css';
import gsourcemaps from 'gulp-sourcemaps';

export default () => {
    return gulp
        .src(['source/**/*.css'])
        .pipe(gsourcemaps.init())
        .pipe(gcleanCss())
        .pipe(gsourcemaps.write('./'))
        .pipe(gulp.dest('public'));
}


text:
import {condition} from "../../src/condition";

describe('The condition decorator', () =>{

  let test;

  beforeAll(()=>{
    test = new TestClass();
  });

  beforeEach(()=>{
    test.log = [];
  });

  it('only executes the function if the condition function return true', () =>{
    test.conditionTest("bar");
    test.conditionTest2("bar");

    expect(test.log.length).toBe(1);
    expect(test.log[0]).toBe("conditionTest2");

  });

  it('considers all arguments to be condition functions, and all conditions have to be met for it to pass', () =>{
    test.conditionTest3();
    test.conditionTest4();

    expect(test.log.length).toBe(1);
    expect(test.log[0]).toBe("conditionTest3");
  });

  it('will use 2nd parameter as an else function if the first parameter is an array of conditional functions ', () =>{
    test.conditionTest5();

    expect(test.log.length).toBe(0);
    expect(test.elseExecuted).toBe(true);
  });

});

export class TestClass {

  constructor(){
    this.log = [];

    this.authorized = false;
    this.debug = true;
  }

  @condition(function(){ return this.authorized === true })
  conditionTest(){
    this.log.push("conditionTest");
  }

  @condition(function(){ return this.authorized === false })
  conditionTest2(){
    this.log.push("conditionTest2");
  }

  @condition(
    function(){ return this.authorized === false },
    function(){ return this.debug === true }
  )
  conditionTest3(){
    this.log.push("conditionTest3");
  }

  @condition(
    function(){ return this.authorized === false },
    function(){ return this.debug === false }
  )
  conditionTest4(){
    this.log.push("conditionTest4");
  }

  @condition([
    function(){ return this.authorized === false },
    function(){ return this.debug === false }
  ], function(){ this.elseExecuted = true })
  conditionTest5(){
    this.log.push("conditionTest5");
  }

}


text:
import optparse
parser = optparse.OptionParser(usage='%prog [options] username[:password]@server[:port] from to subject', description='Sends an email message, reading the password (unless specified on the command line) and body from standard input. The server and port are those of the SMTP server you want to use, and the username is the one you want to log in to that server with.\n' 'Putting the password on the command line is not recommended, as that makes it visible to other processes.')
parser.add_option('--tls', action='store_true', default=True, help='Enable TLS (default)')
parser.add_option('--no-tls', action='store_false', dest='tls', help='Disable TLS')
parser.add_option('--user-agent', default=None, help='Set the User-Agent string')

import sys
opts, args = parser.parse_args()

try:
	hostspec, from_addr, to_addr, subject = args
except ValueError:
	parser.print_help()
	sys.exit(0)

u_p, s_p = hostspec.rsplit('@', 1)
try:
	username, password = u_p.split(':')
except ValueError:
	username = u_p
	import getpass
	password = getpass.getpass() if sys.stdin.isatty() else sys.stdin.readline().rstrip('\n')
else:
	print >>sys.stderr, 'warning: including the password on the command line is insecure (it will show up in ps)'
try:
	hostname, portstr = s_p.split(':')
except ValueError:
	hostname = s_p
	port = 587 if opts.tls else 25
else:
	port = int(portstr)

major, minor, incremental, type, iteration = sys.version_info
python_version = '.'.join(map(str, [major, minor, incremental]))
user_agent_product_tokens = ['simple-mailer/1.0', 'python-smtplib/' + python_version]
if opts.user_agent:
	if '/' not in opts.user_agent:
		# SMTP doesn't really define the User-Agent header, which is why this is a soft warning and not a hard error.
		print >>sys.stderr, 'warning: user-agent product token "%s" is not a valid product token, at least by the HTTP definition' % (opts.user_agent,)
	user_agent_product_tokens.insert(0, opts.user_agent)

import smtplib
smtp = smtplib.SMTP(hostname, port)
smtp.ehlo()
if opts.tls:
	smtp.starttls()
	smtp.ehlo()
smtp.login(username, password)
del password

msg_lines = []
msg_lines.append('From: ' + from_addr + '\r\n')
msg_lines.append('To: ' + to_addr + '\r\n')
msg_lines.append('Subject: ' + subject + '\r\n')
msg_lines.append('User-Agent: ' + ' '.join(user_agent_product_tokens) + '\r\n')
msg_lines += (line.rstrip('\r\n') + '\r\n' for line in sys.stdin)
smtp.sendmail(from_addr, [to_addr], ''.join(msg_lines))
smtp.quit()


text:
When it comes to naming variables, styleguides generally fall into one of two camps: camelcased (`variableName`) and underscores(`variable_name`). This rule focuses on using the camelcase approach. If your styleguide calls for camelcasing your variable names, then this rule is for you!

## Rule Details

This rule looks for any underscores (_) located within the source code. It ignores leading and trailing underscores and only checks those in the middle of a variable name. If ESLint decides that the variable is a constant (all uppercase), then no warning will be thrown. Otherwise, a warning will be thrown.

The following patterns are considered warnings:

```js
var my_favorite_color = "#112C85";
```

The following patterns are considered okay and do not cause warnings:

```js
var myFavoriteColor   = "#112C85";
var _myFavoriteColor  = "#112C85";
var myFavoriteColor_  = "#112C85";
var MY_FAVORITE_COLOR = "#112C85";
```

## When Not To Use It

If you have established coding standards using a different naming convention (separating words with underscores), turn this rule off.


text:
package com.cloudera.hue.livy.spark.batch

import java.lang.ProcessBuilder.Redirect

import com.cloudera.hue.livy.sessions.SessionFactory
import com.cloudera.hue.livy.sessions.batch.BatchSession
import com.cloudera.hue.livy.spark.SparkProcessBuilder.RelativePath
import com.cloudera.hue.livy.spark.{SparkProcess, SparkProcessBuilder, SparkProcessBuilderFactory}
import org.json4s.JValue

abstract class BatchSessionFactory(factory: SparkProcessBuilderFactory) extends SessionFactory[BatchSession] {
  override def create(id: Int, createRequest: JValue) =
    create(id, createRequest.extract[CreateBatchRequest])

  def create(id: Int, request: CreateBatchRequest): BatchSession = {
    val builder = sparkBuilder(request)
    val process = builder.start(RelativePath(request.file), request.args)
    create(id, process)
  }

  protected def create(id: Int, process: SparkProcess): BatchSession

  protected def sparkBuilder(request: CreateBatchRequest): SparkProcessBuilder = {
    val builder = factory.builder()
    builder.conf(request.conf)
    request.proxyUser.foreach(builder.proxyUser)
    request.className.foreach(builder.className)
    request.jars.map(RelativePath).foreach(builder.jar)
    request.pyFiles.map(RelativePath).foreach(builder.pyFile)
    request.files.map(RelativePath).foreach(builder.file)
    request.driverMemory.foreach(builder.driverMemory)
    request.driverCores.foreach(builder.driverCores)
    request.executorMemory.foreach(builder.executorMemory)
    request.executorCores.foreach(builder.executorCores)
    request.totalExecutorCores.foreach(builder.totalExecutorCores)
    request.numExecutors.foreach(builder.numExecutors)
    request.archives.map(RelativePath).foreach(builder.archive)
    request.queue.foreach(builder.queue)
    request.name.foreach(builder.name)

    builder.redirectOutput(Redirect.PIPE)
    builder.redirectErrorStream(true)

    builder
  }
}


text:
require 'logger'
require 'uc/custom_logger'
require 'uc/event_stream'
require 'securerandom'

module Uc
  module Logger

    RUN_ID = SecureRandom.hex(3)

    class << self
      attr_reader :event_queue
    end

    def self.event_queue=(queue_name)
      @event_stream = nil
      @event_queue = queue_name
    end

    def self.logger
      @logger ||= ::Uc::CustomLogger.new(STDOUT)
    end

    def self.stderr
      @stderr ||= ::Logger.new(STDERR)
    end

    def self.event_stream
      @event_stream ||= ::Uc::EventStream.new(event_queue)
    end

    def event_stream
      ::Uc::Logger.event_stream
    end

    def logger
      ::Uc::Logger.logger
    end

    def stderr
      ::Uc::Logger.stderr
    end

    def event_queue
      ::Uc::Logger.event_queue
    end

    def run_id
      RUN_ID
    end
  end
end


text:
package org.elasticsearch.search.aggregations.metrics;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.ScoreMode;
import org.elasticsearch.common.util.ObjectArray;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.search.aggregations.metrics.InternalMedianAbsoluteDeviation.computeMedianAbsoluteDeviation;

public class MedianAbsoluteDeviationAggregator extends NumericMetricsAggregator.SingleValue {

    private final ValuesSource.Numeric valuesSource;
    private final DocValueFormat format;

    private final double compression;

    private ObjectArray<TDigestState> valueSketches;

    MedianAbsoluteDeviationAggregator(
        String name,
        @Nullable ValuesSource valuesSource,
        DocValueFormat format,
        AggregationContext context,
        Aggregator parent,
        Map<String, Object> metadata,
        double compression
    ) throws IOException {

        super(name, context, parent, metadata);

        this.valuesSource = (ValuesSource.Numeric) valuesSource;
        this.format = Objects.requireNonNull(format);
        this.compression = compression;
        this.valueSketches = context.bigArrays().newObjectArray(1);
    }

    private boolean hasDataForBucket(long bucketOrd) {
        return bucketOrd < valueSketches.size() && valueSketches.get(bucketOrd) != null;
    }

    @Override
    public double metric(long owningBucketOrd) {
        if (hasDataForBucket(owningBucketOrd)) {
            return computeMedianAbsoluteDeviation(valueSketches.get(owningBucketOrd));
        } else {
            return Double.NaN;
        }
    }

    @Override
    public ScoreMode scoreMode() {
        if (valuesSource != null && valuesSource.needsScores()) {
            return ScoreMode.COMPLETE;
        } else {
            return ScoreMode.COMPLETE_NO_SCORES;
        }
    }

    @Override
    protected LeafBucketCollector getLeafCollector(LeafReaderContext ctx, LeafBucketCollector sub) throws IOException {
        if (valuesSource == null) {
            return LeafBucketCollector.NO_OP_COLLECTOR;
        }

        final SortedNumericDoubleValues values = valuesSource.doubleValues(ctx);

        return new LeafBucketCollectorBase(sub, values) {
            @Override
            public void collect(int doc, long bucket) throws IOException {

                valueSketches = bigArrays().grow(valueSketches, bucket + 1);

                TDigestState valueSketch = valueSketches.get(bucket);
                if (valueSketch == null) {
                    valueSketch = new TDigestState(compression);
                    valueSketches.set(bucket, valueSketch);
                }

                if (values.advanceExact(doc)) {
                    final int valueCount = values.docValueCount();
                    for (int i = 0; i < valueCount; i++) {
                        final double value = values.nextValue();
                        valueSketch.add(value);
                    }
                }
            }
        };
    }

    @Override
    public InternalAggregation buildAggregation(long bucket) throws IOException {
        if (hasDataForBucket(bucket)) {
            final TDigestState valueSketch = valueSketches.get(bucket);
            return new InternalMedianAbsoluteDeviation(name, metadata(), format, valueSketch);
        } else {
            return buildEmptyAggregation();
        }
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalMedianAbsoluteDeviation(name, metadata(), format, new TDigestState(compression));
    }

    @Override
    public void doClose() {
        Releasables.close(valueSketches);
    }

}


text:
package org.folio.okapi;

import org.folio.okapi.testing.UtilityClassTester;
import org.junit.jupiter.api.Test;

class ConfNameTest {

  @Test
  void utilityClass() {
    UtilityClassTester.assertUtilityClass(ConfNames.class);
  }
}