text:
<?xml version="1.0" encoding="utf-8"?>

<!--

This is one of the layouts contained in the "tweet_fragment" xml

This one holds the actual tweet information.

NOTE: Change it how you want, you don't actually have to keep it in a separate xml file if it makes more sense without.
I just do it this way to organize better. As long as you have the same elements and ID's in the tweet_fragment xml, it
will work the exact same

-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/background"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

    <!-- Tweet's Content -->
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

        <!-- Tweet's Content -->
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingBottom="10dp"
                android:paddingTop="20dp">

            <TextView
                    android:id="@+id/tweet"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:fontFamily="sans-serif-light"
                    android:textStyle="bold"
                    android:textSize="18sp"
                    android:textIsSelectable="true"
                    android:textColor="@color/textColor" />

            <TextView
                    android:id="@+id/time"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:layout_marginTop="16dp"
                    android:textSize="14sp"
                    android:fontFamily="sans-serif-light"
                    android:background="@drawable/pressed_button"
                    android:textColor="@color/textColor"
                    android:alpha=".6"/>

            <TextView
                    android:id="@+id/retweeter"
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:textSize="14sp"
                    android:fontFamily="sans-serif-light"
                    android:textColor="@color/textColor"
                    android:visibility="gone"
                    android:alpha=".6"/>

        </LinearLayout>

        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:orientation="horizontal"
                      android:paddingLeft="15dp"
                      android:paddingRight="15dp"
                      android:paddingBottom="16dp">

            <LinearLayout android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:orientation="vertical"
                          android:id="@+id/favorite"
                          android:padding="12dp"
                          android:background="@drawable/pressed_button" >

                <TextView
                        android:id="@+id/favorite_text"
                        android:text="favorite"
                        android:textAllCaps="true"
                        android:textSize="14sp"
                        android:gravity="center"
                        android:textColor="@color/textColor"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>

                <TextView
                        android:layout_height="match_parent"
                        android:layout_width="match_parent"
                        android:textSize="13sp"
                        android:gravity="right"
                        android:textColor="@color/textColor"
                        android:fontFamily="sans-serif-light"
                        android:alpha=".6"
                        android:id="@+id/fav_count" />

            </LinearLayout>

            <View android:layout_width="8dp" android:layout_height="match_parent" />

            <LinearLayout android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:orientation="horizontal"
                          android:id="@+id/retweet"
                          android:background="@drawable/pressed_button">

                <LinearLayout android:layout_width="wrap_content"
                              android:layout_height="wrap_content"
                              android:orientation="vertical"
                              android:padding="12dp" >

                    <TextView
                            android:id="@+id/retweet_text"
                            android:text="retweet"
                            android:textAllCaps="true"
                            android:textSize="14sp"
                            android:gravity="center"
                            android:textColor="@color/textColor"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"/>

                    <TextView
                            android:layout_height="match_parent"
                            android:layout_width="match_parent"
                            android:textSize="13sp"
                            android:gravity="right"
                            android:textColor="@color/textColor"
                            android:fontFamily="sans-serif-light"
                            android:alpha=".6"
                            android:id="@+id/retweet_count" />

                </LinearLayout>

            </LinearLayout>

            <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" />

            <ImageButton
                    android:id="@+id/view_retweeters"
                    android:layout_width="48dp"
                    android:layout_height="match_parent"
                    android:contentDescription="Share"
                    android:minHeight="48dp" android:minWidth="48dp"
                    android:scaleType="fitCenter" android:adjustViewBounds="true"
                    android:maxWidth="48dp" android:maxHeight="48dp"
                    android:background="@drawable/pressed_button"
                    android:src="@drawable/ic_action_retweeters_dark"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


text:
#include "caf/locks.hpp"
#include "caf/actor_companion.hpp"

namespace caf {

actor_companion::actor_companion(actor_config& cfg) : extended_base(cfg) {
  // nop
}

actor_companion::~actor_companion() {
  // nop
}

void actor_companion::on_enqueue(enqueue_handler handler) {
  std::lock_guard<lock_type> guard(lock_);
  on_enqueue_ = std::move(handler);
}

void actor_companion::on_exit(on_exit_handler handler) {
  on_exit_ = std::move(handler);
}

void actor_companion::enqueue(mailbox_element_ptr ptr, execution_unit*) {
  CAF_ASSERT(ptr);
  shared_lock<lock_type> guard(lock_);
  if (on_enqueue_)
    on_enqueue_(std::move(ptr));
}

void actor_companion::enqueue(strong_actor_ptr src, message_id mid,
                              message content, execution_unit* eu) {
  auto ptr = make_mailbox_element(std::move(src), mid, {}, std::move(content));
  enqueue(std::move(ptr), eu);
}

void actor_companion::launch(execution_unit*, bool, bool hide) {
  if (!hide)
    register_at_system();
}

void actor_companion::on_exit() {
  enqueue_handler tmp;
  { // lifetime scope of guard
    std::lock_guard<lock_type> guard(lock_);
    on_enqueue_.swap(tmp);
  }
  if (on_exit_)
    on_exit_();
}

} // namespace caf

redpajama_set_name: RedPajamaGithub


text:
#ifndef NATIVE_CLIENT_TESTS_GC_INSTRUMENTATION_GC_INSTRUMENTATION_H_
#define NATIVE_CLIENT_TESTS_GC_INSTRUMENTATION_GC_INSTRUMENTATION_H_

extern __thread unsigned int thread_suspend_if_needed_count;

#endif /* NATIVE_CLIENT_TESTS_GC_INSTRUMENTATION_GC_INSTRUMENTATION_H_ */


text:
from src.Text.quiz import Question, Quiz, main

class TestQuizQuestion:
    def setup_method(self, method):
        self.question = Question("2 + 2", "4")

    def test_creation(self):
        assert isinstance(self.question, Question)

    def test_check_answer(self):
        assert self.question.check_answer("4")

    def test_check_answer_incorrect(self):
        assert not self.question.check_answer("53")

class TestQuiz:
    def setup_method(self, method):
        self.question_set = [
            {"question": "2+2", "answer": "4"},
            {"question": "1+1", "answer": "2"},
        ]

    def test_creation(self):
        quiz = Quiz(self.question_set)
        assert isinstance(quiz, Quiz)

def test_game_loop(mocker):
    mocker.patch.object(Quiz, "_create_questions", autospec=True)
    mocker.patch("builtins.input", lambda x: "4")
    Quiz._create_questions.return_value = [Question("2+2", "4")]
    main(debug=False)

def test_game_loop_wrong_answer(mocker):
    mocker.patch.object(Quiz, "_create_questions", autospec=True)
    mocker.patch("builtins.input", lambda x: "5")
    Quiz._create_questions.return_value = [Question("2+2", "4")]
    main(debug=True)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fl. Analyt. Champ. Supér. (Paris) 58 (1953)

#### Original name
Hygrophorus eburneus var. carneipes Kühner

### Remarks
null


text:
layout: "page"
title: Oops! You're lost!
published: true
---

Let's go back to the [homepage](/) .

<script>plausible("404",{ props: { path: document.location.pathname } });</script>


text:
[![Build Status](https://travis-ci.org/diegocfreire/DCFSQLite.svg?branch=master)](https://travis-ci.org/diegocfreire/DCFSQLite)

DCFSQLite
=========

DCFSQLite - Library for easy access, execution of commands and queries in mobile iOS applications using SQLite.

BEFORE
======
You need to import SQLite3 framework.
Frameworks-> Add existing framework->libsql3.dylib

## HOW TO USE
	# import "DCFSQLite.h"

	//Init database
	[DCFSQLite initDB:@"myapp.db"];

	// To create, insert, update and delete
	BOOL ok = [DCFSQLite execSQL:@"INSERT INTO Customer (name, email) VALUES ('Diego', 'diegocfreire@gmail.com')"];

	//OR
	BOOL ok = [DCFSQLite execSQL:@"INSERT INTO Customer (name, email) VALUES (?, ?)", @"Diego", @"diegocfreire@gmail.com"];

	//For get result queryes
	NSArray *qryResult = [DCFSQLite getRows:@"SELECT * FROM Customer"];


text:
package org.jetbrains.plugins.ipnb.format.cells.output;

import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Map;

public class IpnbPngOutputCell extends IpnbImageOutputCell {

  public IpnbPngOutputCell(@Nullable final String png, @Nullable final List<String> text, @Nullable final Integer prompt,
                           @Nullable Map<String, Object> metadata) {
    super(png, text, prompt, metadata);
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2020. Axon Framework
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.axonframework</groupId>
        <artifactId>axon</artifactId>
        <version>4.5-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>axon-spring</artifactId>

    <name>Axon Framework Spring Support</name>
    <description>
        Module providing Spring specific helper functionality to ease configuration / set-up of an Axon application, as
        well as some Spring specific infrastructure components.
    </description>

    <packaging>bundle</packaging>

    <dependencies>
        <dependency>
            <groupId>org.axonframework</groupId>
            <artifactId>axon-configuration</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.eaio.uuid</groupId>
            <artifactId>uuid</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- explicitly define transitive dependencies to increase version priority -->
        <!-- see https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Transitive_Dependencies -->
        <dependency>
            <groupId>org.axonframework</groupId>
            <artifactId>axon-eventsourcing</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.axonframework</groupId>
            <artifactId>axon-modelling</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.axonframework</groupId>
            <artifactId>axon-messaging</artifactId>
            <version>${project.version}</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Automatic-Module-Name>org.axonframework.spring</Automatic-Module-Name>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>${felix.bundle.plugin.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Bundle-Description>${project.description}</Bundle-Description>
                        <Bundle-Version>${project.version}</Bundle-Version>
                        <Export-Package>
                            org.axonframework.spring.*
                        </Export-Package>
                        <Import-Package>
                            org.slf4j.*,
                            *;resolution:=optional
                        </Import-Package>
                    </instructions>
                </configuration>
                <executions>
                    <!-- This execution makes sure that the manifest is available when the tests are executed -->
                    <execution>
                        <goals>
                            <goal>manifest</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
require 'casespace_helper'
require_test_helper_files('../timetable/helpers')
Test::Casespace::Seed.load(config: :timetable)


text:
layout: sidebar-right
title: Music at Latitude 2016
date: 2016-06-17 09:08:00+00:00
author: brandon-king
category: articles
excerpt: Latitude Festival is held at Henham Park, Southwold on 14-17 July 2016.
breadcrumb: articles
---
![Latitude 2016 excerpt from their official poster](/images/featured/featured-latitude-2016.jpg)

Latitude Festival runs from 14 - 17 July 2016 at Henham Park near Southwold. As ever there is a full programme of music. If you enjoy the music or you want to check out a band in advance why not borrow some of these titles from your local library?

Marks to prove it by Maccabees

Indie rock from the rapidly rising Londoners who will soon be performing at a stadium near you.

No no no by Beirut

Front man Zach Condon has an instantly recognisable sound. If you want your fix of rotary valve flugelhorn and the ukulele this is the place to come.

I love you, honeybear by Father John Misty

Former Fleet Foxes drummer promotes the album widely rated as one of the best of 2015.

Sometimes I sit and think, and sometimes I just sit by Courtney Barnett

Australian indie singer with her widely praised debut album.

Second love by Emmy the Great

Indie pop from the London born singer/journalist.

High Violet by The National

One of the headliners for this year. Four of the band's albums were included on NME's 2013 list of the 500 greatest albums of all time.

Every open eye by CHVRCHES

Second album by the Scottish synthpop band. Follow-up to their critically acclaimed debut album, The Bones of What You Believe.

Grey tickles, black pressure by John Grant

Third album by former Czars frontman John Grant. Widely acclaimed as one of the albums of 2015.

Not to disappear by Daughter

Alt pop band. You will recognise a lot of their music from TV drama soundtracks.

Cradle to the grave by Squeeze

Any new record from Difford and Tilbrook is a treat. This was their first new material for some years.

Nathaniel Rateliff and The Night Sweats by Nathaniel Rateliff and The Night Sweats

Contains popular single S.O.B. You may have seen them already on Later with Jools Holland.

Complete music by New Order

Another of the headliners this year. New Order were one of the most critically acclaimed and influential bands of the 1980s.

Cleopatra by The Lumineers

Indie folk which should play well with the festival crowd.

The dreaming room by Laura Mvula

Second album to follow the well received Sing to the Moon.

 by

Rising star who will be opening for Florence & the Machine this year.

Are you satisfied? by Slaves

Play loud.

 by

American indie. Don't be surprised if the band end up in the audience.

Chaleur humaine by Christine And The Queens

French singer/songwriter. Her work combines music, performance, art videos, drawings and photography.

Long way home by Låpsley

One of the acts on the BBC Sound of... 2015 long list. Long way home is her first album.

B'lieve I'm goin' (deep) down... by Kurt Vile

Influenced by Pavement, Springsteen and Neil Young. Kurt Vile is a critically acclaimed songwriter.

Beneath the skin by Of Monsters and Men

Icelandic indie folk pop. This is the follow up to their massive hit album My Head Is an Animal, which contained the hit single Little talks.

In Search of Harperfield by Emma Pollock

The third solo outing from the ex-Delgados vocalist, In Search of Harperfield is Emma Pollock's most revealing and adventurous set of songs to date.


text:
Sequel.migration do
  up do
    alter_table :chief_tame do
      rename_column :qta_elig_useLstrubg, :qta_elig_use
    end
  end

  down do
    alter_table :chief_tame do
      rename_column :qta_elig_use, :qta_elig_useLstrubg
    end
  end
end


text:
import {KeyValueListData} from 'app/components/events/interfaces/keyValueList/types';
import {getMeta} from 'app/components/events/meta/metaProxy';
import {AvatarUser as UserType} from 'app/types';
import {defined} from 'app/utils';

import getUserKnownDataDetails from './getUserKnownDataDetails';
import {UserKnownDataType} from './types';

function getUserKnownData(
  data: UserType,
  userKnownDataValues: Array<UserKnownDataType>
): Array<KeyValueListData> {
  const knownData: Array<KeyValueListData> = [];

  const dataKeys = userKnownDataValues.filter(userKnownDataValue =>
    defined(data[userKnownDataValue])
  );

  for (const key of dataKeys) {
    const knownDataDetails = getUserKnownDataDetails(data, key as UserKnownDataType);
    if ((knownDataDetails && !defined(knownDataDetails.value)) || !knownDataDetails) {
      continue;
    }
    knownData.push({
      key,
      ...knownDataDetails,
      meta: getMeta(data, key),
      subjectDataTestId: `user-context-${key.toLowerCase()}-value`,
    });
  }
  return knownData;
}

export default getUserKnownData;


text:
INSERT INTO t1(rowid, content)
VALUES(2, 'abcdefghijklmnopqrstuvwyxz');
SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz'


text:
function upcoming_trains_listMaker(body){
    return new Promise(function (resolve,reject) {
        all_upcoming_train_list=[];
        if(body.total!=0) {
            //    body.train.forEach(function (train) {
            all_upcoming_train_list=body.train;
            //   })
        }else{
            reject("No Upcoming Trains in Next 4 hrs!!!");
        }
        //console.log("These are all upcoming Trains :"+JSON.stringify(all_upcoming_train_list));
        resolve(all_upcoming_train_list);
    });

}
function upcoming_trains_for_Destination() {
    livestationstatus(sourcedetails.code,4).then(function (body) {
        //console.log(body);
        //console.log(JSON.stringify(body));
        return upcoming_trains_listMaker(body);
    },function (error) {
        //console.log("Problem :"+error);
    }).then(function (all_Upcoming_train_list) {
        var intersection_upcoming=_.intersectionBy(all_Upcoming_train_list,all_train_list,"number");
        //console.log(intersection_upcoming);
        var heading=false;
        $(".table").removeClass("table-striped");
        $(".table").addClass("table-condensed");
        intersection_upcoming.forEach(function (train) {
            var id="."+train.number;
            if(heading==false){
                $(id).attr("id","section1");
                heading=true;
            }
            if(train.delaydep!="RT") {
                $(id).find("#actdep").html("<span strong style='color: red'>" + train.actdep + " </span>");
                $(id).find("#delaytime").html("<span strong style='color: red'>" + train.delaydep + " hrs </span>");
            }else{
                $(id).find("#actdep").html("<span strong style='color:navy'>" + train.actdep + " </span>");
                $(id).find("#delaytime").html("<span strong style='color: navy'>" + train.delaydep + " </span>");
            }
            $(id).css('backgroundColor','#fff9c4 ');
        });

        $('#scroll span').trigger('click');

    }).catch(function (error) {
        //console.log("error :"+error);
    });
}
/**
 * Created by kamlesh on 1/29/2017.
 */


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>JessicaWhite | professional fashion photography</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link href="css/prettyPhoto.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/theme.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<link href="css/docs.css" rel="stylesheet">
<link href="js/google-code-prettify/prettify.css" rel="stylesheet">

<link
	href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600'
	rel='stylesheet' type='text/css'>

Facebook

Vimeo

Tumbrl

Twitter

Delicious

Home

About

Features

-Scaffolding

-Typography

-Shortcodes

-Tables

Portfolio

-2
														Columns

-3
														Columns

-4
														Columns

Blog

-Blog with
														right sidebar

-Blog
														post

Contacts

					Home/Typography

							Typography Headings, paragraphs,
									lists, and other inline type elements

Typographic scale

								The entire typographic grid is based on two Less variables in
								our variables.less file:
								@baseFontSize
								and
								@baseLineHeight
								. The first is the base font-size used throughout and the second
								is the base line-height.

We use those variables, and some math, to create the
								margins, paddings, and line-heights of all our type and more.

Example body text

Nullam quis risus eget urna mollis ornare vel eu leo. Cum
								sociis natoque penatibus et magnis dis parturient montes,
								nascetur ridiculus mus. Nullam id dolor id nibh ultricies
								vehicula ut id elit.

Vivamus sagittis lacus vel augue laoreet rutrum faucibus
								dolor auctor. Duis mollis, est non commodo luctus, nisi erat
								porttitor ligula, eget lacinia odio sem nec elit. Donec sed odio
								dui.

h1. Heading 1

h2. Heading 2

h3. Heading 3

h4. Heading 4

h5. Heading 5

h6. Heading 6

Emphasis, address, and abbreviation

								Element
								Usage
								Optional

								<strong>
								For emphasizing a snippet of text with important

								None

								<em>
								For emphasizing a snippet of text with stress

								None

								<abbr>
								Wraps abbreviations and acronyms to show the expanded
									version on hover

										Include optional
										title
										attribute for expanded text

 Use .initialism class for uppercase
									abbreviations.

								<address>
								For contact information for its nearest ancestor or the
									entire body of work
								Preserve formatting by ending all lines with <br>

Using emphasis

								Fusce dapibus, tellus ac cursus
									commodo, tortor mauris condimentum nibh, ut fermentum
								massa justo sit amet risus. Maecenas faucibus mollis interdum.
								Nulla vitae elit libero, a pharetra augue.

								Note: Feel free to use
								<b>
								and
								<i>
								in HTML5, but their usage has changed a bit.
								<b>
								is meant to highlight words or phrases without conveying
								additional importance while
								<i>
								is mostly for voice, technical terms, etc.

Example addresses

								Here are two examples of how the
								<address>
								tag can be used:

							<address>
								Twitter, Inc.
 795 Folsom Ave, Suite
								600
 San Francisco, CA 94107
 P: (123) 456-7890
							</address>
							<address>
								Full Name
 first.last@gmail.com
							</address>

Example abbreviations

								Abbreviations with a
								title
								attribute have a light dotted bottom border and a help cursor on
								hover. This gives users extra indication something will be shown
								on hover.

								Add the
								initialism
								class to an abbreviation to increase typographic harmony by
								giving it a slightly smaller text size.

								HTML
								is the best thing since sliced bread.

								An abbreviation of the word attribute is attr.

Blockquotes

								Element
								Usage
								Optional

								<blockquote>
								Block-level element for quoting content from another
									source

										Add
										cite
										attribute for source URL

 Use .pull-left and .pull-right
									classes for floated options

								<small>
								Optional element for adding a user-facing citation,
									typically an author with title of work
								Place the <cite> around the title or
									name of source

								To include a blockquote, wrap
								<blockquote>
								around any HTML
								as the quote. For straight quotes we recommend a
								<p>
								.

								Include an optional
								<small>
								element to cite your source and you'll get an em dash
								&mdash;
								before it for styling purposes.

<blockquote>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante venenatis.</p>
  <small>Someone famous</small>
</blockquote>

Example blockquotes

Default blockquotes are styled as such:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
									Integer posuere erat a ante venenatis.

								Someone famous in Body of
										work

								To float your blockquote to the right, add
								class="pull-right"
								:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
									Integer posuere erat a ante venenatis.

								Someone famous in Body of
										work

Lists

Unordered

								<ul>

Lorem ipsum dolor sit amet

Consectetur adipiscing elit

Integer molestie lorem at massa

Facilisis in pretium nisl aliquet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Vestibulum laoreet porttitor sem

Ac tristique libero volutpat at

Faucibus porta lacus fringilla vel

Aenean sit amet erat nunc

Eget porttitor lorem

Unstyled

								<ul class="unstyled">

Lorem ipsum dolor sit amet

Consectetur adipiscing elit

Integer molestie lorem at massa

Facilisis in pretium nisl aliquet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Vestibulum laoreet porttitor sem

Ac tristique libero volutpat at

Faucibus porta lacus fringilla vel

Aenean sit amet erat nunc

Eget porttitor lorem

Ordered

								<ol>

Lorem ipsum dolor sit amet

Consectetur adipiscing elit

Integer molestie lorem at massa

Facilisis in pretium nisl aliquet

Nulla volutpat aliquam velit

Faucibus porta lacus fringilla vel

Aenean sit amet erat nunc

Eget porttitor lorem

Description

								<dl>

Description lists

A description list is perfect for defining terms.

Euismod

Vestibulum id ligula porta felis euismod semper eget
									lacinia odio sem nec elit.

Donec id elit non mi porta gravida at eget metus.

Malesuada porta

Etiam porta sem malesuada magna mollis euismod.

Horizontal description

								<dl class="dl-horizontal">

Description lists

A description list is perfect for defining terms.

Euismod

Vestibulum id ligula porta felis euismod semper eget
									lacinia odio sem nec elit.

Donec id elit non mi porta gravida at eget metus.

Malesuada porta

Etiam porta sem malesuada magna mollis euismod.

Latest tweets

Get in touch!

						<form action="#" method="post">
							<input class="span3" type="text" name="name" id="name"
								value="Name"
								onFocus="if (this.value == 'Name') this.value = '';"
								onBlur="if (this.value == '') this.value = 'Name';" /> <input
								class="span3" type="text" name="email" id="email" value="Email"
								onFocus="if (this.value == 'Email') this.value = '';"
								onBlur="if (this.value == '') this.value = 'Email';" />
							<textarea name="message" id="message" class="span3"
								onFocus="if (this.value == 'Message') this.value = '';"
								onBlur="if (this.value == '') this.value = 'Message';">Message</textarea>

							<input type="reset" class="btn dark_btn" value="Clear form" /> <input
								type="submit" class="btn send_btn" value="Send!" />

						</form>

Testimonials

Orci nisi,
								luctus vitae imperdiet a, iquam vel urna. Pellentesque tincidunt
								laoreet est, in tristique sapien consequat a purus at
								ullamcorper pulvinar, massa libero magna.

Anna Smith, Company inc.

Luctus vitae
								imperdiet a, iquamorci nisi lorem. Pellentesque tincidunt
								laoreet est, in tristique sapien consequat a purus at ullam
								pulvinar, massa libero consequat egestas mas.

John Doe, Company inc.

flickr photostream

© 2020 Jessica White.
								Professional Fashion Photography. All Rights Reserved.

									<form action="#" method="post">
										<input class="inp_search" name="name" type="text"
											value="Search the Site"
											onfocus="if (this.value == 'Search the Site') this.value = '';"
											onblur="if (this.value == '') this.value = 'Search the Site';" />
									</form>

Facebook

Twitter

Tumbrl

Vimeo

Delicious

Home

About

features

Portfolio

Blog

Contacts


text:
module.exports = thunkyp

function thunkyp (fn) {
  let running = null

  return ready

  function ready () {
    if (running) return running
    const p = fn()
    if (!(p instanceof Promise)) running = Promise.resolve(p)
    else running = p
    running.catch(onerror)
    return running
  }

  function onerror () {
    running = null
  }
}


text:
<?php
/*
* Multi shortener plugin for ajaXplorer by FrenandoAloso
*         based in bit.ly plugin
*/
$mess=array(
"multi URL Shortener" => "Verschiedene URL-Kürzungsdienste",
"Shorten Download Links before sending them back to the user." => "Links zum Herunterladen von Dateien vor dem Versand an Benutzer kürzen.",
"User ID" => "Benutzer ID",
"adF.ly account user ID. The numbers after -= ?id= =- in of your referral program's URL" => "adF.ly Benutzer ID.\nDie Zahl nach -= ?id= =- in der URL",
"API Key" => "API Key",
"adF.ly account API Key" => "adF.ly API Key",
"Type of ADS" => "Art der Werbung",
"Type of AD you like to show. Select Fullscreen AD or Top banner AD" => "Art der Werbung, die angezeigt werden soll.\n Wähle Vollbild oder Banner am oberen Bildschirmrand",
"Short domain" => "Kurze Domain",
"adF.ly or q.gs domains, select wich you like" => "Wähle entweder adF.ly oder q.gs Domain.",
"FullScreen" => "Vollbild",
"Banner" => "Banner",
"Bit.ly URL Shortener" => "Bit.ly URL-Kürzungsdienst",
"User Name" => "Benutzername",
"Bit.ly account user name" => "Benutzername bei Bit.ly",
"API Key" => "API Key",
"Bit.ly account API Key" => "Bit.ly API Key",
"Yourls domain" => "Eigene Domain",
"Use IDN" => "Internationalisierten Domainnamen verwenden (IDN)",
"Shorten type" => "Anbieter",
);


text:
package com.logginghub.utils.sof;

import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class StreamWriterAbstraction implements WriterAbstraction, Closeable {
    private DataOutputStream dos;

    public StreamWriterAbstraction(OutputStream stream) {
        dos = new DataOutputStream(stream);
    }

    public void writeShort(short value) throws IOException {
        dos.writeShort(value);
    }

    public void writeLong(long l) throws IOException {
        dos.writeLong(l);
    }

    public void writeFloat(float f) throws IOException {
        dos.writeFloat(f);
    }

    public void writeDouble(double d) throws IOException {
        dos.writeDouble(d);
    }

    public void writeChar(char c) throws IOException {
        dos.writeChar(c);
    }

    public void writeByte(byte type) throws IOException {
        dos.write(type);
    }

    public void writeBoolean(boolean b) throws IOException {
        dos.writeBoolean(b);
    }

    public void write(byte[] bytes) throws IOException {
        dos.write(bytes);
    }

    public void writeInt(int value) throws IOException {
        dos.writeInt(value);
    }

    public void writeUnsignedByte(int value) throws IOException {
        dos.write((byte) (0x000000ff & value));
    }

    public void writeUnsignedShort(int value) throws IOException {
        dos.writeShort((short) (0x0000ffff & value));
    }

    @Override public String toString() {
        return "StreamWriterAbstraction position=" + dos.size();
    }

    public int getPosition() {
        return dos.size();
    }

    public void writeBuffer(ByteBuffer tempBuffer) throws IOException {
        dos.write(tempBuffer.array(), tempBuffer.position(), tempBuffer.remaining());
    }

    public void write(byte[] value, int position, int length) throws IOException {
        dos.write(value, position, length);
    }

    public void close() throws IOException {
        dos.close();
    }

    public void flush() throws IOException {
        dos.flush();
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context=".MainActivity">

    <SurfaceView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/surfaceView"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignEnd="@+id/surfaceView" />
</RelativeLayout>


text:
package statistic

import (
  "fmt"
  "io/ioutil"
  "testing"
  "github.com/stretchr/testify/assert"

  "github.com/YanshuoH/douban-reading-stat/models"
  "github.com/YanshuoH/douban-reading-stat/lib/mock"
  "github.com/YanshuoH/douban-reading-stat/lib/api"
)

const (
  USERNAME = "2274326"
  USER_ASSET = `{"loc_id":"108288","name":"优","created":"2008-03-02 11:04:55","is_banned":false,"is_suicide":false,"loc_name":"北京","avatar":"https://img3.doubanio.com\/icon\/u2274326-10.jpg","signature":"一个被低级趣味拖住死缠烂打的人","uid":"2274326","alt":"http:\/\/www.douban.com\/people\/2274326\/","desc":"丑的真诚 (东北人研究学会)\n\n不谈政治了,门槛太低。","type":"user","id":"2274326","large_avatar":"https://img3.doubanio.com\/icon\/up2274326-10.jpg"}`
)

var Responses []string

// For the sake of my IDE, read file content instead of putting all response in const
func setup() {
  baseDir := "../mock/dataset"
  files, err := ioutil.ReadDir(baseDir)
  checkErr(err)

  dataArray := make([]string, len(files))

  for i, f := range files {
    relativePath := baseDir + "/" + f.Name()
    dat, err := ioutil.ReadFile(relativePath)
    checkErr(err)

    dataArray[i] = string(dat)
  }

  // Prepare books response mock
  for i, content := range dataArray {
    url := fmt.Sprintf(api.BOOK_COLLECTION_URL, USERNAME, (i * 100))
    mock.PrepareResponseMock(url, content)
  }

  // Prepare user response mock
  url := fmt.Sprintf(api.USER_URL, USERNAME)
  mock.PrepareResponseMock(url, USER_ASSET)
}

func TestStat(t *testing.T)  {
  setup()
  assert := assert.New(t)
  userData, _, _ := api.GetUser(USERNAME)
  userBookData, _, _ := api.GetUserBooks(USERNAME)
  user := models.CastApiToModel(userData, userBookData)

  // regroup by year
  result := Stat(user)
  assert.Equal(9, len(result), "Statistic", "Should divide to 9 groups")
  assert.Equal(4, result["2008"].Count, "Statistic", "Should have read 4 books in 2008")
  expectedRating := map[string]int{
    "1": 0,
    "2": 0,
    "3": 1,
    "4": 1,
    "5": 1,
  }
  assert.Equal(expectedRating, result["2008"].Rating, "Statistic", "Should have above rating statistic")
}


text:
#include "precomp.hpp"
using namespace cv;
using namespace cv::dnn;

#if HAVE_PROTOBUF
#include "caffe.pb.h"

#include <iostream>
#include <fstream>
#include <algorithm>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "caffe_io.hpp"

using ::google::protobuf::RepeatedField;
using ::google::protobuf::RepeatedPtrField;
using ::google::protobuf::Message;
using ::google::protobuf::Descriptor;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::Reflection;

namespace
{
    class CaffeImporter : public Importer
    {
        caffe::NetParameter net;
        caffe::NetParameter netBinary;

    public:

        CaffeImporter(const char *pototxt, const char *caffeModel)
        {
            ReadNetParamsFromTextFileOrDie(pototxt, &net);

            if (caffeModel && caffeModel[0])
                ReadNetParamsFromBinaryFileOrDie(caffeModel, &netBinary);
        }

        void addParam(const Message &msg, const FieldDescriptor *field, cv::dnn::LayerParams &params)
        {
            const Reflection *refl = msg.GetReflection();
            int type = field->cpp_type();
            bool isRepeated = field->is_repeated();
            const std::string &name = field->name();

            #define SET_UP_FILED(getter, arrayConstr, gtype)                                    \
                if (isRepeated) {                                                               \
                    const RepeatedField<gtype> &v = refl->GetRepeatedField<gtype>(msg, field);  \
                    params.set(name, DictValue::arrayConstr(v.begin(), (int)v.size()));                  \
                }                                                                               \
                else {                                                                          \
                    params.set(name, refl->getter(msg, field));                               \
                }

            switch (type)
            {
            case FieldDescriptor::CPPTYPE_INT32:
                SET_UP_FILED(GetInt32, arrayInt, ::google::protobuf::int32);
                break;
            case FieldDescriptor::CPPTYPE_UINT32:
                SET_UP_FILED(GetUInt32, arrayInt, ::google::protobuf::uint32);
                break;
            case FieldDescriptor::CPPTYPE_INT64:
                SET_UP_FILED(GetInt32, arrayInt, ::google::protobuf::int64);
                break;
            case FieldDescriptor::CPPTYPE_UINT64:
                SET_UP_FILED(GetUInt32, arrayInt, ::google::protobuf::uint64);
                break;
            case FieldDescriptor::CPPTYPE_BOOL:
                SET_UP_FILED(GetBool, arrayInt, bool);
                break;
            case FieldDescriptor::CPPTYPE_DOUBLE:
                SET_UP_FILED(GetDouble, arrayReal, double);
                break;
            case FieldDescriptor::CPPTYPE_FLOAT:
                SET_UP_FILED(GetFloat, arrayReal, float);
                break;
            case FieldDescriptor::CPPTYPE_STRING:
                if (isRepeated) {
                    const RepeatedPtrField<std::string> &v = refl->GetRepeatedPtrField<std::string>(msg, field);
                    params.set(name, DictValue::arrayString(v.begin(), (int)v.size()));
                }
                else {
                    params.set(name, refl->GetString(msg, field));
                }
                break;
            case FieldDescriptor::CPPTYPE_ENUM:
                if (isRepeated) {
                    int size = refl->FieldSize(msg, field);
                    std::vector<cv::String> buf(size);
                    for (int i = 0; i < size; i++)
                        buf[i] = refl->GetRepeatedEnum(msg, field, i)->name();
                    params.set(name, DictValue::arrayString(buf.begin(), size));
                }
                else {
                    params.set(name, refl->GetEnum(msg, field)->name());
                }
                break;
            default:
                CV_Error(Error::StsError, "Unknown type \"" + String(field->type_name()) + "\" in prototxt");
                break;
            }
        }

        inline static bool ends_with_param(const std::string &str)
        {
            static const std::string _param("_param");
            return (str.size() >= _param.size()) && str.compare(str.size() - _param.size(), _param.size(), _param) == 0;
        }

        void extractLayerParams(const Message &msg, cv::dnn::LayerParams &params, bool isInternal = false)
        {
            const Descriptor *msgDesc = msg.GetDescriptor();
            const Reflection *msgRefl = msg.GetReflection();

            for (int fieldId = 0; fieldId < msgDesc->field_count(); fieldId++)
            {
                const FieldDescriptor *fd = msgDesc->field(fieldId);

                if (!isInternal && !ends_with_param(fd->name()))
                    continue;

                bool hasData =  fd->is_required() ||
                               (fd->is_optional() && msgRefl->HasField(msg, fd)) ||
                               (fd->is_repeated() && msgRefl->FieldSize(msg, fd) > 0);
                if (!hasData)
                    continue;

                if (fd->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
                {
                    if (fd->is_repeated()) //Extract only first item!
                        extractLayerParams(msgRefl->GetRepeatedMessage(msg, fd, 0), params, true);
                    else
                        extractLayerParams(msgRefl->GetMessage(msg, fd), params, true);
                }
                else
                {
                    addParam(msg, fd, params);
                }
            }
        }

        BlobShape blobShapeFromProto(const caffe::BlobProto &pbBlob)
        {
            if (pbBlob.has_num() || pbBlob.has_channels() || pbBlob.has_height() || pbBlob.has_width())
            {
                return BlobShape(pbBlob.num(), pbBlob.channels(), pbBlob.height(), pbBlob.width());
            }
            else if (pbBlob.has_shape())
            {
                const caffe::BlobShape &_shape = pbBlob.shape();
                BlobShape shape(_shape.dim_size());

                for (int i = 0; i < _shape.dim_size(); i++)
                    shape[i] = (int)_shape.dim(i);

                return shape;
            }
            else
            {
                CV_Error(Error::StsError, "Unknown shape of input blob");
                return BlobShape(-1);
            }
        }

        void blobFromProto(const caffe::BlobProto &pbBlob, cv::dnn::Blob &dstBlob)
        {
            BlobShape shape = blobShapeFromProto(pbBlob);

            dstBlob.create(shape, CV_32F);
            CV_Assert(pbBlob.data_size() == (int)dstBlob.matRefConst().total());

            CV_DbgAssert(pbBlob.GetDescriptor()->FindFieldByLowercaseName("data")->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT);
            float *dstData = dstBlob.matRef().ptr<float>();

            for (int i = 0; i < pbBlob.data_size(); i++)
                dstData[i] = pbBlob.data(i);
        }

        void extractBinaryLayerParms(const caffe::LayerParameter& layer, LayerParams& layerParams)
        {
            const std::string &name = layer.name();

            int li;
            for (li = 0; li != netBinary.layer_size(); li++)
            {
                if (netBinary.layer(li).name() == name)
                    break;
            }

            if (li == netBinary.layer_size() || netBinary.layer(li).blobs_size() == 0)
                return;

            const caffe::LayerParameter &binLayer = netBinary.layer(li);
            layerParams.blobs.resize(binLayer.blobs_size());
            for (int bi = 0; bi < binLayer.blobs_size(); bi++)
            {
                blobFromProto(binLayer.blobs(bi), layerParams.blobs[bi]);
            }
        }

        struct BlobNote
        {
            BlobNote(const std::string &_name, int _layerId, int _outNum) :
                name(_name.c_str()), layerId(_layerId), outNum(_outNum) {}

            const char *name;
            int layerId, outNum;
        };

        void populateNet(Net dstNet)
        {
            int layersSize = net.layer_size();
            std::vector<BlobNote> addedBlobs;
            addedBlobs.reserve(layersSize + 1);

            //setup input layer names
            {
                std::vector<String> netInputs(net.input_size());
                for (int inNum = 0; inNum < net.input_size(); inNum++)
                {
                    addedBlobs.push_back(BlobNote(net.input(inNum), 0, inNum));
                    netInputs[inNum] = net.input(inNum);
                }
                dstNet.setNetInputs(netInputs);
            }

            for (int li = 0; li < layersSize; li++)
            {
                const caffe::LayerParameter &layer = net.layer(li);
                String name = layer.name();
                String type = layer.type();
                LayerParams layerParams;

                extractLayerParams(layer, layerParams);
                extractBinaryLayerParms(layer, layerParams);

                int id = dstNet.addLayer(name, type, layerParams);

                for (int inNum = 0; inNum < layer.bottom_size(); inNum++)
                    addInput(layer.bottom(inNum), id, inNum, dstNet, addedBlobs);

                for (int outNum = 0; outNum < layer.top_size(); outNum++)
                    addOutput(layer, id, outNum, addedBlobs);
            }
        }

        void addOutput(const caffe::LayerParameter &layer, int layerId, int outNum, std::vector<BlobNote> &addedBlobs)
        {
            const std::string &name = layer.top(outNum);

            bool haveDups = false;
            for (int idx = (int)addedBlobs.size() - 1; idx >= 0; idx--)
            {
                if (addedBlobs[idx].name == name)
                {
                    haveDups = true;
                    break;
                }
            }

            if (haveDups)
            {
                bool isInplace = layer.bottom_size() > outNum && layer.bottom(outNum) == name;
                if (!isInplace)
                    CV_Error(Error::StsBadArg, "Duplicate blobs produced by multiple sources");
            }

            addedBlobs.push_back(BlobNote(name, layerId, outNum));
        }

        void addInput(const std::string &name, int layerId, int inNum, Net &dstNet, std::vector<BlobNote> &addedBlobs)
        {
            int idx;
            for (idx = (int)addedBlobs.size() - 1; idx >= 0; idx--)
            {
                if (addedBlobs[idx].name == name)
                    break;
            }

            if (idx < 0)
            {
                CV_Error(Error::StsObjectNotFound, "Can't found output blob \"" + name + "\"");
                return;
            }

            dstNet.connect(addedBlobs[idx].layerId, addedBlobs[idx].outNum, layerId, inNum);
        }

        ~CaffeImporter()
        {

        }

    };

}

Ptr<Importer> cv::dnn::createCaffeImporter(const String &prototxt, const String &caffeModel)
{
    return Ptr<Importer>(new CaffeImporter(prototxt.c_str(), caffeModel.c_str()));
}

#else //HAVE_PROTOBUF

Ptr<Importer> cv::dnn::createCaffeImporter(const String&, const String&)
{
    CV_Error(cv::Error::StsNotImplemented, "libprotobuf required to import data from Caffe models");
    return Ptr<Importer>();
}

#endif //HAVE_PROTOBUF


text:
"""
#pokegoons sopel module

Author: Peter "astroman" Rowlands <peter@pmrowla.com>
"""

from __future__ import unicode_literals, absolute_import, division

from sopel import web
from sopel.module import commands, example
from sopel.config import ConfigurationError

from HTMLParser import HTMLParser

from os import path

import json
import sqlite3 as lite
import re

def setup(bot):
    """Setup pokegoons module"""
    setup_fc(bot)

def setup_fc(bot):
    if not bot.db:
        raise ConfigurationError('Database not available')
    conn = bot.db.connect()
    c = conn.cursor()
    try:
        c.execute('SELECT * FROM fc_codes')
    except StandardError:
        c.execute('''
            CREATE TABLE IF NOT EXISTS fc_codes (
                nick TEXT,
                game TEXT,
                code TEXT,
                PRIMARY KEY (nick, game))
            ''')
        conn.commit()
    conn.close()

@commands('fc')
@example('.fc masuda')
def fc(bot, trigger):
    """Retreive your friend codes or codes for the specified nick"""
    if not trigger.match.group(2):
        nick = trigger.nick
    else:
        nick = trigger.match.group(2).strip()
    sub = '?'
    conn = bot.db.connect()
    c = conn.cursor()
    c.execute('SELECT * FROM fc_codes WHERE nick LIKE {0}'.format(sub),
              (nick,))
    rows = c.fetchall()
    if not rows:
        bot.say("Couldn't find any FCs for <%s>" % nick)
    else:
        msgs = []
        for (n, game, code) in rows:
            msgs.append('%s: %s' % (game, code))
        msg = "%s's friend codes: %s" % (nick, msgs[0])
        for m in msgs[1:]:
            if len(msg) >= 400:
                bot.reply(msg)
                msg = '(continued)'
            msg = '%s | %s' % (msg, m)
        bot.say(msg)
    conn.close()

@commands('setfc', 'addfc')
@example('.setfc 3DS = 1234-1234-1234')
def setfc(bot, trigger):
    """Add or update a friend code for the specified game"""
    usage = 'Usage: .setfc <game> = <code>'
    if not trigger.match.group(2):
        bot.reply(usage)
        return
    try:
        (game, code) = trigger.match.group(2).split('=', 1)
    except ValueError:
        bot.reply(usage)
        return
    game = game.strip()
    code = code.strip()
    sub = '?'
    conn = bot.db.connect()
    c = conn.cursor()
    c.execute('''
        SELECT * FROM fc_codes WHERE nick LIKE {0} AND game LIKE {0}
        '''.format(sub), (trigger.nick, game))
    row = c.fetchone()
    if not row:
        c.execute('''
            INSERT INTO fc_codes (nick, game, code) VALUES ({0}, {0}, {0})
            '''.format(sub), (trigger.nick, game, code))
    else:
        (nick, game, old_code) = row
        c.execute('''
            UPDATE fc_codes SET code = {0} WHERE nick = {0} AND game = {0}
            '''.format(sub), (code, trigger.nick, game))
    bot.reply('Set code for <%s> to <%s>' % (game, code))
    conn.commit()
    conn.close()

@commands('delfc', 'remfc')
@example('.delfc 3DS')
def delfc(bot, trigger):
    """Delete your friend code for the specified game"""
    if not trigger.match.group(2):
        return
    game = trigger.match.group(2).strip()
    sub = '?'
    conn = bot.db.connect()
    c = conn.cursor()
    c.execute(
        'SELECT * FROM fc_codes WHERE nick = {0} AND game = {0}'.format(sub),
        (trigger.nick, game))
    if c.fetchone():
        c.execute('''
            DELETE FROM fc_codes WHERE nick = {0} AND game = {0}
            '''.format(sub), (trigger.nick, game))
        bot.reply('Deleted code for %s' % (game))
        conn.commit()
    else:
        bot.reply('Could not find a matching code to delete')
    conn.close()

@commands('clearfc')
def clearfc(bot, trigger):
    """Delete ALL of your friend codes"""
    sub = '?'
    conn = bot.db.connect()
    c = conn.cursor()
    c.execute(
        'SELECT * FROM fc_codes WHERE nick = {0}'.format(sub),
        (trigger.nick,))
    if c.fetchone():
        c.execute('''
            DELETE FROM fc_codes WHERE nick = {0}
            '''.format(sub), (trigger.nick,))
        bot.reply('Deleted all of your friend codes')
        conn.commit()
    else:
        bot.reply('Could not find any matching codes to delete')
    conn.close()

@commands('table')
def table(bot, trigger):
    bot.say(u'(ノ ゜Д゜)ノ ︵ ┻━┻')

@commands('b', 'bulb', 'bulbapedia')
@example('.b charizard')
def bulbapedia(bot, trigger):
    """Search bulbapedia"""

    if trigger.group(2) is None:
        bot.reply("what do you want me to look up?")
        return

    query = trigger.group(2)

    if not query:
        bot.reply('what do you want me to look up?')
        return
    server = 'bulbapedia.bulbagarden.net'
    result = mw_search(server, query, 1)
    if not result:
        bot.reply("i can't find any results for that.")
        return
    (title, snippet) = result

    bot.say('"%s" - http://bulbapedia.bulbagarden.net/wiki/%s' % (
        strip_tags(snippet).strip(), title.replace(' ', '_')))

@commands('data')
@example('.data bulbasaur')
def data(bot, trigger):
    """Give information about selected pokemon"""

    if trigger.group(2):
        """Joke response for missingno"""
        if 'missingno' in trigger.group(2).lower():
            bot.say("PokedexError: 'dex' codec can't find pokemon 0xcc in"
                    " position 0: ordinal not in range(128) (Please stop"
                    " looking)")
        dbDir = path.join(path.dirname(__file__))
        con = lite.connect(path.join(dbDir, '../../pokedex.db'))
        with con:
            # Handle the input to take into account different orderings of the
            # word mega and use of hyphens
            reg = re.compile(
                r"(?:[\ -](mega)|(mega)[\ -])([a-z]*)(?:[\ -](X|Y))?",
                re.IGNORECASE)
            retrieved = trigger.group(2).strip()
            name = reg.search(retrieved)
            poke = reg.findall(retrieved)
            if poke:
                name = name.group(3)
                poke = filter(None, poke[0])
                poke = [poke for poke in poke if poke != name]
                retrieved = reg.sub(r"\3", retrieved)
                for match in poke:
                    retrieved = retrieved + '-' + match

            """Search the database and make the output somewhat pretty"""
            cur = con.cursor()
            cur.execute(
                """
                SELECT dexNo, species, type1, type2, genderRatio, hp, atk,
                pdef, spa, sdef, spd, ability1, ability2, hiddenAbility, egg1,
                egg2 FROM Pokedex WHERE UPPER(species) = {0}
                """.format('?'),
                (retrieved.upper(),))
            rows = cur.fetchall()
            for row in rows:
                dexInfo = 'No. ' + str(row[0]) + ' ' + row[1] + ' [' + row[2]
                if row[3]:
                    dexInfo = dexInfo + ', ' + row[3] + ']'
                else:
                    dexInfo = dexInfo + ']'

                if row[4]:
                    dexInfo = dexInfo + ' M/F '
                    if row[4] == 0.5:
                        dexInfo = dexInfo + '1:1'
                    elif row[4] == 0:
                        dexInfo = dexInfo + '0:1'
                    elif row[4] == 1:
                        dexInfo = dexInfo + '1:0'
                    elif row[4] == 0.875:
                        dexInfo = dexInfo + '7:1'

                dexInfo = dexInfo + ', Hp ' + str(row[5]) + ' | Atk ' + \
                    str(row[6]) + ' | Def ' + str(row[7]) + ' | SpA ' + \
                    str(row[8]) + ' | SpD ' + str(row[9]) + ' | Spe ' + \
                    str(row[10])+','

                if row[12] == '' and row[13] == '':
                    dexInfo = dexInfo + ' Ability: ' + row[11]
                elif row[12] == '':
                    dexInfo = dexInfo + ' Abilities: ' + row[11] + ' <' + \
                        row[13] + '>'
                elif row[13] == '':
                    dexInfo = dexInfo + ' Abilities: ' + row[11] + '/' + \
                        row[12]
                else:
                    dexInfo = dexInfo + ' Abilities: ' + row[11] + '/' + \
                        row[12] + ' <' + row[13] + '>'

                if row[15] == '':
                    dexInfo = dexInfo + ' {Egg: ' + row[14] + row[15] + '}'
                else:
                    dexInfo = dexInfo + ' {Egg: ' + row[14] + ', ' + \
                        row[15] + '}'
                bot.say(dexInfo)

def mw_search(server, query, num):
    """
    Searches the specified MediaWiki server for the given query, and returns
    the specified number of results.
    """
    search_url = ('http://%s/w/api.php?format=json&action=query'
                  '&list=search&srlimit=%d&srprop=timestamp|snippet'
                  '&srwhat=text'
                  '&srsearch=') % (server, num)
    search_url += query
    query = json.loads(web.get(search_url))
    if 'query' in query:
        try:
            query = query['query']['search'][0]
            return (query['title'], query['snippet'])
        except IndexError:
            return None
    else:
        return None

class MLStripper(HTMLParser):

    def __init__(self):
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()


text:
package cgeo.geocaching.storage;

import cgeo.geocaching.R;
import cgeo.geocaching.settings.Settings;

import android.net.Uri;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

/**
 * Enum listing all single-document-Uris which can be persisted
 */
public enum PersistableUri {

    UNUSED_TRACK(R.string.pref_persistableuri_track, R.string.persistableuri_track, null);

    @StringRes
    private final int prefKeyId;
    @StringRes
    private final int nameKeyId;
    private final String mimeType;

    PersistableUri(@StringRes final int prefKeyId, @StringRes final int nameKeyId, final String mimeType) {
        this.prefKeyId = prefKeyId;
        this.nameKeyId = nameKeyId;
        this.mimeType = mimeType;
    }

    @StringRes
    public int getPrefKeyId() {
        return this.prefKeyId;
    }

    @StringRes
    public int getNameKeyId() {
        return nameKeyId;
    }

    public String getMimeType() {
        return mimeType;
    }

    public Uri getUri() {
        final String uriString = Settings.getPersistableUri(this);
        return uriString == null ? null : Uri.parse(uriString);
    }

    public boolean hasValue() {
        return getUri() != null;
    }

    /**
     * Sets a new user-defined location ("null" is allowed). Should be called ONLY by {@link ContentStorage}
     */
    protected void setPersistedUri(@Nullable final Uri uri) {
        Settings.setPersistableUri(this, uri == null ? null : uri.toString());
    }

    @Override
    public String toString() {
        return name() + ": " + getUri();
    }

}


text:
package com.bitdecay.jump.properties;

import com.bitdecay.jump.annotation.ValueRange;

/**
 * Created by Monday on 10/25/2015.
 */
public class JumperProperties {
    /**
     * The number of jumps a body can make before needing to touch the ground again
     */
    @ValueRange(min = 0, max = 10)
    public int jumpCount = 2;

    /**
     * The jump strength of the primary jump
     */
    @ValueRange(min = 0, max = 1000)
    public int jumpStrength = 300;

    /**
     * The jump strength of any jump after the first
     */
    @ValueRange(min = 0, max = 1000)
    public int jumpDoubleJumpStrength = 150;

    /**
     * The window, in seconds, that holding the jump button can increase jump height
     */
    @ValueRange(min = 0, max = 2)
    public float jumpVariableHeightWindow = .2f;

    /**
     * Grace period, in seconds, for allowing a player to either:
     *  - jump early before actually becoming grounded
     *  - jump after running off a ledge
     */
    @ValueRange(min = 0, max = 1)
    public float jumpGraceWindow = .2f;

    /**
     * If true, hitting a platform on the way up during a jump will cause the jump
     * to immediately end.
     */
    public boolean jumpHittingHeadStopsJump = true;

    /**
     * If true, a body can wall slide when falling past a wall
     */
    public boolean wallSlideEnabled;

    /**
     * If true, a body can wall slide when falling past a wall
     */
    public boolean wallJumpEnabled;

    /**
     * How hard a body jumps off the wall when performing a wall jump
     */
    @ValueRange(min = 0, max = 1000)
    public int wallJumpLaunchPower;

    /**
     * The maximum speed at which a a body can slide down a wall
     */
    @ValueRange(min = 0, max = 500)
    public int wallMaxSlideSpeed;
}


text:
<?php
namespace Cerad\Bundle\TournBundle\Form\Type\Person\AYSO;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/* ==================================================================
 */
class RefereeFormType extends AbstractType
{
    public function getName()   { return 'cerad_tourn_person_ayso_referee'; }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Cerad\Bundle\PersonBundle\Entity\PersonCert'
        ));
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('badgex', 'cerad_person_ayso_referee_badge');
     }
}

?>


text:
package com.jetbrains.python.templateLanguages;

import com.intellij.execution.ExecutionException;
import com.intellij.facet.ui.ValidationResult;
import com.intellij.openapi.projectRoots.Sdk;
import com.jetbrains.python.packaging.PyPackage;
import com.jetbrains.python.packaging.PyPackageManager;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class PyTemplatesUtil {
  private PyTemplatesUtil(){}

  public static ValidationResult checkInstalled(@Nullable final Sdk sdk, @NotNull final TemplateLanguagePanel templatesPanel,
                                         @NotNull final String prefix) {
    if (sdk == null) return ValidationResult.OK;
    String templateBinding = null;
    @NonNls String language = templatesPanel.getTemplateLanguage();
    if (language != null) {
      if (language.equals(TemplatesService.JINJA2)) language = "jinja";
      templateBinding = prefix + language.toLowerCase();
    }
    final PyPackageManager packageManager = PyPackageManager.getInstance(sdk);
    if (templateBinding != null) {
      if (TemplatesService.ALL_TEMPLATE_BINDINGS.contains(templateBinding)) {
        try {
          final PyPackage installedPackage = packageManager.findPackage(templateBinding, false);
          if (installedPackage == null)
            return new ValidationResult(templateBinding + " will be installed on selected interpreter");
        }
        catch (ExecutionException ignored) {
        }
      }
    }
    if (language != null) {
      try {
        final PyPackage installedPackage = packageManager.findPackage(language, false);
        if (installedPackage == null) {
          return new ValidationResult(language + " will be installed on selected interpreter");
        }
      }
      catch (ExecutionException ignored) {
      }
    }
    return null;
  }

}


text:
ComfyBlog::Application.routes.draw do
  comfy_route :cms_admin
  comfy_route :blog_admin
  comfy_route :blog
  comfy_route :cms, :sitemap => true
end


text:
package io.jenetics.ext.engine;

import java.util.function.Supplier;
import java.util.stream.Stream;

import io.jenetics.IntegerGene;
import io.jenetics.engine.EvolutionInit;
import io.jenetics.engine.EvolutionStart;
import io.jenetics.engine.EvolutionStream;
import io.jenetics.engine.EvolutionStreamable;

import io.jenetics.ext.EvolutionStreams;

/**
 * @author Franz Wilhelmstötter
 */
final class EvolutionStreamables {
	private EvolutionStreamables() {
	}

	static EvolutionStreamable<IntegerGene, Integer> streamable(final int size) {
		return new EvolutionStreamable<>() {
			@Override
			public EvolutionStream<IntegerGene, Integer>
			stream(final Supplier<EvolutionStart<IntegerGene, Integer>> start) {
				return EvolutionStreams.stream(
					Stream.generate(new Supplier<Integer>() {
						Integer value = null;

						@Override
						public Integer get() {
							if (value == null) {
								value = start.get().population().isEmpty()
									? 0
									: start.get()
									.population()
									.get(0)
									.genotype()
									.gene()
									.intValue();
							}
							value += 1;

							return value;
						}
					}).limit(size)
				);
			}

			@Override
			public EvolutionStream<IntegerGene, Integer>
			stream(final EvolutionInit<IntegerGene> init) {
				return EvolutionStreams.stream(
					Stream.generate(new Supplier<Integer>() {
						Integer value = null;

						@Override
						public Integer get() {
							if (value == null) {
								value = init.population()
									.get(0)
									.gene()
									.intValue();
							}
							value += 1;

							return value;
						}
					}).limit(size)
				);
			}
		};
	}

}


text: python train.py


text:
/* -------------------------------------------------------------------
// markItUp!
// By Jay Salvat - http://markitup.jaysalvat.com/
// ------------------------------------------------------------------*/
.markItUp .tinyUrl a {
	background-image:url(images/tinyurl.png);
}


text:
package org.dcm4chex.archive.mbean;

import java.io.IOException;
import java.rmi.RemoteException;
import java.security.GeneralSecurityException;
import java.util.List;

import javax.management.ObjectName;
import javax.net.ssl.SSLException;

import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.dict.UIDs;
import org.dcm4che.net.AAssociateAC;
import org.dcm4che.net.AAssociateRQ;
import org.dcm4che.net.ActiveAssociation;
import org.dcm4che.net.Association;
import org.dcm4che.net.AssociationFactory;
import org.dcm4che.net.PDU;
import org.dcm4chex.archive.ejb.interfaces.AEManager;
import org.dcm4chex.archive.ejb.interfaces.AEManagerHome;
import org.dcm4chex.archive.ejb.jdbc.AEData;
import org.dcm4chex.archive.util.EJBHomeFactory;
import org.jboss.system.ServiceMBeanSupport;

/**
 * <description>
 *
 * @author     Franz WIller
 * @since      March 24, 2005
 * @version    $Revision: 2495 $ $Date: 2006-05-26 20:33:15 +0800 (周五, 26 5月 2006) $
 */
public class EchoService extends ServiceMBeanSupport
{
    private static final AssociationFactory aFact =
        AssociationFactory.getInstance();
    private static final DcmObjectFactory oFact =
        DcmObjectFactory.getInstance();

    private int acTimeout = 5000;
    private int dimseTimeout = 0;
    private int soCloseDelay = 500;

    private TLSConfigDelegate tlsConfig = new TLSConfigDelegate(this);

    private String callingAET;

	private static final int PCID_ECHO = 1;
    private static final String[] DEF_TS = { UIDs.ImplicitVRLittleEndian };

	/**
	 * @return Returns the callingAET.
	 */
	public String getCallingAET() {
		return callingAET;
	}
	/**
	 * @param callingAET The callingAET to set.
	 */
	public void setCallingAET(String callingAET) {
		this.callingAET = callingAET;
	}
    public final ObjectName getTLSConfigName() {
        return tlsConfig.getTLSConfigName();
    }

    public final void setTLSConfigName(ObjectName tlsConfigName) {
        tlsConfig.setTLSConfigName(tlsConfigName);
    }

    public final int getReceiveBufferSize() {
        return tlsConfig.getReceiveBufferSize();
    }

    public final void setReceiveBufferSize(int size) {
        tlsConfig.setReceiveBufferSize(size);
    }

    public final int getSendBufferSize() {
        return tlsConfig.getSendBufferSize();
    }

    public final void setSendBufferSize(int size) {
        tlsConfig.setSendBufferSize(size);
    }

    public final boolean isTcpNoDelay() {
        return tlsConfig.isTcpNoDelay();
    }

    public final void setTcpNoDelay(boolean on) {
        tlsConfig.setTcpNoDelay(on);
    }

	public final int getAcTimeout() {
        return acTimeout;
    }

    public final void setAcTimeout(int acTimeout) {
        this.acTimeout = acTimeout;
    }

    public final int getDimseTimeout() {
        return dimseTimeout;
    }

    public final void setDimseTimeout(int dimseTimeout) {
        this.dimseTimeout = dimseTimeout;
    }

    public final int getSoCloseDelay() {
        return soCloseDelay;
    }

    public final void setSoCloseDelay(int soCloseDelay) {
        this.soCloseDelay = soCloseDelay;
    }

    public String[] echoAll() throws RemoteException, Exception {
    	List l = lookupAEManager().getAes();
    	String[] sa = new String[ l.size() ];
    	AEData aeData;
    	for ( int i = 0, len = sa.length; i < len ; i++ ) {
    		aeData = (AEData) l.get(i);
    		try {
    			sa[i] = aeData+" : "+echo( aeData, new Integer(3) );
    		} catch ( Exception x ) {
    			sa[i] = aeData+" failed:"+x.getMessage();
    		}
    	}
    	return sa;
    }

    public String echo( String aet, Integer nrOfTests ) throws Exception {
    	return echo( lookupAEManager().getAeByTitle( aet ), nrOfTests );
    }
    public String echo( AEData aeData, Integer nrOfTests ) throws InterruptedException, IOException, GeneralSecurityException {
	    int count = 0;
	    int len = nrOfTests.intValue();
	    ActiveAssociation active = null;
	    try {
	    	active = openAssoc( aeData );
	    } catch( Throwable t ) {
	    	log.error("Echo "+aeData+" failed!", t);
	    	return "Echo failed ("+aeData+")! Reason: unexpected Exception:"+t;
	    }
	    if (active != null) {
	        if (active.getAssociation().getAcceptedTransferSyntaxUID(PCID_ECHO) == null) {
	            return "Echo ("+aeData+") not accepted!";
	        } else
	        	try {
		            for (int j = 0; j < len; ++j, ++count) {
		                active.invoke(
		                    aFact.newDimse(
		                        PCID_ECHO,
		                        oFact.newCommand().initCEchoRQ(j)),
		                    null);
		            }
	        	} catch ( SSLException x ) {
	        		return "Echo failed: "+x.getMessage();
	        	}
	        active.release(true);
	    }
	    return "Echo ("+aeData+") done! "+count+" of "+nrOfTests+" successfully completed.";
	}

    public boolean checkEcho( AEData aeData ) {
    	ActiveAssociation active = null;
    	try {
    		active = openAssoc( aeData );
    		if (active != null && active.getAssociation().getAcceptedTransferSyntaxUID(PCID_ECHO) != null ) {
                active.invoke(
	                    aFact.newDimse(
	                        PCID_ECHO,
	                        oFact.newCommand().initCEchoRQ(0)),
	                    null);
	     		return true;
    		}
    	} catch( Throwable ignore ) {
    	} finally {
    		if ( active != null ) try {
    			active.release(true);
    		} catch ( Exception ignoreit ) {}
    	}
		return false;
    }

    private ActiveAssociation openAssoc(AEData aeData) throws IOException, GeneralSecurityException {
	    Association assoc =
	        aFact.newRequestor( tlsConfig.createSocket(aeData) );

	    assoc.setAcTimeout(acTimeout);
	    assoc.setDimseTimeout(dimseTimeout);
	    assoc.setSoCloseDelay(soCloseDelay);
	    AAssociateRQ assocRQ = aFact.newAAssociateRQ();
	    assocRQ.setCallingAET( this.callingAET );
	    assocRQ.setCalledAET( aeData.getTitle() );
        assocRQ.addPresContext(
                aFact.newPresContext(PCID_ECHO, UIDs.Verification, DEF_TS));
	    PDU assocAC = assoc.connect(assocRQ);
	    if (!(assocAC instanceof AAssociateAC)) {
	        return null;
	    }
	    ActiveAssociation retval = aFact.newActiveAssociation(assoc, null);
	    retval.start();
	    return retval;
	}

	protected AEManager lookupAEManager() throws Exception
	{
		AEManagerHome home =
			(AEManagerHome) EJBHomeFactory.getFactory().lookup(
					AEManagerHome.class,
					AEManagerHome.JNDI_NAME);
		return home.create();
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;

namespace MetroRadiance.Media
{
	public static class ColorHelper
	{
		/// <summary>
		/// 現在の RGB 色空間による色から HSV 色空間の <see cref="HsvColor"/> 構造体を作成します。
		/// </summary>
		public static HsvColor ToHsv(this Color c)
		{
			return HsvColor.FromRgb(c);
		}

		public static uint GetColorAsUInt32(Color color)
		{
			return ((uint)color.A << 24) | ((uint)color.B << 16) | ((uint)color.G << 8) | color.R;
		}

		public static Color GetColorFromUInt32(uint color)
		{
			return Color.FromArgb((byte)(color >> 24), (byte)(color >> 16), (byte)(color >> 8), (byte)color);
		}
	}
}


text:
<?php

package('ack')->install();

file('/home/eater/touch')
    ->contents(time())
    ->requires(package('ack'));


text:
import { RepositoryError } from "./data"

export type RepositoryOutsideFeature = Readonly<{
    webDB: IDBFactory
}>

export interface RepositoryPod<V, R> {
    (converter: RepositoryConverter<V, R>): Repository<V>
}

export interface RepositoryConverter<V, R> {
    toRepository(value: V): R
    fromRepository(raw: R): ConvertRepositoryResult<V>
}

export interface Repository<T> {
    get(): Promise<FetchRepositoryResult<T>>
    set(value: T): Promise<StoreRepositoryResult>
    remove(): Promise<StoreRepositoryResult>
}

export type FetchRepositoryResult<T> =
    | Readonly<{ success: true; found: true; value: T }>
    | Readonly<{ success: true; found: false }>
    | Readonly<{ success: false; err: RepositoryError }>

export type StoreRepositoryResult =
    | Readonly<{ success: true }>
    | Readonly<{ success: false; err: RepositoryError }>

export type ConvertRepositoryResult<T> =
    | Readonly<{ valid: true; value: T }>
    | Readonly<{ valid: false }>


text:
from setuptools import setup

setup(
    name="Bliss",
    version="1.0.0",
    author="Phyks (Lucas Verney)",
    author_email="phyks@phyks.me",
    description="A wrapper around Bliss.",
    license="MIT",
    keywords="example documentation tutorial",
    url="https://github.com/Polochon-street/bliss",
    packages=['bliss'],
    long_description=open("../README.md", 'r').read(),
    # classifiers=[
    #     "Development Status :: 3 - Alpha",
    #     "Topic :: Utilities",
    #     "License :: OSI Approved :: BSD License",
    # ],
    setup_requires=["cffi>=1.0.0"],
    cffi_modules=["./build_bliss.py:ffi"],
    install_requires=["cffi>=1.0.0"],
)


text:
<?php

require_once('lib/bootstrap.php');

class BitmaskTest extends PHPUnit_Framework_TestCase {

  public function testValidValue() {
    // valid values
    $this->assertTrue(Bitmask::validValue(1));
    $this->assertTrue(Bitmask::validValue(2));
    $this->assertTrue(Bitmask::validValue(4));
    $this->assertTrue(Bitmask::validValue(64));
    $this->assertTrue(Bitmask::validValue(256));
    $this->assertTrue(Bitmask::validValue(32768));
    $this->assertTrue(Bitmask::validValue(9007199254740992));

    // invalid values
    $this->assertFalse(Bitmask::validValue(10));
    $this->assertFalse(Bitmask::validValue(13));
    $this->assertFalse(Bitmask::validValue(4.2));
    $this->assertFalse(Bitmask::validValue('string'));
    $this->assertFalse(Bitmask::validValue(array()));
  }

  public function testIncludes() {
    $mask = 1 | 4 | 32;

    // existing values
    $this->assertTrue(Bitmask::includes(1, $mask));
    $this->assertTrue(Bitmask::includes(4, $mask));
    $this->assertTrue(Bitmask::includes(32, $mask));

    // non-existing values
    $this->assertFalse(Bitmask::includes(2, $mask));
    $this->assertFalse(Bitmask::includes(16, $mask));

    // invalid values
    $this->assertFalse(Bitmask::includes(array(), $mask));
    $this->assertFalse(Bitmask::includes('string', $mask));
    $this->assertFalse(Bitmask::includes(13, $mask));
  }

  public function testAdd() {
    $mask = 1 | 4 | 32;

    $this->assertEquals(Bitmask::add(16, $mask), $mask | 16);
    $this->assertEquals(Bitmask::add(4, $mask), $mask);
  }

  public function testAddInvalidThrow() {
    $this->expectException('Exception');
    Bitmask::add(42, 1);
  }

  public function testRemove() {
    $mask = 1 | 4 | 32;

    $this->assertEquals(Bitmask::remove(32, $mask), $mask ^ 32);
    $this->assertEquals(Bitmask::remove(16, $mask), $mask);
  }

  public function testRemoveInvalidThrow() {
    $this->expectException('Exception');
    Bitmask::remove(42, 1);
  }
}


text:
package net.sf.jabref.specialfields;

import net.sf.jabref.Globals;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.event.EntryAddedEvent;

import com.google.common.eventbus.Subscribe;

public class SpecialFieldDatabaseChangeListener {

    private static SpecialFieldDatabaseChangeListener INSTANCE;

    public static SpecialFieldDatabaseChangeListener getInstance() {
        if (SpecialFieldDatabaseChangeListener.INSTANCE == null) {
            SpecialFieldDatabaseChangeListener.INSTANCE = new SpecialFieldDatabaseChangeListener();
        }
        return SpecialFieldDatabaseChangeListener.INSTANCE;
    }

    @Subscribe
    public void listen(EntryAddedEvent event) {
        if (Globals.prefs.isKeywordSyncEnabled()) {
            final BibEntry entry = event.getBibEntry();
            // NamedCompount code similar to SpecialFieldUpdateListener
            NamedCompound nc = new NamedCompound(Localization.lang("Synchronized special fields based on keywords"));
            SpecialFieldsUtils.syncSpecialFieldsFromKeywords(entry, nc);
            // Don't insert the compound into the undoManager,
            // it would be added before the component which undoes the insertion of the entry and creates heavy problems
            // (which prohibits the undo the deleting multiple entries)
        }
    }

}


text:
/**
 * @typedef {import('micromark-util-types').Construct} Construct
 * @typedef {import('micromark-util-types').Resolver} Resolver
 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
 * @typedef {import('micromark-util-types').Token} Token
 * @typedef {import('micromark-util-types').State} State
 */

import {ok as assert} from 'uvu/assert'
import {factorySpace} from 'micromark-factory-space'
import {markdownLineEnding} from 'micromark-util-character'
import {subtokenize} from 'micromark-util-subtokenize'
import {codes} from 'micromark-util-symbol/codes.js'
import {constants} from 'micromark-util-symbol/constants.js'
import {types} from 'micromark-util-symbol/types.js'

/**
 * No name because it must not be turned off.
 * @type {Construct}
 */
export const content = {tokenize: tokenizeContent, resolve: resolveContent}

/** @type {Construct} */
const continuationConstruct = {tokenize: tokenizeContinuation, partial: true}

/**
 * Content is transparent: it's parsed right now. That way, definitions are also
 * parsed right now: before text in paragraphs (specifically, media) are parsed.
 *
 * @type {Resolver}
 */
function resolveContent(events) {
  subtokenize(events)
  return events
}

/** @type {Tokenizer} */
function tokenizeContent(effects, ok) {
  /** @type {Token} */
  let previous

  return start

  /** @type {State} */
  function start(code) {
    assert(
      code !== codes.eof && !markdownLineEnding(code),
      'expected no eof or eol'
    )

    effects.enter(types.content)
    previous = effects.enter(types.chunkContent, {
      contentType: constants.contentTypeContent
    })
    return data(code)
  }

  /** @type {State} */
  function data(code) {
    if (code === codes.eof) {
      return contentEnd(code)
    }

    if (markdownLineEnding(code)) {
      return effects.check(
        continuationConstruct,
        contentContinue,
        contentEnd
      )(code)
    }

    // Data.
    effects.consume(code)
    return data
  }

  /** @type {State} */
  function contentEnd(code) {
    effects.exit(types.chunkContent)
    effects.exit(types.content)
    return ok(code)
  }

  /** @type {State} */
  function contentContinue(code) {
    assert(markdownLineEnding(code), 'expected eol')
    effects.consume(code)
    effects.exit(types.chunkContent)
    previous.next = effects.enter(types.chunkContent, {
      contentType: constants.contentTypeContent,
      previous
    })
    previous = previous.next
    return data
  }
}

/** @type {Tokenizer} */
function tokenizeContinuation(effects, ok, nok) {
  const self = this

  return startLookahead

  /** @type {State} */
  function startLookahead(code) {
    assert(markdownLineEnding(code), 'expected a line ending')
    effects.exit(types.chunkContent)
    effects.enter(types.lineEnding)
    effects.consume(code)
    effects.exit(types.lineEnding)
    return factorySpace(effects, prefixed, types.linePrefix)
  }

  /** @type {State} */
  function prefixed(code) {
    if (code === codes.eof || markdownLineEnding(code)) {
      return nok(code)
    }

    const tail = self.events[self.events.length - 1]

    if (
      !self.parser.constructs.disable.null.includes('codeIndented') &&
      tail &&
      tail[1].type === types.linePrefix &&
      tail[2].sliceSerialize(tail[1], true).length >= constants.tabSize
    ) {
      return ok(code)
    }

    return effects.interrupt(self.parser.constructs.flow, nok, ok)(code)
  }
}


text:
import React from 'react';
import ShCore from 'sh-core';
import * as _ from 'lodash';
import './sh-modal-dialog.scss';

class ShModalDialog extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            classList: {
                displayModal: false,
                fadeIn: false,
                firstRun: true,
                shValid: true
            }
        };

        this.showModal = this.showModal.bind(this);
        this.handleSuccess = this.handleSuccess.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
    }

    showModal(props) {
        this.setState({
            classList: {
                displayModal: true
            }
        }, ()=> {
            setTimeout(()=> {
                let classList = {};
                classList.displayModal=true;
                classList.fadeIn = true;
                classList.shValid = props.shForceValid;

                this.setState({
                    classList: classList
                })
            }, 100)
        })
    }

    componentDidMount() {
        this.showModal(this.props);
    }

    handleSuccess() {
        this.props.shSuccess();

    }

    handleCancel() {
        this.props.shCancel();
    }

    getSaveButton() {
        if (!this.props.shModalSaveButton || _.isString(this.props.shModalSaveButton)) {
            let buttonText = this.props.shModalSaveButton;
            if (!buttonText) {
                buttonText = 'Save';
            }

            return <button id="sh-save-button" className="sh-btn sh-btn-primary"
                           onClick={this.handleSuccess}>{buttonText}</button>
        } else {
            return this.props.shModalSaveButton
        }
    }

    render() {
        return (

{this.props.shModalTitle}

                        {this.props.children}

                        <button className="sh-btn sh-btn-default sh-cancel" onClick={this.handleCancel}>Cancel</button>
                        {this.getSaveButton()}

        )
    }
}

ShModalDialog.propTypes = {
    shModalTitle: React.PropTypes.string,
    shModalSaveButton: React.PropTypes.any,
    shSuccess: React.PropTypes.func,
    shCancel: React.PropTypes.func,
};

export default ShModalDialog;


text:
package org.apereo.cas.oidc.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.oidc.OidcConstants;
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
import org.apereo.cas.web.support.CookieRetrievingCookieGenerator;
import org.apereo.cas.web.support.WebUtils;
import org.jasig.cas.client.util.URIBuilder;
import org.pac4j.cas.client.CasClient;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.profile.ProfileManager;
import org.pac4j.core.profile.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * This is {@link OidcAuthorizationRequestSupport}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public class OidcAuthorizationRequestSupport {

    private static final Logger LOGGER = LoggerFactory.getLogger(OidcAuthorizationRequestSupport.class);

    private final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;
    private final TicketRegistrySupport ticketRegistrySupport;

    public OidcAuthorizationRequestSupport(final CookieRetrievingCookieGenerator tgtCookieGenerator,
                                           final TicketRegistrySupport ticketRegistrySupport) {
        this.ticketGrantingTicketCookieGenerator = tgtCookieGenerator;
        this.ticketRegistrySupport = ticketRegistrySupport;
    }

    /**
     * Gets oidc prompt from authorization request.
     *
     * @param url the url
     * @return the oidc prompt from authorization request
     */
    public static Set<String> getOidcPromptFromAuthorizationRequest(final String url) {
        Assert.notNull(url, "URL cannot be null");
        return new URIBuilder(url).getQueryParams().stream()
                .filter(p -> OidcConstants.PROMPT.equals(p.getName()))
                .map(param -> param.getValue().split(" "))
                .flatMap(Arrays::stream)
                .collect(Collectors.toSet());
    }

    /**
     * Gets oidc prompt from authorization request.
     *
     * @param context the context
     * @return the oidc prompt from authorization request
     */
    public static Set<String> getOidcPromptFromAuthorizationRequest(final WebContext context) {
        return getOidcPromptFromAuthorizationRequest(context.getFullRequestURL());
    }

    /**
     * Gets oidc max age from authorization request.
     *
     * @param context the context
     * @return the oidc max age from authorization request
     */
    public static Optional<Long> getOidcMaxAgeFromAuthorizationRequest(final WebContext context) {
        final URIBuilder builderContext = new URIBuilder(context.getFullRequestURL());
        final Optional<URIBuilder.BasicNameValuePair> parameter = builderContext.getQueryParams()
                .stream().filter(p -> OidcConstants.MAX_AGE.equals(p.getName()))
                .findFirst();

        if (parameter.isPresent()) {
            final long maxAge = NumberUtils.toLong(parameter.get().getValue(), -1);
            return Optional.of(maxAge);
        }
        return Optional.empty();
    }

    /**
     * Is authentication profile available?.
     *
     * @param context the context
     * @return the optional user profile
     */
    public static Optional<UserProfile> isAuthenticationProfileAvailable(final WebContext context) {
        final ProfileManager manager = WebUtils.getPac4jProfileManager(context);
        return manager.get(true);
    }

    /**
     * Is cas authentication available?
     *
     * @param context the context
     * @return the optional authn
     */
    public Optional<Authentication> isCasAuthenticationAvailable(final WebContext context) {
        final J2EContext j2EContext = (J2EContext) context;
        if (j2EContext != null) {
            final String tgtId = ticketGrantingTicketCookieGenerator.retrieveCookieValue(j2EContext.getRequest());

            if (StringUtils.isNotBlank(tgtId)) {
                final Authentication authentication = ticketRegistrySupport.getAuthenticationFrom(tgtId);
                if (authentication != null) {
                    return Optional.of(authentication);
                }
            }
        }
        return Optional.empty();
    }

    /**
     * Is cas authentication old for max age authorization request boolean.
     *
     * @param context            the context
     * @param authenticationDate the authentication date
     * @return true/false
     */
    public boolean isCasAuthenticationOldForMaxAgeAuthorizationRequest(final WebContext context,
                                                                       final ZonedDateTime authenticationDate) {
        final Optional<Long> maxAge = getOidcMaxAgeFromAuthorizationRequest(context);
        if (maxAge.isPresent() && maxAge.get() > 0) {
            final long now = ZonedDateTime.now().toEpochSecond();
            final long authTime = authenticationDate.toEpochSecond();
            final long diffInSeconds = now - authTime;
            if (diffInSeconds > maxAge.get()) {
                LOGGER.info("Authentication is too old: [{}] and was created [{}] seconds ago.",
                        authTime, diffInSeconds);
                return true;
            }
        }
        return false;
    }

    /**
     * Is cas authentication old for max age authorization request?
     *
     * @param context        the context
     * @param authentication the authentication
     * @return true/false
     */
    public boolean isCasAuthenticationOldForMaxAgeAuthorizationRequest(final WebContext context,
                                                                       final Authentication authentication) {
        return isCasAuthenticationOldForMaxAgeAuthorizationRequest(context, authentication.getAuthenticationDate());
    }

    /**
     * Is cas authentication old for max age authorization request?
     *
     * @param context the context
     * @param profile the profile
     * @return true/false
     */
    public boolean isCasAuthenticationOldForMaxAgeAuthorizationRequest(final WebContext context,
                                                                       final UserProfile profile) {

        final Object authTime =
                profile.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE);
        if (authTime == null) {
            return false;
        }
        final ZonedDateTime dt = ZonedDateTime.parse(authTime.toString());
        return isCasAuthenticationOldForMaxAgeAuthorizationRequest(context, dt);
    }

    /**
     * Configure client for max age authorization request.
     * Sets the CAS client to ask for renewed authentication if
     * the authn time is too old based on the requested max age.
     *
     * @param casClient      the cas client
     * @param context        the context
     * @param authentication the authentication
     */
    public void configureClientForMaxAgeAuthorizationRequest(final CasClient casClient, final WebContext context,
                                                             final Authentication authentication) {
        if (isCasAuthenticationOldForMaxAgeAuthorizationRequest(context, authentication)) {
            casClient.getConfiguration().setRenew(true);
        }
    }

    /**
     * Configure client for prompt login authorization request.
     *
     * @param casClient the cas client
     * @param context   the context
     */
    public static void configureClientForPromptLoginAuthorizationRequest(final CasClient casClient, final WebContext context) {
        final Set<String> prompts = getOidcPromptFromAuthorizationRequest(context);
        if (prompts.contains(OidcConstants.PROMPT_LOGIN)) {
            casClient.getConfiguration().setRenew(true);
        }
    }

    /**
     * Configure client for prompt none authorization request.
     *
     * @param casClient the cas client
     * @param context   the context
     */
    public static void configureClientForPromptNoneAuthorizationRequest(final CasClient casClient, final WebContext context) {
        final Set<String> prompts = getOidcPromptFromAuthorizationRequest(context);
        if (prompts.contains(OidcConstants.PROMPT_NONE)) {
            casClient.getConfiguration().setRenew(false);
            casClient.getConfiguration().setGateway(true);
        }
    }
}