text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>it.neef.tu.ba.wectask</groupId>
	<artifactId>WikipediaEditCountTask</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>WikipediaEditCount</name>
	<url>https://github.com/gehaxelt/Flink-WikipediaEditCount</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<flink.version>0.10.1</flink.version>
	</properties>

	<repositories>
		<repository>
			<id>apache.snapshots</id>
			<name>Apache Development Snapshot Repository</name>
			<url>https://repository.apache.org/content/repositories/snapshots/</url>
			<releases>
				<enabled>false</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
	</repositories>

	<!--

		Execute "mvn clean package -Pbuild-jar"
		to build a jar file out of this project!

		How to use the Flink Quickstart pom:

		a) Adding new dependencies:
			You can add dependencies to the list below.
			Please check if the maven-shade-plugin below is filtering out your dependency
			and remove the exclude from there.

		b) Build a jar for running on the cluster:
			There are two options for creating a jar from this project

			b.1) "mvn clean package" -> this will create a fat jar which contains all
					dependencies necessary for running the jar created by this pom in a cluster.
					The "maven-shade-plugin" excludes everything that is provided on a running Flink cluster.

			b.2) "mvn clean package -Pbuild-jar" -> This will also create a fat-jar, but with much
					nicer dependency exclusion handling. This approach is preferred and leads to
					much cleaner jar files.
	-->

	<dependencies>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-java</artifactId>
			<version>${flink.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-streaming-java</artifactId>
			<version>${flink.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-clients</artifactId>
			<version>${flink.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.mahout</groupId>
			<artifactId>mahout-integration</artifactId>
			<version>0.11.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-hadoop-compatibility</artifactId>
			<version>0.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.jacoco</groupId>
			<artifactId>jacoco-maven-plugin</artifactId>
			<version>0.7.5.201505241946</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- We use the maven-shade plugin to create a fat jar that contains all dependencies
			except flink and it's transitive dependencies. The resulting fat-jar can be executed
			on a cluster. Change the value of Program-Class if your program entry point changes. -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>2.4.1</version>
				<executions>
					<!-- Run shade goal on package phase -->
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<artifactSet>
								<excludes>
									<!-- This list contains all dependencies of flink-dist
									Everything else will be packaged into the fat-jar
									-->
									<exclude>org.apache.flink:flink-shaded-*</exclude>
									<exclude>org.apache.flink:flink-core</exclude>
									<exclude>org.apache.flink:flink-java</exclude>
									<exclude>org.apache.flink:flink-scala</exclude>
									<exclude>org.apache.flink:flink-runtime</exclude>
									<exclude>org.apache.flink:flink-optimizer</exclude>
									<exclude>org.apache.flink:flink-clients</exclude>
									<exclude>org.apache.flink:flink-avro</exclude>
									<exclude>org.apache.flink:flink-java-examples</exclude>
									<exclude>org.apache.flink:flink-scala-examples</exclude>
									<exclude>org.apache.flink:flink-streaming-examples</exclude>
									<exclude>org.apache.flink:flink-streaming-java</exclude>

									<!-- Also exclude very big transitive dependencies of Flink

									WARNING: You have to remove these excludes if your code relies on other
									versions of these dependencies.

									-->
									<exclude>org.scala-lang:scala-library</exclude>
									<exclude>org.scala-lang:scala-compiler</exclude>
									<exclude>org.scala-lang:scala-reflect</exclude>
									<exclude>com.amazonaws:aws-java-sdk</exclude>
									<exclude>com.typesafe.akka:akka-actor_*</exclude>
									<exclude>com.typesafe.akka:akka-remote_*</exclude>
									<exclude>com.typesafe.akka:akka-slf4j_*</exclude>
									<exclude>io.netty:netty-all</exclude>
									<exclude>io.netty:netty</exclude>
									<exclude>org.eclipse.jetty:jetty-server</exclude>
									<exclude>org.eclipse.jetty:jetty-continuation</exclude>
									<exclude>org.eclipse.jetty:jetty-http</exclude>
									<exclude>org.eclipse.jetty:jetty-io</exclude>
									<exclude>org.eclipse.jetty:jetty-util</exclude>
									<exclude>org.eclipse.jetty:jetty-security</exclude>
									<exclude>org.eclipse.jetty:jetty-servlet</exclude>
									<exclude>commons-fileupload:commons-fileupload</exclude>
									<exclude>org.apache.avro:avro</exclude>
									<exclude>commons-collections:commons-collections</exclude>
									<exclude>org.codehaus.jackson:jackson-core-asl</exclude>
									<exclude>org.codehaus.jackson:jackson-mapper-asl</exclude>
									<exclude>com.thoughtworks.paranamer:paranamer</exclude>
									<exclude>org.xerial.snappy:snappy-java</exclude>
									<exclude>org.apache.commons:commons-compress</exclude>
									<exclude>org.tukaani:xz</exclude>
									<exclude>com.esotericsoftware.kryo:kryo</exclude>
									<exclude>com.esotericsoftware.minlog:minlog</exclude>
									<exclude>org.objenesis:objenesis</exclude>
									<exclude>com.twitter:chill_*</exclude>
									<exclude>com.twitter:chill-java</exclude>
									<exclude>com.twitter:chill-avro_*</exclude>
									<exclude>com.twitter:chill-bijection_*</exclude>
									<exclude>com.twitter:bijection-core_*</exclude>
									<exclude>com.twitter:bijection-avro_*</exclude>
									<exclude>commons-lang:commons-lang</exclude>
									<exclude>junit:junit</exclude>
									<exclude>de.javakaffee:kryo-serializers</exclude>
									<exclude>joda-time:joda-time</exclude>
									<exclude>org.apache.commons:commons-lang3</exclude>
									<exclude>org.slf4j:slf4j-api</exclude>
									<exclude>org.slf4j:slf4j-log4j12</exclude>
									<exclude>log4j:log4j</exclude>
									<exclude>org.apache.commons:commons-math</exclude>
									<exclude>org.apache.sling:org.apache.sling.commons.json</exclude>
									<exclude>commons-logging:commons-logging</exclude>
									<exclude>org.apache.httpcomponents:httpclient</exclude>
									<exclude>org.apache.httpcomponents:httpcore</exclude>
									<exclude>commons-codec:commons-codec</exclude>
									<exclude>com.fasterxml.jackson.core:jackson-core</exclude>
									<exclude>com.fasterxml.jackson.core:jackson-databind</exclude>
									<exclude>com.fasterxml.jackson.core:jackson-annotations</exclude>
									<exclude>org.codehaus.jettison:jettison</exclude>
									<exclude>stax:stax-api</exclude>
									<exclude>com.typesafe:config</exclude>
									<exclude>org.uncommons.maths:uncommons-maths</exclude>
									<exclude>com.github.scopt:scopt_*</exclude>
									<exclude>org.mortbay.jetty:servlet-api</exclude>
									<exclude>commons-io:commons-io</exclude>
									<exclude>commons-cli:commons-cli</exclude>
								</excludes>
							</artifactSet>
							<filters>
								<filter>
									<artifact>org.apache.flink:*</artifact>
									<excludes>
										<exclude>org/apache/flink/shaded/**</exclude>
										<exclude>web-docs/**</exclude>
									</excludes>
								</filter>
								<filter>
									<!-- Do not copy the signatures in the META-INF folder.
									Otherwise, this might cause SecurityExceptions when using the JAR. -->
									<artifact>*:*</artifact>
									<excludes>
										<exclude>META-INF/*.SF</exclude>
										<exclude>META-INF/*.DSA</exclude>
										<exclude>META-INF/*.RSA</exclude>
									</excludes>
								</filter>
							</filters>
							<transformers>
								<!-- add Main-Class to manifest file -->
								<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>it.neef.tu.ba.wectask.Job</mainClass>
								</transformer>
							</transformers>
							<createDependencyReducedPom>false</createDependencyReducedPom>
						</configuration>
					</execution>
				</executions>
			</plugin>

			<!-- Configure the jar plugin to add the main class as a manifest entry -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<archive>
						<manifestEntries>
							<Main-Class>it.neef.tu.ba.wectask.Job</Main-Class>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source> <!-- If you want to use Java 8, change this to "1.8" -->
					<target>1.8</target> <!-- If you want to use Java 8, change this to "1.8" -->
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.jacoco</groupId>
				<artifactId>jacoco-maven-plugin</artifactId>
				<version>0.7.5.201505241946</version>
				<configuration>
					<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
					<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
				</configuration>
				<executions>
					<execution>
						<id>default-prepare-agent</id>
						<goals>
							<goal>prepare-agent</goal>
						</goals>
					</execution>
					<execution>
						<id>default-report</id>
						<phase>prepare-package</phase>
						<goals>
							<goal>report</goal>
						</goals>
					</execution>
					<execution>
						<id>default-check</id>
						<goals>
							<goal>check</goal>
						</goals>
						<configuration>
							<rules>
								<rule implementation="org.jacoco.maven.RuleConfiguration">
									<element>BUNDLE</element>
									<limits>
										<limit implementation="org.jacoco.report.check.Limit">
											<counter>INSTRUCTION</counter>
											<value>COVEREDRATIO</value>
											<minimum>0.80</minimum>
										</limit>
										<limit implementation="org.jacoco.report.check.Limit">
											<counter>CLASS</counter>
											<value>MISSEDCOUNT</value>
											<maximum>0</maximum>
										</limit>
									</limits>
								</rule>
							</rules>
						</configuration>
					</execution>
					<execution>
						<id>jacoco-initialize</id>
						<goals>
							<goal>prepare-agent</goal>
						</goals>
					</execution>
					<execution>
						<id>jacoco-site</id>
						<phase>package</phase>
						<goals>
							<goal>report</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>

		<!-- If you want to use Java 8 Lambda Expressions uncomment the following lines -->
		<!--
		<pluginManagement>
			<plugins>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.8</source>
						<target>1.8</target>
						<compilerId>jdt</compilerId>
					</configuration>
					<dependencies>
						<dependency>
							<groupId>org.eclipse.tycho</groupId>
							<artifactId>tycho-compiler-jdt</artifactId>
							<version>0.21.0</version>
						</dependency>
					</dependencies>
				</plugin>

				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.apache.maven.plugins</groupId>
										<artifactId>maven-assembly-plugin</artifactId>
										<versionRange>[2.4,)</versionRange>
										<goals>
											<goal>single</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore/>
									</action>
								</pluginExecution>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.apache.maven.plugins</groupId>
										<artifactId>maven-compiler-plugin</artifactId>
										<versionRange>[3.1,)</versionRange>
										<goals>
											<goal>testCompile</goal>
											<goal>compile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore/>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		-->

	</build>
	<profiles>
		<profile>
			<!-- A profile that does everyting correctly:
			We set the Flink dependencies to provided -->
			<id>build-jar</id>
			<activation>
				<activeByDefault>false</activeByDefault>
			</activation>
			<dependencies>
				<dependency>
					<groupId>org.apache.flink</groupId>
					<artifactId>flink-java</artifactId>
					<version>${flink.version}</version>
					<scope>provided</scope>
				</dependency>
				<dependency>
					<groupId>org.apache.flink</groupId>
					<artifactId>flink-streaming-java</artifactId>
					<version>${flink.version}</version>
					<scope>provided</scope>
				</dependency>
				<dependency>
					<groupId>org.apache.flink</groupId>
					<artifactId>flink-clients</artifactId>
					<version>${flink.version}</version>
					<scope>provided</scope>
				</dependency>
			</dependencies>
		</profile>
	</profiles>
</project>


text:
class ThreadSearch : public WorkerThread {
public:
	SimpleUI::Delegate<void> onWar3WindowFound;
	SimpleUI::Delegate<void> onWar3WindowClosed;

	const static uint32_t SEARCH_SLEEP_INTERVAL = 50;

	typedef GameModule::SearchResultType ResultType;

	ThreadSearch() {
		this->win_ = NULL;
		this->term_ = false;
	}

	void StopSignal() {this->term_ = true;}

	virtual ~ThreadSearch() {}
	virtual void Work();
private:
	HWND win_;
	volatile bool term_;
	DISALLOW_COPY_AND_ASSIGN(ThreadSearch);
};

#endif

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="msapplication-tap-highlight" content="no"/>

    <link rel="icon" type="image/png" href="assets/img/favicon-16x16.png" sizes="16x16">
    <link rel="icon" type="image/png" href="assets/img/favicon-32x32.png" sizes="32x32">

    <title>Altair Admin v2.13.0</title>

    <link rel="stylesheet" href="bower_components/codemirror/lib/codemirror.css">

    <link rel="stylesheet" href="bower_components/uikit/css/uikit.almost-flat.min.css" media="all">

    <link rel="stylesheet" href="assets/icons/flags/flags.min.css" media="all">

    <link rel="stylesheet" href="assets/css/style_switcher.min.css" media="all">

    <link rel="stylesheet" href="assets/css/main.min.css" media="all">

    <link rel="stylesheet" href="assets/css/themes/themes_combined.min.css" media="all">

                            

                                                
                                                Mailbox

                                                
                                                Invoices

                                                
                                                Chat

                                                
                                                Scrum Board

                                                
                                                Snippets

                                                
                                                User profile

Components

Accordions

Buttons

Notifications

Sortable

Tabs





                            16

Messages (12)

Alerts (4)

                                                        gl

                                                        Quae perferendis.
                                                        Assumenda veniam suscipit in inventore iure.

                                                        Voluptatem quia doloremque.
                                                        Vero saepe et odit nulla minima consectetur eos.

                                                        ym

                                                        Maxime est.
                                                        Est voluptas hic vero est ut molestiae cum repudiandae aliquid.

                                                        Non dolorem voluptatem.
                                                        Illo fugit consequatur eligendi quas architecto qui alias eligendi qui.

                                                        Voluptates sint sequi.
                                                        Est explicabo voluptas dignissimos rerum sunt debitis vel voluptatum id fugit.

                                                Show All

                                                        

                                                        Fugiat et ratione.
                                                        Enim perspiciatis temporibus et quam officiis sed.

                                                        

                                                        Quam quia atque.
                                                        Ullam quibusdam omnis aut quae.

                                                        

                                                        Id ullam.
                                                        Beatae placeat numquam quo officia voluptatem.

                                                        

                                                        Error et deserunt.
                                                        Voluptatum illum aperiam a commodi sed ab.

My profile

Settings

Login Page

Login Page v2

            
            <form class="uk-form uk-autocomplete" data-uk-autocomplete="{source:'data/search_data.json'}">
                <input type="text" class="header_main_search_input" />
                <button class="header_main_search_btn uk-button-link"></button>

            </form>

                <select id="lang_switcher" name="lang_switcher">
                    <option value="gb" selected>English</option>
                </select>

                        
                        Dashboard

                        
                        Mailbox

                        
                        Invoices

                        
                        Chats

Regular Chat

Chatboxes

                        
                        Scrum Board

                        
                        Snippets

                        
                        User Profile

                        
                        Sticky Notes

                        
                        Forms

Regular Elements

Advanced Elements

Dynamic

File Upload (dropify)

File Upload (uikit)

Validation

Wizard

WYSIWYG Editors

CKeditor

Ckeditor Inline

TinyMCE

                        
                        Layout

Top Menu

Full Header

                        
                        Kendo UI Widgets

Autocomplete

Calendar

ColorPicker

ComboBox

DatePicker

DateTimePicker

DropDownList

Masked Input

Menu

MultiSelect

Numeric TextBox

PanelBar

TimePicker

Toolbar

Window

                        
                        Components

Accordions

MD Animations

Autocomplete

Breadcrumbs

Buttons

Buttons: FAB

Cards

Colors

Common

Dropdowns

Dynamic Grid

Footer

Grid

Icons

Lightbox/Modal

List/Grid View

Lists

Nestable

Notifications

Panels

Preloaders

Scroll to Top

Slider

Slideshow

Sortable

Switcher

Tables

Tables Examples

Tabs

Timeline

Tooltips

Typography

                        
                        E-commerce

Product Details

Product Edit

Products Grid

Products List

Payment Page

                        
                        Plugins

Calendar

Charts

Charts (echarts)

Code Editor

Context Menu

CRUD Table

Datatables

Diff View

File Manager

Gantt Chart

Google Maps

Image Cropper

Idle Timeout

Push Notifications

Tour

Tablesorter

Tree

Vector Maps

X-editable

                        
                        Pages

Blank

Contact List

Contact List Horizontal

Contact List V2

Gallery

Gallery v2

Help/Faq

Login Page

Login Page v2

Mailbox V2

Notes

Pricing Tables

Pricing Tables v2

Search Results

Settings

Todo

User edit

Quiz

Issue Tracker

List View

Issue Details

Blog

Blog List

Blog Article

Errors

Error 404

Error 500

                        
                        Multi level

                            First level

                                    Second Level

                                            Third level

                                            Third level

                                            Third level

                                    Long title to test

                                            Third level

                                            Third level

                                            Third level

                                    Even longer title multi line

                        All

                        PHP

                        CSS

                        jQuery

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

                                        

Smooth scrolling to top of page

                                            Iste animi doloribus quo itaque facilis laudantium eos quos vel qui fuga id totam quaerat id hic est minima harum enim veniam quia alias dolor accusantium.

javascript

function getImageinfo($file, $query) {
  if (!realpath($file)) {
    $file = $_SERVER["DOCUMENT_ROOT"].$file;
  }
  $image = getimagesize($file);
  return $image[$query];
}

                                        

Get Image Information

                                            Aspernatur ea maiores ipsum quaerat debitis eaque non et sed enim et ab et reprehenderit nemo similique corrupti quasi et ipsa vitae et ut et amet non et non assumenda expedita numquam quasi illum omnis ullam ut necessitatibus architecto mollitia dolor.

php

var maxheight = 0;
$("div.col").each(function(){
  if($(this).height() > maxheight) { maxheight = $(this).height(); }
});

$("div.col").height(maxheight);

                                        

Equal height columns

                                            Repellat eius recusandae aliquid nisi similique assumenda ducimus eius aut voluptate ea ab et in modi hic consequuntur aut expedita perferendis illum magnam labore consequatur facere quos occaecati nihil ad perferendis magni sed voluptatem hic nulla deserunt.

javascript

.border-radius {
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

                                        

Border radius

                                            Ducimus distinctio omnis dolorem veritatis qui consequatur sunt et eum quis sapiente sint dolor officia ea mollitia quam temporibus optio delectus possimus nobis facere excepturi dignissimos rerum enim omnis temporibus aut.

css

var imgsrc = 'img/image1.png';
$('').load(function () {
    alert('image loaded');
}).error(function () {
    alert('error loading image');
}).attr('src', imgsrc);

                                        

Check if an image is loaded

                                            Veniam est quia quaerat autem nobis iste vel quasi magni vel eos ut quia mollitia voluptatem suscipit amet iure et fuga porro earum ab voluptatem distinctio qui totam tenetur fugiat maiores atque.

javascript

// Replace source
$('img').error(function(){
  $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
  $(this).hide();
});

                                        

Broken Image Handling

                                            Temporibus quisquam aut aut ullam est natus earum ut est nam nihil molestias quod vel quis ducimus necessitatibus ea facilis doloremque facere in et sunt quas voluptatum exercitationem et omnis eaque dolores dolore aut unde ratione natus.

javascript

<?php for($i=0;$i<10;$i++) { ?>
  <div class="class_<?php if($i%2){ echo "odd"; } else { echo "even"; } ?>">123</div>
<?php }; ?>

                                        

Applying Even/Odd Classes

                                            Laborum magni culpa similique facilis ipsum fugit iste asperiores officia ducimus tempora modi itaque aliquam aut totam aspernatur vel iusto eos rerum voluptatem corrupti assumenda nulla enim aut cumque fuga qui mollitia voluptate sed nostrum facere molestiae alias.

php

.border-box {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

                                        

Border Box

                                            Quis eaque est omnis ipsa quae dolor quaerat numquam voluptas enim incidunt corporis hic nisi corporis est eaque adipisci culpa facere commodi et quasi magnam corporis ut nihil consequatur non aut sunt.

css

.rotate90_ccw {
  -moz-transform: rotate(-90deg);
  -webkit-transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  transform: rotate(-90deg);
}

                                        

Rotate -90deg

                                            Eum nihil voluptatem id id earum eos quidem sint doloremque voluptatem cumque dignissimos et sint ratione facere quia aperiam assumenda atque tempora minima fugiat expedita tempore quae expedita iusto inventore officia corrupti autem.

css

function cleanuserinput($dirty){
  if (get_magic_quotes_gpc()) {
    $clean = mysql_real_escape_string(stripslashes($dirty));
  }else{
    $clean = mysql_real_escape_string($dirty);
  }
  return $clean;
}

                                        

Anti-SQL Injection Function

                                            Ut sed iste numquam et corrupti laboriosam praesentium fugiat dicta et sint aut harum sit cum aspernatur ipsam iure dicta voluptas et omnis ex tenetur ut rerum rem consectetur quidem fugiat omnis.

php

$.fn.serializeObject = function() {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function() {
    if (o[this.name]) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]];
      }
        o[this.name].push(this.value || '');
      } else {
        o[this.name] = this.value || '';
      }
    });
    return o;
};

                                        

Serialize Form to JSON

                                            Aperiam aut tempore enim voluptatem qui quis enim minus in voluptatem neque odio inventore molestias voluptas officia nihil est voluptate cumque nam placeat mollitia voluptatum quod consequatur et deleniti dignissimos labore esse et id occaecati repellat molestiae rem vel.

javascript

function make_seo_name($title) {
  return preg_replace('/[^a-z0-9_-]/i', '', strtolower(str_replace(' ', '-', trim($title))));
}

                                        

SEO-friendly title for URL

                                            Sunt animi culpa quos pariatur libero molestiae ut cupiditate odio dolores impedit odio dignissimos rerum quas qui aliquam consequatur nisi debitis autem maxime aperiam illo qui nesciunt quia et enim voluptatem doloribus quasi hic recusandae error eveniet architecto odit accusamus.

php

@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {
  /* Retina-specific stuff here */
}

                                        

Retina Display Media Query

                                            Et officia sed voluptates aliquid eum quia fugit id molestiae cupiditate molestiae eius similique voluptate quo magnam adipisci saepe placeat facilis ducimus.

css

var resizeTimer;
$(window).on('resize', function(e) {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {
    // Run code here, resizing has "stopped"
  }, 250);
});

                                        

Done Resizing Event

                                            Consequatur voluptatibus quae eius labore aut voluptatem culpa nihil consequatur ut voluptatem totam perspiciatis pariatur reiciendis error ullam reiciendis.

javascript

.cf:before,
.cf:after {
    content: " ";
    display: table;
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.cf {
    *zoom: 1;
}

                                        

A new micro clearfix hack

                                            Vitae quis rerum et sint quasi nisi quod est atque laudantium sapiente voluptas et asperiores nobis ex porro est ipsum tempora mollitia voluptas quia odit nihil sit eligendi quaerat enim eum fugiat neque esse repudiandae mollitia alias ea tempore mollitia iure.

css

::selection { background: #e2eae2; }
::-moz-selection { background: #e2eae2; }
::-webkit-selection { background: #e2eae2; }

                                        

Custom Text Selection

                                            Ipsa voluptatem doloribus ut amet quaerat tenetur quia sint vel quibusdam possimus qui harum tenetur iste sit est veritatis quam adipisci hic voluptate omnis assumenda iusto odit maxime aut ipsa cumque officiis quidem modi ut sapiente in fugit.

css

            

New Snippet

            <form class="uk-form-stacked">

                    Title
                    <input type="text" class="md-input" id="snippet_title" name="snippet_title"/>

                    Language
                    <select class="uk-form-width-medium" name="snippet_language" id="snippet_language" data-md-selectize-inline>
                        <option value="javascript">Javascript</option>
                        <option value="php">PHP</option>
                        <option value="css">CSS</option>
                    </select>

                <textarea id="snippet_content" name="snippet_content"></textarea>
                Don't wrap your snippets in <pre></pre> or <code></code> tags.

                    <button type="button" class="md-btn md-btn-flat uk-modal-close">Close</button><button type="button" class="md-btn md-btn-flat md-btn-flat-primary" id="snippet_new_save">Save</button>

            </form>



Colors

Sidebar

                <input type="checkbox" name="style_sidebar_mini" id="style_sidebar_mini" data-md-icheck />
                Mini Sidebar

                <input type="checkbox" name="style_sidebar_slim" id="style_sidebar_slim" data-md-icheck />
                Slim Sidebar

Layout

                <input type="checkbox" name="style_layout_boxed" id="style_layout_boxed" data-md-icheck />
                Boxed layout

Main menu accordion

                <input type="checkbox" name="accordion_mode_main_menu" id="accordion_mode_main_menu" data-md-icheck />
                Accordion mode


text:
class Solution {
    public int trap(int[] height) {
        if (height == null || height.length == 0) return 0;

        int maxLeft = height[0];
        int maxRight = height[height.length - 1];

        int leftIndex = 0;
        int rightIndex = height.length - 1;

        int count = 0;

        while (leftIndex < rightIndex) {
            if (maxLeft <= maxRight) {
                count += maxLeft - height[leftIndex];
                leftIndex++;
                maxLeft = Math.max(maxLeft, height[leftIndex]);
            } else {
                count += maxRight - height[rightIndex];
                rightIndex--;
                maxRight = Math.max(maxRight, height[rightIndex]);
            }
        }

        return count;
    }
}


text:
package net.ripe.db.whois.update.authentication.strategy;

import com.google.common.collect.Lists;
import net.ripe.db.whois.common.dao.RpslObjectDao;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.update.authentication.credential.AuthenticationModule;
import net.ripe.db.whois.update.domain.Action;
import net.ripe.db.whois.update.domain.PreparedUpdate;
import net.ripe.db.whois.update.domain.UpdateContext;
import net.ripe.db.whois.update.domain.UpdateMessages;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.Collections;
import java.util.List;

import static net.ripe.db.whois.common.domain.CIString.ciSet;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class RouteAutnumAuthenticationTest {
    @Mock
    PreparedUpdate update;
    @Mock
    UpdateContext updateContext;
    @Mock
    AuthenticationModule authenticationModule;
    @Mock
    RpslObjectDao objectDao;
    @InjectMocks
    RouteAutnumAuthentication subject;
    private RpslObject routeObject;

    @Before
    public void setUp() throws Exception {
        routeObject = RpslObject.parse("" +
                "route: 192.91.244.0/23\n" +
                "origin: AS513\n" +
                "mnt-routes: ROUTE-MNT");

        when(update.getUpdatedObject()).thenReturn(routeObject);
    }

    @Test
    public void supports_route_action_create() {
        when(update.getType()).thenReturn(ObjectType.ROUTE);
        when(update.getAction()).thenReturn(Action.CREATE);
        assertThat(subject.supports(update), is(true));
    }

    @Test
    public void supports_route6_action_create() {
        when(update.getType()).thenReturn(ObjectType.ROUTE6);
        when(update.getAction()).thenReturn(Action.CREATE);

        assertThat(subject.supports(update), is(true));
    }

    @Test
    public void no_autnum_found_for_origin_value() {
        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenThrow(EmptyResultDataAccessException.class);

        try {
            subject.authenticate(update, updateContext);
            fail("Expected exception");
        } catch (AuthenticationFailedException e) {
            assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(update.getUpdatedObject(), AttributeType.ORIGIN, Collections.<RpslObject>emptyList())));
        }
    }

    @Test
    public void no_maintainers_found_in_autnum() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);

        try {
            subject.authenticate(update, updateContext);
            fail("Expected exception");
        } catch (AuthenticationFailedException e) {
            assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(autNum, AttributeType.MNT_BY, Collections.<RpslObject>emptyList())));
        }
    }

    @Test
    public void autnum_with_mntroutes_not_exists() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-routes: ROUTE-MNT\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final List<RpslObject> candidates = Collections.emptyList();
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-MNT"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList());

        try {
            subject.authenticate(update, updateContext);
            fail("Expected exception");
        } catch (AuthenticationFailedException e) {
            assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(autNum, AttributeType.MNT_ROUTES, candidates)));
        }
    }

    @Test
    public void autnum_with_mntroutes_auth_fails() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-by: ROUTE-BY\n" +
                "mnt-lower: ROUTE-LOWER\n" +
                "mnt-routes: ROUTE-MNT\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final List<RpslObject> candidates = Lists.newArrayList(RpslObject.parse("mntner: ROUTE-MNT"));
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-MNT"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList());

        try {
            subject.authenticate(update, updateContext);
            fail("Expected exception");
        } catch (AuthenticationFailedException e) {
            assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(autNum, AttributeType.MNT_ROUTES, candidates)));
        }
    }

    @Test
    public void autnum_with_mntroutes_auth_succeeds() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-by: ROUTE-BY\n" +
                "mnt-lower: ROUTE-LOWER\n" +
                "mnt-routes: ROUTE-MNT\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final RpslObject maintainer = RpslObject.parse("mntner: ROUTE-MNT");

        final List<RpslObject> candidates = Lists.newArrayList(maintainer);
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-MNT"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(candidates);

        final List<RpslObject> authenticated = subject.authenticate(update, updateContext);
        assertThat(authenticated, contains(maintainer));

        verify(objectDao, never()).getByKeys(ObjectType.MNTNER, ciSet("ROUTE-LOWER"));
        verify(objectDao, never()).getByKeys(ObjectType.MNTNER, ciSet("ROUTE-BY"));
    }

    @Test
    public void autnum_with_mntlower_auth_skipped() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-by: ROUTE-BY\n" +
                "mnt-lower: ROUTE-LOWER\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final List<RpslObject> candidates = Lists.newArrayList(RpslObject.parse("mntner: ROUTE-BY"));
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-BY"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList());

        try {
            subject.authenticate(update, updateContext);
            fail("Expected exception");
        } catch (AuthenticationFailedException e) {
            assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(autNum, AttributeType.MNT_BY, candidates)));
        }
    }

    @Test
    public void autnum_with_mntlower_auth_succeeds() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-by: ROUTE-BY\n" +
                "mnt-lower: ROUTE-LOWER\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final RpslObject maintainer = RpslObject.parse("mntner: ROUTE-BY");

        final List<RpslObject> candidates = Lists.newArrayList(maintainer);
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-BY"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(candidates);

        final List<RpslObject> authenticated = subject.authenticate(update, updateContext);
        assertThat(authenticated, contains(maintainer));
    }

    @Test
    public void autnum_with_mntby_auth_fails() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-by: ROUTE-BY\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final List<RpslObject> candidates = Lists.newArrayList(RpslObject.parse("mntner: ROUTE-BY"));
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-BY"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList());

        try {
            subject.authenticate(update, updateContext);
            fail("Expected exception");
        } catch (AuthenticationFailedException e) {
            assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(autNum, AttributeType.MNT_BY, candidates)));
        }
    }

    @Test
    public void autnum_with_mntby_auth_succeeds() {
        final RpslObject autNum = RpslObject.parse("" +
                "aut-num: AS513\n" +
                "as-name: AS-5354\n" +
                "mnt-by: ROUTE-BY\n");

        when(objectDao.getByKey(ObjectType.AUT_NUM, "AS513")).thenReturn(autNum);
        final RpslObject maintainer = RpslObject.parse("mntner: ROUTE-BY");

        final List<RpslObject> candidates = Lists.newArrayList(maintainer);
        when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTE-BY"))).thenReturn(candidates);
        when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(candidates);

        final List<RpslObject> authenticated = subject.authenticate(update, updateContext);
        assertThat(authenticated, contains(maintainer));
    }
}


text:
#ifndef MODULES_AUDIO_PROCESSING_AEC3_RENDER_DELAY_CONTROLLER_METRICS_H_
#define MODULES_AUDIO_PROCESSING_AEC3_RENDER_DELAY_CONTROLLER_METRICS_H_

#include "api/optional.h"
#include "rtc_base/constructormagic.h"

namespace webrtc {

// Handles the reporting of metrics for the render delay controller.
class RenderDelayControllerMetrics {
 public:
  RenderDelayControllerMetrics() = default;

  // Updates the metric with new data.
  void Update(rtc::Optional<size_t> delay_samples, size_t buffer_delay_blocks);

  // Returns true if the metrics have just been reported, otherwise false.
  bool MetricsReported() { return metrics_reported_; }

 private:
  // Resets the metrics.
  void ResetMetrics();

  size_t delay_blocks_ = 0;
  int reliable_delay_estimate_counter_ = 0;
  int delay_change_counter_ = 0;
  int call_counter_ = 0;
  int initial_call_counter_ = 0;
  bool metrics_reported_ = false;
  bool initial_update = true;

  RTC_DISALLOW_COPY_AND_ASSIGN(RenderDelayControllerMetrics);
};

}  // namespace webrtc

#endif  // MODULES_AUDIO_PROCESSING_AEC3_RENDER_DELAY_CONTROLLER_METRICS_H_


text:
/*
 * Support and FAQ: visit Atmel Support
 */

#ifndef I2C_MASTER_H_INCLUDED
#define I2C_MASTER_H_INCLUDED

#include "i2c_common.h"
#include <sercom.h>
#include <pinmux.h>

#if I2C_MASTER_CALLBACK_MODE == true
#  include <sercom_interrupt.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifndef PINMUX_DEFAULT
#  define PINMUX_DEFAULT 0
#endif

/**
 * \addtogroup asfdoc_sam0_sercom_i2c_group
 *
 * @{
 */

/**
 * \brief I2C master packet for read/write
 *
 * Structure to be used when transferring I2C master packets.
 */
struct i2c_master_packet {
    /** Address to slave device.  */
    uint16_t address;
    /** Length of data array. */
    uint16_t data_length;
    /** Data array containing all data to be transferred. */
    uint8_t *data;
    /** Use 10-bit addressing. Set to false if the feature is not supported by the device.  */
    bool ten_bit_address;
    /** Use high speed transfer. Set to false if the feature is not supported by the device. */
    bool high_speed;
    /** High speed mode master code (0000 1XXX), valid when high_speed is true. */
    uint8_t hs_master_code;
};

/** \brief Interrupt flags
 *
 * Flags used when reading or setting interrupt flags.
 */
enum i2c_master_interrupt_flag {
    /** Interrupt flag used for write. */
    I2C_MASTER_INTERRUPT_WRITE = 0,
    /** Interrupt flag used for read. */
    I2C_MASTER_INTERRUPT_READ  = 1,
};

/**
 * \brief Values for hold time after start bit.
 *
 * Values for the possible I2C master mode SDA internal hold times after start
 * bit has been sent.
 */
enum i2c_master_start_hold_time {
    /** Internal SDA hold time disabled. */
    I2C_MASTER_START_HOLD_TIME_DISABLED = SERCOM_I2CM_CTRLA_SDAHOLD(0),
    /** Internal SDA hold time 50ns - 100ns. */
    I2C_MASTER_START_HOLD_TIME_50NS_100NS = SERCOM_I2CM_CTRLA_SDAHOLD(1),
    /** Internal SDA hold time 300ns - 600ns. */
    I2C_MASTER_START_HOLD_TIME_300NS_600NS = SERCOM_I2CM_CTRLA_SDAHOLD(2),
    /** Internal SDA hold time 400ns - 800ns. */
    I2C_MASTER_START_HOLD_TIME_400NS_800NS = SERCOM_I2CM_CTRLA_SDAHOLD(3),
};

/**
 * \brief Values for inactive bus time-out.
 *
 * If the inactive bus time-out is enabled and the bus is inactive for
 * longer than the time-out setting, the bus state logic will be set to idle.
 */
enum i2c_master_inactive_timeout {
    /** Inactive bus time-out disabled. */
    I2C_MASTER_INACTIVE_TIMEOUT_DISABLED = SERCOM_I2CM_CTRLA_INACTOUT(0),
    /** Inactive bus time-out 5-6 SCL cycle time-out. */
    I2C_MASTER_INACTIVE_TIMEOUT_55US = SERCOM_I2CM_CTRLA_INACTOUT(1),
    /** Inactive bus time-out 10-11 SCL cycle time-out. */
    I2C_MASTER_INACTIVE_TIMEOUT_105US = SERCOM_I2CM_CTRLA_INACTOUT(2),
    /** Inactive bus time-out 20-21 SCL cycle time-out. */
    I2C_MASTER_INACTIVE_TIMEOUT_205US = SERCOM_I2CM_CTRLA_INACTOUT(3),
};

/**
 * \brief I2C frequencies
 *
 * Values for I2C speeds supported by the module. The driver
 * will also support setting any other value, in which case set
 * the value in the \ref i2c_master_config at desired value divided by 1000.
 *
 * Example: If 10KHz operation is required, give baud_rate in the configuration
 * structure the value 10.
 */
enum i2c_master_baud_rate {
    /** Baud rate at 100KHz (Standard-mode). */
    I2C_MASTER_BAUD_RATE_100KHZ = 100,
    /** Baud rate at 400KHz (Fast-mode). */
    I2C_MASTER_BAUD_RATE_400KHZ = 400,
#ifdef FEATURE_I2C_FAST_MODE_PLUS_AND_HIGH_SPEED
    /** Baud rate at 1MHz (Fast-mode Plus). */
    I2C_MASTER_BAUD_RATE_1000KHZ = 1000,
    /** Baud rate at 3.4MHz (High-speed mode). */
    I2C_MASTER_BAUD_RATE_3400KHZ = 3400,
#endif
};

#ifdef FEATURE_I2C_FAST_MODE_PLUS_AND_HIGH_SPEED
/**
 * \brief Enum for the transfer speed
 *
 * Enum for the transfer speed.
 */
enum i2c_master_transfer_speed {
    /** Standard-mode (Sm) up to 100KHz and Fast-mode (Fm) up to 400KHz. */
    I2C_MASTER_SPEED_STANDARD_AND_FAST = SERCOM_I2CM_CTRLA_SPEED(0),
    /** Fast-mode Plus (Fm+) up to 1MHz. */
    I2C_MASTER_SPEED_FAST_MODE_PLUS = SERCOM_I2CM_CTRLA_SPEED(1),
    /** High-speed mode (Hs-mode) up to 3.4MHz. */
    I2C_MASTER_SPEED_HIGH_SPEED = SERCOM_I2CM_CTRLA_SPEED(2),
};
#endif

#if I2C_MASTER_CALLBACK_MODE == true
/**
 * \brief Callback types
 *
 * The available callback types for the I2C master module.
 */
enum i2c_master_callback {
    /** Callback for packet write complete. */
    I2C_MASTER_CALLBACK_WRITE_COMPLETE = 0,
    /** Callback for packet read complete. */
    I2C_MASTER_CALLBACK_READ_COMPLETE  = 1,
    /** Callback for error. */
    I2C_MASTER_CALLBACK_ERROR          = 2,
#  if !defined(__DOXYGEN__)
    /** Total number of callbacks. */
    _I2C_MASTER_CALLBACK_N             = 3,
#  endif
};

#  if !defined(__DOXYGEN__)
/* Prototype for software module. */
struct i2c_master_module;

typedef void (*i2c_master_callback_t)(
    struct i2c_master_module *const module);
#  endif
#endif

/**
 * \brief SERCOM I2C Master driver software device instance structure.
 *
 * SERCOM I2C Master driver software instance structure, used to
 * retain software state information of an associated hardware module instance.
 *
 * \note The fields of this structure should not be altered by the user
 *       application; they are reserved for module-internal use only.
 */
struct i2c_master_module {
#if !defined(__DOXYGEN__)
    /** Hardware instance initialized for the struct. */
    Sercom *hw;
    /** Module lock. */
    volatile bool locked;
    /** Unknown bus state timeout. */
    uint16_t unknown_bus_state_timeout;
    /** Buffer write timeout value. */
    uint16_t buffer_timeout;
    /** If true, stop condition will be sent after a read/write. */
    bool send_stop;
    /** If true, nack signal will be sent after a read/write. */
    bool send_nack;
#  if I2C_MASTER_CALLBACK_MODE == true
    /** Pointers to callback functions. */
    volatile i2c_master_callback_t callbacks[_I2C_MASTER_CALLBACK_N];
    /** Mask for registered callbacks. */
    volatile uint8_t registered_callback;
    /** Mask for enabled callbacks. */
    volatile uint8_t enabled_callback;
    /** The total number of bytes to transfer. */
    volatile uint16_t buffer_length;
    /**
     * Counter used for bytes left to send in write and to count number of
     * obtained bytes in read.
     */
    volatile uint16_t buffer_remaining;
    /** Data buffer for packet write and read. */
    volatile uint8_t *buffer;
    /** Save direction of async request. 1 = read, 0 = write. */
    volatile enum i2c_transfer_direction transfer_direction;
    /** Status for status read back in error callback. */
    volatile enum status_code status;
#  endif
#endif
};

/**
 * \brief Configuration structure for the I2C Master device
 *
 * This is the configuration structure for the I2C Master device. It
 * is used as an argument for \ref i2c_master_init to provide the desired
 * configurations for the module. The structure should be initialized using the
 * \ref i2c_master_get_config_defaults .
 */
struct i2c_master_config {
    /** Baud rate (in KHz) for I2C operations in
     * standard-mode, Fast-mode and Fast-mode Plus Transfers,
     * \ref i2c_master_baud_rate. */
    uint32_t baud_rate;
#ifdef FEATURE_I2C_FAST_MODE_PLUS_AND_HIGH_SPEED
    /** Baud rate (in KHz) for I2C operations in
     * High-speed mode, \ref i2c_master_baud_rate. */
    uint32_t baud_rate_high_speed;
    /** Transfer speed mode. */
    enum i2c_master_transfer_speed transfer_speed;
#endif
    /** GCLK generator to use as clock source. */
    enum gclk_generator generator_source;
    /** Bus hold time after start signal on data line. */
    enum i2c_master_start_hold_time start_hold_time;
    /** Unknown bus state \ref asfdoc_sam0_sercom_i2c_unknown_bus_timeout "timeout". */
    uint16_t unknown_bus_state_timeout;
    /** Timeout for packet write to wait for slave. */
    uint16_t buffer_timeout;
    /** Set to keep module active in sleep modes. */
    bool run_in_standby;
    /** PAD0 (SDA) pinmux. */
    uint32_t pinmux_pad0;
    /** PAD1 (SCL) pinmux. */
    uint32_t pinmux_pad1;
    /** Set to enable SCL low time-out. */
    bool scl_low_timeout;
    /** Inactive bus time out. */
    enum i2c_master_inactive_timeout inactive_timeout;
#ifdef FEATURE_I2C_SCL_STRETCH_MODE
    /** Set to enable SCL stretch only after ACK bit (required for high speed). */
    bool scl_stretch_only_after_ack_bit;
#endif
#ifdef FEATURE_I2C_SCL_EXTEND_TIMEOUT
    /** Set to enable slave SCL low extend time-out. */
    bool slave_scl_low_extend_timeout;
    /** Set to enable maser SCL low extend time-out. */
    bool master_scl_low_extend_timeout;
#endif
    /** Get more accurate BAUD, considering rise time(required for standard-mode and Fast-mode). */
    uint16_t sda_scl_rise_time_ns;
};

/**
 * \name Lock/Unlock
 * @{
 */

/**
 * \brief Attempt to get lock on driver instance
 *
 * This function checks the instance's lock, which indicates whether or not it
 * is currently in use, and sets the lock if it was not already set.
 *
 * The purpose of this is to enable exclusive access to driver instances, so
 * that, e.g., transactions by different services will not interfere with each
 * other.
 *
 * \param[in,out] module Pointer to the driver instance to lock
 *
 * \retval STATUS_OK If the module was locked
 * \retval STATUS_BUSY If the module was already locked
 */
static inline enum status_code i2c_master_lock(
    struct i2c_master_module *const module)
{
    enum status_code status;

    system_interrupt_enter_critical_section();

    if (module->locked) {
        status = STATUS_BUSY;
    } else {
        module->locked = true;
        status = STATUS_OK;
    }

    system_interrupt_leave_critical_section();

    return status;
}

/**
 * \brief Unlock driver instance
 *
 * This function clears the instance lock, indicating that it is available for
 * use.
 *
 * \param[in,out] module Pointer to the driver instance to lock
 *
 * \retval STATUS_OK If the module was locked
 * \retval STATUS_BUSY If the module was already locked
 */
static inline void i2c_master_unlock(struct i2c_master_module *const module)
{
    module->locked = false;
}

/** @} */

/**
 * \name Configuration and Initialization
 * @{
 */

/**
 * \brief Returns the synchronization status of the module
 *
 * Returns the synchronization status of the module.
 *
 * \param[in]  module  Pointer to software module structure
 *
 * \return Status of the synchronization.
 * \retval true   Module is busy synchronizing
 * \retval false  Module is not synchronizing
 */
static inline bool i2c_master_is_syncing (
    const struct i2c_master_module *const module)
{
    /* Sanity check. */
    Assert(module);
    Assert(module->hw);

    SercomI2cm *const i2c_hw = &(module->hw->I2CM);

#if defined(FEATURE_SERCOM_SYNCBUSY_SCHEME_VERSION_1)
    return (i2c_hw->STATUS.reg & SERCOM_I2CM_STATUS_SYNCBUSY);
#elif defined(FEATURE_SERCOM_SYNCBUSY_SCHEME_VERSION_2)
    return (i2c_hw->SYNCBUSY.reg & SERCOM_I2CM_SYNCBUSY_MASK);
#else
#  error Unknown SERCOM SYNCBUSY scheme!
#endif
}

#if !defined(__DOXYGEN__)
/**
 * \internal
 * Wait for hardware module to sync
 *
 * \param[in]  module  Pointer to software module structure
 */
static void _i2c_master_wait_for_sync(
    const struct i2c_master_module *const module)
{
    /* Sanity check. */
    Assert(module);

    while (i2c_master_is_syncing(module)) {
        /* Wait for I2C module to sync. */
    }
}
#endif

/**
 * \brief Gets the I2C master default configurations
 *
 * Use to initialize the configuration structure to known default values.
 *
 * The default configuration is as follows:
 * - Baudrate 100KHz
 * - GCLK generator 0
 * - Do not run in standby
 * - Start bit hold time 300ns - 600ns
 * - Buffer timeout = 65535
 * - Unknown bus status timeout = 65535
 * - Do not run in standby
 * - PINMUX_DEFAULT for SERCOM pads
 *
 * Those default configuration only available if the device supports it:
 * - High speed baudrate 3.4MHz
 * - Standard-mode and Fast-mode transfer speed
 * - SCL stretch disabled
 * - slave SCL low extend time-out disabled
 * - maser SCL low extend time-out disabled
 *
 * \param[out] config  Pointer to configuration structure to be initiated
 */
static inline void i2c_master_get_config_defaults(
    struct i2c_master_config *const config)
{
    /*Sanity check argument. */
    Assert(config);
    config->baud_rate        = I2C_MASTER_BAUD_RATE_100KHZ;
#ifdef FEATURE_I2C_FAST_MODE_PLUS_AND_HIGH_SPEED
    config->baud_rate_high_speed = I2C_MASTER_BAUD_RATE_3400KHZ;
    config->transfer_speed       = I2C_MASTER_SPEED_STANDARD_AND_FAST;
#endif
    config->generator_source = GCLK_GENERATOR_0;
    config->run_in_standby   = false;
    config->start_hold_time  = I2C_MASTER_START_HOLD_TIME_300NS_600NS;
    config->buffer_timeout   = 65535;
    config->unknown_bus_state_timeout = 65535;
    config->pinmux_pad0      = PINMUX_DEFAULT;
    config->pinmux_pad1      = PINMUX_DEFAULT;
    config->scl_low_timeout  = false;
    config->inactive_timeout = I2C_MASTER_INACTIVE_TIMEOUT_DISABLED;
#ifdef FEATURE_I2C_SCL_STRETCH_MODE
    config->scl_stretch_only_after_ack_bit = false;
#endif
#ifdef FEATURE_I2C_SCL_EXTEND_TIMEOUT
    config->slave_scl_low_extend_timeout   = false;
    config->master_scl_low_extend_timeout  = false;
#endif
    /* The typical value is 215ns */
    config->sda_scl_rise_time_ns = 215;
}

enum status_code i2c_master_init(
    struct i2c_master_module *const module,
    Sercom *const hw,
    const struct i2c_master_config *const config);

/**
 * \brief Enables the I2C module
 *
 * Enables the requested I2C module and set the bus state to IDLE
 * after the specified \ref asfdoc_sam0_sercom_i2c_timeout "timeout" period if no
 * stop bit is detected.
 *
 * \param[in]  module  Pointer to the software module struct
 */
static inline void i2c_master_enable(
    const struct i2c_master_module *const module)
{
    /* Sanity check of arguments. */
    Assert(module);
    Assert(module->hw);

    SercomI2cm *const i2c_module = &(module->hw->I2CM);

    /* Timeout counter used to force bus state. */
    uint32_t timeout_counter = 0;

    /* Wait for module to sync. */
    _i2c_master_wait_for_sync(module);

    /* Enable module. */
    i2c_module->CTRLA.reg |= SERCOM_I2CM_CTRLA_ENABLE;

#if I2C_MASTER_CALLBACK_MODE == true
    /* Enable module interrupts */
    system_interrupt_enable(_sercom_get_interrupt_vector(module->hw));
#endif
    /* Start timeout if bus state is unknown. */
    while (!(i2c_module->STATUS.reg & SERCOM_I2CM_STATUS_BUSSTATE(1))) {
        timeout_counter++;
        if(timeout_counter >= (module->unknown_bus_state_timeout)) {
            /* Timeout, force bus state to idle. */
            i2c_module->STATUS.reg = SERCOM_I2CM_STATUS_BUSSTATE(1);
            /* Workaround #1 */
            return;
        }
    }
}

/**
 * \brief Disable the I2C module
 *
 * Disables the requested I2C module.
 *
 * \param[in]  module  Pointer to the software module struct
 */
static inline void i2c_master_disable(
    const struct i2c_master_module *const module)
{
    /* Sanity check of arguments. */
    Assert(module);
    Assert(module->hw);

    SercomI2cm *const i2c_module = &(module->hw->I2CM);

    /* Wait for module to sync. */
    _i2c_master_wait_for_sync(module);

    /* Disable module. */
    i2c_module->CTRLA.reg &= ~SERCOM_I2CM_CTRLA_ENABLE;

#if I2C_MASTER_CALLBACK_MODE == true
    /* Disable module interrupts */
    system_interrupt_disable(_sercom_get_interrupt_vector(module->hw));
#endif
}

void i2c_master_reset(struct i2c_master_module *const module);

/** @} */

/**
* \name Read and Write
* @{
*/

enum status_code i2c_master_read_packet_wait(
    struct i2c_master_module *const module,
    struct i2c_master_packet *const packet);

enum status_code i2c_master_read_packet_wait_no_stop(
    struct i2c_master_module *const module,
    struct i2c_master_packet *const packet);

enum status_code i2c_master_write_packet_wait(
    struct i2c_master_module *const module,
    struct i2c_master_packet *const packet);

enum status_code i2c_master_write_packet_wait_no_stop(
    struct i2c_master_module *const module,
    struct i2c_master_packet *const packet);

void i2c_master_send_stop(struct i2c_master_module *const module);

void i2c_master_send_nack(struct i2c_master_module *const module);

enum status_code i2c_master_read_byte(
    struct i2c_master_module *const module,
    uint8_t *byte);

enum status_code i2c_master_write_byte(
    struct i2c_master_module *const module,
    uint8_t byte);

enum status_code i2c_master_read_packet_wait_no_nack(
    struct i2c_master_module *const module,
    struct i2c_master_packet *const packet);

/** @} */

#ifdef FEATURE_I2C_DMA_SUPPORT
/**
* \name SERCOM I2C Master with DMA Interfaces
* @{
*/

/**
 * \brief Set I2C for DMA transfer with slave address and transfer size.
 *
 * This function will set the slave address, transfer size and enable the auto transfer
 * mode for DMA.
 *
 * \param[in,out] module Pointer to the driver instance to lock
 * \param[in] addr I2C slave address
 * \param[in] length I2C transfer length with DMA
 * \param[in] direction I2C transfer direction
 *
 */
static inline void i2c_master_dma_set_transfer(struct i2c_master_module *const module,
        uint16_t addr, uint8_t length, enum i2c_transfer_direction direction)
{
    module->hw->I2CM.ADDR.reg =
        SERCOM_I2CM_ADDR_ADDR(addr<<1) |
        SERCOM_I2CM_ADDR_LENEN |
        SERCOM_I2CM_ADDR_LEN(length) |
        direction;
}

/** @} */
#endif

/** @} */

#ifdef __cplusplus
}
#endif

#endif /* I2C_MASTER_H_INCLUDED */


text:
package com.tle.admin.security.tree.model;

import com.tle.beans.item.ItemStatus;
import com.tle.common.i18n.CurrentLocale;
import java.util.ArrayList;
import java.util.List;

/** @author Nicholas Read */
public class ItemSearchNode extends AbstractLazyNode {
  public ItemSearchNode() {
    super(
        CurrentLocale.get("com.tle.admin.security.tree.model.itemsearchnode.name"),
        null); //$NON-NLS-1$
  }

  @Override
  public Object getTargetObject() {
    return null;
  }

  @Override
  protected List<SecurityTreeNode> getChildren() {
    List<SecurityTreeNode> results = new ArrayList<SecurityTreeNode>();
    for (ItemStatus status : ItemStatus.values()) {
      results.add(new ItemStatusLeafNode(null, status));
    }
    return results;
  }
}


text:
name        "osx_data_miner"
description "Chimpstation OSX: apps and packages for data munging"

run_list(
  )


text:
#include "SurfaceScan.h"
#include "PE_Types.h"
#include "ADC_IR_BATT.h"
#include "MotionController.h"
#include "BLUETOOTH.h"
#include "UTIL1.h"
#include "WAIT.h"
#include "RTOS.h"

#include "LED_RED.h"
#include "LED_GREEN.h"

/*
 * Here we calculate a average value of the analog input. We need this one, because the signal has some peaks(200mV/1us) with a frequency (333 kHz).
 * \return analog input IR-sensor
 * */
uint32_t SCN_GetValue(){ // semaphores?

	static uint32_t avgValue = 0;
	uint32_t Value = 0;
	uint16_t IRvalue;
	uint8_t i;

	// summing 200 measurements and wait between 1 us
	for(i = 0; i < 200; i++){

		WAIT_Waitus(1);

		ADC_IR_BATT_MeasureChan(TRUE, 0);
		ADC_IR_BATT_GetChanValue16(0, &IRvalue);
		Value = Value + IRvalue;

	}
	avgValue = Value / 200; // dividing by the number of measurements

	return avgValue;
}

/*
 * We wait here for a rising or falling edge.
 * */
bool SCN_CaptureEdge(){

	uint32_t valuesBuf[measurementsBufferSize];
	uint32_t Value = 0;
	static uint32_t averageValue = 0;
	uint32_t oldValue = 0;
	uint8_t arrayCounter;
	uint8_t i;

	bool edgeCaptured = FALSE;

	for (arrayCounter = 0; arrayCounter <= (measurementsBufferSize-1); arrayCounter++){ // fill the array with the first 10 values
		valuesBuf[arrayCounter] = SCN_GetValue();
		RTOS_Wait(waitBetweenMeasurementsMS);
	}

	arrayCounter = 0;

	do{
		valuesBuf[arrayCounter] = SCN_GetValue();
		RTOS_Wait(waitBetweenMeasurementsMS);

		/* calculate the average */
		Value = 0;
		for (i = 0; i <= (measurementsBufferSize-1); i++){
			Value = Value + valuesBuf[i];
		}
		averageValue = Value / measurementsBufferSize;

		if (averageValue > 0xffff || averageValue < 15000){ // filtering all the high picks
			averageValue = oldValue;
		}
		oldValue = averageValue;

		/* detect an edge */
		if (valuesBuf[arrayCounter] <= (percentFallingEdge * averageValue) || valuesBuf[arrayCounter] >= (percentRisingEdge * averageValue)){ // if the average value is changing more than +-20% we decide to see an edge
			edgeCaptured = TRUE;
		}

		if (arrayCounter >= (measurementsBufferSize-1)){
			arrayCounter = 0;
		} else{
			arrayCounter++;
		}

		if (motionController.step_count_container > 2500){ // when we do not recognize an edge within 30 cm we return to observant
			break;
		}

	} while(!edgeCaptured);

	return edgeCaptured;
}

/*
 * Returns TRUE if we recognized a container. At the moment we do our decision only with the length of the Object.
 * */
bool SCN_IsAContainer(){
	bool isAContainer = FALSE;

	motionController.step_count_container = 0;

	if (SCN_CaptureEdge()){

		LED_GREEN_On();

		// reset step count
		motionController.step_count_container = 0;

		if (SCN_CaptureEdge()){

			LED_GREEN_Off();
			// compare step count
			if (motionController.step_count_container >= containerLengthMinSteps && motionController.step_count_container <= containerLengthMaxSteps){
				isAContainer = TRUE;
				LED_GREEN_Off();
			}
		}
	}
	return isAContainer;
}

/*
 * Functions for the bluetooth interface
 * */
static void SCN_PrintStatus(const BLUETOOTH_StdIOType *io) {
	BLUETOOTH_SendStatusStr((unsigned char*)"\r\nscn", (unsigned char*)"\r\n", io->stdOut);
	BLUETOOTH_SendStatusStr((unsigned char*)"  IR value", (unsigned char*)"", io->stdOut);
	BLUETOOTH_SendNum32s(SCN_GetValue(), io->stdOut);
	BLUETOOTH_SendStr((unsigned char*)"\r\n", io->stdOut);
}
static void SCN_PrintHelp(const BLUETOOTH_StdIOType *io) {
	BLUETOOTH_SendHelpStr((unsigned char*)"scn", (unsigned char*)"Group of scn commands\r\n", io->stdOut);
	BLUETOOTH_SendHelpStr((unsigned char*)"  help|status", (unsigned char*)"Shows scn help or status\r\n", io->stdOut);
}
uint8_t SCN_ParseCommand(const uint8_t *cmd, bool *handled, BLUETOOTH_ConstStdIOType *io){

	uint8_t res = ERR_OK;

	if (UTIL1_strcmp((char*)cmd, (char*)BLUETOOTH_CMD_HELP)==0 || UTIL1_strcmp((char*)cmd, (char*)"scn help")==0) {
		SCN_PrintHelp(io);
		*handled = TRUE;
	} else if (UTIL1_strcmp((char*)cmd, (char*)BLUETOOTH_CMD_STATUS)==0 || UTIL1_strcmp((char*)cmd, (char*)"scn status")==0) {
		SCN_PrintStatus(io);
		*handled = TRUE;
	}

	return res;
}


text:
""" Test tools module """
from __future__ import division, print_function

import os
import shutil
import stat
import subprocess
import sys
from os.path import dirname
from os.path import join as pjoin

import pytest

from ..tmpdirs import InTemporaryDirectory
from ..tools import (
    add_rpath,
    back_tick,
    chmod_perms,
    cmp_contents,
    dir2zip,
    ensure_permissions,
    ensure_writable,
    find_package_dirs,
    get_archs,
    lipo_fuse,
    parse_install_name,
    replace_signature,
    set_install_id,
    set_install_name,
    unique_by_index,
    validate_signature,
    zip2dir,
)
from .pytest_tools import assert_equal, assert_false, assert_raises, assert_true
from .test_install_names import LIBSTDCXX

DATA_PATH = pjoin(dirname(__file__), "data")
LIBM1 = pjoin(DATA_PATH, "libam1.dylib")
LIBM1_ARCH = pjoin(DATA_PATH, "libam1-arch.dylib")
LIB64 = pjoin(DATA_PATH, "liba.dylib")
LIBBOTH = pjoin(DATA_PATH, "liba_both.dylib")
LIB64A = pjoin(DATA_PATH, "liba.a")
ARCH_64 = frozenset(["x86_64"])
ARCH_M1 = frozenset(["arm64"])
ARCH_BOTH = ARCH_64 | ARCH_M1
ARCH_32 = frozenset(["i386"])

@pytest.mark.filterwarnings("ignore:back_tick is deprecated")
def test_back_tick() -> None:
    cmd = '''python -c "print('Hello')"'''
    assert back_tick(cmd) == "Hello"
    assert back_tick(cmd, ret_err=True) == ("Hello", "")
    assert back_tick(cmd, True, False) == (b"Hello", b"")
    with pytest.raises(RuntimeError):
        back_tick('python -c "raise ValueError()"')

def test_uniqe_by_index():
    assert_equal(unique_by_index([1, 2, 3, 4]), [1, 2, 3, 4])
    assert_equal(unique_by_index([1, 2, 2, 4]), [1, 2, 4])
    assert_equal(unique_by_index([4, 2, 2, 1]), [4, 2, 1])

    def gen():
        yield 4
        yield 2
        yield 2
        yield 1

    assert_equal(unique_by_index(gen()), [4, 2, 1])

@pytest.mark.xfail(sys.platform == "win32", reason="Needs chmod.")
def test_ensure_permissions():
    # Test decorator to ensure permissions
    with InTemporaryDirectory():
        # Write, set zero permissions
        sts = {}
        for fname, contents in (
            ("test.read", "A line\n"),
            ("test.write", "B line"),
        ):
            with open(fname, "wt") as fobj:
                fobj.write(contents)
            os.chmod(fname, 0)
            sts[fname] = chmod_perms(fname)

        def read_file(fname):
            with open(fname, "rt") as fobj:
                contents = fobj.read()
            return contents

        fixed_read_file = ensure_permissions(stat.S_IRUSR)(read_file)
        non_read_file = ensure_permissions(stat.S_IWUSR)(read_file)

        def write_file(fname, contents):
            with open(fname, "wt") as fobj:
                fobj.write(contents)

        fixed_write_file = ensure_permissions(stat.S_IWUSR)(write_file)
        non_write_file = ensure_permissions(stat.S_IRUSR)(write_file)

        # Read fails with default, no permissions
        assert_raises(IOError, read_file, "test.read")
        # Write fails with default, no permissions
        assert_raises(IOError, write_file, "test.write", "continues")
        # Read fails with wrong permissions
        assert_raises(IOError, non_read_file, "test.read")
        # Write fails with wrong permissions
        assert_raises(IOError, non_write_file, "test.write", "continues")
        # Read succeeds with fixed function
        assert_equal(fixed_read_file("test.read"), "A line\n")
        # Write fails, no permissions
        assert_raises(IOError, non_write_file, "test.write", "continues")
        # Write succeeds with fixed function
        fixed_write_file("test.write", "continues")
        assert_equal(fixed_read_file("test.write"), "continues")
        # Permissions are as before
        for fname, st in sts.items():
            assert_equal(chmod_perms(fname), st)

@pytest.mark.xfail(sys.platform == "win32", reason="Needs chmod.")
def test_ensure_writable():
    # Test ensure writable decorator
    with InTemporaryDirectory():
        with open("test.bin", "wt") as fobj:
            fobj.write("A line\n")
        # Set to user rw, else r
        os.chmod("test.bin", 0o644)
        st = os.stat("test.bin")

        @ensure_writable
        def foo(fname):
            pass

        foo("test.bin")
        assert_equal(os.stat("test.bin"), st)
        # No-one can write
        os.chmod("test.bin", 0o444)
        st = os.stat("test.bin")
        foo("test.bin")
        assert_equal(os.stat("test.bin"), st)

def test_parse_install_name() -> None:
    # otool on versions previous to Catalina
    line0 = (
        "/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore "
        "(compatibility version 1.2.0, current version 1.11.0)"
    )
    name, cpver, cuver = (
        "/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore",
        "1.2.0",
        "1.11.0",
    )
    assert parse_install_name(line0) == (name, cpver, cuver)
    # otool on Catalina
    line1 = (
        "/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore "
        "(compatibility version 1.2.0, current version 1.11.0, weak)"
    )
    assert parse_install_name(line1) == (name, cpver, cuver)

    # Test bad input.
    with pytest.raises(ValueError, match="Could not parse.*bad-str"):
        parse_install_name("bad-str")

def _write_file(filename, contents):
    with open(filename, "wt") as fobj:
        fobj.write(contents)

@pytest.mark.xfail(sys.platform == "win32", reason="Needs unzip.")
def test_zip2():
    # Test utilities to unzip and zip up
    with InTemporaryDirectory():
        os.mkdir("a_dir")
        os.mkdir("zips")
        _write_file(pjoin("a_dir", "file1.txt"), "File one")
        s_dir = pjoin("a_dir", "s_dir")
        os.mkdir(s_dir)
        _write_file(pjoin(s_dir, "file2.txt"), "File two")
        zip_fname = pjoin("zips", "my.zip")
        dir2zip("a_dir", zip_fname)
        zip2dir(zip_fname, "another_dir")
        assert_equal(os.listdir("another_dir"), ["file1.txt", "s_dir"])
        assert_equal(os.listdir(pjoin("another_dir", "s_dir")), ["file2.txt"])
        # Try zipping from a subdirectory, with a different extension
        dir2zip(s_dir, "another.ext")
        # Remove original tree just to be sure
        shutil.rmtree("a_dir")
        zip2dir("another.ext", "third_dir")
        assert_equal(os.listdir("third_dir"), ["file2.txt"])
        # Check permissions kept in zip unzip cycle
        os.mkdir("a_dir")
        permissions = stat.S_IRUSR | stat.S_IWGRP | stat.S_IXGRP
        fname = pjoin("a_dir", "permitted_file")
        _write_file(fname, "Some script or something")
        os.chmod(fname, permissions)
        dir2zip("a_dir", "test.zip")
        zip2dir("test.zip", "another_dir")
        out_fname = pjoin("another_dir", "permitted_file")
        assert_equal(os.stat(out_fname).st_mode & 0o777, permissions)

def test_find_package_dirs():
    # Test utility for finding package directories
    with InTemporaryDirectory():
        os.mkdir("to_test")
        a_dir = pjoin("to_test", "a_dir")
        b_dir = pjoin("to_test", "b_dir")
        c_dir = pjoin("to_test", "c_dir")
        for dir in (a_dir, b_dir, c_dir):
            os.mkdir(dir)
        assert_equal(find_package_dirs("to_test"), set([]))
        _write_file(pjoin(a_dir, "__init__.py"), "# a package")
        assert_equal(find_package_dirs("to_test"), {a_dir})
        _write_file(pjoin(c_dir, "__init__.py"), "# another package")
        assert_equal(find_package_dirs("to_test"), {a_dir, c_dir})
        # Not recursive
        assert_equal(find_package_dirs("."), set())
        _write_file(pjoin("to_test", "__init__.py"), "# base package")
        # Also - strips '.' for current directory
        assert_equal(find_package_dirs("."), {"to_test"})

def test_cmp_contents():
    # Binary compare of filenames
    assert_true(cmp_contents(__file__, __file__))
    with InTemporaryDirectory():
        with open("first", "wb") as fobj:
            fobj.write(b"abc\x00\x10\x13\x10")
        with open("second", "wb") as fobj:
            fobj.write(b"abc\x00\x10\x13\x11")
        assert_false(cmp_contents("first", "second"))
        with open("third", "wb") as fobj:
            fobj.write(b"abc\x00\x10\x13\x10")
        assert_true(cmp_contents("first", "third"))
        with open("fourth", "wb") as fobj:
            fobj.write(b"abc\x00\x10\x13\x10\x00")
        assert_false(cmp_contents("first", "fourth"))

@pytest.mark.xfail(sys.platform != "darwin", reason="Needs lipo.")
def test_get_archs_fuse():
    # Test routine to get architecture types from file
    assert_equal(get_archs(LIBM1), ARCH_M1)
    assert_equal(get_archs(LIBM1_ARCH), ARCH_M1)
    assert_equal(get_archs(LIB64), ARCH_64)
    assert_equal(get_archs(LIB64A), ARCH_64)
    assert_equal(get_archs(LIBBOTH), ARCH_BOTH)
    assert_raises(RuntimeError, get_archs, "not_a_file")
    with InTemporaryDirectory():
        lipo_fuse(LIBM1, LIB64, "anotherlib")
        assert_equal(get_archs("anotherlib"), ARCH_BOTH)
        lipo_fuse(LIBM1, LIB64, "anotherlib++")
        assert_equal(get_archs("anotherlib++"), ARCH_BOTH)
        lipo_fuse(LIB64, LIBM1, "anotherlib")
        assert_equal(get_archs("anotherlib"), ARCH_BOTH)
        shutil.copyfile(LIBM1, "libcopym1")
        lipo_fuse("libcopym1", LIB64, "anotherlib")
        assert_equal(get_archs("anotherlib"), ARCH_BOTH)
        assert_raises(RuntimeError, lipo_fuse, "libcopym1", LIBM1, "yetanother")
        shutil.copyfile(LIB64, "libcopy64")
        assert_raises(RuntimeError, lipo_fuse, "libcopy64", LIB64, "yetanother")

@pytest.mark.xfail(sys.platform != "darwin", reason="Needs codesign.")
def test_validate_signature() -> None:
    # Fully test the validate_signature tool
    def check_signature(filename: str) -> None:
        """Raises CalledProcessError if the signature can not be verified."""
        subprocess.run(["codesign", "--verify", filename], check=True)

    with InTemporaryDirectory():
        # Copy a binary file to test with, any binary file would work
        shutil.copyfile(LIBBOTH, "libcopy")

        # validate_signature does not add missing signatures
        validate_signature("libcopy")

        # codesign should raise an error (missing signature)
        with pytest.raises(subprocess.CalledProcessError):
            check_signature("libcopy")

        replace_signature("libcopy", "-")  # Force this file to be signed
        validate_signature("libcopy")  # Cover the `is already valid` code path

        check_signature("libcopy")  # codesign now accepts the file

        # Alter the contents of this file, this will invalidate the signature
        add_rpath("libcopy", "/dummy/path", ad_hoc_sign=False)

        # codesign should raise a new error (invalid signature)
        with pytest.raises(subprocess.CalledProcessError):
            check_signature("libcopy")

        validate_signature("libcopy")  # Replace the broken signature
        check_signature("libcopy")

        # Alter the contents of this file, check that by default the file
        # is signed with an ad-hoc signature
        add_rpath("libcopy", "/dummy/path2")
        check_signature("libcopy")

        set_install_id("libcopy", "libcopy-name")
        check_signature("libcopy")

        set_install_name("libcopy", LIBSTDCXX, "/usr/lib/libstdc++.7.dylib")
        check_signature("libcopy")

        # check that altering the contents without ad-hoc sign invalidates
        # signatures
        set_install_id("libcopy", "libcopy-name2", ad_hoc_sign=False)
        with pytest.raises(subprocess.CalledProcessError):
            check_signature("libcopy")

        set_install_name(
            "libcopy",
            "/usr/lib/libstdc++.7.dylib",
            "/usr/lib/libstdc++.8.dylib",
            ad_hoc_sign=False,
        )
        with pytest.raises(subprocess.CalledProcessError):
            check_signature("libcopy")


text:
/*
*      _______                       _____   _____ _____
*     |__   __|                     |  __ \ / ____|  __ \
*        | | __ _ _ __ ___  ___  ___| |  | | (___ | |__) |
*        | |/ _` | '__/ __|/ _ \/ __| |  | |\___ \|  ___/
*        | | (_| | |  \__ \ (_) \__ \ |__| |____) | |
*        |_|\__,_|_|  |___/\___/|___/_____/|_____/|_|
*
* -------------------------------------------------------------
*
* TarsosDSP is developed by Joren Six at IPEM, University Ghent
*
* -------------------------------------------------------------
*
*  Info: http://0110.be/tag/TarsosDSP
*  Github: https://github.com/JorenSix/TarsosDSP
*  Releases: http://0110.be/releases/TarsosDSP/
*
*  TarsosDSP includes modified source code by various authors,
*  for credits and info, see README.
*
*/

package be.tarsos.dsp.io;

import java.io.InputStream;

import be.tarsos.dsp.util.AudioResourceUtils;

/**
 * An audio file can be used to convert and read from. It uses libAV to convert
 * about any audio format to a one channel PCM stream of a chosen sample rate. There is
 * support for movie files as well, the first audio channel is then used as input.
 * The resource is either a local file or a type of stream supported by libAV (e.g. HTTP streams);
 *
 * For a list of audio decoders the following command is practical:
 * <pre>
avconv -decoders | grep -E "^A" | sort

A... 8svx_exp             8SVX exponential
A... 8svx_fib             8SVX fibonacci
A... aac                  AAC (Advanced Audio Coding)
A... aac_latm             AAC LATM (Advanced Audio Coding LATM syntax)
...
 * </pre>
 */
public class PipedAudioStream {

	//private final static Logger LOG = Logger.getLogger(PipedAudioStream.class.getName());

	private final String resource;
	private static PipeDecoder pipeDecoder = new PipeDecoder();

	public static void setDecoder(PipeDecoder decoder){
		pipeDecoder = decoder;
	}

	private final PipeDecoder decoder;
	public PipedAudioStream(String resource){
		this.resource = AudioResourceUtils.sanitizeResource(resource);
		decoder = pipeDecoder;
	}

	/**
	 * Return a one channel, signed PCM stream of audio of a defined sample rate.
	 * @param targetSampleRate The target sample stream.
	 * @return An audio stream which can be used to read samples from.
	 */
	public TarsosDSPAudioInputStream getMonoStream(int targetSampleRate){
		InputStream stream = null;
		stream = decoder.getDecodedStream(resource, targetSampleRate);
		return new UniversalAudioInputStream(stream, getTargetFormat(targetSampleRate));
	}

	private TarsosDSPAudioFormat getTargetFormat(int targetSampleRate){
		return new TarsosDSPAudioFormat(targetSampleRate, 16, 1, true, false);
	}
}