text:
package com.nlworks.wowapi;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.nlworks.wowapi.WowAPI.RegionLocale;
import com.nlworks.wowapi.model.CharacterModel;
import com.nlworks.wowapi.model.PlayerClasses;
import com.nlworks.wowapi.model.PlayerClasses.PlayerClass;
import com.nlworks.wowapi.model.PlayerRaces;
import com.nlworks.wowapi.model.PlayerRaces.PlayerRace;
import com.nlworks.wowapi.params.CharacterParams;

public class TestWowAPI {
	private WowAPI wowApi;

	@Before
	public void setUp() throws Exception {
		wowApi = new WowAPI(RegionLocale.NORTH_AMERICA_en_US);

	}

	@After
	public void tearDown() throws Exception {
	}

//	@Test
	public void characterModel1() throws JsonGenerationException, JsonMappingException, IOException {
		System.out.println("\n##### characterModel1 #####");
		CharacterModel c = wowApi.getCharacter(new CharacterParams("shadowmoon", "Kyrra"));
		if (c != null) {
			System.out.println("lastmod: " + c.getLastModified());
			System.out.println("name: " + c.getName());
		}
		System.out.println(wowApi.mapper.writeValueAsString(c));
	}

	@Test
	public void characterModel2() throws JsonGenerationException, JsonMappingException, IOException {
		System.out.println("\n##### characterModel2 #####");
		CharacterModel c = wowApi.getCharacter(new CharacterParams("shadowmoon", "Kyrra").addAll());
		if (c != null) {
			System.out.println("lastmod: " + c.getLastModified());
			System.out.println("name: " + c.getName());
		}
		System.out.println(wowApi.mapper.writeValueAsString(c));
	}

//	@Test
	public void raceList() throws JsonGenerationException, JsonMappingException, IOException {
		System.out.println("\n##### raceList #####");
		PlayerRaces characterRaces = wowApi.getPlayerRaces();
		Assert.assertNotNull(characterRaces);
		Assert.assertNotNull(characterRaces.getRaces());
		Assert.assertTrue(characterRaces.getRaces().length >= 8);
		System.out.println("ID\t\tRACE NAME");
		for (PlayerRace race : characterRaces.getRaces()) {
			System.out.println(race.getId() + "\t\t" + race.getName());
		}

		System.out.println(wowApi.mapper.writeValueAsString(characterRaces));
	}

//	@Test
	public void itemClasses() {
		System.out.println("\n##### itemClasses #####");
		wowApi.getItemClasses();
	}

//	@Test
	public void playerClasses() throws JsonGenerationException, JsonMappingException, IOException {
		System.out.println("\n##### playerClasses #####");
		PlayerClasses playerClasses = wowApi.getPlayerClasses();
		Assert.assertNotNull(playerClasses);
		Assert.assertNotNull(playerClasses.getClasses());
		Assert.assertTrue(playerClasses.getClasses().length >= 9);
		System.out.println("ID\t\tCLASS NAME");
		for (PlayerClass pc : playerClasses.getClasses()) {
			System.out.println(pc.getId() + "\t\t" + pc.getName().toUpperCase());
		}

		System.out.println(wowApi.mapper.writeValueAsString(playerClasses));
	}
}


text:
Rails.application.config.assets.version = '1.0'

# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w( style.css )
Rails.application.config.assets.precompile += %w( skins.css )
Rails.application.config.assets.precompile += %w( responsive.css )
Rails.application.config.assets.precompile += %w( base.css )
Rails.application.config.assets.precompile += %w( bootstrap.min.css )
Rails.application.config.assets.precompile += %w( prettyPhoto.css )
Rails.application.config.assets.precompile += %w( lists.css )
Rails.application.config.assets.precompile += %w( bootstrap.min.js )
Rails.application.config.assets.precompile += %w( jquery.js )

redpajama_set_name: RedPajamaGithub


text:
void GLCacheInitialize();
void GLCacheFinalize();

void GLCacheActiveTexture(GLenum index);
void GLCacheBindTexture2D(GLTexture2D *texture);

GLuint GLGetDefaultFramebuffer();


text:
package org.approvaltests.hadoop.version2.tests;

import java.io.IOException;
import java.util.Iterator;

import junit.framework.TestCase;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.approvaltests.hadoop.version2.HadoopApprovals;
import org.approvaltests.hadoop.version2.MapperWrapper;
import org.approvaltests.hadoop.version2.ReducerWrapper;
import org.approvaltests.hadoop.version2.SmartMapper;
import org.approvaltests.hadoop.version2.SmartReducer;
import org.approvaltests.reporters.DiffReporter;
import org.approvaltests.reporters.UseReporter;

import com.spun.util.ArrayUtils;

@UseReporter({DiffReporter.class})
public class HadoopApprovalsTest extends TestCase
{
  public void testMap() throws Exception
  {
    SmartMapper mapper = new MapperWrapper(new WordCountMap(), LongWritable.class, Text.class, Text.class,
        LongWritable.class);
    HadoopApprovals.verifyMapping(mapper, 0, "llew gen  llew");
  }
  public void testReduce() throws Exception
  {
    SmartReducer reducer = new ReducerWrapper(new WordCountReduce(), Text.class, LongWritable.class, Text.class,
        LongWritable.class);
    HadoopApprovals.verifyReducer(reducer, "life", 7, 35);
  }
  public void testMapReducer() throws Exception
  {
    SmartMapper mapper = new MapperWrapper(new WordCountMap(), LongWritable.class, Text.class, Text.class,
        LongWritable.class);
    SmartReducer reducer = new ReducerWrapper(new WordCountReduce(), Text.class, LongWritable.class, Text.class,
        LongWritable.class);
    HadoopApprovals.verifyMapReduce(mapper, reducer, 0, "one fish two fish red fish blue fish");
  }
  public static class WordCountReduce extends MapReduceBase
      implements
        Reducer<Text, LongWritable, Text, LongWritable>
  {
    public void reduce(Text token, Iterator<LongWritable> counts, OutputCollector<Text, LongWritable> context,
        Reporter arg3) throws IOException
    {
      long n = 0;
      for (LongWritable count : ArrayUtils.asIterable(counts))
      {
        n += count.get();
      }
      context.collect(token, new LongWritable(n));
    }
  }
  private static class WordCountMap extends MapReduceBase
      implements
        Mapper<LongWritable, Text, Text, LongWritable>
  {
    public void map(LongWritable _, Text text, OutputCollector<Text, LongWritable> context, Reporter reporter)
        throws IOException
    {
      for (String token : text.toString().split("\\s+"))
      {
        context.collect(new Text(token), new LongWritable(1));
      }
    }
  }
}


text:
package org.robolectric.res;

import org.junit.Before;
import org.junit.Test;

import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.util.TestUtil.sdkResources;

public class StyleResourceLoaderTest {
  private PackageResourceTable resourceTable;

  @Before
  public void setUp() throws Exception {
    ResourcePath resourcePath = sdkResources(JELLY_BEAN);
    resourceTable = new ResourceTableFactory().newResourceTable("android", resourcePath);
  }

  @Test
  public void testStyleDataIsLoadedCorrectly() throws Exception {
    TypedResource typedResource = resourceTable.getValue(new ResName("android", "style", "Theme_Holo"), "");
    StyleData styleData = (StyleData) typedResource.getData();
    assertThat(styleData.getName()).isEqualTo("Theme_Holo");
    assertThat(styleData.getParent()).isEqualTo("Theme");
    assertThat(styleData.getPackageName()).isEqualTo("android");
    assertThat(styleData.getAttrValue(new ResName("android", "attr", "colorForeground")).value)
        .isEqualTo("@android:color/bright_foreground_holo_dark");
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="p1.p2">
    <application android:icon="@drawable/icon">
        <activity android:name="MyActivity"/>
    </application>
</manifest>


text:
// Sketch to control AAR Robot via Firmata over Bluetooth

// Do not remove the include below
#include "firmata_aar.h"

#include <Firmata.h>

#define red_line_led 7
#define motor_rf 5
#define motor_rb 6
#define motor_lf 9
#define motor_lb 10
#define led_pin 13

#define echoPin A2 // Echo Pin
#define trigPin A3 // Trigger Pin

#define SPEED_TIMER_BASE 500

namespace {

int volatile speed_timer = 0;
byte volatile mleft_speed = 0;
byte volatile mright_speed = 0;
int volatile mleft_counter = 0;
int volatile mright_counter = 0;

float left_to_right = 1.0;

byte volatile report_speed = 0;

void motorSet(byte lf, byte lb, byte rf, byte rb)
{
	analogWrite(motor_lf, lf);
	analogWrite(motor_lb, lb);
	analogWrite(motor_rf, rf);
	analogWrite(motor_rb, rb);
}

void motorStop()
{
	motorSet(0, 0, 0, 0);
}

void leftForward(byte spd)  // move left forward speed 0..255
{
	motorSet(spd, 0, 0, 0);
}

void leftBackward(byte spd)  // move left backward speed 0..255
{
	motorSet(0, spd, 0, 0);
}

void rightForward(byte spd)  // move right forward speed 0..255
{
	motorSet(0, 0, spd, 0);
}

void rightBackward(byte spd)  // move right backward speed 0..255
{
	motorSet(0, 0, 0, spd);
}

void forward(byte spd)  // move forward speed 0..255
{
	byte const right_speed = static_cast<byte>(left_to_right * spd);

	motorSet(spd, 0, right_speed, 0);
}

void calibrate_forward(void)  // full power
{
	motorSet(255, 0, 255, 0);
}

void backward(byte spd)  // move backward speed 0..255
{
	motorSet(0, spd, 0, spd);
}

void leftFast(byte spd)  // left forward, right back > fast turn
{
	motorSet(spd, 0, 0, spd);
}

void rightFast(byte spd) // left back, right forward > fast turn
{
	motorSet(0, spd, spd, 0);
}

ISR(TIMER2_OVF_vect)
{
	speed_timer++;

	if (speed_timer > SPEED_TIMER_BASE)
	{
		report_speed = 1;
		digitalWrite(led_pin, digitalRead(led_pin) ^ 1);

		if (mright_counter > 255)
			mright_counter = 255;
		mright_speed = mright_counter;
		if (mleft_counter > 255)
			mleft_counter = 255;
		mleft_speed = mleft_counter;
		mright_counter = 0;
		mleft_counter = 0;
		speed_timer = 0;
	}
}

void
calibrate(void)
{
	motorStop();

	noInterrupts();

	mright_counter = 0;
	mleft_counter = 0;

	interrupts();

	calibrate_forward();

	delay(3000);

	motorStop();

	left_to_right = (float) mleft_speed / (float) mright_speed;
}

void leftsens()  //external interrupt left encoder
{
  detachInterrupt(1);
  mleft_counter++;
  attachInterrupt(1, leftsens, CHANGE);
}

void rightsens()  //external interrupt right encoder
{
  detachInterrupt(0);
  mright_counter++;
  attachInterrupt(0, rightsens, CHANGE);
};

enum commands {
    SYSEX_AAR_MOVE = 0x50,
    SYSEX_AAR_REPORT = 0x51,
    SYSEX_AAR_COMMAND = 0x52,
    SYSEX_AAR_REPLY = 0x53
};

enum SYSEX_MOVE {
    SYSEX_MOVE_STOP = 0,
    SYSEX_MOVE_FORWARD = 1,
    SYSEX_MOVE_BACKWARD = 2,
    SYSEX_MOVE_RIGHT = 3,
    SYSEX_MOVE_LEFT = 4
};

enum SYSEX_REPORT {
	SYSEX_REPORT_FIRMWARE = 0
};

enum SYSEX_COMMAND {
	SYSEX_COMMAND_SENSORLIGHT_ON = 0,
	SYSEX_COMMAND_SENSORLIGHT_OFF = 1,
	SYSEX_COMMAND_CALIBRATE = 2
};

enum SYSEX_REPLY {
	SYSEX_REPLY_SPEED = 0
};

void doMove(byte dir, byte speed)
{
	switch (dir)
	{
	case SYSEX_MOVE_STOP:
		motorStop();
		break; // STOP
	case SYSEX_MOVE_FORWARD:
		forward(speed);
		break; // FOREWARD
	case SYSEX_MOVE_LEFT:
		rightForward(speed);
		break; // LEFT
	case SYSEX_MOVE_RIGHT:
		leftForward(speed);
		break; // RIGHT
	case SYSEX_MOVE_BACKWARD:
		backward(speed);
		break; // BACKWARD
	default:
		String data((int) dir);
		data += " ";
		data +=  String((int) speed);
		String msg = "UNKNOWN MOVE ";
		msg += data;
		Firmata.sendString(msg.c_str());
		break;
	}
}

void
doReport(byte what)
{
	switch (what) {
	case SYSEX_REPORT_FIRMWARE:
		Firmata.printFirmwareVersion();
		break;
	default:
		String data((int) what);
		String msg = "UNKNOWN REPORT ";
		msg += data;
		Firmata.sendString(msg.c_str());
		break;
	}
}

void
doCommand(byte what)
{
	switch (what) {
	case SYSEX_COMMAND_SENSORLIGHT_ON:
		digitalWrite(red_line_led, HIGH);
		break;
	case SYSEX_COMMAND_SENSORLIGHT_OFF:
		digitalWrite(red_line_led, LOW);
		break;
	case SYSEX_COMMAND_CALIBRATE:
		calibrate();
		break;
	default:
		String data((int) what);
		String msg = "UNKNOWN COMMAND ";
		msg += data;
		Firmata.sendString(msg.c_str());
		break;
	}
}

/* Decode from serial protocol back to raw bytes, as it happens for Strings */
void decodeSysex(byte *argc, byte*argv)
{
	byte bufferLength = *argc;
	byte i = 0;
	byte j = 0;
	while (j < bufferLength)
	{
		// The string length will only be at most half the size of the
		// stored input buffer so we can decode the string within the buffer.
		argv[j] = argv[i];
		i++;
		argv[j] += (argv[i] << 7);
		i++;
		j++;
	}
	*argc = bufferLength / 2;
}

void sysexCallback(byte command, byte argc, byte*argv)
{
	decodeSysex(&argc, argv);

	switch (command)
	{
	case SYSEX_AAR_MOVE:
		{
			byte dir = argv[0];
			byte speed = argv[1];
			doMove(dir, speed);
		}
		break;
	case SYSEX_AAR_REPORT:
		{
			doReport(argv[0]);
		}
		break;
	case SYSEX_AAR_COMMAND:
		{
			doCommand(argv[0]);
		}
		break;
	default:
		Firmata.sendString("got unknown command");
		break;
	}
}

} // anonymous namespace

/*
 * The AAR Bluetooth device needs 9600 Baud set!
 */
#define BAUDRATE 9600UL

void setup()
{
	//set pin I/O
#if 0
	pinMode(2, INPUT);	// encoder right
	pinMode(3, INPUT);  // encoder left
#endif
	pinMode(motor_rf, OUTPUT);	//right motor foreward
	pinMode(motor_rb, OUTPUT);	//right motor backward
	pinMode(motor_lf, OUTPUT);	//left motor foreward
	pinMode(motor_lb, OUTPUT); //left motor backward

	pinMode(red_line_led, OUTPUT);	// red line LED

	digitalWrite(red_line_led, LOW);

	pinMode(8, OUTPUT);  // status led

	pinMode(A6, INPUT); // linesensor left
	pinMode(A7, INPUT); // linesensor right

	motorStop();

	Serial.begin(BAUDRATE);
	Firmata.setFirmwareVersion(0, 1);
	Firmata.attach(START_SYSEX, sysexCallback);
	Firmata.attach(START_SYSEX, sysexCallback);
	Firmata.begin(BAUDRATE);

	noInterrupts();           // disable all interrupts

	// TIMER2 Settings
	TCCR2B = (1 << CS22) | (0 << CS21) | (1 << CS20); // Fosc/64 (prescaler)
	TCCR2A = (0 << WGM20) | (1 << WGM21) | (0 << COM2A0) | (0 << COM2A1); //CTC mode normal port operation
	OCR2A = 255;
	TIMSK2 |= (1 << TOIE2) | (0 << OCIE2A);

	interrupts();             // enable all interrupts

	// set interrupt for encoders
	attachInterrupt(1, leftsens, CHANGE);
	attachInterrupt(0, rightsens, CHANGE);

	pinMode(trigPin, OUTPUT);
	pinMode(echoPin, INPUT);
}

void loop()
{
	if (report_speed)
	{
	    byte const left_sensor_white = analogRead(A6) >= 60;
	    byte const right_sensor_white = analogRead(A7) >= 60;

		byte msg[] =
		{ SYSEX_REPLY_SPEED, mleft_speed, mright_speed, left_sensor_white,
				right_sensor_white };

		Firmata.sendSysex(SYSEX_AAR_REPLY, sizeof(msg), msg);

		report_speed = 0;
	}

	while (Firmata.available())
	{
		Firmata.processInput();
	}

	// HC-SR04 Ultrasonic Sensor
	digitalWrite(trigPin, HIGH);
	delayMicroseconds(10);
	digitalWrite(trigPin, LOW);
	int duration = pulseIn(echoPin, HIGH);
	int distance = (duration / 2) / 29.1;

	int ledstate = distance > 50;
	digitalWrite(8, ledstate);
}


text:
<?php

class Easylife_DirectLink_Helper_Data extends Mage_Core_Helper_Abstract
{

}


text:
package com.hubspot.blazar.data.service;

import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.hubspot.blazar.base.GitInfo;
import com.hubspot.blazar.base.Module;
import com.hubspot.blazar.data.dao.ModuleDao;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class ModuleService {
  private final ModuleDao moduleDao;

  @Inject
  public ModuleService(ModuleDao moduleDao) {
    this.moduleDao = moduleDao;
  }

  public Set<Module> getByBranch(int branchId) {
    return moduleDao.getByBranch(branchId);
  }

  @Transactional
  public Set<Module> setModules(GitInfo gitInfo, Set<Module> updatedModules) {
    Set<Module> oldModules = getByBranch(gitInfo.getId().get());
    Set<Module> newModules = new HashSet<>();

    Map<String, Module> updatedModulesByName = mapByName(updatedModules);
    Map<String, Module> oldModulesByName = mapByName(oldModules);

    for (String deletedModule : Sets.difference(oldModulesByName.keySet(), updatedModulesByName.keySet())) {
      checkAffectedRowCount(moduleDao.delete(oldModulesByName.get(deletedModule).getId().get()));
    }

    for (String updatedModule : Sets.intersection(oldModulesByName.keySet(), updatedModulesByName.keySet())) {
      Module old = oldModulesByName.get(updatedModule);
      Module updated = updatedModulesByName.get(updatedModule).withId(old.getId().get());
      if (!updated.equals(old)) {
        checkAffectedRowCount(moduleDao.update(updated));
      }
      newModules.add(updated);
    }

    for (String addedModule : Sets.difference(updatedModulesByName.keySet(), oldModulesByName.keySet())) {
      Module added = updatedModulesByName.get(addedModule);
      int id = moduleDao.insert(gitInfo.getId().get(), added);
      newModules.add(added.withId(id));
    }

    return newModules;
  }

  private static void checkAffectedRowCount(int affectedRows) {
    Preconditions.checkState(affectedRows == 1, "Expected to update 1 row but updated %s", affectedRows);
  }

  private static Map<String, Module> mapByName(Set<Module> modules) {
    Map<String, Module> modulesByName = new HashMap<>();
    for (Module module : modules) {
      modulesByName.put(module.getName().toLowerCase(), module);
    }

    return modulesByName;
  }
}


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

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

    <title>34. Unix Specific Services — Python 3.3.6 documentation</title>

    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.3.6 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.3.6 documentation" href="../index.html" />
    <link rel="up" title="The Python Standard Library" href="index.html" />
    <link rel="next" title="34.1. posix — The most common POSIX system calls" href="posix.html" />
    <link rel="prev" title="33.4. winsound — Sound-playing interface for Windows" href="winsound.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.3.6 Documentation »

The Python Standard Library »

34. Unix Specific Services¶

The modules described in this chapter provide interfaces to features that are
unique to the Unix operating system, or in some cases to some or many variants
of it.  Here’s an overview:

34.1. <tt class="docutils literal">posix</tt> — The most common POSIX system calls

34.1.1. Large File Support

34.1.2. Notable Module Contents

34.2. <tt class="docutils literal">pwd</tt> — The password database

34.3. <tt class="docutils literal">spwd</tt> — The shadow password database

34.4. <tt class="docutils literal">grp</tt> — The group database

34.5. <tt class="docutils literal">crypt</tt> — Function to check Unix passwords

34.5.1. Hashing Methods

34.5.2. Module Attributes

34.5.3. Module Functions

34.5.4. Examples

34.6. <tt class="docutils literal">termios</tt> — POSIX style tty control

34.6.1. Example

34.7. <tt class="docutils literal">tty</tt> — Terminal control functions

34.8. <tt class="docutils literal">pty</tt> — Pseudo-terminal utilities

34.8.1. Example

34.9. <tt class="docutils literal">fcntl</tt> — The <tt class="docutils literal">fcntl</tt> and <tt class="docutils literal">ioctl</tt> system calls

34.10. <tt class="docutils literal">pipes</tt> — Interface to shell pipelines

34.10.1. Template Objects

34.11. <tt class="docutils literal">resource</tt> — Resource usage information

34.11.1. Resource Limits

34.11.2. Resource Usage

34.12. <tt class="docutils literal">nis</tt> — Interface to Sun’s NIS (Yellow Pages)

34.13. <tt class="docutils literal">syslog</tt> — Unix syslog library routines

34.13.1. Examples

34.13.1.1. Simple example

Previous topic

33.4. <tt class="docutils literal">winsound</tt> — Sound-playing interface for Windows

Next topic

34.1. <tt class="docutils literal">posix</tt> — The most common POSIX system calls

This Page

Report a Bug

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.3.6 Documentation »

The Python Standard Library »

    © Copyright 1990-2014, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Oct 12, 2014.
    Found a bug?

    Created using Sphinx 1.2.


text:
import { Component } from '@angular/core';
import { JigsawNotification } from "jigsaw/public_api";
import {AsyncDescription} from "../../../template/demo-template/demo-template";

@Component({
    selector: 'notification-functional',
    templateUrl: './demo.component.html',
    styles: [`
        .wrapper {
            width: 250px;
        }
    `]
})
export class NotificationFunctionalDemoComponent extends AsyncDescription {
    public demoPath = "demo/notification/functional";

    public showSuccess() {
        JigsawNotification.showSuccess('这是一条成功的提示消息', { timeout: 8000 });
    }

    public showError() {
        JigsawNotification.showError('这是一条错误的提示消息', { timeout: 8000 });
    }

    public showWarn() {
        JigsawNotification.showWarn('这是一条警告的提示消息', { timeout: 8000 });
    }

    public showInfo() {
        JigsawNotification.showInfo('这是一条消息的提示消息', { timeout: 8000 });
    }

    public showInfo2() {
        JigsawNotification.showInfo('这是一条消息的提示消息', '带有标题的提示消息');
    }
}


text:
/*
 * control test (1): verify that compiler handles (lack of) at-deprecated correctly
 * @test
 * @clean NoDepX X RefX
 * @compile/ref=NoDepX.out -XDrawDiagnostics NoDepX.java RefX.java
 */
class NoDepX
{
}

/**
 * X.
 * not deprecated
 */
class X {
}


text:
 Add New Project

        <form name="addProjectForm">

                Project Name
                <input type="text" ng-model="projectData.Name" class="form-control" name="projectName" id="project-name" placeholder="Project Name" required/>
                Required

                Leader
                <select ng-model="projectData.LeadId" id="project-leader" class="form-control">
                    <option ng-repeat="user in users | orderBy:'Username'" value="{{user.Id}}">{{user.Username}}</option>
                </select>

                Project Key
                <input type="text" ng-model="projectData.ProjectKey" class="form-control" id="project-key" placeholder="Project Key" required/>
                Required

                Priorities (comma separated)
                <input type="text" ng-model="projectData.Priorities" class="form-control" id="project-priorities"
                       placeholder="Available Priorities For The Issues" />

                Labels (comma separated)
                <input type="text" ng-model="projectData.Labels" class="form-control" id="project-labels" placeholder="Labels" />

                Description
                <textarea class="form-control" ng-model="projectData.Description" id="project-description" placeholder="Description" required></textarea>
                Required

            <button ng-click="addNewProject(projectData)" type="submit" class="btn btn-success">Add Project</button>
        </form>


text:
namespace devtools_http_handler {
class DevToolsHttpHandler;
}

namespace chromecast {
namespace shell {

class CastDevToolsManagerDelegate;

class RemoteDebuggingServer {
 public:
  RemoteDebuggingServer();
  ~RemoteDebuggingServer();

 private:
  // Called when pref_enabled_ is changed.
  void OnEnabledChanged();

  // Returns whether or not the remote debugging server should be available
  // on device startup.
  bool ShouldStartImmediately();

  scoped_ptr<devtools_http_handler::DevToolsHttpHandler> devtools_http_handler_;

  BooleanPrefMember pref_enabled_;
  uint16 port_;

  DISALLOW_COPY_AND_ASSIGN(RemoteDebuggingServer);
};

}  // namespace shell
}  // namespace chromecast

#endif  // CHROMECAST_BROWSER_DEVTOOLS_REMOTE_DEBUGGING_SERVER_H_


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Implements parallel traversals over the DOM and flow trees.
//!
//! This code is highly unsafe. Keep this file small and easy to audit.

#![allow(unsafe_code)]

use block::BlockFlow;
use context::LayoutContext;
use flow::{self, Flow};
use flow_ref::FlowRef;
use profile_traits::time::{self, TimerMetadata, profile};
use rayon;
use servo_config::opts;
use smallvec::SmallVec;
use std::mem;
use std::ptr;
use std::sync::atomic::{AtomicIsize, Ordering};
use traversal::{AssignBSizes, AssignISizes, BubbleISizes};
use traversal::{PostorderFlowTraversal, PreorderFlowTraversal};

/// Traversal chunk size.
const CHUNK_SIZE: usize = 16;

pub type FlowList = SmallVec<[UnsafeFlow; CHUNK_SIZE]>;

/// Vtable + pointer representation of a Flow trait object.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct UnsafeFlow(*const Flow);

unsafe impl Sync for UnsafeFlow {}
unsafe impl Send for UnsafeFlow {}

fn null_unsafe_flow() -> UnsafeFlow {
    UnsafeFlow(ptr::null::<BlockFlow>())
}

pub fn mut_owned_flow_to_unsafe_flow(flow: *mut FlowRef) -> UnsafeFlow {
    unsafe { UnsafeFlow(&**flow) }
}

/// Information that we need stored in each flow.
pub struct FlowParallelInfo {
    /// The number of children that still need work done.
    pub children_count: AtomicIsize,
    /// The address of the parent flow.
    pub parent: UnsafeFlow,
}

impl FlowParallelInfo {
    pub fn new() -> FlowParallelInfo {
        FlowParallelInfo {
            children_count: AtomicIsize::new(0),
            parent: null_unsafe_flow(),
        }
    }
}

/// Process current flow and potentially traverse its ancestors.
///
/// If we are the last child that finished processing, recursively process
/// our parent. Else, stop. Also, stop at the root.
///
/// Thus, if we start with all the leaves of a tree, we end up traversing
/// the whole tree bottom-up because each parent will be processed exactly
/// once (by the last child that finishes processing).
///
/// The only communication between siblings is that they both
/// fetch-and-subtract the parent's children count.
fn bottom_up_flow(mut unsafe_flow: UnsafeFlow,
                  assign_bsize_traversal: &AssignBSizes) {
    loop {
        // Get a real flow.
        let flow: &mut Flow = unsafe {
            mem::transmute(unsafe_flow)
        };

        // Perform the appropriate traversal.
        if assign_bsize_traversal.should_process(flow) {
            assign_bsize_traversal.process(flow);
        }

        let base = flow::mut_base(flow);

        // Reset the count of children for the next layout traversal.
        base.parallel.children_count.store(base.children.len() as isize,
                                           Ordering::Relaxed);

        // Possibly enqueue the parent.
        let unsafe_parent = base.parallel.parent;
        if unsafe_parent == null_unsafe_flow() {
            // We're done!
            break
        }

        // No, we're not at the root yet. Then are we the last child
        // of our parent to finish processing? If so, we can continue
        // on with our parent; otherwise, we've gotta wait.
        let parent: &mut Flow = unsafe {
            &mut *(unsafe_parent.0 as *mut Flow)
        };
        let parent_base = flow::mut_base(parent);
        if parent_base.parallel.children_count.fetch_sub(1, Ordering::Relaxed) == 1 {
            // We were the last child of our parent. Reflow our parent.
            unsafe_flow = unsafe_parent
        } else {
            // Stop.
            break
        }
    }
}

fn top_down_flow<'scope>(unsafe_flows: &[UnsafeFlow],
                         pool: &'scope rayon::ThreadPool,
                         scope: &rayon::Scope<'scope>,
                         assign_isize_traversal: &'scope AssignISizes,
                         assign_bsize_traversal: &'scope AssignBSizes)
{
    let mut discovered_child_flows = FlowList::new();

    for unsafe_flow in unsafe_flows {
        let mut had_children = false;
        unsafe {
            // Get a real flow.
            let flow: &mut Flow = mem::transmute(*unsafe_flow);
            flow::mut_base(flow).thread_id =
                pool.current_thread_index().unwrap() as u8;

            if assign_isize_traversal.should_process(flow) {
                // Perform the appropriate traversal.
                assign_isize_traversal.process(flow);
            }

            // Possibly enqueue the children.
            for kid in flow::child_iter_mut(flow) {
                had_children = true;
                discovered_child_flows.push(UnsafeFlow(kid));
            }
        }

        // If there were no more children, start assigning block-sizes.
        if !had_children {
            bottom_up_flow(*unsafe_flow, &assign_bsize_traversal)
        }
    }

    if discovered_child_flows.is_empty() {
        return
    }

    if discovered_child_flows.len() <= CHUNK_SIZE {
        // We can handle all the children in this work unit.
        top_down_flow(&discovered_child_flows,
                      pool,
                      scope,
                      &assign_isize_traversal,
                      &assign_bsize_traversal);
    } else {
        // Spawn a new work unit for each chunk after the first.
        let mut chunks = discovered_child_flows.chunks(CHUNK_SIZE);
        let first_chunk = chunks.next();
        for chunk in chunks {
            let nodes = chunk.iter().cloned().collect::<FlowList>();
            scope.spawn(move |scope| {
                top_down_flow(&nodes, pool, scope, &assign_isize_traversal, &assign_bsize_traversal);
            });
        }
        if let Some(chunk) = first_chunk {
            top_down_flow(chunk, pool, scope, &assign_isize_traversal, &assign_bsize_traversal);
        }
    }
}

/// Run the main layout passes in parallel.
pub fn reflow(
        root: &mut Flow,
        profiler_metadata: Option<TimerMetadata>,
        time_profiler_chan: time::ProfilerChan,
        context: &LayoutContext,
        queue: &rayon::ThreadPool) {
    if opts::get().bubble_inline_sizes_separately {
        let bubble_inline_sizes = BubbleISizes { layout_context: &context };
        bubble_inline_sizes.traverse(root);
    }

    let assign_isize_traversal = &AssignISizes { layout_context: &context };
    let assign_bsize_traversal = &AssignBSizes { layout_context: &context };
    let nodes = [UnsafeFlow(root)];

    queue.install(move || {
        rayon::scope(move |scope| {
            profile(time::ProfilerCategory::LayoutParallelWarmup,
                    profiler_metadata, time_profiler_chan, move || {
                        top_down_flow(&nodes, queue, scope, assign_isize_traversal, assign_bsize_traversal);
            });
        });
    });
}


text:
.. webapi-resource::
   :classname: reviewboard.webapi.resources.patched_file.PatchedFileResource
   :example-url-keys: {"review_request_id": 8, "diff_revision": 1, "filediff_id": 31}


text:
using System;
using System.Net;

namespace UAOOI.Networking.UDPMessageHandler.Configuration
{
  internal static class IPAddressValidationRule
  {

    internal static IPAddress ValidateIP (string value)
    {
      if (String.IsNullOrEmpty(value))
        throw new ArgumentNullException($"The string representing IP Address cannot be empty");
      IPAddress _address;
      if (!IPAddress.TryParse(value, out _address))
        throw new ArgumentOutOfRangeException($"The string <{value}> doesn't represent IP Address");
      if (_address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
        throw new ArgumentOutOfRangeException($"The address family {_address.AddressFamily} is not supported");
      return _address;
    }
    internal static void ValidateMulticast(IPAddress address)
    {
      try
      {
        byte[] _bytesArray = address.GetAddressBytes();
        if (_bytesArray.Length != 4)
          throw new ArgumentOutOfRangeException($"The address length {_bytesArray.Length} is not expected");
        if (_bytesArray[0] > 239 || _bytesArray[0] < 224)
          throw new ArgumentOutOfRangeException($"The address {address} is outside the IP V4 multicast range 224.0.0.0 - 239.255.255.255");
      }
      catch (Exception _ex)
      {
        throw new ArgumentOutOfRangeException($"Validation error: {_ex.GetType().Name}: {_ex.Message}");
      }
    }

  }
}


text:
package org.encog.util.http;

import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

/**
 * This class allows URLConnection objects to process cookies. The loadCookies
 * method grabs the Set-Cookie headers and loads the cookies into the map. The
 * saveCookies method writes out the cookie map to the a URLConnection object as
 * Cookie headers.
 */
public class CookieUtility {

    /**
     * Map that holds all of the cookie values.
     */
    private final Map<String, String> map = new HashMap<String, String>();

    /**
     * Allows access to the name/value pair list of cookies.
     *

     * @return the map
     */
    public Map<String, String> getMap() {
        return this.map;
    }

    /**
     * Load any cookies from the specified URLConnection object. Cookies will be
     * located by their Set-Cookie headers. Any cookies that are found can be
     * moved to a new URLConnection class by calling saveCookies.
     *

     * @param http
     *             The URLConnection object to load the cookies from.
     */
    public void loadCookies(final URLConnection http) {
        String str;
        int n = 1;

        do {
            str = http.getHeaderFieldKey(n);
            if ((str != null) && str.equalsIgnoreCase("Set-Cookie")) {
                str = http.getHeaderField(n);
                final StringTokenizer tok = new StringTokenizer(str, "=");
                final String name = tok.nextToken();
                final String value = tok.nextToken();
                this.map.put(name, value);
            }
            n++;
        } while (str != null);
    }

    /**
     * Once you have loaded cookies with loadCookies, you can call saveCookies
     * to copy these cookies to a new HTTP request. This allows you to easily
     * support cookies.
     *

     * @param http
     *             The URLConnection object to add cookies to.
     */
    public void saveCookies(final URLConnection http) {
        final StringBuilder str = new StringBuilder();

        final Set<String> set = this.map.keySet();
        for (final String key : set) {
            final String value = this.map.get(key);
            if (str.length() > 0) {
                str.append("; ");
            }

            str.append(key + "=" + value);
        }

        http.setRequestProperty("Cookie", str.toString());
    }
}


text:
package com.kissthinker.coder;

import com.alibaba.fastjson.JSON;

/**
 * Mmmm, seems to want javabean methods - So this one really doesn't work yet!
 *
 * @author David Ainslie
 *
 */
public class FastJsonCoder implements Coder
{
    /** */
    public FastJsonCoder()
    {
        super();
    }

    /**
     * @see com.kissthinker.coder.Coder#decode(byte[])
     */
    @SuppressWarnings("unchecked")
    public <O> O decode(byte[] bytes)
    {
        return (O)JSON.parse(bytes);
    }

    /**
     * @see com.kissthinker.coder.Coder#encode(java.lang.Object)
     */
    public <O> byte[] encode(O object)
    {
        return JSON.toJSONBytes(object);
    }

    /**
     *
     * @param <O> Object type
     * @param object Object
     * @return byte[]
     */
    public <O> byte[] prettyEncode(O object)
    {
        return JSON.toJSONString(object, true).getBytes();
    }
}


text:
layout: post
issue: 2017
category: feature
order: 3
title: Art in a climate revolution
subhead: "Environmental crises call for creative solutions"
author:
    name: Laura Poppick
    file: "2017/laura-poppick-2.jpg"
banner:
    file: 2017/p18-caribou-migration.jpg
    position: left
related:
    - title: "Arts Dean's Lecture Series to explore climate justice, art, activism, and the environment"
      url: http://news.ucsc.edu/2016/03/arts-dean-series.html

---
{% include_relative sidebars/2017-caribou-caption.html classes="right" bgcolor="#F5F5F5" %}
Evidence for sea level rise, drought, or collapsing ice sheets may come from scientific studies, but solutions to these problems could arise from another realm—the arts.

That premise inspired **T. J. Demos,** professor in the History of Art and Visual Culture Department, to found the Center for Creative Ecologies at UC Santa Cruz. "Art can transform values through sights and feelings in a way that an argument based solely on scientific information might not succeed," explained
Demos.

Weaving in ideas from politics, ethics, and other
fields, the center takes on tough environmental issues using visual art as a catalyst for change. "The climate change crisis doesn't exist in isolation,"
Demos said. "It is deeply connected to these other areas. We need a range of approaches to bring about meaningful and widespread cultural transition."

In a recent project entitled "Extraction," Demos partnered with UC Santa Cruz art professor **Laurie Palmer** to explore how developed countries and corporations extract resources—materials, energy, labor, and time—from both people and the environment. They drew inspiration from the struggle against injustices toward indigenous communities at Standing Rock Indian Reservation and elsewhere around
the world, said Palmer.

"The aim of the project is to not only look at how extraction is happening and criticize it, but also to imagine other ways to live in the world," she added.

Demos and Palmer encouraged community members to participate in "Extraction" events such as field trips to the Amah Mutsun Relearning Program at the UC Santa Cruz Arboretum and fracking sites in Monterey County; a two-day international conference put on, in part, with the Resource Center for Nonviolence in Santa Cruz; and  invited artist lectures.

Among these events, the  center hosted award-winning American photographer Subhankar Banerjee. His photographs of
caribou migrating across Alaska's Arctic National Wildlife Refuge circulated among the nation's policy makers and may have helped convince the Obama administration to forgo oil
drilling in this region, Palmer said.

This visual approach to environmental activism and emphasis on community involvement drew **Chessa Adsit-Morris,** author of Restorying Environmental Education,  to pursue her doctoral  degree with Demos. "The potential of the center is to draw together  scholars and activists and artists to productively talk about other ways of addressing  these issues," she said.

Demos hopes that community participation and graduate student involvement will increase as the center expands its efforts to re-imagine human relationships with the environment, saying: "We need a multiplicity of paths to carry that out."


text:
<?php

Route::group(array('before' => 'ff.qiwi.gate.auth.basic'), function () {

	Route::resource(
		'qiwi/gate/api/v2/prv/{provider_id}/bills',
		'FintechFab\QiwiGate\Controllers\RestBillController',
		array(
			'only' => array('show', 'update')
		)
	);

	Route::resource(
		'qiwi/gate/api/v2/prv/{provider_id}/bills/{bill_id}/refund',
		'FintechFab\QiwiGate\Controllers\RestRefundController',
		array(
			'only' => array('show', 'update')
		)
	);

});

Route::group(

	array(
		'before'    => 'ff.qiwi.gate.checkUser',
		'prefix'    => 'qiwi/gate',
		'namespace' => 'FintechFab\QiwiGate\Controllers'
	),

	function () {
		Route::get('order/external/main.action', array(
			'as'   => 'qiwi_gate_payIndex',
			'uses' => 'PayController@index'
		));

		Route::post('order/external/main.action', array(
			'as'   => 'qiwiGate_postPay',
			'uses' => 'PayController@postPay'
		));

		Route::get('account', array(
			'as'   => 'qiwiGate_account',
			'uses' => 'AccountController@index'
		));

		Route::post('account', array(
			'as'   => 'qiwiGate_postAccountReg',
			'uses' => 'AccountController@postRegistration'
		));

		Route::post('account/changeData', array(
			'as'   => 'qiwiGate_postChangeData',
			'uses' => 'AccountController@postChangeData'
		));

		Route::get('account/billsTable', array(
			'as'   => 'qiwiGate_billsTable',
			'uses' => 'AccountController@billsTable'
		));

		Route::get('account/billsTable/getRefund/{bill_id}', array(
			'as'   => 'qiwiGate_GetRefundTable',
			'uses' => 'AccountController@GetRefundTable'
		));

		Route::post('account/billsTable/expireBill', array(
			'as'   => 'qiwiGate_postExpireBill',
			'uses' => 'AccountController@postExpireBill'
		));

		Route::post('account/billsTable/cancelBill', array(
			'as'   => 'qiwiGate_postCancelBill',
			'uses' => 'AccountController@postCancelBill'
		));

		Route::get('authError', array(
			'as'   => 'qiwiGate_AuthError',
			'uses' => 'AccountController@authError',
		));

	}

);

Route::get('qiwi/gate/about', array(
	'as'   => 'qiwiGate_about',
	'uses' => 'FintechFab\QiwiGate\Controllers\AccountController@about',
));


text:
<?php

namespace Helthe\Bundle\CQRSBundle\Tests\DependencyInjection;

use Helthe\Bundle\CQRSBundle\DependencyInjection\HeltheCQRSExtension;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class HeltheCQRSExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $container = new ContainerBuilder();
        $loader = new HeltheCQRSExtension();
        $loader->load(array(), $container);

        // Command Bus
        $this->assertTrue($container->hasParameter('helthe_cqrs.command_bus.sequential.class'));
        $this->assertEquals('Helthe\Component\CQRS\Bus\SequentialCommandBus', $container->getParameter('helthe_cqrs.command_bus.sequential.class'));
        $this->assertTrue($container->hasDefinition('helthe_cqrs.command_bus.sequential'));

        $this->assertTrue($container->hasAlias('helthe_cqrs.command_bus'));
        $this->assertEquals(new Alias('helthe_cqrs.command_bus.sequential'), $container->getAlias('helthe_cqrs.command_bus'));

        // Command Handler Locator
        $this->assertTrue($container->hasParameter('helthe_cqrs.command_handler_locator.container_aware.class'));
        $this->assertEquals('Helthe\Bundle\CQRSBundle\CommandHandler\ContainerAwareCommandHandlerLocator', $container->getParameter('helthe_cqrs.command_handler_locator.container_aware.class'));
        $this->assertTrue($container->hasDefinition('helthe_cqrs.command_handler_locator.container_aware'));

        $this->assertTrue($container->hasAlias('helthe_cqrs.command_handler_locator'));
        $this->assertEquals(new Alias('helthe_cqrs.command_handler_locator.container_aware'), $container->getAlias('helthe_cqrs.command_handler_locator'));
    }
}


text:
package com.amazonaws.services.autoscaling.model;

import java.io.Serializable;

/**
 *
 */
public class DescribeTagsResult implements Serializable, Cloneable {

    /**
     *

     * The tags.
     *

     */
    private com.amazonaws.internal.SdkInternalList<TagDescription> tags;
    /**
     *

     * The token to use when requesting the next set of items. If there are no
     * additional items to return, the string is empty.
     *

     */
    private String nextToken;

    /**
     *

     * The tags.
     *

     *
     * @return The tags.
     */
    public java.util.List<TagDescription> getTags() {
        if (tags == null) {
            tags = new com.amazonaws.internal.SdkInternalList<TagDescription>();
        }
        return tags;
    }

    /**
     *

     * The tags.
     *

     *
     * @param tags
     *        The tags.
     */
    public void setTags(java.util.Collection<TagDescription> tags) {
        if (tags == null) {
            this.tags = null;
            return;
        }

        this.tags = new com.amazonaws.internal.SdkInternalList<TagDescription>(
                tags);
    }

    /**
     *

     * The tags.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setTags(java.util.Collection)} or
     * {@link #withTags(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param tags
     *        The tags.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeTagsResult withTags(TagDescription... tags) {
        if (this.tags == null) {
            setTags(new com.amazonaws.internal.SdkInternalList<TagDescription>(
                    tags.length));
        }
        for (TagDescription ele : tags) {
            this.tags.add(ele);
        }
        return this;
    }

    /**
     *

     * The tags.
     *

     *
     * @param tags
     *        The tags.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeTagsResult withTags(java.util.Collection<TagDescription> tags) {
        setTags(tags);
        return this;
    }

    /**
     *

     * The token to use when requesting the next set of items. If there are no
     * additional items to return, the string is empty.
     *

     *
     * @param nextToken
     *        The token to use when requesting the next set of items. If there
     *        are no additional items to return, the string is empty.
     */
    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The token to use when requesting the next set of items. If there are no
     * additional items to return, the string is empty.
     *

     *
     * @return The token to use when requesting the next set of items. If there
     *         are no additional items to return, the string is empty.
     */
    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The token to use when requesting the next set of items. If there are no
     * additional items to return, the string is empty.
     *

     *
     * @param nextToken
     *        The token to use when requesting the next set of items. If there
     *        are no additional items to return, the string is empty.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeTagsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTags() != null)
            sb.append("Tags: " + getTags() + ",");
        if (getNextToken() != null)
            sb.append("NextToken: " + getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeTagsResult == false)
            return false;
        DescribeTagsResult other = (DescribeTagsResult) obj;
        if (other.getTags() == null ^ this.getTags() == null)
            return false;
        if (other.getTags() != null
                && other.getTags().equals(this.getTags()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null
                && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getTags() == null) ? 0 : getTags().hashCode());
        hashCode = prime * hashCode
                + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeTagsResult clone() {
        try {
            return (DescribeTagsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
import Router, { withRouter, WithRouterProps } from "next/router";
import * as React from "react";
import * as qs from "querystring";

Router.readyCallbacks.push(() => {
    console.log("I'll get called when the router initializes.");
});
Router.ready(() => {
    console.log(
        "I'll get called immediately if the router initializes, or when it eventually does.",
    );
});

// Access readonly properties of the router.

Object.keys(Router.components).forEach(key => {
    const c = Router.components[key];
    c.err.isAnAny;

    return <c.Component />;
});

function split(routeLike: string) {
    routeLike.split("/").forEach(part => {
        console.log("path part: ", part);
    });
}

if (Router.asPath) {
    split(Router.asPath);
    split(Router.asPath);
}

split(Router.pathname);

const query = `?${qs.stringify(Router.query)}`;

// Assign some callback methods.
Router.events.on('routeChangeStart', (url: string) => console.log("Route is starting to change.", url));
Router.events.on('beforeHistoryChange', (as: string) => console.log("History hasn't changed yet.", as));
Router.events.on('routeChangeComplete', (url: string) => console.log("Route change is complete.", url));
Router.events.on('routeChangeError', (err: any, url: string) => console.log("Route change errored.", err, url));

// Call methods on the router itself.
Router.reload("/route").then(() => console.log("route was reloaded"));
Router.back();
Router.beforePopState(({ url }) => !!url);

Router.push("/route").then((success: boolean) =>
    console.log("route push success: ", success),
);
Router.push("/route", "/asRoute").then((success: boolean) =>
    console.log("route push success: ", success),
);
Router.push("/route", "/asRoute", { shallow: false }).then((success: boolean) =>
    console.log("route push success: ", success),
);

Router.replace("/route").then((success: boolean) =>
    console.log("route replace success: ", success),
);
Router.replace("/route", "/asRoute").then((success: boolean) =>
    console.log("route replace success: ", success),
);
Router.replace("/route", "/asRoute", {
    shallow: false,
}).then((success: boolean) => console.log("route replace success: ", success));

Router.prefetch("/route").then(Component => {
    const element = <Component />;
});

interface TestComponentProps {
    testValue: string;
}

class TestComponent extends React.Component<TestComponentProps & WithRouterProps> {
    state = { ready: false };

    constructor(props: TestComponentProps & WithRouterProps) {
        super(props);
        props.router.ready(() => {
            this.setState({ ready: true });
        });
    }

    render() {
        return (

{this.state.ready ? 'Ready' : 'Not Ready'}

Route: {this.props.router.route}

Another prop: {this.props.testValue}

        );
    }
}

withRouter(TestComponent);

interface TestSFCQuery {
    test?: string;
}

interface TestSFCProps extends WithRouterProps<TestSFCQuery> { }

const TestSFC: React.SFC<TestSFCProps> = ({ router }) => {
    return
{router.query && router.query.test}
;
};


text:
package me.seeber.gradle.project.base;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.jdt.annotation.NonNull;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.SelfResolvingDependency;
import org.gradle.api.artifacts.dsl.ArtifactHandler;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.internal.ConventionMapping;
import org.gradle.api.internal.DomainObjectContext;
import org.gradle.api.internal.project.ProjectIdentifier;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.tasks.Copy;
import org.gradle.api.tasks.wrapper.Wrapper;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.model.Defaults;
import org.gradle.model.Each;
import org.gradle.model.Finalize;
import org.gradle.model.Model;
import org.gradle.model.ModelMap;
import org.gradle.model.Mutate;
import org.gradle.model.RuleSource;
import org.gradle.model.internal.core.Hidden;
import org.gradle.util.GradleVersion;

import com.dorongold.gradle.tasktree.TaskTreePlugin;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;

import me.seeber.gradle.plugin.AbstractProjectConfigPlugin;
import me.seeber.gradle.util.Validate;

/**
 * Plugin that applies general project configuration
 */
public class ProjectConfigPlugin extends AbstractProjectConfigPlugin {

    /**
     * Required Gradle version used for version checks
     */
    protected static final GradleVersion REQUIRED_GRADLE_VERSION = Validate.notNull(GradleVersion.version("3.4"));

    /**
     * Plugin rules
     */
    public static class PluginRules extends RuleSource {

        /**
         * Logger if we feel talkative...
         */
        private static final Logger LOGGER = Logging.getLogger(ProjectConfigPlugin.class);

        /**
         * Provide the project configuration
         *
         * @param projectConfig Project configuration
         */
        @Model
        public void projectConfig(ProjectConfig projectConfig) {
        }

        /**
         * Initialize the project configuration
         *
         * @param projectConfig Project configuration
         */
        @Defaults
        public void initializeProjectConfig(ProjectConfig projectConfig) {
            License license = projectConfig.getLicense();

            license.setExcludes(new ArrayList<>());

            VersionControl versionControl = projectConfig.getVersionControl();

            versionControl.ignore("*~");
            versionControl.ignore("/.classpath");
            versionControl.ignore("/.gradle");
            versionControl.ignore("/.project");
            versionControl.ignore("/.settings");
            versionControl.ignore("/bin/");
            versionControl.ignore("/build/");
            versionControl.ignore("/target/");
            versionControl.ignore("#*#");
        }

        /**
         * Finalize the project configuration
         *
         *

         *
Initialize the license URLs if not set
         *

         *
         * @param projectConfig Project configuration to finalize
         */
        @Finalize
        public void finalizeProjectConfig(ProjectConfig projectConfig) {
            License license = projectConfig.getLicense();
            String licenseId = license.getId();

            if (licenseId != null) {
                if (license.getUrl() == null) {
                    license.setUrl("https://opensource.org/licenses/" + licenseId.replace(' ', '-'));
                }

                if (license.getSourceUrl() == null) {
                    license.setSourceUrl(
                            "https://raw.githubusercontent.com/github/choosealicense.com/gh-pages/_licenses/"
                                    + licenseId.toLowerCase().replace(' ', '-') + ".txt");
                }
            }
        }

        /**
         * Validate the project configuration
         *
         * @param projectConfig Project configuration to validate
         */
        @org.gradle.model.Validate
        public void validateProjectConfig(ProjectConfig projectConfig) {
            if (!Strings.isNullOrEmpty(projectConfig.getGradleVersion())) {
                if (GradleVersion.current().compareTo(GradleVersion.version(projectConfig.getGradleVersion())) < 0) {
                    throw new IllegalArgumentException(
                            "This project requires at least Gradle " + projectConfig.getGradleVersion());
                }
            }

            Organization organization = projectConfig.getOrganization();

            if (projectConfig.getInceptionYear() == null) {
                LOGGER.warn("Please configure projectConfig.inceptionYear");
            }

            if (projectConfig.getWebsiteUrl() == null) {
                LOGGER.warn("Please configure projectConfig.websiteUrl");
            }

            if (organization.getName() == null) {
                LOGGER.warn("Please configure projectConfig.organization.name");
            }

            if (organization.getWebsiteUrl() == null) {
                LOGGER.warn("Please configure projectConfig.organization.websiteUrl");
            }

            me.seeber.gradle.project.base.License license = projectConfig.getLicense();

            if (license.getId() == null) {
                LOGGER.warn("Please configure projectConfig.license.id");
            }

            if (license.getUrl() == null) {
                LOGGER.warn("Please configure projectConfig.license.url");
            }

            if (license.getSourceUrl() == null) {
                LOGGER.warn("Please configure projectConfig.license.sourceUrl");
            }

            Repository repository = projectConfig.getRepository();

            if (repository.getName() == null) {
                LOGGER.warn("Please configure projectConfig.repository.name");
            }

            if (repository.getType() == null) {
                LOGGER.warn("Please configure projectConfig.repository.type");
            }

            if (repository.getWebsiteUrl() == null) {
                LOGGER.warn("Please configure projectConfig.repository.websiteUrl");
            }

            if (repository.getConnection() == null) {
                LOGGER.warn("Please configure projectConfig.repository.connection");
            }

            if (repository.getDeveloperConnection() == null) {
                LOGGER.warn("Please configure projectConfig.repository.developerConnection");
            }

            IssueTracker tracker = projectConfig.getIssueTracker();

            if (tracker.getId() == null) {
                LOGGER.warn("Please configure projectConfig.tracker.id");
            }

            if (tracker.getWebsiteUrl() == null) {
                LOGGER.warn("Please configure projectConfig.tracker.websiteUrl");
            }
        }

        /**
         * Provide the project as model
         *
         * @param services Service registry to look up services
         * @return Current project
         */
        @Model
        @Hidden
        public Project project(ServiceRegistry services) {
            Project project = (Project) services.get(DomainObjectContext.class);
            return project;
        }

        /**
         * Provide the artifact handler as model
         *
         * @param services Service registry to look up services
         * @return Artifact handler
         */
        @Model
        @Hidden
        public ArtifactHandler artifactHandler(ServiceRegistry services) {
            return services.get(ArtifactHandler.class);
        }

        /**
         * Provide the configurations as model
         *
         * @param services Service registry to look up services
         * @return Configurations
         */
        @Model
        @Hidden
        public ConfigurationContainer configurations(ServiceRegistry services) {
            return services.get(ConfigurationContainer.class);
        }

        /**
         * Provide the project context
         *
         * @param extensions Extension container to look up the context
         * @return Project context
         */
        @Model
        public ProjectContext projectContext(ExtensionContainer extensions) {
            return extensions.getByType(ProjectContext.class);
        }

        /**
         * Create task to update readme file from template
         *
         * @param tasks Task container to create new tasks
         * @param projectConfig Project configuration
         * @param projectContext Project context
         * @param extensions Extension container
         */
        @Mutate
        public void createReadmeUpdateTasks(ModelMap<Task> tasks, ProjectConfig projectConfig,
                ProjectContext projectContext, ExtensionContainer extensions) {
            // Create task to update the README
            Map<String, Object> context = new HashMap<>();

            extensions.getExtraProperties().getProperties().forEach((name, value) -> {
                context.put(name, value);
            });

            context.put("project", projectContext);
            context.put("projectConfig", projectConfig);

            tasks.create("readmeUpdate", Copy.class, t -> {
                t.setDescription("Update README from template.");
                t.setGroup("documentation");
                t.from("src/doc/templates");
                t.include("README.template.md");
                t.rename(n -> n.replace(".template.", "."));
                t.expand(context);

                ConventionMapping parameters = t.getConventionMapping();
                parameters.map("destinationDir", () -> projectContext.getProjectDir());
            });

            tasks.named("assemble", t -> {
                t.dependsOn("readmeUpdate");
            });
        }

        /**
         * Configure the wrapper task
         *
         * @param wrapper Wrapper task to configure
         * @param projectConfig Project configuration to get required Gradle version
         */
        @Defaults
        public void configureWrapperTask(@Each Wrapper wrapper, ProjectConfig projectConfig) {
            if (!Strings.isNullOrEmpty(projectConfig.getGradleVersion())) {
                wrapper.setGradleVersion(projectConfig.getGradleVersion());
            }
        }

        /**
         * Create debug tasks
         *
         * @param tasks Task container to create new tasks
         * @param config Project configuration
         * @param project Current project identifier
         */
        @Mutate
        public void createDebugTasks(ModelMap<Task> tasks, ProjectConfig config, ProjectIdentifier project) {
            // Create debug task to dump dependencies
            if (config.isEnableDebugTasks()) {
                tasks.create("debugDependencies", Task.class, tt -> {
                    tt.doLast(t -> {
                        PrintStream out = System.out;
                        out.print("Project: ");
                        out.println(project.getName());

                        for (Configuration configuration : t.getProject().getConfigurations()) {
                            out.print("  Configuration: ");
                            out.println(configuration.getName());

                            for (Dependency dependency : configuration.getDependencies()) {
                                out.print("    Dependency: ");
                                out.println(formatDependency(dependency));
                            }
                        }
                    });
                });
            }
        }

        /**
         * Create task to configure project
         *
         * @param tasks Task container to create task
         */
        @Mutate
        public void createConfigureTask(ModelMap<Task> tasks) {
            tasks.create("configure", Task.class, t -> {
                t.setDescription("Configure project environment");
                t.setGroup("build setup");
            });
        }

        /**
         * Format a dependency for printing
         *
         * @param dependency Dependency to format
         * @return Dependency information for printing
         */
        private String formatDependency(Dependency dependency) {
            @NonNull String info;

            if (dependency instanceof SelfResolvingDependency) {
                SelfResolvingDependency selfResolvingDependency = (SelfResolvingDependency) dependency;
                info = Validate.notNull(Joiner.on(", ").join(selfResolvingDependency.resolve()));
            }
            else {
                info = dependency.getGroup() + ":" + dependency.getName() + ":" + dependency.getVersion();
            }

            return info;
        }
    }

    /**
     * @see me.seeber.gradle.plugin.AbstractProjectConfigPlugin#initialize()
     */
    @Override
    protected void initialize() {
        checkGradleVersion();

        getProject().getPlugins().apply(TaskTreePlugin.class);

        ProjectContext context = new ProjectContext(getProject());
        getProject().getExtensions().add("projectContext", context);

        RepositoryHandler repositories = getProject().getRepositories();
        repositories.add(repositories.mavenLocal());
        repositories.add(repositories.mavenCentral());
        repositories.add(repositories.maven(r -> r.setUrl("https://plugins.gradle.org/m2")));
        repositories.add(repositories.jcenter());

        getProject().getConfigurations().all(c -> {
            c.resolutionStrategy(s -> {
                s.preferProjectModules();
                s.cacheChangingModulesFor(0, "seconds");
            });
        });
    }

    /**
     * Check the Gradle version
     *
     * @throws GradleException if the Gradle version is smaller than the required version
     */
    protected void checkGradleVersion() {
        if (GradleVersion.current().compareTo(REQUIRED_GRADLE_VERSION) < 0) {
            throw new GradleException("Project config plugin requires at least Gradle " + REQUIRED_GRADLE_VERSION);
        }
    }
}


text:
<?php

/**
 * The request line of an HTTP request.
 * @see http://tools.ietf.org/html/rfc2616#section-5.1
 */
class Bringit_Header_RequestLine
{
	private
		$_requestMethod,
		$_requestUri,
		$_httpVersion;

	/**
	 * @param string $requestMethod
	 * @param string $requestUri
	 * @param string $httpVersion
	 */
	public function __construct($requestMethod, $requestUri, $httpVersion)
	{
		$this->_requestMethod = $requestMethod;
		$this->_requestUri = $requestUri;
		$this->_httpVersion = $httpVersion;
	}

	/**
	 * @return string
	 */
	public function reqestMethod()
	{
		return $this->_requestMethod;
	}

	/**
	 * @return string
	 */
	public function reqestUri()
	{
		return $this->_requestUri;
	}

	/**
	 * @return string
	 */
	public function httpVersion()
	{
		return $this->_httpVersion;
	}

	/**
	 * @return string
	 */
	public function __toString()
	{
		return sprintf("%s %s HTTP/%s\r\n",
			$this->reqestMethod(),
			$this->reqestUri(),
			$this->httpVersion()
		);
	}

	/**
	 * @param string $statusLine
	 * @return Bringit_Header_RequestLine
	 */
	public static function fromString($requestLine)
	{
		$regex = '#^([A-Z]+)\s+(\S+) HTTP/(\d+\.\d+)[\r\n]{0,2}$#';

		if (!preg_match($regex, $requestLine, $matches))
			throw new Bringit_Exception("Malformed request line: '$requestLine'");

		list(, $requestMethod, $requestUrl, $httpVersion) = $matches;
		return new self($requestMethod, $requestUrl, $httpVersion);
	}
}


text:
#include <mitsuba/core/rfilter.h>

MTS_NAMESPACE_BEGIN

/**
 * Box filter: this is the fastest, but also about the worst possible
 * reconstruction filter, since it is extremely prone to aliasing.
 *
 * It is included mainly for completeness, though some rare situations
 * may warrant its use.
 */
class BoxFilter : public ReconstructionFilter {
public:
	BoxFilter(const Properties &props)
		: ReconstructionFilter(props) {
		/* Filter radius in pixels. A tiny epsilon is added, since some
		   samplers (Hammersley and Halton in particular) place samples
		   at positions like (0, 0). Without such an epsilon and rounding
		   errors, samples may end up not contributing to any pixel. */
		m_radius = props.getFloat("radius", 0.5f) + 1e-5f;
	}

	BoxFilter(Stream *stream, InstanceManager *manager)
		: ReconstructionFilter(stream, manager) {
		configure();
	}

	Float eval(Float x) const {
		return std::abs(x) <= m_radius ? 1.0f : 0.0f;
	}

	std::string toString() const {
		return formatString("GaussianFilter[radius=%f]", m_radius);
	}

	MTS_DECLARE_CLASS()
};

MTS_IMPLEMENT_CLASS_S(BoxFilter, false, ReconstructionFilter);
MTS_EXPORT_PLUGIN(BoxFilter, "Box filter");
MTS_NAMESPACE_END


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

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Token (Spring Security 2.0.4 API)
</TITLE>

<META NAME="keywords" CONTENT="org.springframework.security.token.Token interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Spring Security Framework

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.springframework.security.token

Interface Token

All Known Implementing Classes:
DefaultToken

public interface Token

A token issued by TokenService.

 It is important that the keys assigned to tokens are sufficiently randomised and secured that
 they can serve as identifying a unique user session. Implementations of TokenService
 are free to use encryption or encoding strategies of their choice. It is strongly recommended that
 keys are of sufficient length to balance safety against persistence cost. In relation to persistence
 cost, it is strongly recommended that returned keys are small enough for encoding in a cookie.

Since:

2.0.1

Author:

Ben Alex

Method Summary

 String
getExtendedInformation()

          Obtains the extended information associated within the token, which was presented when the token
 was first created.

 String
getKey()

          Obtains the randomised, secure key assigned to this token.

 long
getKeyCreationTime()

          The time the token key was initially created is available from this method.

Method Detail

getKey

String getKey()

Obtains the randomised, secure key assigned to this token. Presentation of this token to
 TokenService will always return a Token that is equal to the original
 Token issued for that key.

Returns:
a key with appropriate randomness and security.

getKeyCreationTime

long getKeyCreationTime()

The time the token key was initially created is available from this method. Note that a given
 token must never have this creation time changed. If necessary, a new token can be
 requested from the TokenService to replace the original token.

Returns:
the time this token key was created, in the same format as specified by {@link Date#getTime()).

getExtendedInformation

String getExtendedInformation()

Obtains the extended information associated within the token, which was presented when the token
 was first created.

Returns:
the user-specified extended information, if any

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Spring Security Framework

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2004-2008 SpringSource, Inc. All Rights Reserved.


text:
define([],function(){

		function MenuItem(title,action,type){
			this.title  = title;
			this.action = action;
			this.type   = type;
		}

		return MenuItem;
});


text:
@interface PodsDummy_Pods_LYSimple_Tests : NSObject
@end
@implementation PodsDummy_Pods_LYSimple_Tests
@end


text:
import hashlib
import json
import functools
import logging

from django.conf import settings
from django.core.cache import caches
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Count
from django.http import HttpResponseBadRequest, HttpResponseNotAllowed

from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic import TemplateView

from braces.views import JSONResponseMixin
from django_filters.views import FilterView

from rfdocs.filter_sets import (RFLibraryFilter, RFKeywordFilter, RFTagFilter,
                                RFLibraryVersionFilter)
from rfdocs.models import (RFLibrary, RFKeyword, RFLibraryVersion, RFTag)
from rfdocs.templatetags.rfdocs_tags import generate_node_key

PAGINATE_BY = settings.RFDOCS.get('PAGINATE_BY', 25)

logger = logging.getLogger(name=__name__)

def select_template(template_ajax, template_not_ajax):
    """
    Sets template name based on type of the request.

    Can be used as a decorator of `get_template_names` method of a generic class-based views.
    """
    def wrapper(func):
        @functools.wraps(func)
        def worker(self):
            if self.request.is_ajax():
                self.template_name = template_ajax
            else:
                self.template_name = template_not_ajax
            return func(self)
        return worker
    return wrapper

class ErrorHandler(TemplateView):
    @classmethod
    def raiseError(cls):
        v = cls.as_view()

        def view(request):
            r = v(request)
            if isinstance(r, HttpResponseNotAllowed):
                json_context = json.dumps(
                    {u"errors": [u"Improperly formatted request", ]},
                    cls=DjangoJSONEncoder,
                )
                return HttpResponseNotAllowed(['GET', 'POST', ], json_context)
            r.render()
            return r
        return view

class NotFound404(ErrorHandler):
    @select_template('404ajax.html', '404.html')
    def get_template_names(self):
        return [self.template_name, ]

class ApplicationError500(ErrorHandler):
    @select_template('500ajax.html', '500.html')
    def get_template_names(self):
        return [self.template_name, ]

class HomeView(TemplateView):
    template_name = 'rfdocs/base/base.html'

class BrowseView(TemplateView):
    template_name = 'rfdocs/base/browse.html'

class HandleBadRequestJSONResponseMixin(JSONResponseMixin):
    error_response_dict = {u"errors": [u"Improperly formatted request", ]}
    http_resp_class = HttpResponseBadRequest

    def render_bad_request_response(self, error_dict=None):
        if error_dict is None:
            error_dict = self.error_response_dict
        json_context = json.dumps(
            error_dict,
            cls=DjangoJSONEncoder,
            **self.get_json_dumps_kwargs()
        )
        return self.http_resp_class(json_context, content_type=self.get_content_type())

class LoadLibrariesView(HandleBadRequestJSONResponseMixin, ListView):
    model = RFLibrary
    context_object_name = 'libraries_list'
    content_type = 'application/json'

    _cache_key_prefix = 'data_set'
    _cache_time = 604800  # 1 week

    def get_request_json_params(self):
        if not self.request.method == 'GET':
            self.error_response_dict = {u"errors": [u"Method not allowed", ]}
            self.http_resp_class = HttpResponseNotAllowed
            return None
        try:
            return self.request.GET.getlist('library')
        except ValueError:
            return None

    @staticmethod
    def _update_context(context):
        libraries = []
        for l in context['libraries_list']:
            library = {
                'children': [],
                'href': l.get_absolute_url(),
                'iconClass': 'icon-folder-close',
                'isVersion': True,
                'isFolder': True,
                'key': generate_node_key(l.name),
                'title': l.name,
                'tooltip': unicode(l),
            }
            for v in l.versions.not_draft():
                tags = v.tags_as_list
                version = {
                    'children': [],
                    'href': v.get_absolute_url(),
                    'hideCheckbox': True,
                    'iconClass': 'icon-folder-close-alt',
                    'isFolder': True,
                    'isLibrary': True,
                    'key': generate_node_key(l.name, v.name),
                    'status': v.status,
                    'tags': tags,
                    'title': v.name,
                    'tooltip': unicode(v),
                }
                for k in v.keywords.all():
                    keyword = {
                        'api_href': k.get_api_url(),
                        'href': k.get_absolute_url(),
                        'hideCheckbox': True,
                        'iconClass': 'icon-key',
                        'title': k.name,
                        'key': generate_node_key(l.name, v.name, k.name),
                        'tooltip': unicode(k),
                    }
                    version['children'].append(keyword)
                library['children'].append(version)
            libraries.append(library)
        return libraries

    def _build_cache_key(self):
        try:
            key = ':'.join([v for v in self.request_json_params])
            return '%s:%s:%s' % (self._cache_key_prefix, hashlib.md5(key).hexdigest(),
                                 len(self.request_json_params))
        except Exception as err:
            logger.exception(err)
            return '%s:%s' % (self._cache_key_prefix, hashlib.md5('').hexdigest())

    def dispatch(self, request, *args, **kwargs):
        self.request_json_params = self.get_request_json_params()
        if self.request_json_params is None:
            return self.render_bad_request_response()
        return super(LoadLibrariesView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(LoadLibrariesView, self).get_context_data(**kwargs)
        cached_key = self._build_cache_key()
        dataset_cache = caches['dataset']
        cached_context = dataset_cache.get(cached_key)
        if cached_context:
            return cached_context
        objects = RFLibrary.objects.all()
        if self.request_json_params:
            context['libraries_list'] = objects.filter(name__in=self.request_json_params). \
                prefetch_related('versions__keywords', 'versions__tags')
            updated_context = self._update_context(context)
            dataset_cache.set(cached_key, updated_context, self._cache_time)
            return updated_context
        context['libraries_list'] = objects.prefetch_related('versions__keywords',
                                                             'versions__tags')
        updated_context = self._update_context(context)
        dataset_cache.set(cached_key, updated_context, self._cache_time)
        return updated_context

    def render_to_response(self, context, **response_kwargs):
        return self.render_json_response(context, **response_kwargs)

class RFLibraryDetailView(DetailView):
    queryset = RFLibrary.objects.prefetch_related('versions')

    @select_template('rfdocs/library/detail/ajax.html', 'rfdocs/library/detail/detail.html')
    def get_template_names(self):
        return [self.template_name, ]

    def get_context_data(self, **kwargs):
        context = super(RFLibraryDetailView, self).get_context_data(**kwargs)
        qs = self.queryset.filter(slug=context['rflibrary'].slug)
        context.update(qs.aggregate(number_of_keywords=Count('versions__keywords')))
        context.update(qs.aggregate(number_of_versions=Count('versions')))
        return context

class RFLibraryListViewFilter(FilterView):
    context_object_name = 'libraries_list'
    filterset_class = RFLibraryFilter
    paginate_by = PAGINATE_BY

    @select_template('rfdocs/library/list/ajax.html', 'rfdocs/library/list/filter.html', )
    def get_template_names(self):
        return [self.template_name, ]

class RFLibraryVersionDetailView(DetailView):
    queryset = RFLibraryVersion.objects.not_draft()

    @select_template('rfdocs/version/detail/ajax.html', 'rfdocs/version/detail/detail.html')
    def get_template_names(self):
        return [self.template_name, ]

    def get_queryset(self):
        return self.queryset.select_related('library').prefetch_related('keywords', 'tags').\
            filter(library__slug=self.kwargs['library_slug'])

class RFLibraryVersionListViewFilter(FilterView):
    context_object_name = 'versions_list'
    filterset_class = RFLibraryVersionFilter
    paginate_by = PAGINATE_BY

    @select_template('rfdocs/version/list/ajax.html', 'rfdocs/version/list/filter.html', )
    def get_template_names(self):
        return [self.template_name, ]

class RFKeywordDetailView(DetailView):
    slug_field = 'name'
    queryset = RFKeyword.objects.select_related('version')

    @select_template('rfdocs/keyword/detail/ajax.html', 'rfdocs/keyword/detail/detail.html')
    def get_template_names(self):
        return [self.template_name, ]

    def get_queryset(self):
        return self.queryset.filter(
            version__library__slug=self.kwargs['library_slug'],
            version__slug=self.kwargs['version_slug']
        )

class RFKeywordListViewFilter(FilterView):
    context_object_name = 'keywords_list'
    filterset_class = RFKeywordFilter
    paginate_by = PAGINATE_BY

    @select_template('rfdocs/keyword/list/ajax.html', 'rfdocs/keyword/list/filter.html', )
    def get_template_names(self):
        return [self.template_name, ]

class RFTagDetailView(DetailView):
    model = RFTag

    @select_template('rfdocs/tag/detail/ajax.html', 'rfdocs/tag/detail/detail.html')
    def get_template_names(self):
        return [self.template_name, ]

class RFTagListViewFilter(FilterView):
    context_object_name = 'tags_list'
    filterset_class = RFTagFilter
    paginate_by = PAGINATE_BY

    @select_template('rfdocs/tag/list/ajax.html', 'rfdocs/tag/list/filter.html', )
    def get_template_names(self):
        return [self.template_name, ]


text:
layout: post
status: publish
published: true
title: Sails.JS Part 1
author:
  display_name: Ian Littman
  login: Ian
  email: iansltx@gmail.com
  url: ''
author_login: Ian
author_email: iansltx@gmail.com
excerpt: ! "http://www.youtube.com/watch?v=PUQFnXbnJgU\r\n"
wordpress_id: 606
wordpress_url: http://www.austintechvideos.com/?p=606
date: !binary |-
  MjAxMy0wNS0wOCAyMDoyNDo0MiAtMDUwMA==
date_gmt: !binary |-
  MjAxMy0wNS0wOCAyMDoyNDo0MiAtMDUwMA==
categories:
- Sails.JS
tags:
- js
- sailsjs
comments: []
videoid: PUQFnXbnJgU
---

Mike McNeil, creator of Sails.JS, gives an introduction to the Sails.JS framework.

4.2.2013 (meetup)


text:
<?php

/* File: ./custom/Extension/application/Ext/Language/en_us.lang.cal.ext.php */

$app_strings['LBL_CAL_DASHLET'] = 'My Graphical Calendar';
$app_strings['LBL_CAL_DASHLET_DESC'] = 'Graphical calendar dashlet for current user';

?>


text:
<?php namespace Pantono\Products\Entity;

use Doctrine\ORM\Mapping as ORM;
use Pantono\Database\Entity\EntityAbstract;

/**
 * Class SearchItem
 *
 * @package Pantono\Products\Entity
 * @ORM\Entity
 * @ORM\Table(name="product_search_item")
 */
class SearchItem extends EntityAbstract
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;
    /**
     * @ORM\ManyToOne(targetEntity="Pantono\Products\Entity\Search")
     */
    protected $search;
    /**
     * @ORM\Column(type="string")
     */
    protected $brands;
    /**
     * @ORM\Column(type="string")
     */
    protected $sku;
    /**
     * @var int
     * @ORM\Column(type="integer")
     */
    protected $minPrice = 0;
    /**
     * @var int
     * @ORM\Column(type="integer")
     */
    protected $maxPrice = 0;
    /**
     * @ORM\Column(type="string")
     */
    protected $categories;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aspergillus terrestris var. terrestris

### Remarks
null


text:
@interface SortController ()
@property (nonatomic, strong, nullable)SortModel *model; //
@end

@implementation SortController

#pragma mark - --- lift cycle 生命周期 ---

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"%s, %@", __FUNCTION__, self.model.state);
}

#pragma mark - --- delegate 视图委托 ---

#pragma mark - --- event response 事件相应 ---

#pragma mark - --- private methods 私有方法 ---

#pragma mark - --- getters and setters 属性 ---

- (SortModel *)model
{
    if (!_model) {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"Sort" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:nil];
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _model = [SortModel mj_objectWithKeyValues:dictionary];
    }
    return _model;
}

@end


text:
/*
 * Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you import will output into a single css file (app.css in this case)
import './styles/frontend.scss';

// start the Stimulus application
import './bootstrap_frontend';


text: """Module loader file for /ciscripts/deploy/conan."""


text:
<?php

namespace ConnectHolland\OpenAPISpecificationGenerator\Schema;

/**
 * ObjectElement.
 *
 * @author Niels Nijens <niels@connectholland.nl>
 */
class ObjectElement extends AbstractElement
{
    /**
     * The minimum amount of properties.
     *
     * @var int
     */
    private $minProperties;

    /**
     * The maximum amount of properties.
     *
     * @var int
     */
    private $maxProperties;

    /**
     * The array with properties on the object element.
     *
     * @var array
     */
    private $properties = array();

    /**
     * The boolean indicating if additional properties are allowed.
     *
     * @var bool
     */
    private $additionalProperties;

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'object';
    }

    /**
     * Sets the minimum amount of properties.
     *
     * @param int $minProperties
     *
     * @return ObjectElement
     */
    public function setMinProperties($minProperties)
    {
        $this->minProperties = $minProperties;

        return $this;
    }

    /**
     * Sets the maximum amount of properties.
     *
     * @param int $maxProperties
     *
     * @return ObjectElement
     */
    public function setMaxProperties($maxProperties)
    {
        $this->maxProperties = $maxProperties;

        return $this;
    }

    /**
     * Sets the boolean indicating if additional properties are allowed.
     *
     * @param bool $additionalProperties
     *
     * @return ObjectElement
     */
    public function setAdditionalProperties($additionalProperties)
    {
        $this->additionalProperties = $additionalProperties;

        return $this;
    }

    /**
     * Adds a property to the object element.
     *
     * @param string                 $name
     * @param SchemaElementInterface $property
     *
     * @return ObjectElement
     */
    public function addProperty($name, SchemaElementInterface $property)
    {
        $this->properties[$name] = $property;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function jsonSerialize()
    {
        $element = parent::jsonSerialize();
        if (isset($this->minProperties)) {
            $element['minProperties'] = $this->minProperties;
        }
        if (isset($this->maxProperties)) {
            $element['maxProperties'] = $this->maxProperties;
        }

        $requiredProperties = array();
        if (empty($this->properties) === false) {
            $element['properties'] = array();
            foreach ($this->properties as $name => $property) {
                $element['properties'][$name] = $property->jsonSerialize();

                if ($property->isRequired()) {
                    $requiredProperties[] = $name;
                }
            }
        }

        if (empty($requiredProperties) === false) {
            $element['required'] = $requiredProperties;
        }
        if (isset($this->additionalProperties)) {
            $element['additionalProperties'] = $this->additionalProperties;
        }

        return $element;
    }

    /**
     * Returns a new ObjectElement instance.
     *
     * @return ObjectElement
     */
    public static function create()
    {
        return new self();
    }
}


text:
namespace Problem_03.Animal_hierarchy.Enumerations
{
    using System;

    public enum Gender
    {
        Male,
        Female
    }
}


text:
import './main';
import './tables';
import './forms';
import './epiOrganSite';
import './forestPlot';


text:
var req = require('request'),
	vows = require('vows'),
	assert = require('assert');

vows.describe('something').addBatch({
	'Some context': {
		topic: function () {
			return true;
		},
		'is true': function  (topic) {
			assert.equal(topic, true);
		}
	},
	teardown: function () {
		console.log('well, we\'ve called the teardown...');
		req('https://www.google.com', function (err, resp, body) {
			if (err) {throw err;}
			console.log(resp.statusCode);
		});
	}
}).export(module);


text:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using P01_BillsPaymentSystem.Data.Models;

namespace P01_BillsPaymentSystem.Data.EntityConfig
{
    public class BankAccountConfiguration : IEntityTypeConfiguration<BankAccount>
    {
        public void Configure(EntityTypeBuilder<BankAccount> builder)
        {
            builder.HasKey(e => e.BankAccountId);

            builder.Property(e => e.Balance)
                .IsRequired();

            builder.Property(e => e.BankName)
                .IsRequired()
                .IsUnicode()
                .HasMaxLength(50);

            builder.Property(e => e.SwiftCode)
                .IsRequired()
                .IsUnicode(false)
                .HasMaxLength(20);
        }
    }
}


text:
import multiprocessing
from time import sleep

from rtgraph.core.constants import Constants
from rtgraph.common.logger import Logger as Log

TAG = "Parser"

class ParserProcess(multiprocessing.Process):
    """
    Process to parse incoming data, parse it, and then distribute it to graph and storage.
    """
    def __init__(self, data_queue, store_reference=None,
                 split=Constants.csv_delimiter,
                 consumer_timeout=Constants.parser_timeout_ms):
        """

        :param data_queue: Reference to Queue where processed data will be put.
        :type data_queue: multiprocessing Queue.
        :param store_reference: Reference to CSVProcess instance, if needed.
        :type store_reference: CSVProcess (multiprocessing.Process)
        :param split: Delimiter in incoming data.
        :type split: str.
        :param consumer_timeout: Time to wait after emptying the internal buffer before next parsing.
        :type consumer_timeout: float.
        """
        multiprocessing.Process.__init__(self)
        self._exit = multiprocessing.Event()
        self._in_queue = multiprocessing.Queue()
        self._out_queue = data_queue
        self._consumer_timeout = consumer_timeout
        self._split = split
        self._store_reference = store_reference
        Log.d(TAG, "Process ready")

    def add(self, txt):
        """
        Adds new raw data to internal buffer.
        :param txt: Raw data comming from acquisition process.
        :type txt: basestring.
        :return:
        """
        self._in_queue.put(txt)

    def run(self):
        """
        Process will monitor the internal buffer to parse raw data and distribute to graph and storage, if needed.
        The process will loop again after timeout if more data is available.
        :return:
        """
        Log.d(TAG, "Process starting...")
        while not self._exit.is_set():
            self._consume_queue()
            sleep(self._consumer_timeout)
        # last check on the queue to completely remove data.
        self._consume_queue()
        Log.d(TAG, "Process finished")

    def stop(self):
        """
        Signals the process to stop parsing data.
        :return:
        """
        Log.d(TAG, "Process finishing...")
        self._exit.set()

    def _consume_queue(self):
        """
        Consumer method for the queues/process.
        Used in run method to recall after a stop is requested, to ensure queue is emptied.
        :return:
        """
        while not self._in_queue.empty():
            queue = self._in_queue.get(timeout=self._consumer_timeout)
            self._parse_csv(queue[0], queue[1])

    def _parse_csv(self, time, line):
        """
        Parses incoming data and distributes to external processes.
        :param time: Timestamp.
        :type time: float.
        :param line: Raw data coming from acquisition process.
        :type line: basestring.
        :return:
        """
        if len(line) > 0:
            try:
                if type(line) == bytes:
                    values = line.decode("UTF-8").split(self._split)
                elif type(line) == str:
                    values = line.split(self._split)
                else:
                    raise TypeError
                values = [float(v) for v in values]
                Log.d(TAG, values)
                self._out_queue.put((time, values))
                if self._store_reference is not None:
                    self._store_reference.add(time, values)
            except ValueError:
                Log.w(TAG, "Can't convert to float. Raw: {}".format(line.strip()))
            except AttributeError:
                Log.w(TAG, "Attribute error on type ({}). Raw: {}".format(type(line), line.strip()))


text:
<?php

namespace Opltda\EntidadesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('OpltdaEntidadesBundle:Default:index.html.twig', array('name' => $name));
    }

}