text:
class NewCatalog

	def initialize(url)
		@url = url
		@user_agent_list = [
												"Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (FM Scene 4.6.1)",
												"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
												"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36",
												"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
												"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
												"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36",
												"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
												"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/602.3.12 (KHTML, like Gecko) Version/10.0.2 Safari/602.3.12",
												"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
												"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0",
												"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0"
											 ]
		@structure = []
	end

	def execute
		grab_main_category_links
		grab_category_content(@structure)
		parse_all_products(@structure)
	end

	def grab_main_category_links
		url = "#{@url}/production/catalog"
		page=Nokogiri::HTML(open(url,"User-Agent" => @user_agent_list.sample))
		page.css('div#main_content_navigation ul li')
				.reject do |li|
					# if 'class' attribute exist then it's third level category
					third_level = li.parent.attributes.any?
					# if url not include 'catalog' then it's not a category
					not_category = !(li.at('a')['href'].include?('catalog'))
					third_level || not_category
				end
				.each do |li|
					url = set_url(li.at('a')['href'])
					@structure << wrap_as_category( category_name:li.at('a').text.strip.capitalize,
																				  link:url )
				end
	end

	def grab_category_content(parent_categories)
		parent_categories.each do |category|
			page=Nokogiri::HTML(open(category[:link],"User-Agent" => @user_agent_list.sample))

			# Save category image
			imgs = page.css('div.SectionPicture img')
			category[:image] = "#{@url}#{imgs.first['src']}" if imgs.any?

			# Save category description
			category[:description] = page.css('div.SectionText p')
																	 .map(&:to_s).join("\n")

			# Grab sub categories if exist
			third_level_categories_node = page.css('table.SubSections div strong a')
			if third_level_categories_node.any?
				sub_categories = third_level_categories_node.map do |cat|
						cat_url = set_url(cat['href'])
					  wrap_as_category(category_name:cat.text.strip.capitalize,
														 link:cat_url,
														 parent:category[:category_name])
				end
				category[:childs] = sub_categories
				grab_category_content(sub_categories)
			else
				save_products_links(page,category)
			end
		end
	end

	private

		def set_url(url_fragment)
			new_url = url_fragment
			unless URI(url_fragment).host
				new_url = "#{@url}#{url_fragment}"
			end
			new_url
		end

		def parse_all_products(categories)
			categories.each do |category|
				parse_category_products(category[:products])
				parse_all_products(category[:childs]) if category[:childs].any?
			end
			categories
		end

		def save_products_links(page,category)
			# Grab products from category
			product_list_node = page.css('div.ProductsList div.row')
			if product_list_node.any?
				product_list_node.each do |product|
					url_node = product.css('div.name a').first
					url = "#{@url}#{url_node['href']}"
					name = url_node.text.strip.capitalize
					short_description = product.css('div.preview').text
					category[:products]	<< wrap_as_product(link:url,
																								 product_name:name,
																								 short_description:short_description)
				end
			end
		end

		def parse_category_products(product_list)
			product_list.reject{|e| e[:link].nil?}
				.each do |item|
				ue = @user_agent_list.sample
				page = Nokogiri::HTML(open(item[:link],"User-Agent" => ue ))
				image_node = page.css('div.picture img').first
				desc_node = page.css('div#main_content_block')
				desc_node.css('div#main_shortnav').remove
				desc_node.css('div.ProductCard div.picture').remove
				desc_node.css('div.ProductPrint').remove
				desc_node.css('div.ProductAltTitle').remove
				desc_node.css('div.TogetherTitle').remove
				desc_node.css('div.TogetherList').remove
				desc_node.css('div#main_cnt_sidebar').remove

				if image_node
					item[:product_image] =  "#@url#{image_node['src']}"
				end

				if desc_node.any?
					item[:long_description] = desc_node.to_s
				end
			end
		end

		def grab_category_info(url)
			products = []
			image = ''
			description = ''
			page = Nokogiri::HTML(open(url))

			# Save category image
			imgs = page.css('div.catalog_page img')
			image = "#{@url}#{imgs.first['src']}" if imgs.any?

			# Save category description
			description = page.css('div.catalog_page p')
			description = description.map(&:to_s).join("\n") if description.any?

			{image:image, description:description}
		end

		def wrap_as_product(opt={})
			{
				link:opt[:link],
				product_name:opt[:product_name],
		    price:opt[:price],
		    legacy_id:opt[:legacy_id],
		    product_image:opt[:product_image],
		    label_image:opt[:label_image],
		    short_description:opt[:short_description],
		    long_description:opt[:long_description],
		    availability:false,
		    rating:nil,
		    certificates:[]
			}
		end

		def wrap_as_category(opt={})
			 {
				category_name:opt[:category_name],
				link:opt[:link],
				parent:opt[:parent],
				childs:opt[:childs]||[],
				products:opt[:products]||[],
				image:opt[:image],
				description:opt[:description]
			 }
		end

end


text:
use std::path::Path;

use git2;

use util::{CargoResult, process};

pub struct HgRepo;
pub struct GitRepo;

impl GitRepo {
    pub fn init(path: &Path, _: &Path) -> CargoResult<GitRepo> {
        try!(git2::Repository::init(path));
        Ok(GitRepo)
    }
    pub fn discover(path: &Path, _: &Path) -> Result<git2::Repository,git2::Error> {
        git2::Repository::discover(path)
    }
}

impl HgRepo {
    pub fn init(path: &Path, cwd: &Path) -> CargoResult<HgRepo> {
        try!(process("hg").cwd(cwd).arg("init").arg(path).exec());
        Ok(HgRepo)
    }
    pub fn discover(path: &Path, cwd: &Path) -> CargoResult<HgRepo> {
        try!(process("hg").cwd(cwd).arg("root").cwd(path).exec_with_output());
        Ok(HgRepo)
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?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" >

    <RelativeLayout
        android:id="@+id/scoreTab"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@color/tab_color" >

        <View
            android:id="@+id/view1"
            android:layout_width="1dp"
            android:layout_height="fill_parent"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:background="@color/appBg_color" />

        <TextView
            android:id="@+id/score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/scoreTxt"
            android:layout_alignBottom="@+id/scoreTxt"
            android:layout_marginLeft="18dp"
            android:layout_toRightOf="@+id/scoreTxt"
            android:text="0"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffff" />

        <TextView
            android:id="@+id/complete_ratio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/complatedTxt"
            android:layout_alignBottom="@+id/complatedTxt"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/complatedTxt"
            android:text=" 0%"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffff" />

        <TextView
            android:id="@+id/complatedTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:text="Complete :"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffff" />

        <TextView
            android:id="@+id/scoreTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/complete_ratio"
            android:layout_alignBottom="@+id/complete_ratio"
            android:layout_marginLeft="24dp"
            android:layout_toRightOf="@+id/view1"
            android:text="Score   :"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffff" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/mainDiagramHeart"
        android:layout_width="340dp"
        android:layout_height="300dp"
        android:layout_below="@+id/scoreTab"
        android:layout_centerHorizontal="true"
        android:src="@drawable/human_ear" />

    <ImageView
        android:id="@+id/tagHolder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:adjustViewBounds="true"
        android:src="@drawable/holder" />

    <ImageView
        android:id="@+id/pinnaBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignLeft="@+id/mainDiagramHeart"
        android:layout_alignTop="@+id/mainDiagramHeart"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="17dp"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/malleusBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_below="@+id/pinnaBlb"
        android:layout_centerHorizontal="true"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/incusBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_below="@+id/pinnaBlb"
        android:layout_marginLeft="9dp"
        android:layout_toRightOf="@+id/malleusBlb"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/canalsBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/pinnaBlb"
        android:layout_marginLeft="44dp"
        android:layout_marginTop="7dp"
        android:layout_toRightOf="@+id/incusBlb"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/earnerveBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_below="@+id/canalsBlb"
        android:layout_marginLeft="13dp"
        android:layout_marginTop="7dp"
        android:layout_toRightOf="@+id/canalsBlb"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/stapesBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="7dp"
        android:layout_toRightOf="@+id/incusBlb"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/earcanalBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_below="@+id/stapesBlb"
        android:layout_marginRight="7dp"
        android:layout_marginTop="7dp"
        android:layout_toLeftOf="@+id/eardrumBlb"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/outerearBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/earcanalBlb"
        android:layout_marginTop="11dp"
        android:layout_toRightOf="@+id/pinnaBlb"
        android:src="@drawable/marker" />

    <TextView
        android:id="@+id/pinnaTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/mainDiagramHeart"
        android:layout_below="@+id/mainDiagramHeart"
        android:layout_marginTop="55dp"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="Pinna"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/cochleaTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/canalsBlb"
        android:layout_alignTop="@+id/eardrumTag"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="cochlea"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/eardrumTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/ear_canalTag"
        android:layout_alignBottom="@+id/ear_canalTag"
        android:layout_alignRight="@+id/stapesBlb"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="eardrum"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/ear_canalTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/pinnaTag"
        android:layout_alignBottom="@+id/pinnaTag"
        android:layout_toLeftOf="@+id/eardrumBlb"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="ear canal"
        android:textColor="#ffff" />

    <ImageView
        android:id="@+id/cochleaBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_above="@+id/stapesBlb"
        android:layout_marginBottom="31dp"
        android:layout_toRightOf="@+id/canalsBlb"
        android:src="@drawable/marker" />

    <ImageView
        android:id="@+id/eardrumBlb"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_above="@+id/stapesBlb"
        android:layout_alignLeft="@+id/malleusBlb"
        android:src="@drawable/marker" />

    <TextView
        android:id="@+id/incusTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/earnerveTag"
        android:layout_alignBottom="@+id/earnerveTag"
        android:layout_alignLeft="@+id/eardrumTag"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="incus"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/outerearTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/incusTag"
        android:layout_alignBottom="@+id/incusTag"
        android:layout_alignRight="@+id/cochleaTag"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="outer ear"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/canalsTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/stapesTag"
        android:layout_alignBottom="@+id/stapesTag"
        android:layout_toRightOf="@+id/outerearBlb"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="canals"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/malleusTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/canalsTag"
        android:layout_below="@+id/ear_canalTag"
        android:layout_marginTop="15dp"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="malleus"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/earnerveTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/stapesTag"
        android:layout_alignLeft="@+id/pinnaTag"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="nerve"
        android:textColor="#ffff" />

    <TextView
        android:id="@+id/stapesTag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/earnerveTag"
        android:layout_below="@+id/malleusTag"
        android:layout_marginTop="14dp"
        android:background="@drawable/custom_textview"
        android:paddingBottom="3dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="3dp"
        android:text="stapes"
        android:textColor="#ffff" />

</RelativeLayout>


text:
@page testing Testing Cookbook
@parent getstarted 1

JavaScriptMVC puts a tremendous emphasis on
testing. It uses [FuncUnit] to provide easy to write functional and
unit tests that can be run in the browser or automated!

When you scaffolded recipe, it created tests for you.  This guide will show you how to:

- Run unit tests.
- Understand the unit tests.
- Run functional tests.
- Understand the functional tests.
- Test isTasty functionality.

## Run Unit Tests

FuncUnit uses QUnit unit test things like models and basic plugins.  You can run these
tests in the browser or Envjs (and now PhantomJS with a little extra work).

### Run Unit Tests in the Browser

Open `cookbook/qunit.html`.  You should see something like:

@image site/images/test_cookbook_example.png

We'll see how this works in a second.  First, lets run the unit tests
in Envjs.

### Run Unit Tests with Selenium

Selenium automates browsers. FuncUnit can run your tests in this environment.

In a command window type:

    > js funcunit/open/selenium cookbook/qunit.html

This runs qunit.html in a simulated
browser environment. The output should look like:

## Understanding the Unit Tests

FuncUnit uses [http://docs.jquery.com/QUnit QUnit] for assertions and
organizing them into tests and modules.  The best place to start understanding the
unit tests is to read through [http://docs.jquery.com/QUnit QUnit's documentation].

__cookbook/qunit.html__ loads [steal] and tells it to load
`cookbook/test/qunit/qunit.js` which loads your unit tests:

 - `cookbook/test/qunit/cookbook_test.js`
 - `cookbook/test/qunit/recipe_test.js`

These files steal `funcunit/qunit` then
declare tests that get run once
all scripts have loaded.

Open __cookbook/test/qunit/recipe_test.js__,
and lets see how the __findAll__ test works:

    //creates a test
    test("findAll", function(){
      //prevents the next test from running
      stop(2000);

      //requests recipes
      Cookbook.Models.Recipe.findAll({}, function(recipes){

        //makes sure we have something
        ok(recipes)

        //makes sure we have at least 1 recipe
        ok(recipes.length)

        //makes sure a recipe looks right
        ok(recipes[0].name)
        ok(recipes[0].description)

        //allows the next test to start
        start()
      });
    })

## Run Functional Tests

Functional tests are used to test things
that require user interaction like widgets that listen for
clicks and key events.

Cookbook's functional tests test the recipe create and recipe lists widgets.

### Run Functional Tests in the Browser

Open `cookbook/funcunit.html`.  You should see something like:

### Run Functional Tests in Selenium

[http://seleniumhq.org/ Selenium] can automate launching browsers and is packaged
with FuncUnit.

In a command window type:

    > js funcunit/open/selenium cookbook/funcunit.html

This should open Firefox and IE if you are using Windows.  The results of the
test should look like:

	If Selenium is unable to open your browsers, it's likely you have them in an
	unusual location.  Read [FuncUnit.static.browsers] for information on how to configure browsers
	so selenium can find them.

If you are having trouble running the tests in Internet Explorer, you need to change a
few settings in the browser.  Please see the [FuncUnit FuncUnit documentation] for troubleshooting help.

## Understanding FuncUnit Tests

FuncUnit adds to QUnit the ability to open another page, in this case
`cookbook/cookbook.html`, perform actions on it, and
get information from it.

The `cookbook/funcunit.html`  page
works just like `qunit.html` except the 'funcunit' plugin is loaded which
provides [FuncUnit]. FuncUnit is aliased to `S` to highlight the similarity between its API
and jQuery's API.

Let take a quick look at a FuncUnit test:

    test("create recipes", function(){

      //type Ice in the name field
      S("[name=name]").type("Ice")

      //type Cold Water in the description field
      S("[name=description]").type("Cold Water")

      //click the submit button
      S("[type=submit]").click()

      //wait until the 2nd recipe exists
      S('.recipe:nth-child(2)').exists()

      //Gets the text of the first td
      S('.recipe:nth-child(2) td:first').text(function(text){

        //checks taht it has ice
        ok(text.match(/Ice/), "Typed Ice");
      });

    })

Functional tests are largely many asynchronous actions
(clicks and keypresses)
with relatively few checks/assertions.
FuncUnit's goal is to provide as readable and linear syntax as possible.
FuncUnit statements are actually stored and then run asynchronously.  This requires that
getting a value from the page happens in a callback function.

For more information on FuncUnit, read its [FuncUnit documentation]


text:
package com.github.sunnybat.paxchecker.status;

import com.github.sunnybat.paxchecker.PAXChecker;
import com.github.sunnybat.paxchecker.resources.ResourceLoader;
import java.awt.Image;
import java.io.IOException;
import java.util.Calendar;

/**
 *
 * @author SunnyBat
 */
public class Tickets extends com.github.sunnybat.commoncode.javax.swing.JFrame {

	static {
		try {
			myIcon = javax.imageio.ImageIO.read(ResourceLoader.loadResource("Alert.png"));
		} catch (IOException iOE) {
			iOE.printStackTrace();
			System.out.println("Failed to load ImageIcon for Tickets window -- program will still function normally.");
		}
	}

	private static Image myIcon;

	public Tickets(final String link) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				initComponents();
				setIconImage(myIcon);
				String newline = System.getProperty("line.separator");
				jTextArea1.append(newline + newline + "Tickets found at " + currentTime());
				jTextArea1.append(newline + newline + "URL found: " + link);
				jTextArea1.append(newline + newline + "Version: " + PAXChecker.VERSION);
				setAlwaysOnTop(true);
				setVisible(true);
				toFront();
				requestFocus();
			}
		});
	}

	private static String currentTime() {
		StringBuilder ret = new StringBuilder();
		Calendar myCal = Calendar.getInstance();
		int hours = myCal.get(Calendar.HOUR);
		if (hours == 0) {
			hours = 12; // noon+midnight are 0, not 12, so fix it
		}
		ret.append(hours).append(":");
		int minutes = myCal.get(Calendar.MINUTE);
		ret.append(minutes).append(":");
		int seconds = myCal.get(Calendar.SECOND);
		ret.append(seconds).append(" ");
		int ampm = myCal.get(Calendar.AM_PM);
		if (ampm == Calendar.AM) {
			ret.append("AM");
		} else if (ampm == Calendar.PM) {
			ret.append("PM");
		} else {
			ret.append("[AM/PM?]");
		}
		return ret.toString();
	}

	/**
	 * This method is called from within the constructor to initialize the form. WARNING: Do NOT
	 * modify this code. The content of this method is always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("PAX Update Found!");
    setResizable(false);

    jTextArea1.setEditable(false);
    jTextArea1.setColumns(20);
    jTextArea1.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N
    jTextArea1.setForeground(new java.awt.Color(255, 51, 0));
    jTextArea1.setLineWrap(true);
    jTextArea1.setRows(5);
    jTextArea1.setText("An update has been found!\n\nAn attempt to open the link found in your default browser has been made. If it did not open, you will have to do so manually.\n\nGood luck buying tickets!\n- /u/SunnyBat (Sunnybat@yahoo.com)\n\nIf this was a false positive, feel free to post on /r/PAXChecker or PM /u/SunnyBat individually.");
    jTextArea1.setWrapStyleWord(true);
    jScrollPane1.setViewportView(jTextArea1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 579, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JTextArea jTextArea1;
  // End of variables declaration//GEN-END:variables
}


text:
// Code generated by go-swagger; DO NOT EDIT.

package account_manager

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"
	"time"

	"golang.org/x/net/context"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"

	strfmt "github.com/go-openapi/strfmt"

	"openpitrix.io/openpitrix/test/models"
)

// NewJoinGroupParams creates a new JoinGroupParams object
// with the default values initialized.
func NewJoinGroupParams() *JoinGroupParams {
	var ()
	return &JoinGroupParams{

		timeout: cr.DefaultTimeout,
	}
}

// NewJoinGroupParamsWithTimeout creates a new JoinGroupParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewJoinGroupParamsWithTimeout(timeout time.Duration) *JoinGroupParams {
	var ()
	return &JoinGroupParams{

		timeout: timeout,
	}
}

// NewJoinGroupParamsWithContext creates a new JoinGroupParams object
// with the default values initialized, and the ability to set a context for a request
func NewJoinGroupParamsWithContext(ctx context.Context) *JoinGroupParams {
	var ()
	return &JoinGroupParams{

		Context: ctx,
	}
}

// NewJoinGroupParamsWithHTTPClient creates a new JoinGroupParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewJoinGroupParamsWithHTTPClient(client *http.Client) *JoinGroupParams {
	var ()
	return &JoinGroupParams{
		HTTPClient: client,
	}
}

/*JoinGroupParams contains all the parameters to send to the API endpoint
for the join group operation typically these are written to a http.Request
*/
type JoinGroupParams struct {

	/*Body*/
	Body *models.OpenpitrixJoinGroupRequest

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithTimeout adds the timeout to the join group params
func (o *JoinGroupParams) WithTimeout(timeout time.Duration) *JoinGroupParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the join group params
func (o *JoinGroupParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the join group params
func (o *JoinGroupParams) WithContext(ctx context.Context) *JoinGroupParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the join group params
func (o *JoinGroupParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the join group params
func (o *JoinGroupParams) WithHTTPClient(client *http.Client) *JoinGroupParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the join group params
func (o *JoinGroupParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithBody adds the body to the join group params
func (o *JoinGroupParams) WithBody(body *models.OpenpitrixJoinGroupRequest) *JoinGroupParams {
	o.SetBody(body)
	return o
}

// SetBody adds the body to the join group params
func (o *JoinGroupParams) SetBody(body *models.OpenpitrixJoinGroupRequest) {
	o.Body = body
}

// WriteToRequest writes these params to a swagger request
func (o *JoinGroupParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.Body != nil {
		if err := r.SetBodyParam(o.Body); err != nil {
			return err
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
package dao;
import java.util.List;
import beans.BikePart;

public interface BikePartDAO {

    List<BikePart> findAll();
    List<BikePart> findById();
    List<BikePart> findByName();
    boolean insertBikePart(BikePart bikePart);
    boolean updateBikePart(BikePart bikePart);
    boolean deleteBikePart(BikePart bikePart);

}


text:
package com.ubiquity.datastorage.kernel.interfaces;

public interface IFieldTemplate {
            String getIdentifier();

    Type getType();

    Kind getKind();

    enum Type {
        INTEGER,
        DOUBLE,
        STRING,
        BOOLEAN,
        OBJECT,
        CHAR,
        DATE,
        TIME,
        DURATION
    }
    enum Kind {
        PRIMARY(true, true, true),
        INDEXED(true, true, false),
        MANDATORY(true, false, false),
        OPTIONAL(false, false, false);

        private final boolean isMandatory;
        private final boolean isIndexed;
        private final boolean isUnique;

        Kind(boolean isMandatory, boolean isIndexed, boolean isUnique) {
            this.isMandatory = isMandatory;
            this.isIndexed = isIndexed;
            this.isUnique = isUnique;
        }

        public boolean isMandatory() {
            return isMandatory;
        }

        public boolean isIndexed() {
            return isIndexed;
        }

        public boolean isUnique() {
            return isUnique;
        }
    }

}


text:
FactoryBot.define do
  factory :application, class: Doorkeeper::Application do
    name { 'sample app' }
    redirect_uri { 'urn:ietf:wg:oauth:2.0:oob' }
  end
end


text:
// Copyright (c) 2016-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef FUJICOIN_POLICY_RBF_H
#define FUJICOIN_POLICY_RBF_H

#include <consensus/amount.h>
#include <primitives/transaction.h>
#include <threadsafety.h>
#include <txmempool.h>

#include <cstddef>
#include <cstdint>
#include <optional>
#include <set>
#include <string>

class CFeeRate;
class uint256;

/** Maximum number of transactions that can be replaced by RBF (Rule #5). This includes all
 * mempool conflicts and their descendants. */
static constexpr uint32_t MAX_REPLACEMENT_CANDIDATES{100};

/** The rbf state of unconfirmed transactions */
enum class RBFTransactionState {
    /** Unconfirmed tx that does not signal rbf and is not in the mempool */
    UNKNOWN,
    /** Either this tx or a mempool ancestor signals rbf */
    REPLACEABLE_BIP125,
    /** Neither this tx nor a mempool ancestor signals rbf */
    FINAL,
};

/**
 * Determine whether an unconfirmed transaction is signaling opt-in to RBF
 * according to BIP 125
 * This involves checking sequence numbers of the transaction, as well
 * as the sequence numbers of all in-mempool ancestors.
 *
 * @param tx   The unconfirmed transaction
 * @param pool The mempool, which may contain the tx
 *
 * @return     The rbf state
 */
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx);

/** Get all descendants of iters_conflicting. Checks that there are no more than
 * MAX_REPLACEMENT_CANDIDATES potential entries. May overestimate if the entries in
 * iters_conflicting have overlapping descendants.
 * @param[in]   iters_conflicting   The set of iterators to mempool entries.
 * @param[out]  all_conflicts       Populated with all the mempool entries that would be replaced,
 *                                  which includes iters_conflicting and all entries' descendants.
 *                                  Not cleared at the start; any existing mempool entries will
 *                                  remain in the set.
 * @returns an error message if MAX_REPLACEMENT_CANDIDATES may be exceeded, otherwise a std::nullopt.
 */
std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx, CTxMemPool& pool,
                                                  const CTxMemPool::setEntries& iters_conflicting,
                                                  CTxMemPool::setEntries& all_conflicts)
    EXCLUSIVE_LOCKS_REQUIRED(pool.cs);

/** The replacement transaction may only include an unconfirmed input if that input was included in
 * one of the original transactions.
 * @returns error message if tx spends unconfirmed inputs not also spent by iters_conflicting,
 * otherwise std::nullopt. */
std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx, const CTxMemPool& pool,
                                               const CTxMemPool::setEntries& iters_conflicting)
    EXCLUSIVE_LOCKS_REQUIRED(pool.cs);

/** Check the intersection between two sets of transactions (a set of mempool entries and a set of
 * txids) to make sure they are disjoint.
 * @param[in]   ancestors           Set of mempool entries corresponding to ancestors of the
 *                                  replacement transactions.
 * @param[in]   direct_conflicts    Set of txids corresponding to the mempool conflicts
 *                                  (candidates to be replaced).
 * @param[in]   txid                Transaction ID, included in the error message if violation occurs.
 * @returns error message if the sets intersect, std::nullopt if they are disjoint.
 */
std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors,
                                                   const std::set<uint256>& direct_conflicts,
                                                   const uint256& txid);

/** Check that the feerate of the replacement transaction(s) is higher than the feerate of each
 * of the transactions in iters_conflicting.
 * @param[in]   iters_conflicting  The set of mempool entries.
 * @returns error message if fees insufficient, otherwise std::nullopt.
 */
std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting,
                                                 CFeeRate replacement_feerate, const uint256& txid);

/** The replacement transaction must pay more fees than the original transactions. The additional
 * fees must pay for the replacement's bandwidth at or above the incremental relay feerate.
 * @param[in]   original_fees       Total modified fees of original transaction(s).
 * @param[in]   replacement_fees    Total modified fees of replacement transaction(s).
 * @param[in]   replacement_vsize   Total virtual size of replacement transaction(s).
 * @param[in]   relay_fee           The node's minimum feerate for transaction relay.
 * @param[in]   txid                Transaction ID, included in the error message if violation occurs.
 * @returns error string if fees are insufficient, otherwise std::nullopt.
 */
std::optional<std::string> PaysForRBF(CAmount original_fees,
                                      CAmount replacement_fees,
                                      size_t replacement_vsize,
                                      CFeeRate relay_fee,
                                      const uint256& txid);

#endif // FUJICOIN_POLICY_RBF_H


text:
#ifndef _TCC_LIBM_H_
#define _TCC_LIBM_H_

#include "../math.h"

/* TCC uses 8 bytes for double and long double, so effectively the l variants
 * are never used. For now, they just run the normal (double) variant.
 */

/*
 * most of the code in this file is taken from MUSL rs-1.0 (MIT license)
 * - musl-libc: http://git.musl-libc.org/cgit/musl/tree/src/math?h=rs-1.0
 * - License:   http://git.musl-libc.org/cgit/musl/tree/COPYRIGHT?h=rs-1.0
 */

/*******************************************************************************
  Start of code based on MUSL
*******************************************************************************/
/*
musl as a whole is licensed under the following standard MIT license:

----------------------------------------------------------------------
Copyright © 2005-2014 Rich Felker, et al.

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.
----------------------------------------------------------------------
*/

/* fpclassify */

__CRT_INLINE int __cdecl __fpclassify (double x) {
  union {double f; uint64_t i;} u = {x};
  int e = u.i>>52 & 0x7ff;
  if (!e) return u.i<<1 ? FP_SUBNORMAL : FP_ZERO;
  if (e==0x7ff) return u.i<<12 ? FP_NAN : FP_INFINITE;
  return FP_NORMAL;
}

__CRT_INLINE int __cdecl __fpclassifyf (float x) {
  union {float f; uint32_t i;} u = {x};
  int e = u.i>>23 & 0xff;
  if (!e) return u.i<<1 ? FP_SUBNORMAL : FP_ZERO;
  if (e==0xff) return u.i<<9 ? FP_NAN : FP_INFINITE;
  return FP_NORMAL;
}

__CRT_INLINE int __cdecl __fpclassifyl (long double x) {
  return __fpclassify(x);
}

/* signbit */

__CRT_INLINE int __cdecl __signbit (double x) {
  union {double d; uint64_t i;} y = { x };
  return y.i>>63;
}

__CRT_INLINE int __cdecl __signbitf (float x) {
  union {float f; uint32_t i; } y = { x };
  return y.i>>31;
}

__CRT_INLINE int __cdecl __signbitl (long double x) {
  return __signbit(x);
}

/* fmin*, fmax* */

#define TCCFP_FMIN_EVAL (isnan(x) ? y :                                      \
                         isnan(y) ? x :                                      \
                         (signbit(x) != signbit(y)) ? (signbit(x) ? x : y) : \
                         x < y ? x : y)

__CRT_INLINE double __cdecl fmin (double x, double y) {
  return TCCFP_FMIN_EVAL;
}

__CRT_INLINE float __cdecl fminf (float x, float y) {
  return TCCFP_FMIN_EVAL;
}

__CRT_INLINE long double __cdecl fminl (long double x, long double y) {
  return TCCFP_FMIN_EVAL;
}

#define TCCFP_FMAX_EVAL (isnan(x) ? y :                                      \
                         isnan(y) ? x :                                      \
                         (signbit(x) != signbit(y)) ? (signbit(x) ? y : x) : \
                         x < y ? y : x)

__CRT_INLINE double __cdecl fmax (double x, double y) {
  return TCCFP_FMAX_EVAL;
}

__CRT_INLINE float __cdecl fmaxf (float x, float y) {
  return TCCFP_FMAX_EVAL;
}

__CRT_INLINE long double __cdecl fmaxl (long double x, long double y) {
  return TCCFP_FMAX_EVAL;
}

/* *round* */

#define TCCFP_FORCE_EVAL(x) do {            \
if (sizeof(x) == sizeof(float)) {           \
  volatile float __x;                       \
  __x = (x);                                \
} else if (sizeof(x) == sizeof(double)) {   \
  volatile double __x;                      \
  __x = (x);                                \
} else {                                    \
  volatile long double __x;                 \
  __x = (x);                                \
}                                           \
} while(0)

__CRT_INLINE double __cdecl round (double x) {
  union {double f; uint64_t i;} u = {x};
  int e = u.i >> 52 & 0x7ff;
  double y;

  if (e >= 0x3ff+52)
    return x;
  if (u.i >> 63)
    x = -x;
  if (e < 0x3ff-1) {
    /* raise inexact if x!=0 */
    TCCFP_FORCE_EVAL(x + 0x1p52);
    return 0*u.f;
  }
  y = (double)(x + 0x1p52) - 0x1p52 - x;
  if (y > 0.5)
    y = y + x - 1;
  else if (y <= -0.5)
    y = y + x + 1;
  else
    y = y + x;
  if (u.i >> 63)
    y = -y;
  return y;
}

__CRT_INLINE long __cdecl lround (double x) {
  return round(x);
}

__CRT_INLINE long long __cdecl llround (double x) {
  return round(x);
}

__CRT_INLINE float __cdecl roundf (float x) {
  return round(x);
}

__CRT_INLINE long __cdecl lroundf (float x) {
  return round(x);
}

__CRT_INLINE long long __cdecl llroundf (float x) {
  return round(x);
}

__CRT_INLINE long double __cdecl roundl (long double x) {
  return round(x);
}

__CRT_INLINE long __cdecl lroundl (long double x) {
  return round(x);
}

__CRT_INLINE long long __cdecl llroundl (long double x) {
  return round(x);
}

/*******************************************************************************
  End of code based on MUSL
*******************************************************************************/

#endif /* _TCC_LIBM_H_ */


text:
from ._sip_routing_client import SipRoutingClient
from ._generated.models import SipTrunkRoute
from ._models import SipTrunk

__all__ = [
    'SipRoutingClient',
    'SipTrunk',
    'SipTrunkRoute'
]


text:
from django.db.models import signals

from haystack.signals import BaseSignalProcessor

from mozillians.users.models import UserProfile
from mozillians.groups.models import Group

# Django Haystack signals
class SearchSignalProcessor(BaseSignalProcessor):

    def setup(self):
        signals.post_save.connect(self.handle_save, sender=UserProfile)
        signals.post_delete.connect(self.handle_delete, sender=UserProfile)
        signals.post_save.connect(self.handle_save, sender=Group)
        signals.post_delete.connect(self.handle_delete, sender=Group)

    def handle_save(self, sender, instance, **kwargs):
        # Do not index incomplete profiles and not visible groups.
        if ((isinstance(instance, UserProfile) and instance.is_complete) or
                (isinstance(instance, Group) and instance.visible)):
            super(SearchSignalProcessor, self).handle_save(sender, instance, **kwargs)

    def teardown(self):
        signals.post_save.disconnect(self.handle_save, sender=UserProfile)
        signals.post_delete.disconnect(self.handle_delete, sender=UserProfile)
        signals.post_save.disconnect(self.handle_save, sender=Group)
        signals.post_delete.disconnect(self.handle_delete, sender=Group)


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XbfAnalyzer.Xbf
{
    public class XbfHeader
    {
        public XbfHeader(BinaryReader reader)
        {
            // Verify magic number
            var magicNumber = reader.ReadBytes(4);
            if (magicNumber[0] != 'X' || magicNumber[1] != 'B' || magicNumber[2] != 'F' || magicNumber[3] != 0)
                throw new InvalidDataException("File does not have XBF header");
            MagicNumber = magicNumber;

            MetadataSize = reader.ReadUInt32();
            NodeSize = reader.ReadUInt32();
            MajorFileVersion = reader.ReadUInt32();
            MinorFileVersion = reader.ReadUInt32();
            StringTableOffset = reader.ReadUInt64();
            AssemblyTableOffset = reader.ReadUInt64();
            TypeNamespaceTableOffset = reader.ReadUInt64();
            TypeTableOffset = reader.ReadUInt64();
            PropertyTableOffset = reader.ReadUInt64();
            XmlNamespaceTableOffset = reader.ReadUInt64();
            Hash = reader.ReadChars(32);
        }

        public byte[] MagicNumber { get; private set; }
        public UInt32 MetadataSize { get; private set; }
        public UInt32 NodeSize { get; private set; }
        public UInt32 MajorFileVersion { get; private set; }
        public UInt32 MinorFileVersion { get; private set; }
        public UInt64 StringTableOffset { get; private set; }
        public UInt64 AssemblyTableOffset { get; private set; }
        public UInt64 TypeNamespaceTableOffset { get; private set; }
        public UInt64 TypeTableOffset { get; private set; }
        public UInt64 PropertyTableOffset { get; private set; }
        public UInt64 XmlNamespaceTableOffset { get; private set; }
        public char[] Hash { get; private set; }
    }
}


text:
export const HACK_FIX_HPM_PARTIAL_RESPONSE_HEADERS = {
  Connection: 'keep-alive',
};


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>水平滚动条拖动</title>


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require('../../config.php');
require_once("$CFG->dirroot/$CFG->admin/roles/lib.php");
require_once("permissions_forms.php");

$contextid  = required_param('contextid',PARAM_INT);

$roleid     = optional_param('roleid', 0, PARAM_INT);
$capability = optional_param('capability', false, PARAM_CAPABILITY);
$confirm    = optional_param('confirm', 0, PARAM_BOOL);
$prevent    = optional_param('prevent', 0, PARAM_BOOL);
$allow      = optional_param('allow', 0, PARAM_BOOL);
$unprohibit = optional_param('unprohibit', 0, PARAM_BOOL);
$prohibit   = optional_param('prohibit', 0, PARAM_BOOL);

list($context, $course, $cm) = get_context_info_array($contextid);

$url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $contextid));

if ($course) {
    $isfrontpage = ($course->id == SITEID);
} else {
    $isfrontpage = false;
    if ($context->contextlevel == CONTEXT_USER) {
        $course = $DB->get_record('course', array('id'=>optional_param('courseid', SITEID, PARAM_INT)), '*', MUST_EXIST);
        $user = $DB->get_record('user', array('id'=>$context->instanceid), '*', MUST_EXIST);
        $url->param('courseid', $course->id);
        $url->param('userid', $user->id);
    } else {
        $course = $SITE;
    }
}

// security first
require_login($course, false, $cm);
require_capability('moodle/role:review', $context);
$PAGE->set_url($url);
$PAGE->set_context($context);
$courseid = $course->id;

// These are needed early because of tabs.php
$assignableroles = get_assignable_roles($context, ROLENAME_BOTH);
list($overridableroles, $overridecounts, $nameswithcounts) = get_overridable_roles($context, ROLENAME_BOTH, true);
if ($capability) {
    $capability = $DB->get_record('capabilities', array('name'=>$capability), '*', MUST_EXIST);
}

$allowoverrides     = has_capability('moodle/role:override', $context);
$allowsafeoverrides = has_capability('moodle/role:safeoverride', $context);

$contextname = print_context_name($context);
$title = get_string('permissionsincontext', 'role', $contextname);
$straction = get_string('permissions', 'role'); // Used by tabs.php
$currenttab = 'permissions';

$PAGE->set_pagelayout('admin');
$PAGE->set_title($title);
switch ($context->contextlevel) {
    case CONTEXT_SYSTEM:
        print_error('cannotoverridebaserole', 'error');
        break;
    case CONTEXT_USER:
        $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
        $PAGE->set_heading($fullname);
        $showroles = 1;
        break;
    case CONTEXT_COURSECAT:
        $PAGE->set_heading("$SITE->fullname: ".get_string("categories"));
        break;
    case CONTEXT_COURSE:
        if ($isfrontpage) {
            admin_externalpage_setup('frontpageroles', '', array(), $PAGE->url);
        } else {
            $PAGE->set_heading($course->fullname);
        }
        break;
    case CONTEXT_MODULE:
        $PAGE->set_heading(print_context_name($context, false));
        $PAGE->set_cacheable(false);
        break;
    case CONTEXT_BLOCK:
        $PAGE->set_heading($PAGE->course->fullname);
        break;
}

// handle confirmations and actions
// We have a capability and overrides are allowed or safe overrides are allowed and this is safe
if ($capability && ($allowoverrides || ($allowsafeoverrides && is_safe_capability($capability)))) {
    // If we already know the the role ID, it is overrideable, and we are setting prevent or unprohibit
    if (isset($overridableroles[$roleid]) && ($prevent || $unprohibit)) {
        // We are preventing
        if ($prevent) {
            if ($confirm && data_submitted() && confirm_sesskey()) {
                role_change_permission($roleid, $context, $capability->name, CAP_PREVENT);
                redirect($PAGE->url);

            } else {
                $a = (object)array('cap'=>get_capability_docs_link($capability)." ($capability->name)", 'role'=>$overridableroles[$roleid], 'context'=>$contextname);
                $message = get_string('confirmroleprevent', 'role', $a);
                $continueurl = new moodle_url($PAGE->url, array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability->name, 'prevent'=>1, 'sesskey'=>sesskey(), 'confirm'=>1));
            }
        }
        // We are unprohibiting
        if ($unprohibit) {
            if ($confirm && data_submitted() && confirm_sesskey()) {
                role_change_permission($roleid, $context, $capability->name, CAP_INHERIT);
                redirect($PAGE->url);
            } else {
                $a = (object)array('cap'=>get_capability_docs_link($capability)." ($capability->name)", 'role'=>$overridableroles[$roleid], 'context'=>$contextname);
                $message = get_string('confirmroleunprohibit', 'role', $a);
                $continueurl = new moodle_url($PAGE->url, array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability->name, 'unprohibit'=>1, 'sesskey'=>sesskey(), 'confirm'=>1));
            }
        }
        // Display and print
        echo $OUTPUT->header();
        echo $OUTPUT->heading($title);
        echo $OUTPUT->confirm($message, $continueurl, $PAGE->url);
        echo $OUTPUT->footer();
        die;
    }

    if ($allow || $prohibit) {
        if ($allow) {
            $mform = new role_allow_form(null, array($context, $capability, $overridableroles));
            if ($mform->is_cancelled()) {
                redirect($PAGE->url);
            } else if ($data = $mform->get_data() and !empty($data->roleid)) {
                $roleid = $data->roleid;
                if (isset($overridableroles[$roleid])) {
                    role_change_permission($roleid, $context, $capability->name, CAP_ALLOW);
                }
                redirect($PAGE->url);
            } else {
                $a = (object)array('cap'=>get_capability_docs_link($capability)." ($capability->name)", 'context'=>$contextname);
                $message = get_string('roleallowinfo', 'role', $a);
            }
        }
        if ($prohibit) {
            $mform = new role_prohibit_form(null, array($context, $capability, $overridableroles));
            if ($mform->is_cancelled()) {
                redirect($PAGE->url);
            } else if ($data = $mform->get_data() and !empty($data->roleid)) {
                $roleid = $data->roleid;
                if (isset($overridableroles[$roleid])) {
                    role_change_permission($roleid, $context, $capability->name, CAP_PROHIBIT);
                }
                redirect($PAGE->url);
            } else {
                $a = (object)array('cap'=>get_capability_docs_link($capability)." ($capability->name)", 'context'=>$contextname);
                $message = get_string('roleprohibitinfo', 'role', $a);
            }
        }
        echo $OUTPUT->header();
        echo $OUTPUT->heading($title);
        echo $OUTPUT->box($message);
        $mform->display();
        echo $OUTPUT->footer();
        die;
    }
}

echo $OUTPUT->header();
echo $OUTPUT->heading($title);

$table = new permissions_table($context, $contextname, $allowoverrides, $allowsafeoverrides, $overridableroles);
echo $OUTPUT->box_start('generalbox capbox');
// print link to advanced override page
if ($overridableroles) {
    $overrideurl = new moodle_url('/admin/roles/override.php', array('contextid' => $context->id));
    $select = new single_select($overrideurl, 'roleid', $nameswithcounts);
    $select->label = get_string('advancedoverride', 'role');
    echo html_writer::tag('div', $OUTPUT->render($select), array('class'=>'advancedoverride'));
}
$table->display();
echo $OUTPUT->box_end();

if ($context->contextlevel > CONTEXT_USER) {
    echo html_writer::start_tag('div', array('class'=>'backlink'));
    echo html_writer::tag('a', get_string('backto', '', $contextname), array('href'=>get_context_url($context)));
    echo html_writer::end_tag('div');
}

echo $OUTPUT->footer($course);


text:
/**
* @file tia_server.h
* @brief This file includes the TiAServer class.
**/

#ifndef TIA_SERVER_H
#define TIA_SERVER_H

// STL
#include <map>

#ifdef WIN32
  #include	<conio.h>
  #include	<stdio.h>
#endif

// Boost
#include <boost/asio.hpp>
#include <boost/cstdint.hpp>
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>

// local
#include "tia/constants.h"
#include "tia/ss_meta_info.h"

// forward declarations

namespace tia
{

  class ControlConnectionServer;
  class TCPDataServer;
  class UDPDataServer;

  class TiAServerStateServer;
  class ControlConnectionServer2;
  class DataServer;
  class HardwareInterface;
  class DataPacket;
  class DataPacketImpl;
  class DataPacket3Impl;

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

/**
* @class TiAServer
*
* @brief The core of TOBI Interface A (TiA)
*
* The TiAServer represents the main entry point for using the TiA library.
* TiA consists out of a separation between meta information transmitted via xml
* and a seperated data stream devlivering raw data.
*
* It provides an interface to set this meta data and transmit acquired data using
* TiA data packets.
*
* @todo Implement mechanisms to detect "impossible" configurations.
* @todo Define "invisible magic constants" like fs = 0 for aperiodic devices.
* @todo Implement mechanisms to ensure that aperiodics are used correctly (e.g. blocksize)
*/
class TiAServer : boost::noncopyable
{
  /** \example tia-simple-example.cpp
   * This is an example how to use the TiA server.
   * Parameters to configure the TiA server have to be provided by the
   * data acquisition system. Variables introduced in this example are
   * only for demonstration purposes and should demonstrate how to
   * configure the TiA server.
   *
   * The TiA server needs boost::asio installed on the system.
   */

  friend class ControlConnectionServer;

    // Methods
    //-----------------------------------
  public:
    /**
    * @brief Constructor
    * \param the boost::asio::io_service to use
    */
    TiAServer(boost::asio::io_service& io_service, bool new_tia = false);

    /**
     * @brief Destructor
     * @param[in]  packet
     */
    virtual ~TiAServer();

    /**
    * @brief Initialize the server
    * param[in] map<std::string,std::string> subject_info
    * param[in] map<std::string,std::string> server_settings
    *
    * The server needs to be initializedwith subject specific information (birthday,...) and
    * parameters for the server configuration (ctrl port, udp port, udp broadcast addr).
    *
    * @todo Check if wrong configuration is checked within this code.
    * @todo Is it a good idea to use maps for configuration (especially server config)?
    */
    void initialize(std::map<std::string,std::string>& subject_info,
                    std::map<std::string,std::string>& server_settings);

    /**
    * @brief todo
    */
    DataPacket* getEmptyDataPacket();

    /**
    * @brief Sends a DataPacket to connected clients
    * @param[in]  packet
    * @throws
    */
    void sendDataPacket();

    /**
     * @brief Set the sampling rate of the master device
     * @param[in]  value
     */
    void setMasterSamplingRate(boost::uint32_t value) { master_samplingrate_ = value; }

    /**
     * @brief Set the blocksize of the master device
     * @param[in]  value
     */
    void setMasterBlocksize(boost::uint32_t value) { master_blocksize_ = value; }

    /**
     * @brief Set the acquired signal types
     * @param[in]  vector<uint32_t> types (have to be in ascending order ... 0x01, 0x04, ...)
     */
    void setAcquiredSignalTypes(const std::vector<boost::uint32_t>& sig_types)
      { sig_types_ = sig_types; }

    /**
     * @brief Set the blocksize for every signal type
     * @param[in]  vector<uint16_t> bs (has to be aligned with the order of signal types)
     */
    void setBlockSizesPerSignalType(const std::vector<boost::uint16_t>& blocksizes)
      { blocksizes_ = blocksizes; }

    /**
     * @brief Set the sampling rate for every signal type
     * @param[in]  vector<uint32_t> fs (has to be aligned with the order of signal types)
     */
    void setSamplingRatePerSignalType(const std::vector<boost::uint32_t>& fs_per_sig_type)
      { fs_per_sig_type_ = fs_per_sig_type; }

    /**
     * @brief Set the channel names for the channels of every signal type
     * @param[in]  map<uint32_t, vector<string> > names
     *
     * Every signal type has a defined number of channels; the vector< string > holds
     * the names for every channel from a signal type.
     */
    void setChannelNames(const std::map<boost::uint32_t, std::vector<std::string> >& channels_per_sig_type)
      { channels_per_sig_type_ = channels_per_sig_type; }

  private:
    /**
     * @brief Creates the SubjectInfo object
     */
    void createSubjectInfo(std::map<std::string,std::string> subject_info_map);

    /**
     * @brief Creates the SignalInfo object
     */
    void createSignalInfo();

    DataPacketImpl  makeDataPacketCopy(DataPacketImpl& packet);
    DataPacket3Impl makeDataPacketCopy(DataPacket3Impl& packet);

  private:
    boost::asio::io_service&            io_service_; ///<
    std::map<std::string, std::string>  server_settings_; ///< A map holding an identifier + value (e.g. port + number)
    TCPDataServer*                      tcp_data_server_; ///<
    UDPDataServer*                      udp_data_server_; ///<
    ControlConnectionServer*            control_connection_server_; ///<

    tia::TiAServerStateServer*          server_state_server_;
    bool const new_tia_;
    tia::ControlConnectionServer2*            control_connection_server_2_; ///<
    tia::DataServer*                          data_server_;
    tia::HardwareInterface*                   hardware_interface_;

    boost::uint32_t                                       master_blocksize_; ///<
    boost::uint32_t                                       master_samplingrate_; ///<
    std::vector<boost::uint32_t>                          sig_types_; ///<
    std::vector<boost::uint16_t>                          blocksizes_; ///<
    std::vector<boost::uint32_t>                          fs_per_sig_type_; ///<
    std::map<boost::uint32_t, std::vector<std::string> >  channels_per_sig_type_; ///<

    SubjectInfo                         subject_info_;
    SignalInfo                          signal_info_;

    DataPacket*       data_packet_;

    boost::shared_ptr<DataPacketImpl>                     data_packet_impl_;
    boost::shared_ptr<DataPacket3Impl>                    data_packet_3_impl_;

    DataPacket*       work_data_packet_;
    DataPacketImpl*                     work_data_packet_impl_;
    DataPacket3Impl*                    work_data_packet_3_impl_;

    Constants                           cst_; ///<

#ifdef TIMING_TEST
    boost::posix_time::ptime timestamp_;
    boost::posix_time::time_duration diff_;
    boost::posix_time::time_duration t_mean_;
    boost::posix_time::time_duration t_min_total_;
    boost::posix_time::time_duration t_max_total_;
    boost::posix_time::time_duration t_min_last_;
    boost::posix_time::time_duration t_max_last_;
    std::vector<boost::posix_time::time_duration> t_diffs_;
    boost::int64_t t_var_;
    boost::uint64_t counter_;

    bool  lpt_flag_;

#endif
};

} // Namespace tobiss

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

#endif // TIA_SERVER_H


text:
"""Tests for Greenlet and its emulator.

by pts@fazekas.hu at Sat Jan  9 03:10:51 CET 2010
--- Sun May  9 20:05:50 CEST 2010

Stackless python 2.6.5 sometimes segfaults on this (if the .pyc file doesn't
exist) with greenlet_test.py, with cryptic error messages like:
Python 2.6.5 Stackless 3.1b3 060516 (python-2.65:81025M, May  9 2010, 14:53:06)
[GCC 4.4.1] on linux2.

  AttributeError: 'greenlet' object has no attribute 'parent'

This seems to be related of lots of non-cleaned-up tasklets. It hasn't been
happening recently.
"""

__author__ = 'pts@fazekas.hu (Peter Szabo)'

import gc
import sys
import unittest

# We introduce one namespace layer (named Template) so unittest.main() won't
# find GreenletTestTemplate as a class to run tests methods of.
class Template(object):
  class GreenletTestTemplate(unittest.TestCase):
    greenlet = None
    """greenlet class, will be overridden by subclasses."""

    def setUp(self):
      self.assertEqual(1, self.getruncount())

    def tearDown(self):
      self.assertEqual(1, self.getruncount())

    def getruncount(self):  # Dummy.
      return 1

    def testGreenlet(self):
      events = []

      m = self.greenlet.getcurrent()
      assert m.parent is None
      assert m
      assert not m.dead

      def A(x, y, z):
        events.append('%s/%s/%s' % (x, y, z))
        events.append(m.switch('C'))

      g = self.greenlet(A)
      assert not g.dead
      assert not g
      assert self.greenlet.getcurrent() is m
      events.append(str(g.switch(3, 4, 5)))
      assert self.greenlet.getcurrent() is m
      assert not g.dead
      assert g
      events.append(str(g.switch('D')))
      #print ' '.join(events)
      assert ' '.join(events) == '3/4/5 C D None'
      assert g.dead
      assert not g

      def B():
        1 / 0

      g = self.greenlet(B)
      assert self.greenlet.getcurrent() is m
      assert g.parent is m
      assert not g
      assert not g.dead
      try:
        g.switch()
        assert 0, 'not reached'
      except ZeroDivisionError:
        pass
      assert self.greenlet.getcurrent() in (g, m)
      assert self.greenlet.getcurrent() is m

      gc = []

      def C():
        events.append('C')

      def D():
        events.append('D1')
        gc.append(self.greenlet(C))
        events.append('D2')
        events.append(m.switch('D3'))
        events.append('D4')

      assert self.greenlet.getcurrent() is m
      del events[:]
      g = self.greenlet(D)
      events.append('M')
      events.append(g.switch())
      assert ' '.join(events) == 'M D1 D2 D3'
      assert gc[0] is not self.greenlet.getcurrent()
      try:
        gc[0].throw(ValueError, 'VE')
      except ValueError, e:
        events.append(str(e))
      assert ' '.join(events) == 'M D1 D2 D3 VE'

    def testSwitchValue(self):
      gc = self.greenlet.getcurrent()
      self.assertEqual('self0', gc.switch('self0'))
      self.assertEqual((), gc.switch())  # The default is the empty tuple.
      next = {}
      items = []
      def Switcher(name):
        if name == 'g2':
          items.append(gc.switch())
        else:
          items.append(gc.switch(name))
        items.append(next[name].switch('+' + name))
      g1 = self.greenlet(lambda: Switcher('g1'))
      g2 = self.greenlet(lambda: Switcher('g2'))
      g3 = self.greenlet(lambda: Switcher('g3'))
      next['g1'] = g2
      next['g2'] = g3
      next['g3'] = gc
      assert not (g1 or g1.dead)
      assert not (g2 or g2.dead)
      assert not (g3 or g3.dead)
      self.assertEqual('self1', gc.switch('self1'))
      self.assertEqual('g1', g1.switch())
      self.assertEqual((),   g2.switch())
      self.assertEqual('g3', g3.switch())
      self.assertEqual('self2', gc.switch('self2'))
      self.assertEqual([], items)
      assert g1 and not g1.dead
      assert g2 and not g2.dead
      assert g3 and not g3.dead
      self.assertEqual('+g3', g1.switch('base'))
      self.assertEqual(['base', '+g1', '+g2'], items)
      assert g1 and not g1.dead
      assert g2 and not g2.dead
      assert g3 and not g3.dead
      self.assertEqual(None, g3.switch('d3'))
      assert not g3 and g3.dead
      self.assertEqual(['base', '+g1', '+g2', 'd3'], items)
      self.assertEqual(None, g2.switch('d2'))
      assert not g2 and g2.dead
      self.assertEqual(['base', '+g1', '+g2', 'd3', 'd2'], items)
      self.assertEqual(None, g1.switch('d1'))
      assert not g1 and g1.dead
      self.assertEqual(['base', '+g1', '+g2', 'd3', 'd2', 'd1'], items)

    def testThrow(self):
      self.assertRaises(ValueError,
                        self.greenlet.getcurrent().throw, ValueError)
      items = []
      gc = self.greenlet.getcurrent()

      def Catcher(do_switch):
        assert do_switch is True
        try:
          gc.switch('catcher')
          items.append('ok')
        except BaseException, e:
          items.append(type(e))

      gp = self.greenlet(Catcher)
      self.assertEqual('catcher', gp.switch(True))
      ge = self.greenlet(lambda: 1 / 0, gp)
      # The Catcher (gp) catches this ValueError, because it is the parent of ge.
      ge.throw(ValueError)
      self.assertEqual([ValueError], items)

      del items[:]
      gp = self.greenlet(Catcher)
      ge = self.greenlet(lambda: 1 / 0, gp)
      assert not (gp or gp.dead)
      # The Catcher can't catch this ValueError, because it's not running yet.
      self.assertRaises(ValueError, ge.throw, ValueError)
      assert not gp
      assert gp.dead
      assert not ge
      assert ge.dead
      self.assertEqual([], items)

      del items[:]
      gp = self.greenlet(Catcher)
      self.assertEqual('catcher', gp.switch(True))
      ge = self.greenlet(lambda: 42, gp)
      self.assertEqual(None, ge.switch())
      assert gp.dead
      assert ge.dead
      self.assertEqual(['ok'], items)

    def testThrowWithDummyTasklet(self):
      if 'stackless' not in sys.modules:
        return
      import stackless
      def DummyWorker():
        while True:
          stackless.schedule()
      dummy_tasklet = stackless.tasklet(DummyWorker)()
      try:
        self.testThrow()
      finally:
        dummy_tasklet.kill()

    def testSwitchToParent(self):
      greenlet1 = self.greenlet(lambda x=None: 'P:' + repr(x))
      greenlet2 = self.greenlet(lambda x: x * 10, parent=greenlet1)
      self.assertEqual('P:210', greenlet2.switch(21))

      def Raiser(x):
        raise self.greenlet.GreenletExit(x)
      greenlet3 = self.greenlet(Raiser)
      try:
        # The exception is returned to the parent, not raised.
        self.assertEqual('42', str(greenlet3.switch(42)))
      except self.greenlet.GreenletExit, e:
        self.assertFalse('unexpected GreenletExit: %s', e)

      greenlet4 = self.greenlet(lambda x: 1 / x)
      self.assertRaises(ZeroDivisionError, greenlet4.switch, 0)

      greenlet5 = self.greenlet(lambda: 42)
      greenlet6 = self.greenlet(lambda x: 1 / x, parent=greenlet5)
      self.assertRaises(ZeroDivisionError, greenlet6.switch, 0)

    def testGreenletExitOnDelete(self):
      exits = []
      def Reporter():
        exits.append('HI')
        try:
          self.greenlet.getcurrent().parent.switch()
        except BaseException, e:
          exits.append(isinstance(e, self.greenlet.GreenletExit))
      greenlets = [self.greenlet(Reporter)]
      self.assertEqual([], exits)
      greenlets[-1].switch()
      self.assertEqual(['HI'], exits)
      greenlets.pop()
      # GreenletExit is raised when all references to the greenlet go aways.
      self.assertEqual(['HI', True], exits)

    def testParentChangeOnDelete(self):
      x = []

      def Work():
        g1 = self.greenlet(x.append)
        g2 = self.greenlet(lambda: 1 / 0, parent=g1)
        del g2  #  This updates the parent of g2 to the current greenlet.
        self.assertFalse(g1)
        self.assertFalse(g1.dead)
        self.assertEqual([], x)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testParentOnKill(self):
      x = []

      def Work():
        g1 = self.greenlet(lambda value: x.append(type(value)))
        g2 = self.greenlet(lambda: 1 / 0, parent=g1)
        g2.throw()
        self.assertTrue(g1.dead)
        self.assertEqual([self.greenlet.GreenletExit], x)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testParentOnKillWithGreenletExit(self):
      x = []

      def Work():
        g1 = self.greenlet(lambda value: x.append(type(value)))
        g2 = self.greenlet(lambda: 1 / 0, parent=g1)
        g2.throw(self.greenlet.GreenletExit)
        self.assertTrue(g1.dead)
        self.assertEqual([self.greenlet.GreenletExit], x)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testParentOnKillWithGreenletExitSubclass(self):
      x = []

      class MyGreenletExit(self.greenlet.GreenletExit):
        pass

      def Work():
        g1 = self.greenlet(lambda value: x.append(type(value)))
        g2 = self.greenlet(lambda: 1 / 0, parent=g1)
        g2.throw(MyGreenletExit)
        self.assertTrue(g1.dead)
        self.assertEqual([MyGreenletExit], x)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testParentOnKillWithOtherError(self):
      x = []

      def Work():
        g1 = self.greenlet(lambda: ()[0])
        g2 = self.greenlet(lambda: 1 / 0, parent=g1)
        e = None
        try:
          g2.throw(ValueError, 42)
        except ValueError, e:
          e = e.args
        self.assertEqual((42,), e)
        self.assertTrue(g1.dead)
        self.assertEqual([], x)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testParentCatchOnKill(self):
      x = []

      def Work():
        gw = self.greenlet.getcurrent()
        g1 = self.greenlet(lambda value: x.append(type(value)))
        def F2():
          try:
            x.append('A')
            x.append(self.greenlet.getcurrent().parent is g1)
            gw.switch()
          except self.greenlet.GreenletExit:
            # For `del g2', parent becomes gw (who deleted it),
            # for normal throw(), parent remains.
            x.append('B')
            x.append(self.greenlet.getcurrent().parent is gw)
            x.append(self.greenlet.getcurrent().parent is g1)
            x.append('C')
            raise
        g2 = self.greenlet(F2, parent=g1)
        self.assertEqual([], x)
        g2.switch()
        self.assertEqual(['A', True], x)
        g2.throw()
        self.assertEqual(['A', True, 'B', False, True, 'C',
                          self.greenlet.GreenletExit], x)
        self.assertTrue(g1.dead)
        self.assertTrue(g2.dead)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testParentCatchOnDelete(self):
      x = []

      def Work():
        gw = self.greenlet.getcurrent()
        g1 = self.greenlet(lambda value: x.append(type(value)))
        def F2():
          try:
            x.append('A')
            x.append(self.greenlet.getcurrent().parent is g1)
            gw.switch()
          except self.greenlet.GreenletExit:
            # For `del g2', parent becomes gw (who deleted it),
            # for normal throw(), parent remains.
            x.append('B')
            x.append(self.greenlet.getcurrent().parent is gw)
            x.append(self.greenlet.getcurrent().parent is g1)
            x.append('C')
            raise
        g2 = self.greenlet(F2, parent=g1)
        self.assertEqual([], x)
        g2.switch()
        self.assertEqual(['A', True], x)
        del g2
        self.assertEqual(['A', True, 'B', True, False, 'C'], x)
        self.assertFalse(g1)
        self.assertFalse(g1.dead)
        x[:] = [()]

      self.greenlet(Work).switch()
      self.assertEqual([()], x)

    def testCircularCoroutineReferences(self):
      def F(other_ref, x):
        self.greenlet.getcurrent().parent.switch(42)
      x = []
      xr = sys.getrefcount(x)
      g = [self.greenlet(F), self.greenlet(F)]
      self.assertEqual(42, g[0].switch(g[1], x))
      self.assertEqual(42, g[1].switch(g[0], x))
      del g[:]
      gc.collect()
      # It's 4 eith both greenlet_using_stackless.py and native greenlet.
      # TODO(pts): Why do we end up with 4 references in
      # greenlet_using_stackess.py? Shouldn't it go down to 0?
      self.assertEqual(0, sys.getrefcount(x) - xr)

if __name__ == '__main__':
  class GreenletTest(Template.GreenletTestTemplate):
    from syncless.best_greenlet.greenlet import greenlet
    if hasattr(greenlet, 'is_pts_greenlet_emulated'):
      print >>sys.stderr, 'info: using stackless with greenlet emulation'
      from stackless import getruncount
      getruncount = staticmethod(getruncount)  # Extra check.
    else:
      print >>sys.stderr, 'info: using greenlet'

    assert isinstance(greenlet.GreenletExit(), BaseException)

    def testGreenletModule(self):
      self.assertTrue('greenlet' in sys.modules)
      self.assertEqual(self.greenlet, sys.modules['greenlet'].greenlet)

  unittest.main()


text:
AUDIT_RULES_FILE="/etc/audit/audit.rules"

# General form / skeleton of an audit rule to search for
BASE_SEARCH_RULE='-a always,exit .* -F auid>=500 -F auid!=4294967295 -k perm_mod'

# System calls group to search for
SYSCALL_GROUP="xattr"

# Retrieve hardware architecture of the underlying system
[ $(getconf LONG_BIT) = "32" ] && ARCHS=("b32") || ARCHS=("b32" "b64")

# Perform the remediation depending on the system's architecture:
# * on 32 bit system, operate just at '-F arch=b32' audit rules
# * on 64 bit system, operate at both '-F arch=b32' & '-F arch=b64' audit rules
for ARCH in ${ARCHS[@]}
do

  # Create expected audit rule form for particular system call & architecture
  EXPECTED_RULE="-a always,exit -F arch=${ARCH} -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=500 -F auid!=4294967295 -k perm_mod"

  # Indicator that we want to append $EXPECTED_RULE for key & arch into
  # audit.rules by default
  APPEND_EXPECTED_RULE=0

  # From all the existing /etc/audit.rule definitions select those, which:
  # * follow the common audit rule form ($BASE_SEARCH_RULE above)
  # * meet the hardware architecture requirement, and
  # * are current $SYSCALL_GROUP specific
  IFS=$'\n' EXISTING_KEY_ARCH_RULES=($(sed -e "/${BASE_SEARCH_RULE}/!d" -e "/${ARCH}/!d" -e "/${SYSCALL_GROUP}/!d"  ${AUDIT_RULES_FILE}))

  # Process found rules case by case
  for RULE in ${EXISTING_KEY_ARCH_RULES[@]}
  do
    # Found rule is for same arch & syscall group, but differs slightly (in count of -S arguments)
    if [ ${RULE} != ${EXPECTED_RULE} ]
    then
      # If so, isolate just '-S syscall' substring of that rule
      RULE_SYSCALLS=$(echo ${RULE} | grep -o -P '(-S \w+ )+')

        # Check if list of '-S syscall' arguments of that rule is a subset
        # '-S syscall' list from the expected form ($EXPECTED_RULE)
        if [ $(echo ${EXPECTED_RULE} | grep -- ${RULE_SYSCALLS}) ]
        then
          # If so, this audit rule is covered when we append expected rule
          # later & therefore the rule can be deleted.
          #
          # Thus delete the rule from both - the audit.rules file and
          # our $EXISTING_KEY_ARCH_RULES array
          sed -i -e "/${RULE}/d" ${AUDIT_RULES_FILE}
          EXISTING_KEY_ARCH_RULES=(${EXISTING_KEY_ARCH_RULES[@]//${RULE}/})
        else
          # Rule isn't covered by $EXPECTED_RULE - in other words it besides
          # $SYSCALL_GROUP -S arguments contains also -S arguments for other
          # syscall group. Example: '-S chown -S setxattr'
          #
          # Therefore:
          # * delete the original rule for arch & key from audit.rules
          #   (original '-S chown -S setxattr' rule would be deleted)
          # * delete $SYSCALL_GROUP -S arguments from the rule,
          #   but keep those not from this $SYSCALL_GROUP
          #   (original '-S chown -S setxattr' would become '-S chown')
          # * append the modified (filtered) rule again into audit.rules
          #   if the same rule not already present
          #   (new rule for same arch & key with '-S chown' would be appended
          #    if not present yet)
          sed -i -e "/${RULE}/d" ${AUDIT_RULES_FILE}
          # Drop ' -S (lsetxattr|fsetxattr|setxattr|fremovexattr|lremovexattr|removexattr)'
          # from the rule's system calls list
          NEW_SYSCALLS_FOR_RULE=$(echo ${RULE_SYSCALLS} | sed -r -e "s/[\s]*-S (lsetxattr|fsetxattr|setxattr|fremovexattr|lremovexattr|removexattr)//g")
          UPDATED_RULE=$(echo ${RULE} | sed "s/${RULE_SYSCALLS}/${NEW_SYSCALLS_FOR_RULE}/g")
          # Squeeze repeated whitespace characters in rule definition (if any) into one
          UPDATED_RULE=$(echo ${UPDATED_RULE} | tr -s '[:space:]')
          # Insert updated rule into /etc/audit/audit.rules only in case it's not
          # present yet to prevent duplicate same rules
          if [ ! $(grep -- ${UPDATED_RULE} ${AUDIT_RULES_FILE}) ]
          then
            echo ${UPDATED_RULE} >> ${AUDIT_RULES_FILE}
          fi
        fi

    else
      # /etc/audit/audit.rules already contains the expected rule form for this
      # architecture & key => don't insert it second time
      APPEND_EXPECTED_RULE=1
    fi
  done

  # We deleted all rules that were subset of the expected one for this arch & key.
  # Also isolated rules containing system calls not from this system calls group.
  # Now append the expected rule if it's not present in audit.rules yet
  if [[ ${APPEND_EXPECTED_RULE} -eq "0" ]]
  then
    echo ${EXPECTED_RULE} >> ${AUDIT_RULES_FILE}
  fi
done


text:
package org.springframework.flex.security3;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.flex.core.ExceptionTranslator;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import flex.messaging.FlexSession;

/**
 * Infrastructure class for setting up the necessary integration points with Spring Security.
 *
 *
Given existing Spring Security configuration for implementations of {@link SessionAuthenticationStrategy}, {@link RememberMeServices},
 * will configure the {@link SpringSecurityLoginCommand} and {@link FilterChainProxy} to work with those services as necessary.  An existing
 * SessionAuthentiactionStrategy will be wrapped with a {@link FlexSessionAwareSessionAuthenticationStrategy} in order to ensure
 * proper handling of the {@link FlexSession}.
 *
 *
This class will be configured automatically through use of the XML namespace tags.
 *
 * @author Jeremy Grelle
 */
public class SecurityConfigurationPostProcessor implements MergedBeanDefinitionPostProcessor, InitializingBean, ApplicationContextAware {

	private SessionAuthenticationStrategy sessionAuthenticationStrategy;

	private RememberMeServices rememberMeServices;

	private FilterChainProxy filterChainProxy;

	private ApplicationContext context;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) {
		if (SpringSecurityLoginCommand.class.isAssignableFrom(beanType)) {
			MutablePropertyValues pv = beanDefinition.getPropertyValues();
			boolean rememberMeServicesConfigured = (pv.getPropertyValue("rememberMeServices") != null);
			if (this.sessionAuthenticationStrategy != null && pv.getPropertyValue("sessionAuthenticationStrategy") == null) {
				pv.add("sessionAuthenticationStrategy", this.sessionAuthenticationStrategy);
			}
			if (this.rememberMeServices != null && !rememberMeServicesConfigured) {
				pv.add("rememberMeServices", this.rememberMeServices);
			}
			if (pv.getPropertyValue("logoutHandlers") == null) {
				ManagedList handlers = new ManagedList();
				SecurityContextLogoutHandler contextHandler = new SecurityContextLogoutHandler();
				boolean invalidateHttpSession = (Boolean) beanDefinition.getAttribute("invalidateHttpSession");
				contextHandler.setInvalidateHttpSession(invalidateHttpSession);
				handlers.add(contextHandler);
				if (this.rememberMeServices != null && !rememberMeServicesConfigured && ClassUtils.isAssignableValue(LogoutHandler.class, this.rememberMeServices)) {
					handlers.add(this.rememberMeServices);
				}
				pv.add("logoutHandlers", handlers);
			}
		}
	}

	public void afterPropertiesSet() throws Exception {
		if (this.sessionAuthenticationStrategy != null) {
			this.sessionAuthenticationStrategy = new FlexSessionAwareSessionAuthenticationStrategy(this.sessionAuthenticationStrategy);

			Set<Filter> allFilters = new HashSet<Filter>(BeanFactoryUtils.beansOfTypeIncludingAncestors(context, Filter.class, false, false).values());
	        if (this.filterChainProxy != null) {
	            allFilters.addAll(new FilterChainAccessor(this.filterChainProxy).getFilters());
	        }
	        for (Filter filter : allFilters) {
	        	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(filter);
	        	for (PropertyDescriptor pd : bw.getPropertyDescriptors()) {
	        		if (ClassUtils.isAssignableValue(pd.getPropertyType(), this.sessionAuthenticationStrategy) && bw.isWritableProperty(pd.getName())) {
	        			bw.setPropertyValue(pd.getName(), this.sessionAuthenticationStrategy);
	        		}
	        	}
	        }
		}

		Map<String, ExceptionTranslator> exceptionTranslators = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ExceptionTranslator.class);
		if (!CollectionUtils.isEmpty(exceptionTranslators)) {
			Map<String, FlexAuthenticationEntryPoint> entryPoints = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, FlexAuthenticationEntryPoint.class);
			for (FlexAuthenticationEntryPoint entryPoint: entryPoints.values()) {
				if (CollectionUtils.isEmpty(entryPoint.getExceptionTranslators())) {
					entryPoint.setExceptionTranslators(new HashSet<ExceptionTranslator>(exceptionTranslators.values()));
				}
			}
		}
	}

	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

	public void setFilterChainProxy(FilterChainProxy filterChainProxy) {
		this.filterChainProxy = filterChainProxy;
	}

	public void setRememberMeServices(RememberMeServices rememberMeServices) {
		this.rememberMeServices = rememberMeServices;
	}

	public void setSessionAuthenticationStrategy(
			SessionAuthenticationStrategy sessionAuthenticationStrategy) {
		this.sessionAuthenticationStrategy = sessionAuthenticationStrategy;
	}

	private static final class FilterChainAccessor {

    	private final Set<Filter> filters;

    	public FilterChainAccessor(FilterChainProxy proxy) {
    		this.filters = new LinkedHashSet<Filter>();

            for (List<Filter> filters : proxy.getFilterChainMap().values()) {
                this.filters.addAll(filters);
            }
    	}

    	public Set<Filter> getFilters() {
    		return this.filters;
    	}
    }
}


text:
import time
import logging
import traceback
import gevent
import json
import datetime

from .utils import merge_cookie, import_object

from .fetcher import Fetcher
from .db import Session, ScopedSession, SpiderProject, SpiderTask, SpiderScheduler, get_result_class
from .mq import build_redis_queue

class EasyProcessor:
    def __init__(self, project, spider, qname):
        self.project = project
        self.spider = spider
        self.fetcher = Fetcher()
        self.qname = qname #'q_'+project+time.time()

        self.queue = build_redis_queue(qname=qname)
        self.db = Session()
        self.status = 1

    def run(self):
        try:
            fail_count = 0
            while True:
                try:
                    if self.status != 1:
                        break
                    task = self.queue.get()
                    if task == '':
                        # self.clear_queue()
                        # self.close()
                        logging.info("processor %s get empty task." % self.project)
                        break
                    if task is None:
                        fail_count += 1
                        if fail_count > 1000:
                            # self.close()
                            logging.info("processor %s try get task(empty) counts from queue(%s) > 10." % (self.project,self.qname))
                            # break
                            gevent.sleep(10)
                        else:
                            tasks = self.load_tasks()
                            if len(tasks)<=0:
                                logging.debug("load project(%s) empty tasks from database" % (self.project))
                                gevent.sleep(10)
                    else:
                        fail_count = 0
                        self.do_fetch(task)
                except:
                    logging.error("run processor error!\n%s" % traceback.format_exc())
        except:
            logging.error("Worker error!\n%s" % traceback.format_exc())
        logging.info("processor %s exit." % self.project)
        self.close()

    def close(self):
        self.db.close()
        self.queue.close()
        self.status = -1

    def clear_queue(self):
        while True:
            task = self.queue.get()
            if task is None:
                break
            if task == '':
                pass
            task_id = task.get('task_id')
            dbtask = self.db.query(SpiderTask).filter(SpiderTask.task_id==task_id).first()
            dbtask.status = 0
            self.db.add(dbtask)
            self.db.commit()

    def do_fetch(self, task):
        logging.debug("do fetch task: %s", json.dumps(task))

        project_name = task.get('project')
        headers = self.spider.config.http_headers
        url = task.get('url')
        task_id = task.get('task_id')
        task_type = task.get('type')
        if task_type == 'scheduler':
            method = task.get('method')
            if method is not None and method != '':
                logging.debug("call method %s" % method)
                method_func = getattr(self.spider, method)
                if method_func:
                    method_func()
        else:
            response = self.fetcher.fetch(self.spider, task, headers)
            if 'set-cookie' in response:
                new_cookie = response['set-cookie']
                old_cookie = headers.get('Cookie', None)
                headers['Cookie'] = merge_cookie(new_cookie, old_cookie)

            result_code = response['code']
            ResultClass = get_result_class(project_name)
            if 'result' in response:
                res = response['result']
                if 'code' in res:
                    result_code = res['code']

                sr = self.db.query(ResultClass).filter_by(task_id=task_id).first()
                if sr is None:
                    sr = ResultClass()
                sr.project = task.get('project')
                sr.task_id = task_id
                sr.url = url
                sr.result = json.dumps(res)
                sr.create_at = datetime.datetime.now()
                self.db.add(sr)
                print("save result to db %s,%s" % (task_id, url))
            st = self.db.query(SpiderTask).filter_by(task_id=task_id).first()
            if st is None:
                return
            st.status = result_code
            st.last_time = time.time()
            self.db.add(st)
            self.db.commit()
            self.db.close()

    def load_tasks(self):
        # db = Session()
        tasks = self.db.query(SpiderTask).filter(SpiderTask.project==self.project, SpiderTask.status==0).order_by('priority').limit(30).all()

        new_tasks = []
        if len(tasks)<=0:
            # logging.debug("load project(%s) tasks is empty." % (self.project))
            self.db.close()
            return new_tasks

        for task in tasks:
            task.status = 1
            self.db.add(task)
            # db.commit()
            new_task={}
            new_task['id'] = task.id
            new_task['task_id'] = task.task_id
            new_task['project'] = task.project
            new_task['url'] = task.url
            new_task['callback'] = task.callback
            new_tasks.append(new_task)
        self.db.commit()
        self.db.close()
        for task in new_tasks:
            self.queue.put(task)
        return new_tasks


text:
import { Application, TaskMonitor, TaskMonitorBuilder } from '@spinnaker/core';
import { IController, module } from 'angular';
import { IModalServiceInstance } from 'angular-ui-bootstrap';
import { chain, cloneDeep, last } from 'lodash';

import { IGceAutoHealingPolicy, IGceServerGroup } from 'google/domain/index';
import { GCE_HEALTH_CHECK_READER, GceHealthCheckReader } from 'google/healthCheck/healthCheck.read.service';

import './upsertAutoHealingPolicy.modal.less';

class GceUpsertAutoHealingPolicyModalCtrl implements IController {
  public autoHealingPolicy: IGceAutoHealingPolicy;
  public taskMonitor: TaskMonitor;
  public httpHealthChecks: string[];
  public action: 'Edit' | 'New';
  public isNew: boolean;
  public submitButtonLabel: string;

  constructor(private $uibModalInstance: IModalServiceInstance,
              private application: Application,
              public serverGroup: IGceServerGroup,
              private gceHealthCheckReader: GceHealthCheckReader,
              private taskMonitorBuilder: TaskMonitorBuilder,
              private gceAutoscalingPolicyWriter: any) {
    'ngInject';
    this.initialize();
  }

  public submit(): void {
    const submitMethod = () => {
      return this.gceAutoscalingPolicyWriter
        .upsertAutoHealingPolicy(this.application, this.serverGroup, this.autoHealingPolicy);
    };
    this.taskMonitor.submit(submitMethod);
  }

  public cancel(): void {
    this.$uibModalInstance.dismiss();
  }

  public setAutoHealingPolicy(autoHealingPolicy: IGceAutoHealingPolicy): void {
    this.autoHealingPolicy = autoHealingPolicy;
  }

  public onHealthCheckRefresh(): void {
    this.gceHealthCheckReader.listHealthChecks('HTTP')
      .then((healthChecks) => {
        this.httpHealthChecks = chain(healthChecks)
          .filter({account: this.serverGroup.account})
          .map('name')
          .value() as string[];
      });
  }

  private initialize(): void {
    this.onHealthCheckRefresh();
    this.action = this.serverGroup.autoHealingPolicy ? 'Edit' : 'New';
    this.isNew = !this.serverGroup.autoHealingPolicy;
    this.submitButtonLabel = this.isNew ? 'Create' : 'Update';
    if (!this.isNew) {
      this.autoHealingPolicy = cloneDeep(this.serverGroup.autoHealingPolicy);
      if (this.autoHealingPolicy.healthCheck) {
        this.autoHealingPolicy.healthCheck = last(this.autoHealingPolicy.healthCheck.split('/'));
      }
    }
    this.taskMonitor = this.taskMonitorBuilder.buildTaskMonitor({
      application: this.application,
      title: `${this.action} autohealing policy for ${this.serverGroup.name}`,
      modalInstance: this.$uibModalInstance,
    });
  }
}

export const GCE_UPSERT_AUTOHEALING_POLICY_MODAL_CTRL = 'spinnaker.gce.upsertAutoHealingPolicy.modal.controller';
module(GCE_UPSERT_AUTOHEALING_POLICY_MODAL_CTRL, [
  GCE_HEALTH_CHECK_READER,
  require('google/autoscalingPolicy/autoscalingPolicy.write.service.js'),
]).controller('gceUpsertAutoHealingPolicyModalCtrl', GceUpsertAutoHealingPolicyModalCtrl);