text:
require "goodreads"
load "secrets.rb" # Needs KEY, SECRET, USER_ID constants

client = Goodreads::Client.new(api_key: KEY, api_secret: SECRET)

File.open("../data/to-read.yaml", "w") do |file|
  book_list = []
  sorted_books = []

  page = 1
  total_pages = 2 # Each page holds 200 books, adjust total_pages accordingly.

  while page <= total_pages do

    shelf = client.shelf(USER_ID,
                         "to-read",
                         sort: "author",
                         per_page: 200,
                         page: page)
    shelf.books.each do |book|
      book_list << book
    end

    page += 1
  end

  sorted_books << book_list.sort_by do |book|
    [book["book"]["authors"]["author"]["name"].split[-1], book["book"]["title"]]
  end

  sorted_books[0].each do |book|
    author = book["book"]["authors"]["author"]["name"]
    title = book["book"]["title"]
    url = book["book"]["link"]
    file.puts "- author: #{author}\n  title: \"#{title}\"\n  url: \"#{url}\""
  end
end

redpajama_set_name: RedPajamaGithub


text:
RxFire

Firebase and RxJS for all frameworks

## What is RxFire?

- **Observable creators** - Observables bindings for most Firebase web libraries.
- **Portable** - Use across any framework or no framework at all.
- **Tree shake-able** - Import only what you need. Shake the rest out with your favorite module bundler like Webpack or Rollup.
- **Combine multiple data sources** - Need to join two Firestore references? Want to combine an image from Cloud Storage with a Firestore document? Super easy with observables and operators.
- **Simplify code-splitting of Firebase** - Using RxFire with Webpack makes it easy to load Firebase features on-demand.

Status: Beta

## Install

```bash
# npm
npm i rxfire firebase rxjs --save
# yarn
yarn add rxfire firebase rxjs
```

Make sure to install Firebase and RxJS individually as they are peer dependencies of RxFire.

## Example use:

```ts
import firebase from 'firebase/app';
import 'firebase/firestore';
import { collectionData } from 'rxfire/firestore';
import { tap } from 'rxjs/operators';

const app = firebase.initializeApp({ /* config */ });
const citiesRef = app.firestore().collection('cities');
citiesRef.where('state', '==', 'CO');

collectionData(citiesRef, 'id')
  .pipe(
    tap(cities => console.log('This is just an observable!'))
  )
  .subscribe(cities => { /* update UI */ })
```

## Easily combine multiple Firebase data sources

RxJS provides multiple operators and creation methods for combining observable streams. This makes it easy to combine data from multiple Firebase resources. You can also handle simplify high asynchronous tasks like joins into a flat stream.

The example below streams a list of "cities" from Firestore and then retrieves their image from a Cloud Storage bucket. Both tasks are asynchronous but RxJS makes it easy to combine these tasks together.

```ts
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/storage';
import { collectionData } from 'rxfire/firestore';
import { getDownloadURL } from 'rxfire/storage';
import { switchMap } from 'rxjs/operators';

const app = firebase.initializeApp({ /* config */ });
const citiesRef = app.firestore().collection('cities');
citiesRef.where('state', '==', 'CO');

collectionData(citiesRef, 'id')
  .pipe(
    switchMap(cities => {
      return combineLatest(...cities.map(c => {
        const ref = storage.ref(`/cities/${c.id}.png`);
        return getDownloadURL(ref).pipe(map(imageURL => ({ imageURL, ...c })));
      }));
    })
  )
  .subscribe(cities => {
    cities.forEach(c => console.log(c.imageURL));
  });
```

## Understanding RxFire imports

RxFire is a complementary library to Firebase. It is not meant to wrap the entire Firebase SDK. RxFire's purpose is to simplify async streams from Firebase. You need to import the Firebase SDK and initialize an app before using RxFire.

```ts
import firebase from 'firebase/app';
import 'firebase/storage'; // import only the features needed
import { getDownloadURL } from 'rxfire/storage';

const app = firebase.initializeApp({ /* config */ });
const ref = app.storage().ref('data.json');

// Now you can use RxFire!
const url$ = getDownloadURL(ref);
```

RxFire contains multiple entry points for module imports. Each Firebase library is an entry point.

```ts
import { } from 'rxfire/firestore';
import { } from 'rxfire/database';
import { } from 'rxfire/storage';
import { } from 'rxfire/auth';
import { } from 'rxfire/functions';
```

## Simple functions
RxFire is a set of functions. Most functions create observables and from there you can use regular RxJS operators. Some functions are custom operators. But at the end of the day, it's all just functions. This is important for **tree shaking**. Any unused functions are stripped from your final build if you use a module bundler like Webpack or Rollup.

```ts
import firebase from 'firebase/app';
import 'firebase/storage';
import { getDownloadURL, put /* not used! */ } 'rxfire/storage';

const app = firebase.initializeApp({ /* config */ });
const ref = app.storage().ref('data.json');

const url$ = getDownloadURL(ref);
```

## Documentation

- [Firestore](docs/firestore.md)
- [Authentication](docs/auth.md)
- [Storage](docs/storage.md)
- [Realtime Database](docs/database.md)

## Examples

[Examples](https://github.com/davideast/rxfire-samples): See this example repository for a list of ways to configure and use RxFire.


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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
# Overview

Apache ZooKeeper is a high-performance coordination service for distributed
applications. It exposes common services such as naming, configuration
management, synchronization, and group services in a simple interface. Use it
off-the-shelf to implement consensus, group management, leader election, and
presence protocols.

This charm provides the Zookeeper component of the [Apache Bigtop][] platform.

[Apache Bigtop]: http://bigtop.apache.org/

# Deploying

A working Juju installation is assumed to be present. If Juju is not yet set
up, please follow the [getting-started][] instructions prior to deploying this
charm.

Deploy a Zookeeper unit. With only one unit, the application will be running in
`standalone` mode:

    juju deploy zookeeper

## Network-Restricted Environments
Charms can be deployed in environments with limited network access. To deploy
in this environment, configure a Juju model with appropriate proxy and/or
mirror options. See [Configuring Models][] for more information.

[getting-started]: https://jujucharms.com/docs/stable/getting-started
[Configuring Models]: https://jujucharms.com/docs/stable/models-config

## Configuring Network Interfaces
In some network environments, zookeeper may need to be restricted to
listen for incoming connections on a specific network interface
(e.g.: for security reasons). To do so, configure zookeeper with either a
network interface name or a CIDR range specifying a subnet. For example:

    juju config zookeeper network_interface=eth0
    juju config zookeeper network_interface=10.0.2.0/24

> **Note**: The above assumes Juju 2.0 or greater. If using an earlier version
of Juju, the syntax is `juju set-config zookeeper network_interface=eth0`.

Each zookeeper unit in the cluster will lookup the IP address of that
network interface, or find the first network interface with an IP
address in the specified subnet, and bind Zookeeper to that address.

If a mistake is made and an invalid name for the network interface is
configured, recover by re-configuring with the correct name and then
run "juju resolved" on any failed units:

    juju config zookeeper network_interface=eth0
    juju resolved zookeeper/0

> **Note**: The above assumes Juju 2.0 or greater. If using an earlier version
of Juju, the syntax is `juju set-config zookeeper network_interface=eth0;
juju resolved -r zookeeper/0`.

To go back to listening on all interfaces, configure zookeeper with
`network_interface=0.0.0.0`:

    juju config zookeeper network_interface=0.0.0.0

> **Note**: The above assumes Juju 2.0 or greater. If using an earlier version
of Juju, the syntax is `juju set-config zookeeper network_interface=0.0.0.0`.

# Verifying

## Status
Apache Bigtop charms provide extended status reporting to indicate when they
are ready:

    juju status

This is particularly useful when combined with `watch` to track the on-going
progress of the deployment:

    watch -n 2 juju status

The message column will provide information about a given unit's state.
This charm is ready for use once the status message indicates that it is
ready.

## Smoke Test
This charm provides a `smoke-test` action that can be used to verify the
application is functioning as expected. Run the action as follows:

    juju run-action zookeeper/0 smoke-test

> **Note**: The above assumes Juju 2.0 or greater. If using an earlier version
of Juju, the syntax is `juju action do zookeeper/0 smoke-test`.

Watch the progress of the smoke test actions with:

    watch -n 2 juju show-action-status

> **Note**: The above assumes Juju 2.0 or greater. If using an earlier version
of Juju, the syntax is `juju action status`.

Eventually, the action should settle to `status: completed`.  If it
reports `status: failed`, the application is not working as expected. Get
more information about a specific smoke test with:

    juju show-action-output <action-id>

> **Note**: The above assumes Juju 2.0 or greater. If using an earlier version
of Juju, the syntax is `juju action fetch <action-id>`.

## Utilities
This charm includes Zookeeper command line utilities that can also be used to
verify that the application is running as expected. Check the status of the
Zookeeper daemon with `zkServer.sh`:

    juju run --application=zookeeper '/usr/lib/zookeeper/bin/zkServer.sh status'

A successful deployment will report the service mode as either `standalone`
(if only one Zookeeper unit has been deployed) or `leader` / `follower` (if
a Zookeeper quorum has been formed).

# Scaling

Running ZooKeeper in `standalone` mode is convenient for evaluation, some
development, and testing. In production, however, ZooKeeper should be run in
`replicated` mode. A replicated group of servers in the same application is
called a quorum, and in `replicated` mode, all servers in the quorum have
copies of the same configuration file.

In order to add new Zookeeper servers to the quorum, simply add more units.
For example, add two more zookeeper units with:

    juju add-unit -n 2 zookeeper

The Zookeeper nodes will automatically perform a rolling restart to update the
Zookeeper quorum without losing any jobs in progress. Once the rolling restart
has completed, all of the Zookeeper nodes should report the following status:

    ready (n units)

(Where 'n' is the total number of Zookeeper units in the quorum.)

# Integrating

To integrate Zookeeper into solutions with other charms, update the charms
that require Zookeeper as follows:

1) Add following lines to `metadata.yaml`:

    requires:
      zookeeper:
         interface: zookeeper

2) Add a `zookeeper-relation-changed` hook. Example contents:

    from charmhelpers.core.hookenv import relation_get
    ZK_hostname = relation_get('private-address')
    ZK_port = relation_get('port')

# Contact Information

- <bigdata@lists.ubuntu.com>

# Resources

- [Apache Bigtop](http://bigtop.apache.org/) home page
- [Apache Bigtop mailing lists](http://bigtop.apache.org/mail-lists.html)
- [Apache Zookeeper home page](https://zookeeper.apache.org/)
- [Apache Zookeeper issue tracker](https://issues.apache.org/jira/browse/ZOOKEEPER)
- [Juju Bigtop charms](https://jujucharms.com/q/apache/bigtop)
- [Juju mailing list](https://lists.ubuntu.com/mailman/listinfo/juju)
- [Juju community](https://jujucharms.com/community)


text:
package io.bootique.jdbc.junit5.tc;

import io.bootique.jdbc.junit5.Table;
import io.bootique.jdbc.junit5.tc.unit.BaseMySQLTest;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Table_MySQLIT extends BaseMySQLTest {

    static final Table t1 = db.getTable("t1");
    static final Table t5 = db.getTable("t5");

    @Test
    public void testDateTime_ViaSelect() {
        LocalDateTime ldt = LocalDateTime.of(2018, 1, 10, 4, 0, 1);
        t1.insertColumns("c1", "c2").values(1, ldt).exec();

        t1.matcher().assertOneMatch();
        Object[] data = t1.selectColumns("c2").where("c1", 1).selectOne(null);
        assertEquals(Timestamp.valueOf(ldt), data[0], "Timestamps do not match");
    }

    @Test
    public void testDateTime_ViaMatcher() {
        LocalDateTime ldt = LocalDateTime.of(2018, 1, 10, 4, 0, 1);
        t1.insertColumns("c1", "c2").values(1, ldt).exec();

        t1.matcher().assertOneMatch();
        t1.matcher().eq("c1", 1).eq("c2", ldt).assertOneMatch();
    }

    @Test
    public void testInsertNumericColumns() throws SQLException {
        t5.insertColumns("id", "c1", "c2")
                .values(1, null, null)
                .values(2, Long.MAX_VALUE - 5, new BigDecimal("2.345"))
                .values(3, 0, BigDecimal.ZERO)
                .exec();
        t5.matcher().assertMatches(3);

        try (Connection c = db.getConnection()) {
            try (Statement s = c.createStatement()) {
                try (ResultSet rs = s.executeQuery("select `id`, `c1`, `c2` from `t5` order by `id`")) {
                    rs.next();
                    assertEquals(1, rs.getInt(1));
                    assertEquals(null, rs.getObject(2));
                    assertEquals(null, rs.getObject(3));

                    rs.next();
                    assertEquals(2, rs.getInt(1));
                    assertEquals(Long.MAX_VALUE - 5, rs.getLong(2));
                    assertEquals(new BigDecimal("2.345"), rs.getBigDecimal(3));

                    rs.next();
                    assertEquals(3, rs.getInt(1));
                    assertEquals(0L, rs.getLong(2));
                    assertEquals(new BigDecimal("0.000"), rs.getBigDecimal(3));
                }
            }
        }
    }
}


text:
using EatSmart.Models;
using GalaSoft.MvvmLight;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using Parse;

namespace EatSmart.ViewModels.Basic
{
    public class FoodCategoryItemViewModel : ViewModelBase
    {
        public static Expression<Func<FoodCategoryItem, FoodCategoryItemViewModel>> FromData
        {
            get
            {
                return f => new FoodCategoryItemViewModel()
                {
                    Name = f.Name,
                    CategoryName = f.Category.FetchAsync().Result.Name,
                    Image = f.Image.Url.AbsoluteUri,
                    KCal = f.KCal,
                    Protein = f.Protein,
                    Carbohydrates = f.Carbohydrates,
                    Fats = f.Fats
                };
            }
        }

        [AutoIncrement]
        [PrimaryKey]
        public int Id { get; set; }

        public string CategoryName { get; set; }

        public string Description
        {
            get
            {
                return string.Format("KCals: {0}, Proteins: {1}, Carbohydrates: {2}, Fats: {3}",
                                    this.KCal, this.Protein, this.Carbohydrates, this.Fats);
            }
        }

        public string Name { get; set; }

        public string Image { get; set; }

        public double KCal { get; set; }

        public double Protein { get; set; }

        public double Carbohydrates { get; set; }

        public double Fats { get; set; }
    }
}


text:
<!DOCTYPE html>

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

  <link href="//appsforoffice.microsoft.com/fabric/1.0/fabric.min.css" rel="stylesheet">

  <link href="../content/Office.css" rel="stylesheet" type="text/css" />
  <link href="../bower_components/microsoft.office.js/styles/OfficeThemes.css" rel="stylesheet" type="text/css" />

Welcome


text:
<?php

/**
 * Checks for resources being loaded from CDNs.
 */

class CDNCheck implements themecheck {
	protected $error = array();

	function check( $php_files, $css_files, $other_files) {

		$ret = true;
		$php_code = implode( ' ', $php_files );
		$css_code = implode( ' ', $css_files );
		$all_code = $php_code . ' ' . $css_code;

		checkcount();

		$cdn_list = array(
			'bootstrap-maxcdn'      => 'maxcdn.bootstrapcdn.com/bootstrap',
			'bootstrap-netdna'      => 'netdna.bootstrapcdn.com/bootstrap',
			'bootswatch-maxcdn'     => 'maxcdn.bootstrapcdn.com/bootswatch',
			'bootswatch-netdna'     => 'netdna.bootstrapcdn.com/bootswatch',
			'font-awesome-maxcdn'   => 'maxcdn.bootstrapcdn.com/font-awesome',
			'font-awesome-netdna'   => 'netdna.bootstrapcdn.com/font-awesome',
			'html5shiv-google'      => 'html5shiv.googlecode.com/svn/trunk/html5.js',
			'html5shiv-maxcdn'      => 'oss.maxcdn.com/libs/html5shiv',
			'jquery'                => 'code.jquery.com/jquery-',
			'respond-js'            => 'oss.maxcdn.com/libs/respond.js',
		);

		foreach( $cdn_list as $cdn_slug => $cdn_url ) {
			if ( false !== strpos( $all_code, $cdn_url ) ) {
				$this->error[] = '' . __('RECOMMENDED','theme-check') . ': ' . sprintf( __( 'Found the URL of a CDN in the code: %s. You should not load CSS or Javascript resources from a CDN, please bundle them with the theme.', 'theme-check' ), '' . esc_html( $cdn_url ) . '' );
				//$ret = false;
			}
		}

		return $ret;
	}

	function getError() { return $this->error; }
}
$themechecks[] = new CDNCheck;


text:
include_recipe 'openresty::ohai_plugin'
include_recipe 'openresty::commons_user'
include_recipe 'openresty::commons_dir'
include_recipe 'openresty::commons_script'
include_recipe 'openresty::commons_build'

chef_gem 'httpclient' do
  compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
end
chef_gem 'archive-zip' do
  compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
end
require 'httpclient'
require 'archive/zip'
require 'fileutils'

time = Time.new.strftime('%Y-%m-%d-%H%M%S')
chef_dir = Chef::Config[:file_cache_path]

if node['3scale']['config-version'].nil?
  Chef::Log.warn("3SCALE - deploying gateway with LATEST configuration version: #{time}")
  version_dir = File.join(chef_dir, time)
  mode = node['3scale']['config-source']
else
  Chef::Log.warn("3SCALE - rolling back to configuration version: #{node['3scale']['config-version']}")
  version_dir = File.join(chef_dir, node['3scale']['config-version'])
  mode = 'rollback'
end

if mode == '3scale'
  # create directory to store downloaded configuration
  directory version_dir do
    owner node['openresty']['user']
    recursive true
    action :create
  end

  ruby_block 'fetch configuration files from 3scale' do
    block do
      Helpers.fetch_3scale_config(node['3scale']['admin-domain'],
                                  node['3scale']['provider-key'],
                                  version_dir)
    end
    action :run
  end
elsif mode == 'url'
  # create directory to store downloaded configuration
  directory version_dir do
    owner node['openresty']['user']
    recursive true
    action :create
  end

  ruby_block 'fetch configuration files from a URL' do
    block do
      Helpers.fetch_from_url(node['3scale']['config-url'], version_dir)
    end
    action :run
  end
elsif mode == 'local'
  # copy configuration files located at files/default/config
  remote_directory version_dir do
    source 'config'
    owner node['openresty']['user']
    group node['openresty']['group']
    mode '0755'
    files_owner node['openresty']['user']
    files_group node['openresty']['group']
    files_mode '0644'
    action :create
  end
end

# create links for configuration files that should be used
# in the nginx configuration directory
ruby_block 'symlink configuration files' do
  block do
    Helpers.link_files(version_dir, node['openresty']['dir'])
  end
  action :run

  # reload nginx if it was already running
  if node['openresty']['service']['start_on_boot']
    notifies :reload, node['openresty']['service']['resource']
  end
end

include_recipe 'openresty::commons_cleanup'
unless node['openresty']['service']['recipe'].nil?
  include_recipe(node['openresty']['service']['recipe'])
end


text:
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Corkboard{% endblock %}</title>
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    {% block content %}{% endblock %}
    <script src="zepto.min.js"></script>
    <script src="client.coffee"></script>
</body>
</html>


text:
package org.projectfloodlight.openflow.protocol.oxm;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.jboss.netty.buffer.ChannelBuffer;

public interface OFOxmVlanPcp extends OFObject, OFOxm<VlanPcp> {
    long getTypeLen();
    VlanPcp getValue();
    MatchField<VlanPcp> getMatchField();
    boolean isMasked();
    OFOxm<VlanPcp> getCanonical();
    VlanPcp getMask();
    OFVersion getVersion();

    void writeTo(ChannelBuffer channelBuffer);

    Builder createBuilder();
    public interface Builder extends OFOxm.Builder<VlanPcp> {
        OFOxmVlanPcp build();
        long getTypeLen();
        VlanPcp getValue();
        Builder setValue(VlanPcp value);
        MatchField<VlanPcp> getMatchField();
        boolean isMasked();
        OFOxm<VlanPcp> getCanonical();
        VlanPcp getMask();
        OFVersion getVersion();
    }
}


text: export const CLASS_SERIALIZER_OPTIONS = 'class_serializer:options';


text:
package name.reidmiller.iesoreports.client;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.net.MalformedURLException;

import name.reidmiller.iesoreports.IesoPublicReportBindingsConfig;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

import ca.ieso.reports.schema.iomspublicplanneodutagemonth.DocBody;
import ca.ieso.reports.schema.iomspublicplanneodutagemonth.DocHeader;
import ca.ieso.reports.schema.iomspublicplanneodutagemonth.Document;

public class PlannedTransmissionOutagesMonthClientTest {
	private Logger logger = LogManager.getLogger(this.getClass());
	private PlannedTransmissionOutagesMonthClient plannedTransmissionOutagesMonthClient;

	@Before
	public void setUp() throws Exception {
		plannedTransmissionOutagesMonthClient = IesoPublicReportBindingsConfig
				.plannedTransmissionOutagesMonthClient();
	}

	@Test
	public void testGetDefaultDocument() {
		try {
			assertNotNull(Document.class.getName()
					+ " could not be retrieved from XML",
					plannedTransmissionOutagesMonthClient.getDefaultDocument());
		} catch (MalformedURLException e) {
			fail(e.getMessage());
		} catch (IOException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void testGetDefaultDocHeader() {
		try {
			assertNotNull(DocHeader.class.getName()
					+ " could not be retrieved from XML",
					plannedTransmissionOutagesMonthClient.getDefaultDocHeader());
		} catch (MalformedURLException e) {
			fail(e.getMessage());
		} catch (IOException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void testGetDefaultDocBody() {
		try {
			assertNotNull(DocBody.class.getName()
					+ " could not be retrieved from XML",
					plannedTransmissionOutagesMonthClient.getDefaultDocBody());
		} catch (MalformedURLException e) {
			fail(e.getMessage());
		} catch (IOException e) {
			fail(e.getMessage());
		}
	}
}


text:
package fr.goui.gouitify.listener;

/**
 *
 */
public interface OnTrackClickListener {

    void onTrackClick(String trackId);
}


text:
var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var venueSchema = new Schema({
    name: String,
    going: Number
});

var Venue = mongoose.model('Venue', venueSchema);

module.exports = {
    venue: Venue
}


text:
from __future__ import absolute_import, division, print_function

import os
import sys
import shutil
import textwrap
from fnmatch import fnmatch

from setuptools import Command, setup, convert_path

#------------------------------------------------------------------------
# Top Level Packages
#------------------------------------------------------------------------

def ispackage(x):
    return os.path.isdir(x) and os.path.exists(os.path.join(x, '__init__.py'))

def istestdir(x):
    return os.path.isdir(x) and not os.path.exists(os.path.join(x, '__init__.py'))

def find_packages(where='blaze', exclude=('ez_setup', 'distribute_setup'),
                  predicate=ispackage):
    if sys.version_info[0] == 3:
        exclude += ('*py2only*', '*__pycache__*')

    func = lambda x: predicate(x) and not any(fnmatch(x, exc)
                                              for exc in exclude)
    return list(filter(func, [x[0] for x in os.walk(convert_path(where))]))

packages = find_packages()
testdirs = find_packages(predicate=(lambda x: istestdir(x) and
                                    os.path.basename(x) == 'tests'))

#------------------------------------------------------------------------
# Minimum Versions
#------------------------------------------------------------------------

#------------------------------------------------------------------------
# Utilities
#------------------------------------------------------------------------

# Some functions for showing errors and warnings.
def _print_admonition(kind, head, body):
    tw = textwrap.TextWrapper(
        initial_indent='   ', subsequent_indent='   ')

    print(".. %s:: %s" % (kind.upper(), head))
    for line in tw.wrap(body):
        print(line)

def exit_with_error(head, body=''):
    _print_admonition('error', head, body)
    sys.exit(1)

def check_import(pkgname, pkgver):
    try:
        mod = __import__(pkgname)
    except ImportError:
            exit_with_error(
                "You need %(pkgname)s %(pkgver)s or greater to run Blaze!"
                % {'pkgname': pkgname, 'pkgver': pkgver} )
    else:
        if mod.__version__ < pkgver:
            exit_with_error(
                "You need %(pkgname)s %(pkgver)s or greater to run Blaze!"
                % {'pkgname': pkgname, 'pkgver': pkgver} )

    print("* Found %(pkgname)s %(pkgver)s package installed."
            % {'pkgname': pkgname, 'pkgver': mod.__version__} )
    globals()[pkgname] = mod

#------------------------------------------------------------------------
# Commands
#------------------------------------------------------------------------

class CleanCommand(Command):
    """Custom distutils command to clean the .so and .pyc files."""

    user_options = []

    def initialize_options(self):
        self._clean_me = []
        self._clean_trees = []

        for toplevel in packages:
            for root, dirs, files in list(os.walk(toplevel)):
                for f in files:
                    if os.path.splitext(f)[-1] in ('.pyc', '.so', '.o', '.pyd'):
                        self._clean_me.append(os.path.join(root, f))

        for d in ('build',):
            if os.path.exists(d):
                self._clean_trees.append(d)

    def finalize_options(self):
        pass

    def run(self):
        for clean_me in self._clean_me:
            try:
                print('flushing', clean_me)
                os.unlink(clean_me)
            except Exception:
                pass
        for clean_tree in self._clean_trees:
            try:
                print('flushing', clean_tree)
                shutil.rmtree(clean_tree)
            except Exception:
                pass

#------------------------------------------------------------------------
# Setup
#------------------------------------------------------------------------

def find_data_files(exts, where='blaze'):
    exts = tuple(exts)
    for root, dirs, files in os.walk(where):
        for f in files:
            if any(fnmatch(f, pat) for pat in exts):
                yield os.path.join(root, f)

exts = '*.h5', '*.csv', '*.xls', '*.xlsx', '*.db', '*.json', '*.gz', '*.hdf5'
package_data = [os.path.join(x.replace('blaze' + os.sep, ''),
                             '*.py') for x in testdirs]
package_data += [x.replace('blaze' + os.sep, '') for x in find_data_files(exts)]

with open('README.md') as f:
    longdesc = f.read()

setup(
    name='blaze',
    version='0.7.3',
    author='Continuum Analytics',
    author_email='blaze-dev@continuum.io',
    description='Blaze',
    long_description=longdesc,
    install_requires=open('requirements-strict.txt').read().strip().split('\n'),
    license='BSD',
    platforms = ['any'],
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Intended Audience :: Education',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering',
        'Topic :: Utilities',
    ],
    package_data={'blaze': package_data},
    packages=packages,
    cmdclass={'clean': CleanCommand}
)


text:
import { join } from "path"
import { WebServer, WebServerOptions } from "../server/webServer"
import { ANSIColor, color } from "../utils/ansi"
import { HTTPRequest, HTTPResponse } from "../utils/httpServer"
import { containsPath, getDir, getName } from "../utils/path"
import { Builder } from "./builder"
import { i18n } from "./i18n"
import { GeneratedModule } from "./module"

/** 表示一个开发服务器 */
export class Server extends WebServer {

	// #region 选项

	/** 获取所属的构建器 */
	readonly builder: Builder

	/**
	 * 初始化新的开发服务器
	 * @param builder 所属的构建器
	 * @param options 服务器的附加选项
	 */
	constructor(builder: Builder, options: ServerOptions = {}) {
		super({ mimeTypes: builder.mimeTypes, ...options })
		this.builder = builder
		// @ts-ignore
		this.directoryList = options.directoryList !== false
	}

	/** 启动服务器 */
	async start() {
		try {
			await super.start()
			this.builder.logger.info(`${color(i18n`Server running at`, ANSIColor.brightCyan)} ${this.url}`, true)
		} catch (e) {
			if (e.code === "EADDRINUSE") {
				this.builder.logger.fatal(i18n`Cannot start server: Port ${e.port} is used by other program`)
			} else {
				this.builder.logger.fatal(i18n`Cannot start server: ${e.stack}`)
			}
		}
	}

	/** 关闭服务器 */
	async close() {
		await super.close()
		this.builder.logger.info(color(i18n`Server stopped`, ANSIColor.brightCyan), true)
	}

	// #endregion

	// #region 请求

	/**
	 * 默认路由
	 * @param request 当前的请求对象
	 * @param response 当前的响应对象
	 */
	async defaultRouter(request: HTTPRequest, response: HTTPResponse) {
		// 执行自定义文件
		// 如果在用户请求一个文件时,该文件被更新,我们希望获取到该文件的最新版本
		// 技术上可以做到只等待当前文件生成,忽略其它文件
		// 假设一个页面引用了 2 个文件,第 1 个已生成,第 2 个文件正在生成
		// 如果此时 2 个文件都被修改,可能导致这个页面引了第 1 个文件的老版本和第 2 个文件的新版本
		// 为避免这个情况,只要任意文件正在构建,都延迟响应
		// 这个策略可能会降低某些情况的性能,但提高了服务器的稳定性
		await this.builder.watcher!.ready()
		const path = join(this.builder.rootDir, request.path)
		const module = this.builder.emittedModules.get(path)
		if (module) {
			return this.writeModule(request, response, module)
		}
		const entries = await this.readDir(path)
		if (entries.length > 0) {
			if (this.directoryList) {
				this.writeDir(request, response, entries)
			} else {
				this.writeError(request, response, 403)
			}
			return
		}
		this.writeError(request, response, 404)
	}

	/**
	 * 响应一个文件
	 * @param request 当前的请求对象
	 * @param response 当前的响应对象
	 * @param module 要响应的文件
	 */
	writeModule(request: HTTPRequest, response: HTTPResponse, module: GeneratedModule) {
		const ifNoneMatch = request.headers["if-none-match"]!
		if (ifNoneMatch === module.hash) {
			response.writeHead(304, this.headers)
			return response.end()
		}
		module.type = module.type || this.builder.getMimeType(module.path)
		if (module.bufferOrContent === undefined) {
			return new Promise<void>(resolve => {
				const stream = this.builder.fs.createReadStream(module.originalModule!.originalPath)
				stream.on("open", () => {
					response.writeHead(200, {
						"Content-Type": module.type,
						"ETag": module.hash,
						...this.headers
					})
				})
				stream.on("error", error => {
					this.writeError(request, response, error)
				})
				stream.pipe(response)
				stream.on("close", resolve)
			})
		} else {
			response.writeHead(200, {
				"Content-Type": module.type,
				"ETag": module.hash,
				...this.headers
			})
			response.end(module.bufferOrContent)
		}
	}

	/**
	 * 读取文件夹信息
	 * @param path 要读取的文件夹路径(相对于根路径)
	 */
	async readDir(path: string) {
		path = path.replace(/[\/\\]$/, "")
		const entries: Promise<{ name: string, isDir?: boolean, modified?: Date, size?: number, title?: string }>[] = []
		const dirs = new Set<string>()
		for (const [filePath, module] of this.builder.emittedModules) {
			if (containsPath(path, filePath, false)) {
				if (getDir(filePath) === path) {
					const originalPath = module.originalModule!.originalPath
					if (originalPath) {
						entries.push(this.fs.getStat(originalPath).then(stats => ({
							name: getName(module.path),
							isDir: false,
							modified: stats.mtime,
							size: module.bufferOrContent === undefined ? stats.size : module.size,
							title: i18n`Generated from ${this.builder.relativePath(originalPath)}`
						}), () => ({
							name: getName(module.path),
							isDir: false,
							size: module.bufferOrContent === undefined ? undefined : module.size,
							title: i18n`Generated from ${this.builder.relativePath(originalPath)}`
						})))
					} else {
						entries.push({
							name: getName(module.path),
							isDir: false,
							title: i18n`Generated`
						} as any)
					}
				} else {
					const dir = filePath.substring(path.length).replace(/^[\/\\]/, "").replace(/[\/\\].*$/, "")
					if (!dirs.has(dir)) {
						dirs.add(dir)
						entries.push(this.fs.getStat(this.builder.resolvePath(`${path || "."}/${dir}`)).then(stats => ({
							name: dir,
							isDir: true,
							modified: stats.mtime
						}), () => ({
							name: dir,
							isDir: true
						})))
					}
				}
			}
		}
		return await Promise.all(entries)
	}

	// #endregion

}

/** 表示开发服务器的选项 */
export interface ServerOptions extends WebServerOptions {
	/**
	 * 设置是否在文件修改后自动刷新页面
	 * @default true
	 */
	autoReload?: boolean
	/**
	 * 设置是否启用模块热替换
	 * @default true
	 */
	hotReload?: boolean
}


text:
package github

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
)

// HasLabel checks if label is in the label set "issueLabels".
func HasLabel(label string, issueLabels []Label) bool {
	for _, l := range issueLabels {
		if strings.ToLower(l.Name) == strings.ToLower(label) {
			return true
		}
	}
	return false
}

// ImageTooBig checks if image is bigger than github limits
func ImageTooBig(url string) (bool, error) {
	// limit is 10MB
	limit := 10000000
	// try to get the image size from Content-Length header
	resp, err := http.Head(url)
	if err != nil {
		return true, fmt.Errorf("HEAD error: %v", err)
	}
	if sc := resp.StatusCode; sc != http.StatusOK {
		return true, fmt.Errorf("failing %d response", sc)
	}
	size, _ := strconv.Atoi(resp.Header.Get("Content-Length"))
	if size > limit {
		return true, nil
	}
	return false, nil
}

// LevelFromPermissions adapts a repo permissions struct to the
// appropriate permission level used elsewhere
func LevelFromPermissions(permissions RepoPermissions) RepoPermissionLevel {
	if permissions.Admin {
		return Admin
	} else if permissions.Push {
		return Write
	} else if permissions.Pull {
		return Read
	} else {
		return None
	}
}

// PermissionsFromLevel adapts a repo permission level to the
// appropriate permissions struct used elsewhere
func PermissionsFromLevel(permission RepoPermissionLevel) RepoPermissions {
	switch permission {
	case None:
		return RepoPermissions{}
	case Read:
		return RepoPermissions{Pull: true}
	case Write:
		return RepoPermissions{Pull: true, Push: true}
	case Admin:
		return RepoPermissions{Pull: true, Push: true, Admin: true}
	default:
		return RepoPermissions{}
	}
}