text:
android-code-generator-plugin-fx
================================

Eclipse plugin for faster activity creation from xml layouts

This project based on http://code.google.com/p/android-code-generator-plugin/.

List of new features:
=====================
 - auto creating packages if they are not exist;
 - dividing code from "onCreate()" to several methods:
	- initView() which contains all "findViewById";
	- setFonts() which contains all "setTypeface" to support Roboto fonts to Android 2.3.3 and less.
	- setListeners which contains all listeners.
 - auto creating adapter class with classic holder implementation. It calls dialog to choose a layout for adapter item.

How to use it
=============
1. Select xml files with activity layout.
2. Right click -> Android Code Generator.
3. Wait few seconds.
4. Use files from %packagename%.activity and %packagename%.adapter

How it works
============

Original activity layout file
-----------------------------

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/news_list_activity_news_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        <ProgressBar
            android:id="@+id/articles_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/articles_exist_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             />

	<Button
            android:id="@+id/articles_exist_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </RelativeLayout>

</RelativeLayout>

Original item layout file
-----------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="15dp"
    android:paddingRight="15dp" >

    <TextView
        android:id="@+id/row_news_date_header_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         />

    <RelativeLayout
        android:id="@+id/news_main_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <FrameLayout
            android:id="@+id/row_news_image_container"
            android:layout_width="96dp"
            android:layout_height="68dp"
             >

            <ImageView
                android:id="@+id/row_news_icon"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>

        <TextView
            android:id="@+id/row_news_title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/row_news_type_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />

        <ImageView
            android:id="@+id/row_news_date_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/row_news_date_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </RelativeLayout>

    <View
        android:id="@+id/row_news_items_divider"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="@drawable/divider_gray_horizontal" />

</LinearLayout>

Result Activity.java
--------------------

package com.test.activity;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.graphics.Typeface;
import com.test.R;
import android.widget.ListView;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.View;

public class NewsListActivityActivity extends Activity {
	private static final String TAG = NewsListActivityActivity.class.getSimpleName();

	private ProgressBar articlesProgress;
	private ListView newsListActivityNewsList;
	private TextView articlesExistTextView;
	private Button articlesExistButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_list_activity);

		initActionBar();
		initViews();
		setFonts();
		setListeners();
	}

	private void initActionBar(){
	}

	private void initViews(){
		articlesProgress = (ProgressBar) findViewById(R.id.articles_progress);
		newsListActivityNewsList = (ListView) findViewById(R.id.news_list_activity_news_list);
		articlesExistTextView = (TextView) findViewById(R.id.articles_exist_text_view);
		articlesExistButton = (Button) findViewById(R.id.articles_exist_button);
	}

	private void setFonts(){
		Typeface roboto = null;//TODO init this by utils
		articlesExistTextView.setTypeface(roboto);
	}

	private void setListeners(){
		articlesExistButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});
	}
}

Result Adapter.java
--------------------

package com.test.adapter;

import com.test.R;
import android.graphics.Typeface;
import android.content.Context;
import java.util.List;
import android.widget.ArrayAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.graphics.Typeface;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.view.View.OnClickListener;
import android.view.View;

public class NewsListActivityAdapter extends ArrayAdapter<String>{
	private static final String TAG = NewsListActivityAdapter.class.getSimpleName();

	private Context context;
	private LayoutInflater inflater;

	public NewsListActivityAdapter(Context context, List<String> objects) {
		super(context, R.layout.news_list_item, objects);
		inflater = LayoutInflater.from(context);
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null){
			convertView = inflater.inflate(R.layout.news_list_item, parent, false);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		String item = getItem(position);
		if (item != null){
			holder.populateForm(item);		}
		return convertView;
	}

	private class ViewHolder{

		private TextView rowNewsDateHeaderText;
		private TextView rowNewsDateText;
		private TextView rowNewsTypeText;
		private TextView rowNewsTitleText;

		public ViewHolder(View v){
			initViews(v);
			setFonts();
		}
		private void initViews(View v){
			rowNewsDateHeaderText = (TextView) v.findViewById(R.id.row_news_date_header_text);
			rowNewsDateText = (TextView) v.findViewById(R.id.row_news_date_text);
			rowNewsTypeText = (TextView) v.findViewById(R.id.row_news_type_text);
			rowNewsTitleText = (TextView) v.findViewById(R.id.row_news_title_text);
		}

		private void setFonts(){
			Typeface roboto = null;//TODO init this by utils
			rowNewsDateHeaderText.setTypeface(roboto);
			rowNewsDateText.setTypeface(roboto);
			rowNewsTypeText.setTypeface(roboto);
			rowNewsTitleText.setTypeface(roboto);
		}

		public void populateForm(String item) {

		}
	}
}

Authors
-------
 - Vladislav Mironov
 - Vadim Kotov

License
-------

Copyright 2013 Vladislav Mironov, SurfStudio

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.


text:
import {bootstrap} from '@angular/platform-browser-dynamic';
import {AppComponent} from "./app.component";
import {HTTP_PROVIDERS} from '@angular/http';
import {GetService} from './services/getService.service';
bootstrap(AppComponent, [HTTP_PROVIDERS]);

redpajama_set_name: RedPajamaGithub


text:
package com.team2502.robot2017.command.autonomous;

import com.team2502.robot2017.command.ShooterCommand;

import edu.wpi.first.wpilibj.command.CommandGroup;

public class AutoCommandG1 extends CommandGroup
{
    public AutoCommandG1()
    {
        addSequential(new DriveTimeCommand(1.0D));
//        addSequential(new TurnLeftCommand(1.0D));
//        addSequential(new DriveTimeCommand(1.0D));
//        addSequential(new AutoVCommand(true));
//        addSequential(new GearCommandG(true));
//        addSequential(new GearCommandG(false));
//        addSequential(new AutoVCommand(false));
//        addSequential(new FlywheelCommand(1.2D));

    }
}


text:
<!DOCTYPE html>

    <link rel="import" href="https://raw.githubusercontent.com/Download/polymer-cdn/1.2.3.2/lib/polymer/polymer.html">
    <link rel="import" href="https://raw.githubusercontent.com/Download/polymer-cdn/1.2.3.2/lib/paper-button/paper-button.html">
    <link rel="import" href="https://raw.githubusercontent.com/Download/polymer-cdn/1.2.3.2/lib/paper-toolbar/paper-toolbar.html">
    <link rel="import" href="https://raw.githubusercontent.com/Download/polymer-cdn/1.2.3.2/lib/paper-radio-button/paper-radio-button.html">

    <link rel="import" href="/static/diff.html">

    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <dom-module id="commits-list">
      <template>

        <paper-toolbar>
          {{toggleIcon}}
          Changes:
          <paper-button raised on-tap="toggleInline">{{inlineButtonTitle}}</paper-button>
        </paper-toolbar>

          <template is="dom-repeat" items="{{commits}}">

              {{item.name}}
              <friendly-timestamp timestamp="{{item.details.time}}"></friendly-timestamp>
              {{item.details.authorEmail}}
              {{item.details.summary}}

                <paper-radio-button name="lhs"
                                    checked="{{item.isLhs}}"
                                    hidden$="{{item.hideLeftHandSelect}}"
                                    disabled="true">
                </paper-radio-button>

                <paper-radio-button name="rhs"
                                    checked="{{item.isRhs}}"
                                    hidden$="{{item.hideRightHandSelect}}"
                                    disabled="true">
                </paper-radio-button>

          </template>

        <unified-diff summary="{{diff}}" inline="{{inline}}" hidden$="{{hidden}}"></unified-diff>
      </template>

    </dom-module>


text:
package org.apache.felix.ipojo.test.scenarios.configuration;

import java.util.Properties;

import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.junit4osgi.OSGiTestCase;
import org.apache.felix.ipojo.test.scenarios.configuration.service.CheckService;
import org.apache.felix.ipojo.test.scenarios.configuration.service.FooService;
import org.apache.felix.ipojo.test.scenarios.util.Utils;
import org.osgi.framework.ServiceReference;

public class TestPropertyModifier extends OSGiTestCase {

    public void testPropertyModifier() {
        ComponentInstance ci = null;
        Factory factory =  Utils.getFactoryByName(getContext(), "org.apache.felix.ipojo.test.scenarios.component.PropertyModifier");
        Properties props = new Properties();
        props.put("cls", new String[] {FooService.class.getName()});
        try {
            ci = factory.createComponentInstance(props);
        } catch (Exception e) {
            fail(e.getMessage());
        }

        ServiceReference ref = Utils.getServiceReferenceByName(getContext(), CheckService.class.getName(), ci.getInstanceName());
        assertNotNull("Check ref", ref);

        // Check the service property
        // Not exposed here:
        assertNull("Classes -0", ref.getProperty("classes"));

        CheckService check = (CheckService) getContext().getService(ref);
        assertTrue(check.check());

        // Property exposed now.
        ref = Utils.getServiceReferenceByName(getContext(), CheckService.class.getName(), ci.getInstanceName());
        Class[] str = (Class[]) ref.getProperty("classes");
        assertEquals("Classes size", 1, str.length);
        assertEquals("Classes[0]", FooService.class.getName(), str[0].getName());

        Properties p = check.getProps();
        Class[] str2 = (Class[]) p.get("classes");
        assertEquals("Classes size -2", 1, str2.length);
        assertEquals("Classes[0] -2", FooService.class.getName(), str2[0].getName());

        Properties props2 = new Properties();
        props2.put("cls", new String[] {FooService.class.getName(), CheckService.class.getName()});
        try {
            ci.reconfigure(props2);
        } catch (Exception e) {
            fail(e.getMessage());
        }

        // Check the service property
        ref = Utils.getServiceReferenceByName(getContext(), CheckService.class.getName(), ci.getInstanceName());
        assertNotNull("Check ref", ref);
        str = (Class[]) ref.getProperty("classes");
        assertEquals("Classes size -3", 2, str.length);
        assertEquals("Classes[0] -3", FooService.class.getName(), str[0].getName());
        assertEquals("Classes[1] -3", CheckService.class.getName(), str[1].getName());

        check = (CheckService) getContext().getService(ref);
        p = check.getProps();
        str2 = (Class[]) p.get("classes");
        assertEquals("Classes size -4", 2, str2.length);
        assertEquals("Classes[0] -4", FooService.class.getName(), str2[0].getName());
        assertEquals("Classes[1] -4", CheckService.class.getName(), str2[1].getName());

        ci.dispose();
        getContext().ungetService(ref);

    }

}


text:
/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2008  litl, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <config.h>
#include <glib.h>
#include <glib-object.h>
#include <util/crash.h>

#include "test.h"

/* we redefine main in test.h so we can include files with tests that have a main();
 * here we actually want main, so we have to kill that off
 */
#undef main
int
main(int    argc,
     char **argv)
{
    g_type_init ();

    gjs_crash_after_timeout(60*7); /* give the unit tests 7 minutes to complete */
    gjs_init_sleep_on_crash();

    g_test_init(&argc, &argv, NULL);

    gjstest_add_all_tests();

    g_test_run();

    return 0;
}


text:
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import Avatar from '../assets/Avatar'
import { ChevronCircleIcon, RolesIcon, ShareIcon } from '../assets/Icons'
import { AppleStore, GooglePlayStore } from '../assets/Sprites'
import { css, hover, media, parent, select } from '../../styles/jss'
import * as s from '../../styles/jso'
import ENV from '../../../env'

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

const storesStyle = css(
  s.absolute, s.zIndex2, { bottom: 12, left: 10 }, s.displayNone,
  media(s.minBreak2, { left: 20 }, s.block),
  media(s.minBreak4, { left: 40 }),
)

export const HeroAppStores = () =>
  (

    <AppleStore />
    <GooglePlayStore />

)

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

const creditsStyle = css(
  s.absolute,
  { right: 10, bottom: 10 },
  s.zIndex1,
  media(s.minBreak2,
    { right: 20, bottom: 20 },
  ),
)

const creditsStyleExpanded = css(
  { ...creditsStyle },
  s.fontSize14,
  s.colorWhite,
  { transition: 'color 0.2s ease, opacity 0.2s ease' },
  hover(s.colorC),
  parent('.isCreditsHidden', s.pointerNone, s.opacity0),
  parent('.ArtistInvites', { right: 20 }),
  parent('.AuthenticationFormDialog.inModal', { right: 20 }),
  media(s.minBreak2,
    { right: 20, bottom: 20 },
    parent('.HeroHeader', { right: 40 }),
    parent('.Editorial', { right: 40 }),
    parent('.AuthenticationFormDialog.inModal', { right: 30 }),
  ),
  media(s.minBreak4,
    parent('.ArtistInvites', { right: 60 }),
    parent('.Editorial', { right: 60 }),
  ),
  media(s.maxBreak2,
    s.flex,
    s.justifyEnd,
    s.itemsCenter,
    s.fullWidth,
    s.pl10,
    {
      whiteSpace: 'nowrap',
      maxWidth: '100%',
    },
    select('& .inHeroPromotionCredits', { flex: 'none' }),
  ),
)

const creditsAuthorStyle = css(
  s.inlineBlock,
  s.ml10,
  { marginRight: 15, lineHeight: 1.2, borderBottom: '1px solid' },
  media(s.maxBreak2,
    parent('.HeroPromotionCredits',
      s.relative,
      s.inlineBlock,
      s.truncate,
      { maxWidth: 'calc(100% - 60px)' },
    ),
    select('&.with-label',
      parent('.HeroPromotionCredits',
        { maxWidth: 'calc(100% - 136px)' },
      ),
    ),
  ),
)

const creditsByStyle = media(s.maxBreak2,
  parent('.HeroPromotionCredits', s.inlineBlock),
)

export const HeroPromotionCredits = ({
  collapsed,
  label,
  sources,
  username,
  trackingLabel,
}, context) => {
  const { onClickTrackCredits } = context
  const track = () => onClickTrackCredits(trackingLabel)
  return (
    <Link
      className={`HeroPromotionCredits ${collapsed ? creditsStyle : creditsStyleExpanded}`}
      onClick={track}
      to={`/${username}`}
    >
      {!collapsed && label && {label}}
      {!collapsed &&
        <span className={`${creditsAuthorStyle}${label ? ' with-label' : ''}`}>@{username}
      }
      <Avatar className="inHeroPromotionCredits" sources={sources} username={username} />
    </Link>
  )
}

HeroPromotionCredits.contextTypes = {
  onClickTrackCredits: PropTypes.func.isRequired,
}

HeroPromotionCredits.propTypes = {
  collapsed: PropTypes.bool,
  label: PropTypes.string,
  sources: PropTypes.object,
  username: PropTypes.string,
  trackingLabel: PropTypes.string,
}
HeroPromotionCredits.defaultTypes = {
  collapsed: false,
}

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

const ctaStyle = css(
  { lineHeight: 1.3 },
)

const ctaTextStyle = css({ borderBottom: '1px solid' })

export const HeroPromotionCTA = ({ caption, to, trackingLabel }, context) => {
  const { onClickTrackCTA } = context
  const track = () => onClickTrackCTA(trackingLabel)
  if (caption && to) {
    const re = new RegExp(ENV.AUTH_DOMAIN.replace('https://', ''))
    if (re.test(to)) {
      return (
        <Link className={ctaStyle} onClick={track} to={to}>
          {caption}
        </Link>
      )
    }
    return (

        {caption}

    )
  }
  return
}

HeroPromotionCTA.contextTypes = {
  onClickTrackCTA: PropTypes.func.isRequired,
}

HeroPromotionCTA.propTypes = {
  caption: PropTypes.string,
  to: PropTypes.string,
  trackingLabel: PropTypes.string,
}

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

const scrollToContentButton = css(
  s.absolute,
  { bottom: 60, left: 'calc(50% - 20px)', borderRadius: 20 },
  s.wv40,
  s.hv40,
  s.bgcBlack,
  media(s.maxBreak2, s.displayNone),
)

export const HeroScrollToContentButton = (props, { onClickScrollToContent }) =>
  (<button className={`HeroScrollToContentButton ${scrollToContentButton}`} onClick={onClickScrollToContent}>
    <ChevronCircleIcon />
  </button>)

HeroScrollToContentButton.contextTypes = {
  onClickScrollToContent: PropTypes.func.isRequired,
}

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

const shareButtonStyle = css(
  s.absolute,
  { top: 40, right: 40, borderRadius: 20 },
  s.displayNone,
  s.wv40,
  s.hv40,
  s.bgcBlack,
  media(s.minBreak2, s.block),
  select('& .ShareIcon',
    s.colorWhite,
    {
      marginTop: -6,
    },
  ),
)

export const HeroShareUserButton = (props, { onClickShareProfile }) =>
  (<button className={`HeroShareUserButton ${shareButtonStyle}`} onClick={onClickShareProfile} >
    <ShareIcon />
  </button>)

HeroShareUserButton.contextTypes = {
  onClickShareProfile: PropTypes.func.isRequired,
}

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

const userRolesButtonStyle = css(
  { ...shareButtonStyle },
  { right: 95 },
  select('& .RolesIcon',
    s.colorWhite,
    {
      marginTop: -3,
    },
    select('& g',
      {
        strokeWidth: 0,
      },
      select('& path',
        {
          strokeWidth: 0,
          fill: '#fff',
        },
      ),
    ),
  ),
)

export const HeroUserRolesButton = (props, { onClickOpenUserRoles }) => {
  if (!props.isRoleAdministrator && !props.userHasRoles) { return null }
  return (<button className={`HeroUserRolesButton ${userRolesButtonStyle}`} onClick={onClickOpenUserRoles} >
    <RolesIcon />
  </button>)
}
HeroUserRolesButton.propTypes = {
  isRoleAdministrator: PropTypes.bool.isRequired,
  userHasRoles: PropTypes.bool.isRequired,
}
HeroUserRolesButton.contextTypes = {
  onClickOpenUserRoles: PropTypes.func.isRequired,
}


text:
require 'rails_helper'

RSpec.describe GenericAnnouncement, type: :model do
  it { is_expected.to belong_to(:instance).optional.inverse_of(:announcements) }
  it { is_expected.to validate_presence_of(:title) }

  let(:instance) { create(:instance) }
  with_tenant(:instance) do
    let!(:active_system_announcements) { create_list(:system_announcement, 1) }
    let!(:active_instance_announcements) { create_list(:instance_announcement, 1) }

    describe 'validations' do
      subject { build(:generic_announcement) }
      context 'when start date is after end date' do
        before { subject.start_at = subject.end_at + 3.days }
        it 'is invalid' do
          expect(subject).to be_invalid
          expect(subject.errors[:start_at]).to include(I18n.t('activerecord.errors.models.' \
            'generic_announcement.attributes.start_at.cannot_be_after_end_at'))
        end
      end
    end

    describe '.currently_active' do
      let!(:now) { Time.zone.now }
      let!(:inactive_announcements) do
        [
          create_list(:system_announcement, 3, start_at: now + 1.day, end_at: now + 2.days),
          create_list(:system_announcement, 3, start_at: now - 2.days, end_at: now - 1.day),
          create_list(:instance_announcement, 3, start_at: now + 1.day, end_at: now + 2.days),
          create_list(:instance_announcement, 3, start_at: now - 2.days, end_at: now - 1.day)
        ].flatten
      end

      it 'shows currently active announcements' do
        active_announcements = active_system_announcements + active_instance_announcements
        all = GenericAnnouncement.currently_active.where(id: active_announcements.map(&:id))
        expect(all).to contain_exactly(*active_announcements)
      end

      it 'does not show inactive announcements' do
        active = GenericAnnouncement.currently_active.where(id: inactive_announcements.map(&:id))
        expect(active).to be_empty
      end
    end

    describe '.default_scope' do
      it 'orders by descending start_at within type' do
        all = GenericAnnouncement.with_instance([nil, instance])
        system_announcements, instance_announcements = all.partition do |a|
          a.is_a?(System::Announcement)
        end

        comparator = proc { |x, y| x >= y }
        system_sorted = system_announcements.map(&:start_at).each_cons(2).all?(&comparator)
        instance_sorted = instance_announcements.map(&:start_at).each_cons(2).all?(&comparator)

        expect(system_sorted).to be_truthy
        expect(instance_sorted).to be_truthy
      end

      it 'orders system announcements before instance announcements' do
        announcements = GenericAnnouncement.with_instance([nil, instance])
        instance_announcements = announcements.drop_while { |a| a.is_a?(System::Announcement) }
        all_instance = instance_announcements.all? { |a| a.is_a?(Instance::Announcement) }
        expect(all_instance).to be_truthy
      end
    end

    describe '.for_instance' do
      it 'retrieves both instance announcements and global announcements' do
        announcements = GenericAnnouncement.for_instance(instance)
        expect(announcements).to include(*active_system_announcements)
        expect(announcements).to include(*active_instance_announcements)
      end
    end

    describe 'unread state' do
      let(:creator) { create(:creator) }
      let!(:user) { create(:user) }
      let!(:system_announcement) { create(:system_announcement, creator: creator) }
      let!(:instance_announcement) { create(:instance_announcement, creator: creator) }

      it 'has been read by the creator' do
        expect(creator.have_read?(instance_announcement)).to eq(true)
        expect(creator.have_read?(system_announcement)).to eq(true)
      end

      it 'is unread by other users' do
        expect(user.have_read?(instance_announcement)).to eq(false)
        expect(user.have_read?(system_announcement)).to eq(false)
      end
    end
  end
end


text:
package play.utils.crud;

import com.google.common.collect.ImmutableSortedSet;

import play.Application;
import play.GlobalSettings;
import play.Logger;
import play.Logger.ALogger;
import play.api.Play;
import play.utils.inject.InjectAdapter;
import play.utils.meta.ConverterRegistry;
import play.utils.meta.ControllerRegistry;
import play.utils.meta.cp.ClasspathScanningControllerRegistry;
import play.utils.meta.cp.ClasspathScanningConverterRegistry;
import play.utils.meta.cp.ClasspathScanningModelRegistry;

public class CRUDManager {

	private static ALogger log = Logger.of(CRUDManager.class);

	GlobalSettings global;

	InjectAdapter injections = InjectAdapter.getInstance();

	RouterRestController dynamicRestController;

	RouterCrudController dynamicCrudController;

	ClasspathScanningModelRegistry models;

	private static CRUDManager instance;

	public CRUDManager(GlobalSettings global) {
		this.global = global;
	}

	public void initialize(Application app) {
		if (log.isDebugEnabled())
			log.debug("initialize <-");
		ClassLoader appClassloader = Play.classloader(Play.current());
		ClassLoader libClassloader = getClass().getClassLoader();
		ClassLoader[] classLoaders = new ClassLoader[] { appClassloader, libClassloader };
		ConverterRegistry converters = new ClasspathScanningConverterRegistry(classLoaders);
		models = new ClasspathScanningModelRegistry(converters, classLoaders);
		ControllerRegistry crudControllers = new ClasspathScanningControllerRegistry(global, models, classLoaders);
		dynamicRestController = new RouterRestController(crudControllers, models);
		dynamicCrudController = new RouterCrudController(crudControllers, models, appClassloader);
		instance = this;
	}

	@SuppressWarnings("unchecked")
	public <A> A getController(Class<A> type) throws Exception {
		if (RouterRestController.class.equals(type))
			return (A) dynamicRestController;

		if (RouterCrudController.class.equals(type))
			return (A) dynamicCrudController;

		return injections.getInstance(type);
	}

    public static CRUDManager getInstance() {
		return instance;
	}

	public Iterable<String> modelNames() {
        return ImmutableSortedSet.<String>naturalOrder().addAll(models.getModelNames()).build();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright 2019 Google LLC
   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.
-->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/lib/com.google.android.apps.authenticator2"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:background="@color/howItWorksBackgroundColor">
  <android.support.v4.view.ViewPager android:id="@+id/howitworks_pager"
                                     android:layout_width="match_parent"
                                     android:layout_height="match_parent"
                                     android:paddingBottom="@dimen/nav_panel_height">
  </android.support.v4.view.ViewPager>

  <FrameLayout android:layout_width="match_parent"
               android:layout_height="@dimen/nav_panel_height"
               android:layout_gravity="bottom">
    <Button android:id="@+id/howitworks_button_skip"
            style="@style/HowItWorksButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginStart="4dp"
            android:layout_marginLeft="4dp"
            android:layout_gravity="start|center_vertical"
            android:text="@string/howitworks_page_button_skip"/>
    <com.google.android.apps.authenticator.howitworks.PagingIndicator
      android:id="@+id/paging_indicator"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:background="@android:color/transparent"
      app:currentPageIndicatorColor="@color/pagination_active"
      app:pageIndicatorColor="@color/pagination_inactive"/>
    <ImageButton
      android:id="@+id/howitworks_button_next"
      style="@style/Widget.AppCompat.Button.Borderless"
      android:layout_width="@dimen/nav_panel_height"
      android:layout_height="match_parent"
      android:layout_gravity="end|center_vertical"
      android:contentDescription="@string/howitworks_page_button_next"
      android:scaleType="center"
      android:src="@drawable/quantum_ic_navigate_next_white_24"/>
    <Button
      android:id="@+id/howitworks_button_done"
      style="@style/HowItWorksButtonStyle"
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:layout_marginEnd="4dp"
      android:layout_marginRight="4dp"
      android:layout_gravity="end|center_vertical"
      android:text="@string/howitworks_page_button_done"
      android:visibility="gone"/>
  </FrameLayout>

  <View android:id="@+id/separator"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="@dimen/nav_panel_height"
        android:layout_gravity="bottom"
        android:background="#33ffffff"/>
</FrameLayout>


text:
package de.madcyph3r.materialnavigationdrawer.listener;

import android.view.View;

import de.madcyph3r.materialnavigationdrawer.menu.item.section.MaterialItemSection;

public interface MaterialSectionOnClickListener {

    public void onClick(MaterialItemSection section, View v);
}


text:
'use strict';

/**
 * The response from the List Container Services operation.
 */
class ContainerServiceListResult extends Array {
  /**
   * Create a ContainerServiceListResult.
   * @member {string} [nextLink] The URL to get the next set of container
   * service results.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ContainerServiceListResult
   *
   * @returns {object} metadata of ContainerServiceListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ContainerServiceListResult',
      type: {
        name: 'Composite',
        className: 'ContainerServiceListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ContainerServiceElementType',
                  type: {
                    name: 'Composite',
                    className: 'ContainerService'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            readOnly: true,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ContainerServiceListResult;


text:
This is to test and describe the steps to create a ASP.Net Core web application

1. Installations
    1. [DotNet Core](https://www.microsoft.com/net/core)
	2. [NodeJS with npm](https://nodejs.org)
	3. [Visual Studio Code](https://code.visualstudio.com)

restart

> npm install npm -g
> npm install yo -g
> npm install generator-aspnet -g
> yo aspnet
-> Select Empty Web Application
-> Enter «appName>
(as instructed by yo)
> cd core
> dotnet restore
> dotnet build
> dotnet run
test browser http://localhost:5000/
Open VS Code
> code .


text:
/* 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.flowable.engine.delegate.variable;

import org.flowable.bpmn.model.VariableAggregationDefinition;

/**
 * @author Filip Hrisafov
 */
public interface VariableAggregatorContext {

    /**
     * State when the execution is completed and the aggregation needs to be prepared.
     * e.g. This can be done for different executions:
     *

     *
After the child execution of a multi instance execution completes

     *
After the multi instance execution completes

     *
After any execution completes

     *

     */
    String COMPLETE = "complete";
    /**
     * State when the execution is not yet completed and we need to see an overview state.
     * e.g. This can be done for different executions:
     *

     *
For an active child execution of a multi instance execution

     *
For an active multi instance execution

     *
For any execution

     *

     */
    String OVERVIEW = "overview";

    VariableAggregationDefinition getDefinition();

    String getState();
}


text:
"""
Base R2C2 3B Model.

3 Pre-training datasets (pushshift.io Reddit, RoBERTa, & CC)
"""
from parlai.zoo.seeker.seeker_download import download_with_model_type

def download(datapath):
    download_with_model_type(datapath, 'r2c2_base_3B', 'v1.0')


text:
import { TextElement } from './TextElement'

export class TRefElement extends TextElement {
  override type = 'tref'

  override getText() {
    const element = this.getHrefAttribute().getDefinition()

    if (element) {
      const firstChild = element.children[0] as TextElement

      if (firstChild) {
        return firstChild.getText()
      }
    }

    return ''
  }
}


text:
package org.dspace.app.webui.util;

import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.dspace.core.ConfigurationManager;

/**
 * Based on the com.oreilly.servlet.MultipartWrapper object, this is an HTTP
 * request wrapper for multi-part (MIME) POSTs. It uses DSpace configuration
 * properties to determine the temporary directory to use and the maximum
 * allowable upload size.
 *
 * @author Robert Tansley
 * @version $Revision$
 */
public class FileUploadRequest extends HttpServletRequestWrapper
{
    private Map<String, String> parameters = new HashMap<String, String>();

    private Map<String, FileItem> fileitems = new HashMap<String, FileItem>();

    private List<String> filenames = new ArrayList<String>();

    private String tempDir = null;

    /** Original request */
    private HttpServletRequest original = null;

    /**
     * Parse a multipart request and extracts the files
     *
     * @param req
     *            the original request
     */
    public FileUploadRequest(HttpServletRequest req) throws IOException, FileSizeLimitExceededException
    {
        super(req);

        original = req;

        tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        long maxSize = ConfigurationManager.getLongProperty("upload.max");

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File(tempDir));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        try
        {
            upload.setSizeMax(maxSize);
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items)
            {
                if (item.isFormField())
                {
                    parameters.put(item.getFieldName(), item.getString("UTF-8"));
                }
                else
                {
                    parameters.put(item.getFieldName(), item.getName());
                    fileitems.put(item.getFieldName(), item);
                    filenames.add(item.getName());

                    String filename = getFilename(item.getName());
                    if (filename != null && !"".equals(filename))
                    {
                        item.write(new File(tempDir + File.separator
                                        + filename));
                    }
                }
            }
        }
        catch (Exception e)
        {
            if(e.getMessage().contains("exceeds the configured maximum"))
            {
                // ServletFileUpload is not throwing the correct error, so this is workaround
                // the request was rejected because its size (11302) exceeds the configured maximum (536)
                int startFirstParen = e.getMessage().indexOf("(")+1;
                int endFirstParen = e.getMessage().indexOf(")");
                String uploadedSize = e.getMessage().substring(startFirstParen, endFirstParen).trim();
                Long actualSize = Long.parseLong(uploadedSize);
                throw new FileSizeLimitExceededException(e.getMessage(), actualSize, maxSize);
            }
            throw new IOException(e.getMessage(), e);
        }
    }

    // Methods to replace HSR methods
    public Enumeration getParameterNames()
    {
        Collection<String> c = parameters.keySet();
        return Collections.enumeration(c);
    }

    public String getParameter(String name)
    {
        return parameters.get(name);
    }

    public String[] getParameterValues(String name)
    {
        return parameters.values().toArray(new String[parameters.values().size()]);
    }

    public Map getParameterMap()
    {
        Map<String, String[]> map = new HashMap<String, String[]>();
        Enumeration eNum = getParameterNames();

        while (eNum.hasMoreElements())
        {
            String name = (String) eNum.nextElement();
            map.put(name, getParameterValues(name));
        }

        return map;
    }

    public String getFilesystemName(String name)
    {
        String filename = getFilename((fileitems.get(name))
                .getName());
        return tempDir + File.separator + filename;
    }

    public String getContentType(String name)
    {
        return (fileitems.get(name)).getContentType();
    }

    public File getFile(String name)
    {
        FileItem temp = fileitems.get(name);
        String tempName = temp.getName();
        String filename = getFilename(tempName);
        if ("".equals(filename.trim()))
        {
            return null;
        }
        return new File(tempDir + File.separator + filename);
    }

    public Enumeration<String> getFileParameterNames()
    {
        Collection<String> c = fileitems.keySet();
        return Collections.enumeration(c);
    }

    public Enumeration<String> getFileNames()
    {
        return Collections.enumeration(filenames);
    }

    /**
     * Get back the original HTTP request object
     *
     * @return the original HTTP request
     */
    public HttpServletRequest getOriginalRequest()
    {
        return original;
    }

    // Required due to the fact the contents of getName() may vary based on
    // browser
    private String getFilename(String filepath)
    {
        String filename = filepath.trim();

        int index = filepath.lastIndexOf(File.separator);
        if (index > -1)
        {
            filename = filepath.substring(index);
        }
        return filename;
    }
}