text:
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"math"
	"strconv"
)

type listFormatter struct {
	subjSize int
	projSize int
}

func listCmd(args []string) int {
	if len(args) <= 0 {
		fmt.Println("")
		listCmdExec("outgoing")
		listCmdExec("incoming")
		listCmdExec("closed")
		return 0
	} else {
		fmt.Println("")
		for len(args) > 0 {
			listCmdExec(args[0][2:])
			args = args[1:]
		}
	}
	return 1
}

func listCmdExec(op string) {
	headers, list := getChanges(op)
	lf := analyzeSizes(list)
	printDefaultList(headers, list, lf)
	fmt.Println("")
}

func getChanges(op string) (string, []ChangeInfo) {
	cmd := NewGrtCmd("GET", changes_endpoint)
	var headers string
	switch op {
	case "outgoing":
		headers = "Outgoing reviews (--outgoing):"
		cmd.getVars = map[string]string{
			"q": "is:open+owner:self",
		}

	case "incoming":
		headers = "Incoming reviews (--incoming):"
		cmd.getVars = map[string]string{
			"q": "is:open+reviewer:self+-owner:self",
		}

	case "closed":
		headers = "Incoming reviews (--closed):"
		cmd.getVars = map[string]string{
			"q": "is:closed+owner:self+limit:15&o=LABELS",
		}

	default:
		log.Fatal("--" + op + " is an invalid option.")
	}

	resp := cmd.Call()

	var list []ChangeInfo
	json.Unmarshal([]byte(resp), &list)

	return headers, list
}

func analyzeSizes(list []ChangeInfo) listFormatter {
	var lf listFormatter
	lf.subjSize = 8
	lf.projSize = 8

	for i := 0; i < len(list); i++ {
		if len(list[i].Subject) > lf.subjSize {
			lf.subjSize = len(list[i].Subject)
		}

		if len(list[i].Project) > lf.projSize {
			lf.projSize = len(list[i].Project)
		}
	}

	return lf
}

func printDefaultList(headers string, list []ChangeInfo, formatter listFormatter) {
	idHeader := "ID:  "
	subjHeader := "Subject:"
	projHeader := "Project:"
	mergeHeader := "Review:  "

	fmt.Println(headers)

	for i := len(subjHeader); i < formatter.subjSize; i++ {
		subjHeader += " "
	}

	for i := len(projHeader); i < formatter.projSize; i++ {
		projHeader += " "
	}

	fmt.Println(idHeader + "\t" + subjHeader + "\t" + projHeader + "\t" + mergeHeader)

	for i := 0; i < len(list); i++ {
		for j := len(list[i].Subject); j < formatter.subjSize; j++ {
			list[i].Subject += " "
		}

		for j := len(list[i].Project); j < formatter.projSize; j++ {
			list[i].Project += " "
		}

		cr := getCodeReview(strconv.Itoa(list[i].Number))

		fmt.Println(strconv.Itoa(list[i].Number) + "\t" + list[i].Subject + "\t" + list[i].Project + "\t" + strconv.Itoa(cr))
	}
}

func getCodeReview(id string) int {
	crh := 0
	crl := 0

	details := getChangeDetails(id)
	for i := 0; i < len(details.Labels.CodeReview.All); i++ {
		if details.Labels.CodeReview.All[i].Value < crl {
			crl = details.Labels.CodeReview.All[i].Value
		}

		if crh < details.Labels.CodeReview.All[i].Value {
			crh = details.Labels.CodeReview.All[i].Value
		}
	}

	var cr int
	if math.Abs(float64(crl)) >= float64(crh) {
		cr = crl
	} else {
		cr = crh
	}

	return cr
}


text:
.class public Lcom/android/internal/policy/impl/keyguard/KeyguardStatusViewExtendManager;
.super Ljava/lang/Object;
.source "KeyguardStatusViewExtendManager.java"

# direct methods
.method public constructor <init>(Landroid/view/View;Lcom/android/internal/policy/impl/keyguard/KeyguardUpdateMonitor;Lcom/android/internal/widget/LockPatternUtils;Lcom/android/internal/policy/impl/keyguard/KeyguardSecurityCallback;Z)V
    .locals 0
    .parameter "view"
    .parameter "updateMonitor"
    .parameter "lockPatternUtils"
    .parameter "callback"
    .parameter "emergencyButtonEnabledInScreen"

    .prologue
    .line 13
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 15
    return-void
.end method

# virtual methods
.method public cleanUp()V
    .locals 0

    .prologue
    .line 19
    return-void
.end method

.method public onResume()V
    .locals 0

    .prologue
    .line 22
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'dashboard-cmp',
    templateUrl: 'dashboard.component.html'
})

export class DashboardComponent{}


text:
class AdminUser < ActiveRecord::Base

  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable,
         :validatable, :lockable

  has_and_belongs_to_many :virtual_domains, :join_table => :users_domains

  attr_accessible :name, :email, :password, :password_confirmation, :virtual_domain_ids

  attr_accessor :password_confirmation

  validates :email,
    :presence   => true,
    :uniqueness => true,
    :format     => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i }
  #validates :password,
  #  :presence   => true,
  #  :unless     => 'selfpassword.empty?'

  before_create :be_super!, :if => 'AdminUser.first.nil?'

  def be_super!
    self.super = true
  end

  def domains
    vd = self.super == true ? VirtualDomain.all : self.virtual_domains
    vd.each do |domain|
      VirtualUser.drop_domain_from_email_each(domain.virtual_users)
    end
    vd
  end

  def domain(id)
    (self.super == true ? VirtualDomain : self.virtual_domains).find(id)
  end

  def build_domain(params)
    domain = self.virtual_domains.build
    domain[:name] = params[:name]
    domain
  end

  def change_data(params)
    attrs = params.symbolize_keys
    if attrs[:password].blank?
      attrs.delete(:password)
      update_without_password(attrs)
    else
      update_with_password(attrs)
    end
  end

end


text:
var space = require('./space');

// Listen for when the watchface is opened
Pebble.addEventListener('ready',
                        function(e) {
                            console.log('PebbleKit JS ready!');
                        }
                       );

// Listen for when an AppMessage is received
Pebble.addEventListener('appmessage',
                        function(e) {
                            console.log('AppMessage received!');
                            loadSettings();
                            getLocation();
                        }
                       );

function locationSuccess(pos) {
    var lat = pos.coords.latitude;
    var lon = pos.coords.longitude;

    var date = new Date();

    //getCity(lat, lon);
    getWeather(lat, lon);
    getSpace(lat, lon, date);
}

function getCity(lat, lon) {
    var key = '1fea09dcd5fb19e812f9';
    var url = 'http://locationiq.org/v1/reverse.php?format=json&key=' + key + '&lat=' + lat + '&lon=' + lon + '&zoom=10';
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        // responseText contains a JSON object with weather info
        var json = JSON.parse(this.responseText);

        console.log(JSON.stringify(json, null, 2));

        var cityname = json.address.city;

        // Assemble dictionary using our keys
        var dictionary = {
            'CITY': cityname,
        };

        // Send to Pebble
        Pebble.sendAppMessage(dictionary,
                              function(e) {
                                  console.log('City info sent to Pebble successfully!');
                              },
                              function(e) {
                                  console.log('Error sending city info to Pebble!');
                              }
                             );
    } ;
    xhr.open('GET', url);
    xhr.send();
}

function getWeather(lat, lon) {

    var apiKey = settings.CFG_DARKSKY_KEY.trim();
    var units = settings.CFG_CELSIUS ? 'si' : 'us';

    if (apiKey !== "") {

        var url = 'https://api.darksky.net/forecast/' + apiKey + '/' + lat + ',' + lon + '?units=' + units;
        console.log(url);
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            // responseText contains a JSON object with weather info
            var json = JSON.parse(this.responseText);

            // Temperature in Kelvin requires adjustment
            var temperature = Math.round(json.currently.temperature);
            console.log('Temperature is ' + temperature);

            // Conditions
            var conditions = json.currently.icon;
            console.log('Conditions are ' + conditions);

            var nextDay = "";
            for (var i = 0; i < 24; i++) {
                //clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
                // c, r, s, p, _, ?
                switch(json.hourly.data[i].icon) {
                    case 'clear-day':
                    case 'clear-night':
                    case 'wind':
                        nextDay += '_';
                        break;
                    case 'rain':
                        nextDay += 'r';
                        break;
                    case 'snow':
                    case 'sleet':
                        nextDay += 's';
                        break;
                    case 'fog':
                    case 'cloudy':
                        nextDay += 'c';
                        break;
                    case 'partly-cloudy-day':
                    case 'partly-cloudy-night':
                        nextDay += 'p';
                        break;
                    default:
                        nextDay += '?';
                        break;
                }
            }

            console.log("Next 24 hours: " + nextDay);

            // Assemble dictionary using our keys
            var dictionary = {
                'TEMPERATURE': temperature,
                'CONDITIONS': conditions,
                'FORECAST': nextDay
            };

            // Send to Pebble
            Pebble.sendAppMessage(dictionary,
                                  function(e) {
                                      console.log('Weather info sent to Pebble successfully!');
                                  },
                                  function(e) {
                                      console.log('Error sending weather info to Pebble!');
                                  }
                                 );
        } ;
        xhr.open('GET', url);
        xhr.send();
    }
}

function locationError(err) {
    console.log('Error requesting location!');
}

function getSpace(lat, lon, date) {
    space.calculate(lat, lon, date);
    // Assemble dictionary using our keys
    var dictionary = {
        'SPACE_SUN': space.sun,
        'SPACE_SUNRISE': space.sunrise,
        'SPACE_SUNSET': space.sunset,
        'SPACE_MOON': space.moon,
        'SPACE_MERCURY': space.mercury,
        'SPACE_VENUS': space.venus,
        'SPACE_MARS': space.mars,
        'SPACE_JUPITER': space.jupiter,
        'SPACE_SATURN': space.saturn,
    };

    // Send to Pebble
    Pebble.sendAppMessage(dictionary,
                          function(e) {
                              console.log('Space info sent to Pebble successfully!');
                          },
                          function(e) {
                              console.log('Error sending space info to Pebble!');
                          }
                         );
}

function getLocation() {
    navigator.geolocation.getCurrentPosition(
        locationSuccess,
        locationError,
        {timeout: 15000, maximumAge: 60000}
    );
}

// Import the Clay package
var Clay = require('pebble-clay');
// Load our Clay configuration file
var clayConfig = require('./config');
// Initialize Clay
var clay = new Clay(clayConfig);

var defaultSettings = {'CFG_ANALOG':true, 'CFG_CELSIUS':true, 'CFG_DARKSKY_KEY':'' }
var settings = {};

function loadSettings() {
    try {
        settings = JSON.parse(localStorage.getItem('clay-settings')) || defaultSettings;
        console.log("Settings: " + settings);
    } catch (e) {
        console.log("Failed to get settings: " + e);
    }
}

loadSettings();

// Listen for when the watchface is opened
Pebble.addEventListener('ready',
                        function(e) {
                            console.log('PebbleKit JS ready!');

                            // Get the initial weather
                            getLocation();
                        }
                       );


text:
package at.kc.tugraz.sss.app.datatypes.par;

import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.serv.datatype.SSTextComment;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.datatype.par.SSServPar; import at.tugraz.sss.serv.util.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SSAppAddPar extends SSServPar{

  public SSLabel             label                  = null;
  public SSTextComment       descriptionShort       = null;
  public SSTextComment       descriptionFunctional  = null;
  public SSTextComment       descriptionTechnical   = null;
  public SSTextComment       descriptionInstall     = null;
  public List<SSUri>         downloads              = new ArrayList<>();
  public SSUri               downloadIOS            = null;
  public SSUri               downloadAndroid        = null;
  public SSUri               fork                   = null;
  public List<SSUri>         screenShots            = new ArrayList<>();
  public List<SSUri>         videos                 = new ArrayList<>();

  public void setLabel(final String label) throws SSErr{
    this.label = SSLabel.get(label);
  }

  public void setDescriptionShort(final String descriptionShort) throws SSErr{
    this.descriptionShort = SSTextComment.get(descriptionShort);
  }

  public void setDescriptionFunctional(final String descriptionFunctional)throws SSErr{
    this.descriptionFunctional = SSTextComment.get(descriptionFunctional);
  }

  public void setDescriptionTechnical(final String descriptionTechnical)throws SSErr{
    this.descriptionTechnical = SSTextComment.get(descriptionTechnical);
  }

  public void setDescriptionInstall(final String descriptionInstall)throws SSErr{
    this.descriptionInstall = SSTextComment.get(descriptionInstall);
  }

  public void setDownloads(final List<String> downloads)throws SSErr{
    this.downloads = SSUri.get(downloads);
  }

  public void setDownloadIOS(final String downloadIOS)throws SSErr{
    this.downloadIOS =  SSUri.get(downloadIOS);
  }

  public void setDownloadAndroid(final String downloadAndroid)throws SSErr{
    this.downloadAndroid =  SSUri.get(downloadAndroid);
  }

  public void setFork(final String fork)throws SSErr{
    this.fork =  SSUri.get(fork);
  }

  public void setScreenShots(final List<String> screenShots)throws SSErr{
    this.screenShots =  SSUri.get(screenShots);
  }

  public void setVideos(final List<String> videos) throws SSErr{
    this.videos =  SSUri.get(videos);
  }

  public String getLabel(){
    return SSStrU.toStr(label);
  }

  public String getDescriptionShort(){
    return SSStrU.toStr(descriptionShort);
  }

  public String getDescriptionFunctional(){
    return SSStrU.toStr(descriptionFunctional);
  }

  public String getDescriptionTechnical(){
    return SSStrU.toStr(descriptionTechnical);
  }

  public String getDescriptionInstall(){
    return SSStrU.toStr(descriptionInstall);
  }

  public List<String> getDownloads() throws SSErr{
    return SSStrU.toStr(downloads);
  }

  public String getDownloadIOS(){
    return SSStrU.toStr(downloadIOS);
  }

  public String getDownloadAndroid(){
    return SSStrU.toStr(downloadAndroid);
  }

  public String getFork(){
    return SSStrU.toStr(fork);
  }

  public List<String> getScreenShots()throws SSErr{
    return SSStrU.toStr(screenShots);
  }

  public List<String> getVideos()throws SSErr{
    return SSStrU.toStr(videos);
  }

  public SSAppAddPar(){/* Do nothing because of only JSON Jackson needs this */ }

  public SSAppAddPar(
    final SSServPar servPar,
    final SSUri               user,
    final SSLabel             label                  ,
    final SSTextComment       descriptionShort       ,
    final SSTextComment       descriptionFunctional  ,
    final SSTextComment       descriptionTechnical   ,
    final SSTextComment       descriptionInstall     ,
    final List<SSUri>         downloads              ,
    final SSUri               downloadIOS            ,
    final SSUri               downloadAndroid        ,
    final SSUri               fork                   ,
    final List<SSUri>         screenShots            ,
    final List<SSUri>         videos                 ,
    final boolean             withUserRestriction,
    final boolean             shouldCommmit){

    super(SSVarNames.appAdd, null, user, servPar.sqlCon);

    this.label                  = label;
    this.descriptionShort       = descriptionShort;
    this.descriptionFunctional  = descriptionFunctional;
    this.descriptionTechnical   = descriptionTechnical;
    this.descriptionInstall     = descriptionInstall;

    if(downloads != null){
      this.downloads.addAll(downloads);
    }

    this.downloadIOS            = downloadIOS;
    this.downloadAndroid        = downloadAndroid;
    this.fork                   = fork;

    if(screenShots != null){
      this.screenShots.addAll(screenShots);
    }

    if(videos != null){
      this.videos.addAll(videos);
    }

    this.withUserRestriction = withUserRestriction;
    this.shouldCommit        = shouldCommmit;
  }
}


text:
package net.brightkite4j.brightkite.resources;

import net.brightkite4j.brightkite.exceptions.DeserializationException;
import net.brightkite4j.brightkite.utils.BrightkiteUtils;

public class Placemark extends BrightkiteObject {

	private String placemark;
	private Person user;
	private Place place;

	public String getPlacemark() {
		return placemark;
	}

	public void setPlacemark(String placemark) {
		this.placemark = placemark;
	}

	public Person getUser() {
		return user;
	}

	public void setUser(Person user) {
		this.user = user;
	}

	public Place getPlace() {
		return place;
	}

	public void setPlace(Place place) {
		this.place = place;
	}

	public final static Placemark fromXML(String xml) {
		try {
			Placemark placemark = (Placemark)BrightkiteUtils.fromXML(xml, Placemark.class);
			return placemark;
		} catch (Exception e) {
			throw new DeserializationException("Could not deserialize Placemark.", e);
		}
	}

}


text:
package dtos;

public class ContentDto
{
    private String content1;
    private String content2;
    private String divName;

    public ContentDto(String content1, String content2, String divName) {
        this.content1 = content1;
        this.content2 = content2;
        this.divName = divName;
    }
}


text:
			<?php get_sidebar('components'); ?>

Nestable

Create nestable lists that can be sorted by drag and drop.

The Nestable allows you to sort items through drag and drop. This is great, if you want to organize different categories or menu items in administration areas, for example.

Usage

A nestable list consists of the list itself and its items, a handle and a toggle.

									Class/Data attribute
									Description

									.nestable
									Add this class to a
										<ul> element to define the component.

									data-nestable
									To enable the necessary JavaScript, just add this data attribute.

									.nestable-item
									Add this class to a
										<div> element inside each list item.

									.nestable-handle
									This class creates the handle to enable drag and drop sorting.

									data-nestable-action="toggle"
									This data attribute allows you to hide or show nested list items.

Example

 Item 1

 Item 2

 Item 3

Markup

<ul class="nestable" data-nestable>
    <li>
        <div class="nestable-item">
            <div class="nestable-handle"></div>
            <div data-nestable-action="toggle"></div>
            ...
        </div>
    </li>
</ul>

Sort multiple lists

To be able to sort items from one list to another, you can group them by adding the data-nestable="{group:'GROUP-NAME'}" attribute to each list. By default, lists without any group name are automatically in the same group.

Example

 Item 1

 Item 2

 Item 3

Second list

 Item 4

Markup

<ul class="nestable" data-nestable="{group:'my-group'}">...</ul>
<ul class="nestable" data-nestable="{group:'my-group'}">...</ul>

Disable nesting

To disable nesting of list items, just add the data-nestable="{maxDepth:1}" attribute. You can also use this data attribute to determine to what depth nesting is possible.

 Item 1

 Item 2

 Item 3

Markup

<ul class="nestable" data-nestable="{maxDepth:1}">...</ul>

JavaScript options

This is an example of how to set options via attribute:

data-nestable="{maxDepth:0, group:'widgets'}"

									Option
									Possible value
									Default
									Description

									group
									integer (0..6)
									0
									List group

									maxDepth
									integer
									10
									Max nesting level

Init element manually

var nestable = Clique.nestable(element, {
    /* options */
});

Events

									Name
									Parameter
									Description

									start.clique.nestable
									event, nestable object
									On nestable drag start

									move.clique.nestable
									event, nestable object
									On nestable move item

									stop.clique.nestable
									event, nestable object
									On nestable stop dragging

									change.clique.nestable
									event, nestable item, action
									On nestable change item

				<?php get_microdata('author'); ?>


text:
"""Temp drops in the fall"""
from calendar import month_abbr
from datetime import date

import pandas as pd
from pyiem.plot import figure
from pyiem.util import get_autoplot_context, get_sqlalchemy_conn
from pyiem.exceptions import NoDataFound

def get_description():
    """Return a dict describing how to call this plotter"""
    desc = {}
    desc["data"] = True
    desc[
        "description"
    ] = """This plot presents the largest drop in low
    temperature during a period between 1 July and 30 June of the next year,
    but not including the July data of that year. The drop compares the lowest
    low previous to the date with the low for that date.  For example,
    if your coldest low to date was 40, you would not expect to see a
    low temperature of 20 the next night without first setting colder
    daily low temperatures. See also
    this autoplot
    for more details."""
    desc["arguments"] = [
        dict(
            type="station",
            name="station",
            default="IATAME",
            label="Select Station:",
            network="IACLIMATE",
        ),
        dict(
            type="year",
            name="year",
            default=date.today().year,
            label="Year to Highlight",
        ),
    ]
    return desc

def plotter(fdict):
    """Go"""
    ctx = get_autoplot_context(fdict, get_description())
    station = ctx["station"]
    year = ctx["year"]
    with get_sqlalchemy_conn("coop") as conn:
        df = pd.read_sql(
            """
        with obs as (
        select day, (case when month < 7 then year - 1 else year end)
            as myyear,
        low, month from alldata where station = %s
        ), obs2 as (
            select day, myyear, low, month,
            low - min(low) OVER
            (PARTITION by myyear ORDER by day ASC ROWS between 400 PRECEDING
            and 1 PRECEDING) as drop from obs
        ), agg as (
            select day, myyear, low, drop,
            rank() OVER (PARTITION by myyear ORDER by drop ASC) as rank
            from obs2 WHERE month != 7
        )
        select myyear as year, day, low, drop as largest_change
        from agg where rank = 1
        """,
            conn,
            params=(station,),
            index_col="year",
            parse_dates="day",
        )
    if df.empty:
        raise NoDataFound("No Data Found.")
    df["largest_change"] = df["largest_change"] * -1
    title = (
        f"{ctx['_sname']}\n"
        "Max 1 Aug till 30 Jun Low Temp Drop Exceeding "
        "Previous Min Low for Season"
    )

    fig = figure(title=title, apctx=ctx)
    ax = fig.add_axes([0.1, 0.1, 0.4, 0.75])
    df2 = df.groupby("year").max()
    ax.bar(
        df2.index.values,
        df2["largest_change"],
        fc="b",
        ec="b",
        zorder=1,
    )
    if year in df.index:
        ax.bar(
            year,
            df.at[year, "largest_change"],
            fc="red",
            ec="red",
            zorder=2,
        )
        ax.set_xlabel(f"{year} value is {df.at[year, 'largest_change']}")
    mv = df["largest_change"].mean()
    ax.axhline(mv, lw=2, color="k")
    ax.grid(True)
    ax.set_ylabel(r"Largest Low Temp Drop $^\circ$F, " f"Avg: {mv:.1f}")
    ax.set_xlim(df.index.values.min() - 1, df.index.values.max() + 1)

    ax = fig.add_axes([0.58, 0.12, 0.4, 0.32])
    ax.scatter(
        [int(x) for x in df["day"].dt.strftime("%j").values],
        df["largest_change"].values,
    )
    ax.set_xticks([1, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335])
    ax.set_xticklabels(month_abbr[1:], rotation=45)
    ax.set_ylabel(r"Drop $^\circ$F")
    ax.set_xlabel("On Date")
    ax.grid(True)

    ax = fig.add_axes([0.58, 0.56, 0.4, 0.32])
    ax.scatter(
        df["low"].values,
        df["largest_change"].values,
    )
    ax.set_ylabel(r"Drop $^\circ$F")
    ax.set_xlabel(r"At Temperature $^\circ$F")
    ax.grid(True)

    return fig, df

if __name__ == "__main__":
    plotter({"year": 2022})


text:
<?php

namespace phpDocumentor;

/**
 * Exception thrown when Factory was not available for a certain service or entity.
 */
final class FactoryNotFoundException extends Exception
{

}


text:
> This plugin places a `"use strict";` directive at the top of all files to enable [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode).

This plugin may be enabled via `babel-plugin-transform-es2015-modules-commonjs`.
If you wish to disable it you can either turn `strict` off or pass
`strictMode: false` as an option to the commonjs transform.

## Example

**In**

```javascript
foo();
```

**Out**

```javascript
"use strict";

foo();
```

## Installation

```sh
npm install --save-dev babel-plugin-transform-strict-mode
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```js
// without options
{
  "plugins": ["transform-strict-mode"]
}

// with options
{
  "plugins": [
    ["transform-strict-mode", {
      "strict": true
    }]
  ]
}
```

### Via CLI

```sh
babel --plugins transform-strict-mode script.js
```

### Via Node API

```javascript
require("babel-core").transform("code", {
  plugins: ["transform-strict-mode"]
});
```


text:
export const PUSH = 'QUEUE/PUSH';
export const POP = 'QUEUE/POP';
export const FLUSH = 'QUEUE/FLUSH';

export const push = (name, payload = {}) => ({
  type: PUSH,
  payload,
  meta: { name },
});

export const pop = name => ({
  type: POP,
  meta: { name },
});

export const flush = name => ({
  type: FLUSH,
  meta: { name },
});


text:
from typing import Optional  # noqa: E402
import pkg_resources  # noqa: E402
import sys  # noqa: E402

if sys.version_info < (3, 6):
    raise EnvironmentError('Hail requires Python 3.6 or later, found {}.{}'.format(
        sys.version_info.major, sys.version_info.minor))

__pip_version__ = pkg_resources.resource_string(__name__, 'hail_pip_version').decode().strip()
del pkg_resources
del sys

__doc__ = r"""
    __  __     <>__
   / /_/ /__  __/ /
  / __  / _ `/ / /
 /_/ /_/\_,_/_/_/
===================

For API documentation, visit the website: https://www.hail.is

For help, visit either:
 - the forum: https://discuss.hail.is
 - or our Zulip chatroom: https://hail.zulipchat.com

To report a bug, please open an issue: https://github.com/hail-is/hail/issues
"""

# F403 'from .expr import *' used; unable to detect undefined names
# F401 '.expr.*' imported but unused
# E402 module level import not at top of file
from .table import Table, GroupedTable, asc, desc  # noqa: E402
from .matrixtable import MatrixTable, GroupedMatrixTable  # noqa: E402
from .expr import *  # noqa: F401,F403,E402
from .genetics import *  # noqa: F401,F403,E402
from .methods import *  # noqa: F401,F403,E402
from . import expr  # noqa: E402
from . import genetics  # noqa: E402
from . import methods  # noqa: E402
from . import stats  # noqa: E402
from . import linalg  # noqa: E402
from . import plot  # noqa: E402
from . import ggplot  # noqa: E402
from . import experimental  # noqa: E402
from . import ir  # noqa: E402
from . import backend  # noqa: E402
from . import nd  # noqa: E402
from . import vds  # noqa: E402
from hail.expr import aggregators as agg  # noqa: E402
from hail.utils import (Struct, Interval, hadoop_copy, hadoop_open, hadoop_ls,  # noqa: E402
                        hadoop_stat, hadoop_exists, hadoop_is_file,
                        hadoop_is_dir, hadoop_scheme_supported, copy_log)

from .context import (init, init_local, init_batch, stop, spark_context, tmp_dir,  # noqa: E402
                      default_reference, get_reference, set_global_seed, _set_flags, _get_flags, _with_flags,
                      _async_current_backend, current_backend, debug_info, citation, cite_hail,
                      cite_hail_bibtex, version, TemporaryFilename, TemporaryDirectory)

scan = agg.aggregators.ScanFunctions({name: getattr(agg, name) for name in agg.__all__})

__all__ = [
    'init',
    'init_local',
    'init_batch',
    'stop',
    'spark_context',
    'tmp_dir',
    'TemporaryFilename',
    'TemporaryDirectory',
    'default_reference',
    'get_reference',
    'set_global_seed',
    '_set_flags',
    '_get_flags',
    '_with_flags',
    'Table',
    'GroupedTable',
    'MatrixTable',
    'GroupedMatrixTable',
    'asc',
    'desc',
    'hadoop_open',
    'hadoop_copy',
    'hadoop_is_dir',
    'hadoop_is_file',
    'hadoop_stat',
    'hadoop_exists',
    'hadoop_ls',
    'hadoop_scheme_supported',
    'copy_log',
    'Struct',
    'Interval',
    'agg',
    'scan',
    'genetics',
    'methods',
    'stats',
    'linalg',
    'nd',
    'plot',
    'ggplot',
    'experimental',
    'ir',
    'vds',
    'backend',
    '_async_current_backend',
    'current_backend',
    'debug_info',
    'citation',
    'cite_hail',
    'cite_hail_bibtex',
    'version'
]

__all__.extend(genetics.__all__)
__all__.extend(methods.__all__)

# don't overwrite builtins in `from hail import *`
import builtins  # noqa: E402

__all__.extend([x for x in expr.__all__ if not hasattr(builtins, x)])
del builtins

ir.register_functions()
ir.register_aggregators()

__version__: Optional[str] = None  # set by hail.version()
__revision__: Optional[str] = None  # set by hail.revision()

import warnings  # noqa: E402

warnings.filterwarnings('once', append=True)
del warnings


text:
title: "Mini app : Downloader"
layout: default
section: example
---

  This mini application let you choose the files you want in a list, download
  them, zip them and give the result to the user.

  This demo requires a recent browser, see
  the howto.

  This demo depends on the following libraries:

jQuery (to manipulate the DOM)

JSZipUtils (to download files)

bootstrap (for the progress bar)

            result

            js code

            js helpers

            html code

                {% include_relative downloader.inc/downloader.html %}

{% highlight js %}
{% include_relative downloader.inc/downloader.js %}
{% endhighlight %}

{% highlight js %}
{% include_relative downloader.inc/helpers.js %}
{% endhighlight %}

{% highlight html %}
{% include_relative downloader.inc/downloader.html %}
{% endhighlight %}


text:
namespace Arduino.Model
{
    /// <summary>
    /// To set a threshold on a specific hardware
    /// </summary>
    public class HardwareSettings
    {
        public Hardware Hardware { get; set; }
        public int Threshold { get; set; }
    }
}


text:
---
layout: post
title: React Native常用组件(二)
date: 2016-6-25
categories: blog
tags: [React Native]
description: React Native实例
---

**本文主要包括以下内容**

1. listView实例
2. Image组件实例
3. ProgressBarAndroid组件
4. DrawerLayoutAndroid组件
5. ScrollView组件

### listView实例

主要讲述了从通过网络获取数据,并且加载到listView中的实例

**ListView的介绍**

Let's now modify this application to render all of this data in a ListView component, rather than just rendering the first movie.

Why is a ListView better than just rendering all of these elements or putting them in a ScrollView? Despite React being fast, rendering a possibly infinite list of elements could be slow. ListView schedules rendering of views so that you only display the ones on screen and those already rendered but off screen are removed from the native view hierarchy.

**简单例子**

```
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  ListView,
} from 'react-native';
var ListViewDemo = React.createClass({
    getInitialState: function() {
      var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        return {
          dataSource: ds.cloneWithRows(['row 1', 'row 2','row 3','row 4','row 5','row 6','row 7','row 8']),
        };
    },
    render: function() {
      return (
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData}</Text>}
        />
      );
    }
});
AppRegistry.registerComponent('ListViewDemo', () => ListViewDemo);
```

**复杂例子代码**

```
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
   Navigator,
   ScrollView,
   TextInput,
   ListView,
  Text,
  Image,
    PixelRatio,
  View
} from 'react-native';

var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';

var MOCKED_MOVIES_DATA = [
  {title: 'Title', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];

class Abc extends Component {
    constructor(props) {
    super(props);
     this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  }
 fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
          loaded: true,
        });
      })
      .done();
  }
  componentDidMount() {
    this.fetchData();
  }
  render() {
      if (!this.state.loaded) {
      return this.renderLoadingView();
    }

   return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderMovie}
        style={styles.listView}
      />
    );

    }

renderLoadingView() {
    return (
      <View style={styles.container}>
        <Text>
          Loading movies...
        </Text>
      </View>
    );
  }

  renderMovie(movie1) {
    return (
      <View style={styles.container}>
        <Image
          source={{uri: movie1.posters.thumbnail}}
          style={styles.thumbnail}
        />
        <View style={styles.rightContainer}>
          <Text style={styles.title}>{movie1.title}</Text>
          <Text style={styles.year}>{movie1.year}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({

   container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  thumbnail: {
    width: 53,
    height: 81,
  },
   rightContainer: {
    flex: 1,
  },
  title: {
    fontSize: 20,
    marginBottom: 8,
    textAlign: 'center',
  },
  year: {
    textAlign: 'center',
  },
   listView: {
    paddingTop: 20,
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('Abc', () => Abc);
```

**效果如下**

![](https://facebook.github.io/react-native/img/TutorialFinal.png)

### Image组件实例

**访问本地图片**

```
<View  style={{marginLeft:10,marginTop:10}}>
      <Text style={{fontSize:16}}>'测试本地图片'</Text>
      <Image source={require('./img/my_icon.png')} />
 </View>
```

**加载使用APP中的图片**

```
<Image source={{uri:'ic_launcher'}} style={{width: 40, height: 40}} />
```

不过如果要显示效果:希望大家做如下修改,因为现在android项目采用gradle,现在不会默认生成drawable文件夹中了,所以大家如果要演示效果,需要在res下面新建一个drawable文件夹,然后放一个图片进入,接着在重新打包运行即可(这边测试的是把ic_launcher.png图片放入到res/drawable文件夹中)。不过经测试drawable-hdpi这类的不同分辨率格式文件夹也可以运行。

该适用于调试版本,如果采用发布版本就需要例如'image!xx.png'格式的访问方式了

**加载网络图片**

```
<Image source={{uri:'http://mta.zttit.com:8080/images/ZTT_1404756641470_image.jpg'}}  style={{width:100,height:100}}/>
```

**Image实现某些控件的背景图效果**

React Native中支持嵌套的方式,例如我们现在有一个Text组件,假如要实现背景图的效果,那么可以使用Image嵌套的Text的方式,然后Image加载图片方式实现,例如代码如下:

```
<Image source={require('./img/my_icon.png')} >
           <Text style={{color:'red'}}>下面是背景图</Text>
</Image>
```

**Image实例仿美团头部**

```
/**
 * 模仿美团首页顶部分类效果
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  Image,
} from 'react-native';
class TestImage extends Component {
  render() {
    return (
      <View style={{marginLeft:5,marginTop:10,marginRight:5}}>

         <View style={{flexDirection:'row'}}>
             <View style={{width:70}}>
                 <Image source={require('./img/one.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,textAlign:'center',fontSize:11,color:'#555555'}}>美食</Text>
             </View>
              <View style={{width:70}}>
                 <Image source={require('./img/two.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>电影</Text>
             </View>
             <View style={{width:70}}>
                 <Image source={require('./img/three.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>酒店</Text>
             </View>
             <View style={{width:70}}>
                 <Image source={require('./img/four.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>KTV</Text>
             </View>
             <View style={{width:70}}>
                 <Image source={require('./img/five.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>外卖</Text>
             </View>
          </View>
          <View style={{flexDirection:'row',marginTop:10}}>
             <View style={{width:70}}>
                 <Image source={require('./img/six.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,textAlign:'center',fontSize:11,color:'#555555'}}>优惠买单</Text>
             </View>
              <View style={{width:70}}>
                 <Image source={require('./img/seven.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>周边游</Text>
             </View>
             <View style={{width:70}}>
                 <Image source={require('./img/eight.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>休闲娱乐</Text>
             </View>
             <View style={{width:70}}>
                 <Image source={require('./img/nine.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>今日新单</Text>
             </View>
             <View style={{width:70}}>
                 <Image source={require('./img/ten.png')} style={{alignSelf:'center',width:45,height:45}} />
                 <Text style={{marginTop:5,alignSelf:'center',fontSize:11,color:'#555555',textAlign:'center'}}>丽人</Text>
             </View>
          </View>
      </View>
    );
  }
}

AppRegistry.registerComponent('TestImage', () => TestImage);
```

![](http://lookcode-wordpress.stor.sinaapp.com/uploads/2016/01/64.jpg)

### ProgressBarAndroid组件

**属性方法**

支持View控件的属性方法 (这些属性是从View控件中继承下来)  例如:大小,布局,边距啊

- color  设置进度的颜色属性值
- indeterminate 设置是否要显示一个默认的进度信息,该如果styleAttr的风格设置成Horizontal的时候该值必须设置成false
- progress  number  设置当前的加载进度值(该值在0-1之间)
- styleAttr    进度条框的风格 ,可以取的值如下:
- Horizontal
 +Small
 +Large
 +Inverse
 +SmallInverse
 +LargeInverse

**ProgressBarAndroid使用实例**

```
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  ProgressBarAndroid,
} from 'react-native';

class ProgressBarDemo extends Component {
  render() {
    return (
      <View >
        <Text>
            ProgressBarAndroid控件实例
        </Text>
        <ProgressBarAndroid  color="red" styleAttr='Inverse'/>
        <ProgressBarAndroid  color="green" styleAttr='Horizontal' progress={0.2}
            indeterminate={false} style={{marginTop:10}}/>
        <ProgressBarAndroid  color="green" styleAttr='Horizontal'
            indeterminate={true} style={{marginTop:10}}/>
        <ProgressBarAndroid  color="black" styleAttr='SmallInverse'
            style={{marginTop:10}}/>
        <ProgressBarAndroid  styleAttr='LargeInverse'
            style={{marginTop:10}}/>
      </View>
    );
  }
}
AppRegistry.registerComponent('ProgressBarDemo', () => ProgressBarDemo);
```

**效果如下**

![](http://lookcode-wordpress.stor.sinaapp.com/uploads/2016/01/212.jpg)

### DrawerLayoutAndroid组件

具体基本使用实例代码如下:

```
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  DrawerLayoutAndroid,
} from 'react-native';

class DrawerLayoutDemo extends Component {
 statics: {
    title: '<ScrollView>',
    description: 'Component that enables scrolling through child components.'
  },
 makeItems: function(nItems: number, styles): Array<any> {
    var items = [];
    for (var i = 0; i < nItems; i++) {
       items[i] = (
         <TouchableOpacity key={i} style={styles}>
           <Text>{'Item ' + i}</Text>
         </TouchableOpacity>
       );
    }
    return items;
  },
  render() {
   // One of the items is a horizontal scroll view
    var items = this.makeItems(NUM_ITEMS, styles.itemWrapper);
    items[4] = (
      <ScrollView key={'scrollView'} horizontal={true}>
        {this.makeItems(NUM_ITEMS, [styles.itemWrapper, styles.horizontalItemWrapper])}
      </ScrollView>
    );

    var verticalScrollView = (
      <ScrollView style={styles.verticalScrollView}>
        {items}
      </ScrollView>
    );

    return verticalScrollView;
  }
}
const styles = StyleSheet.create({
});
AppRegistry.registerComponent('DrawerLayoutDemo', () => DrawerLayoutDemo);
```

**效果如下**

![](http://lookcode-wordpress.stor.sinaapp.com/uploads/2016/01/213.jpg)

### ScrollView组件

```
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Image,
  Text,
  TextInput,
   ScrollView,
    TouchableOpacity,
  DrawerLayoutAndroid,
   ProgressBarAndroid,
  View
} from 'react-native';
var NUM_ITEMS = 20;

class MyProject extends Component {
   statics: {
    title: '<ScrollView>',
    description: 'Component that enables scrolling through child components.'
  }

  makeItems(nItems: number, styles): Array<any> {
    var items = [];
    for (var i = 0; i < nItems; i++) {
       items[i] = (
         <TouchableOpacity key={i} style={styles}>
           <Text>{'Item ' + i}</Text>
         </TouchableOpacity>
       );
    }
    return items;
  }

  render() {
    // One of the items is a horizontal scroll view
    var items = this.makeItems(NUM_ITEMS, styles.itemWrapper);
    items[4] = (
      <ScrollView key={'scrollView'} horizontal={true}>
        {this.makeItems(NUM_ITEMS, [styles.itemWrapper, styles.horizontalItemWrapper])}
      </ScrollView>
    );

    var verticalScrollView = (
      <ScrollView style={styles.verticalScrollView}>
        {items}
      </ScrollView>
    );

    return verticalScrollView;
  }
}

const styles = StyleSheet.create({

   verticalScrollView: {
    margin: 10,
  },
  itemWrapper: {
    backgroundColor: '#dddddd',
    alignItems: 'center',
    borderRadius: 5,
    borderWidth: 5,
    borderColor: '#a52a2a',
    padding: 30,
    margin: 5,
  },
  horizontalItemWrapper: {
    padding: 50
  }
});

AppRegistry.registerComponent('MyProject', () => MyProject);
```

**效果如下**

![](https://raw.githubusercontent.com/whuhan2013/ImageRepertory/master/react1.png)


text:
class Alternative < ActiveRecord::Base
  belongs_to :question

  validates_presence_of :text
end


text:
#include "config.h"
#include "GraphicsContext.h"

#include "AffineTransform.h"
#include "Color.h"
#include "Font.h"
#include "FontData.h"
#include "NotImplemented.h"
#include "Path.h"
#include <wtf/text/CString.h>
#include <GraphicsDefs.h>
#include <Region.h>
#include <View.h>
#include <Window.h>
#include <stdio.h>

namespace WebCore {

class GraphicsContextPlatformPrivate {
public:
    GraphicsContextPlatformPrivate(BView* view);
    ~GraphicsContextPlatformPrivate();

    BView* m_view;
};

GraphicsContextPlatformPrivate::GraphicsContextPlatformPrivate(BView* view)
    : m_view(view)
{
}

GraphicsContextPlatformPrivate::~GraphicsContextPlatformPrivate()
{
}

void GraphicsContext::platformInit(PlatformGraphicsContext* context)
{
    m_data = new GraphicsContextPlatformPrivate(context);
    setPaintingDisabled(!context);
}

void GraphicsContext::platformDestroy()
{
    delete m_data;
}

PlatformGraphicsContext* GraphicsContext::platformContext() const
{
    return m_data->m_view;
}

void GraphicsContext::savePlatformState()
{
    m_data->m_view->PushState();
}

void GraphicsContext::restorePlatformState()
{
    m_data->m_view->PopState();
}

// Draws a filled rectangle with a stroked border.
void GraphicsContext::drawRect(const IntRect& rect)
{
    if (paintingDisabled())
        return;

    m_data->m_view->FillRect(rect);
    if (strokeStyle() != NoStroke)
        m_data->m_view->StrokeRect(rect, getHaikuStrokeStyle());
}

// This is only used to draw borders.
void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
{
    if (paintingDisabled())
        return;

    if (strokeStyle() == NoStroke)
        return;

    m_data->m_view->StrokeLine(point1, point2, getHaikuStrokeStyle());
}

// This method is only used to draw the little circles used in lists.
void GraphicsContext::drawEllipse(const IntRect& rect)
{
    if (paintingDisabled())
        return;

    m_data->m_view->FillEllipse(rect);
    if (strokeStyle() != NoStroke)
        m_data->m_view->StrokeEllipse(rect, getHaikuStrokeStyle());
}

void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan)
{
    if (paintingDisabled())
        return;

    m_data->m_view->StrokeArc(rect, startAngle, angleSpan, getHaikuStrokeStyle());
}

void GraphicsContext::strokePath(const Path&)
{
    notImplemented();
}

void GraphicsContext::drawConvexPolygon(size_t pointsLength, const FloatPoint* points, bool shouldAntialias)
{
    if (paintingDisabled())
        return;

    BPoint bPoints[pointsLength];
    for (size_t i = 0; i < pointsLength; i++)
        bPoints[i] = points[i];

    m_data->m_view->FillPolygon(bPoints, pointsLength);
    if (strokeStyle() != NoStroke)
        // Stroke with low color
        m_data->m_view->StrokePolygon(bPoints, pointsLength, true, getHaikuStrokeStyle());
}

void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
{
    if (paintingDisabled())
        return;

    if (numPoints <= 1)
        return;

    // FIXME: IMPLEMENT!!
}

void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, ColorSpace colorSpace)
{
    if (paintingDisabled())
        return;

    rgb_color oldColor = m_data->m_view->HighColor();
    m_data->m_view->SetHighColor(color);
    m_data->m_view->FillRect(rect);
    m_data->m_view->SetHighColor(oldColor);
}

void GraphicsContext::fillRect(const FloatRect& rect)
{
    if (paintingDisabled())
        return;
}

void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace)
{
    if (paintingDisabled() || !color.alpha())
        return;

    notImplemented();
    // FIXME: A simple implementation could just use FillRoundRect if all
    // the sizes are the same, or even if they are not. Otherwise several
    // FillRect and FillArc calls are needed.
}

void GraphicsContext::fillPath(const Path&)
{
    notImplemented();
}

void GraphicsContext::clip(const FloatRect& rect)
{
    if (paintingDisabled())
        return;

    BRegion region(rect);
    m_data->m_view->ConstrainClippingRegion(&region);
}

void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color)
{
    // FIXME: implement
}

void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int /* width */, int /* offset */, const Color& color)
{
    if (paintingDisabled())
        return;

    unsigned rectCount = rects.size();

    // FIXME: maybe we should implement this with BShape?

    if (rects.size() > 1) {
        BRegion    region;
        for (int i = 0; i < rectCount; ++i)
            region.Include(BRect(rects[i]));

        m_data->m_view->SetHighColor(color);
        m_data->m_view->StrokeRect(region.Frame(), B_MIXED_COLORS);
    }
}

void GraphicsContext::drawLineForText(const IntPoint& origin, int width, bool printing)
{
    if (paintingDisabled())
        return;

    IntPoint endPoint = origin + IntSize(width, 0);
    drawLine(origin, endPoint);
}

void GraphicsContext::drawLineForTextChecking(const IntPoint&, int width, TextCheckingLineStyle)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& rect)
{
    notImplemented();
    return rect;
}

void GraphicsContext::beginPlatformTransparencyLayer(float opacity)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::endPlatformTransparencyLayer()
{
    if (paintingDisabled())
        return;

    notImplemented();
}

bool GraphicsContext::supportsTransparencyLayers()
{
    return false;
}

void GraphicsContext::clearRect(const FloatRect& rect)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::strokeRect(const FloatRect& rect, float width)
{
    if (paintingDisabled())
        return;

    float oldSize = m_data->m_view->PenSize();
    m_data->m_view->SetPenSize(width);
    m_data->m_view->StrokeRect(rect, getHaikuStrokeStyle());
    m_data->m_view->SetPenSize(oldSize);
}

void GraphicsContext::setLineCap(LineCap lineCap)
{
    if (paintingDisabled())
        return;

    cap_mode mode = B_BUTT_CAP;
    switch (lineCap) {
    case RoundCap:
        mode = B_ROUND_CAP;
        break;
    case SquareCap:
        mode = B_SQUARE_CAP;
        break;
    case ButtCap:
    default:
        break;
    }

    m_data->m_view->SetLineMode(mode, m_data->m_view->LineJoinMode(), m_data->m_view->LineMiterLimit());
}

void GraphicsContext::setLineJoin(LineJoin lineJoin)
{
    if (paintingDisabled())
        return;

    join_mode mode = B_MITER_JOIN;
    switch (lineJoin) {
    case RoundJoin:
        mode = B_ROUND_JOIN;
        break;
    case BevelJoin:
        mode = B_BEVEL_JOIN;
        break;
    case MiterJoin:
    default:
        break;
    }

    m_data->m_view->SetLineMode(m_data->m_view->LineCapMode(), mode, m_data->m_view->LineMiterLimit());
}

void GraphicsContext::setMiterLimit(float limit)
{
    if (paintingDisabled())
        return;

    m_data->m_view->SetLineMode(m_data->m_view->LineCapMode(), m_data->m_view->LineJoinMode(), limit);
}

void GraphicsContext::setAlpha(float opacity)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::setPlatformCompositeOperation(CompositeOperator op)
{
    if (paintingDisabled())
        return;

    drawing_mode mode = B_OP_COPY;
    switch (op) {
    case CompositeClear:
    case CompositeCopy:
        // Use the default above
        break;
    case CompositeSourceOver:
        mode = B_OP_OVER;
        break;
    default:
        printf("GraphicsContext::setPlatformCompositeOperation: Unsupported composite operation %s\n",
                compositeOperatorName(op).utf8().data());
    }
    m_data->m_view->SetDrawingMode(mode);
}

void GraphicsContext::clip(const Path& path)
{
    if (paintingDisabled())
        return;

    m_data->m_view->ConstrainClippingRegion(path.platformPath());
}

void GraphicsContext::canvasClip(const Path& path)
{
    clip(path);
}

void GraphicsContext::clipOut(const Path& path)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::clipToImageBuffer(const FloatRect&, const ImageBuffer*)
{
    notImplemented();
}

AffineTransform GraphicsContext::getCTM() const
{
    notImplemented();
    return AffineTransform();
}

void GraphicsContext::translate(float x, float y)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::rotate(float radians)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::scale(const FloatSize& size)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::clipOut(const IntRect& rect)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::concatCTM(const AffineTransform& transform)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::setCTM(const AffineTransform& transform)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::setPlatformShouldAntialias(bool enable)
{
    if (paintingDisabled())
        return;

    notImplemented();
}

void GraphicsContext::setImageInterpolationQuality(InterpolationQuality)
{
}

InterpolationQuality GraphicsContext::imageInterpolationQuality() const
{
    notImplemented();
    return InterpolationDefault;
}

void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
{
    notImplemented();
}

void GraphicsContext::setPlatformFont(const Font& font)
{
    m_data->m_view->SetFont(font.primaryFont()->platformData().font());
}

void GraphicsContext::setPlatformStrokeColor(const Color& color, ColorSpace colorSpace)
{
    if (paintingDisabled())
        return;

    m_data->m_view->SetHighColor(color);
}

pattern GraphicsContext::getHaikuStrokeStyle()
{
    switch (strokeStyle()) {
    case SolidStroke:
        return B_SOLID_HIGH;
        break;
    case DottedStroke:
        return B_MIXED_COLORS;
        break;
    case DashedStroke:
        // FIXME: use a better dashed stroke!
        notImplemented();
        return B_MIXED_COLORS;
        break;
    default:
        return B_SOLID_LOW;
        break;
    }
}

void GraphicsContext::setPlatformStrokeStyle(StrokeStyle strokeStyle)
{
    // FIXME: see getHaikuStrokeStyle.
    notImplemented();
}

void GraphicsContext::setPlatformStrokeThickness(float thickness)
{
    if (paintingDisabled())
        return;

    m_data->m_view->SetPenSize(thickness);
}

void GraphicsContext::setPlatformFillColor(const Color& color, ColorSpace colorSpace)
{
    if (paintingDisabled())
        return;

    m_data->m_view->SetHighColor(color);
}

void GraphicsContext::clearPlatformShadow()
{
    notImplemented();
}

void GraphicsContext::setPlatformShadow(FloatSize const&, float, Color const&, ColorSpace)
{
    notImplemented();
}

} // namespace WebCore


text:
HACCSY
========

HACCSY abbreviation stands for Hackerspace Access Control and Checkin System and that's pretty much what it does.

HACCSY app is meant to run on a RaspberryPi that's connected to internet and the front door electric strike lock. It does the job of a simple Check in System and Door Access Control System (2 in 1), it queries a REST service by handing it the scanned in RFID card reader and it will return 'true' if the key owner owes less than 2 months worth of their monthly payment. It will return 'false' otherwise. It does the same for checking in and out. The computer would then send the signal to the door lock actuator to open it if returned true or do nothing if false. It has a check IN/OUT button to indicate Check IN or Check OUT. It also has an LCD backlight display that displays messages for the user, and an RGB LED that turns RED for Access Denied, GREEN for Access Granted and WHITE to indicate offline mode. Through the REST API, you can also make it available for others to see if the hackerspace is open or not. See working example on the website header at www.prishtinahackerspace.org

HACCSY is built with the following hardware and electronic components:
* Raspberry Pi
* USB RFID reader (hidraw0)
* AdaFruit LCD screen,
* 12V Power supply (12V LED power supply)
* 2 push buttons (Check in/out button, Exit button)
* Electric strike lock.
* N-Channel Mosfet (FK106269)
* Mosfet Resistor 1/4W ~47 kOhm
* Display Resistor 1/4W 470 Ohm
* Display Pot 10 kOhm
* 3x LED resistors ~330 Ohm
* Protection Diode 1N4007
* Snubber Resistor 100 Ohm
* Snubber Capacitor 0.47 uF 100V (not electrolythic)

See a demo video here: https://www.youtube.com/watch?v=QnXSiL62yJ0
Pics from the buildout: http://www.prishtinahackerspace.org/haccsy-hackerspace-access-control-and-check-in-system/

## Credits ##

HACCSY's code is based on ACON

https://github.com/MelbourneMakerSpace/RFIDLock

This code is broken into two parts to make HACCSY work with Seltzer.

https://github.com/elplatt/seltzer

***Code Author***: Altin Ukshini - altin.uskhini@gmail.com

***Hardware and wiring***: Dijon Vula - dijonvula@gmail.com

## Wiring schema ##

Credits: Dijon Vula - dijonvula@gmail.com

***Note***: We will update the schema soon, until then, please use a Snubber or an reverse-biased diode at the electric strike lock to eliminate any noise / inductive kick in the circuit - this usually affects the LCD screen and will make it display scrambled characters.

## Installation ##

The python files stored in the RaspberryPi folder go in the /home/pi folder.
The Seltzer PHP files need to be uploaded via FTP to the same web server where you've installed Seltzer.
It should line up where this "api" folder is under the "crm" folder so that the URL looks like "http://yourserver.com/crm/api/query.php....."

If you don't want it to interface with Seltzer you could take out the part that updates the whitelist file and just populate the file manually with the valid users and their RFID serial numbers.  The whitelist file should have a JSON array like this:

	[{"firstName":"Josh","lastName":"Pritt","serial":"8045AB453449"},{"firstName":"Tony","lastName":"Bellomo","serial":"6554557774BC"},{"firstName":"Arlo","lastName":"Del Rosario","serial":"4944D8938D11"}]

Then make sure to create the new tables and new columns by importing the update.sql file via phpmyadmin to your seltzer database.

See the documentation here for more detailed steps: https://github.com/PrishtinaHackerspace/HACCSY/tree/master/Seltzer/crm/api

There are several variables to set.  They are all at the top and usually are ALL CAPS.  Change these values if you need to such as the USERNAME and PASSWORD for your email server or HTTPAuth authenticating with htaccess when using REST API.

You need to run a few commands on the Raspberry Pi command line (terminal) to get it to run the Python scripts correctly.

	sudo apt-get install python-dev python-rpi.gpio

Then get the AdaFruit LCD screen library and setup the I2C pins on the GPIO by following these directions:

https://learn.adafruit.com/adafruit-16x2-character-lcd-plus-keypad-for-raspberry-pi/usage

***NOTE:*** In our case, we have used different pins, so when testing the libraries, make sure to use our pin setup!

Finally, set up the RPi so that it runs the main python script as soon as it boots up as root user:

	sudo su
	crontab -e

add this to the end of the cron:

	@reboot python /home/pi/HACCSY.py & python /home/pi/UpdateWhiteList.py & python /home/pi/Watchdog.py &
	@reboot bash /home/pi/WifiTest.sh

then save and exit and reboot the pi

If you're using a Wifi USB adapter, edit /etc/network/interfaces/ and at the wlan0 configuration add

	allow-hotplug wlan0
	#and
	wireless-power off

Your configuration should look somewhat like this:

	auto lo
	iface lo inet loopback

	iface etho0 dhcp
	auto eth0
	allow-hotplug eth0
	iface eth0 inet manual

	auto wlan0
	allow-hotplug wlan0
	iface wlan0 inet dhcp
	wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
	wireless-power off

Here's another tweak for the power management configuration

Create a new file:

	sudo nano /etc/modprobe.d/8192cu.conf

add

	options 8192cu rtw_power_mgnt=0 rtw_enusbss=0

then save and exit and reboot the pi.

The following should output 0 after reboot

	cat /sys/module/8192cu/parameters/rtw_power_mgnt


text:
/**
 * package containing some system related configuration service logics.
 */
package com.mtt.myapp.operation.service;


text:
> Author: JunJianSyu <br />
> Slogan: Whenever you have eliminated the impossible, whatever remains, however improbable, must be the truth.


text:
package org.apache.axis2.xmlbeans;

import org.apache.axis2.description.AxisMessage;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.util.SchemaUtil;
import org.apache.axis2.util.URLProcessor;
import org.apache.axis2.util.XMLUtils;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.axis2.wsdl.WSDLUtil;
import org.apache.axis2.wsdl.codegen.CodeGenConfiguration;
import org.apache.axis2.wsdl.codegen.extension.XMLBeansExtension;
import org.apache.axis2.wsdl.databinding.DefaultTypeMapper;
import org.apache.axis2.wsdl.databinding.JavaTypeMapper;
import org.apache.axis2.wsdl.databinding.TypeMapper;
import org.apache.axis2.wsdl.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.commons.schema.XmlSchema;
import org.apache.ws.commons.schema.XmlSchemaCollection;
import org.apache.xmlbeans.BindingConfig;
import org.apache.xmlbeans.Filer;
import org.apache.xmlbeans.SchemaGlobalElement;
import org.apache.xmlbeans.SchemaProperty;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import org.w3c.dom.Element;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * Framework-linked code used by XMLBeans data binding support. This is accessed via reflection from
 * the XMLBeans code generation extension when XMLBeans data binding is selected.
 */
public class CodeGenerationUtility {
    public static final String SCHEMA_FOLDER = "schemas";

    public static String MAPPINGS = "mappings";
    public static String MAPPING = "mapping";
    public static String MESSAGE = "message";
    public static String JAVA_NAME = "javaclass";

    public static final String MAPPING_FOLDER = "Mapping";
    public static final String MAPPER_FILE_NAME = "mapper";
    public static final String SCHEMA_PATH = "/org/apache/axis2/wsdl/codegen/schema/";

    private static final Log log = LogFactory.getLog(CodeGenerationUtility.class);
    boolean debug = false;

    /**
     * @param additionalSchemas
     * @throws RuntimeException
     */
    public static TypeMapper processSchemas(List schemas,
                                            Element[] additionalSchemas,
                                            CodeGenConfiguration cgconfig,
                                            String typeSystemName) throws RuntimeException {
        try {

            //check for the imported types. Any imported types are supposed to be here also
            if (schemas == null || schemas.isEmpty()) {
                //there are no types to be code generated
                //However if the type mapper is left empty it will be a problem for the other
                //processes. Hence the default type mapper is set to the configuration
                return new DefaultTypeMapper();
            }

            SchemaTypeSystem sts;
            List completeSchemaList = new ArrayList();
            List topLevelSchemaList = new ArrayList();

            //create the type mapper
            //First try to take the one that is already there
            TypeMapper mapper = cgconfig.getTypeMapper();
            if (mapper == null) {
                mapper = new JavaTypeMapper();
            }

            //change the  default class name of the mapper to
            //xmlbeans specific XMLObject
            mapper.setDefaultMappingName(XmlObject.class.getName());

            Map nameSpacesMap = new HashMap();
            List axisServices = cgconfig.getAxisServices();
            AxisService axisService;
            for (Iterator iter = axisServices.iterator(); iter.hasNext();) {
                axisService = (AxisService)iter.next();
                nameSpacesMap.putAll(axisService.getNamespaceMap());
            }

            // process all the schemas and make a list of all of them for
            // resolving entities
            for (int i = 0; i < schemas.size(); i++) {
                XmlSchema schema = (XmlSchema)schemas.get(i);
                XmlOptions options = new XmlOptions();
                options.setLoadAdditionalNamespaces(
                        nameSpacesMap); //add the namespaces
                XmlSchema[] allSchemas = SchemaUtil.getAllSchemas(schema);
                for (int j = 0; j < allSchemas.length; j++) {
                    completeSchemaList.add(allSchemas[j]);
                }
            }

            //make another list of top level schemas for passing into XMLbeans
            for (int i = 0; i < schemas.size(); i++) {
                XmlSchema schema = (XmlSchema)schemas.get(i);
                XmlOptions options = new XmlOptions();
                options.setLoadAdditionalNamespaces(
                        nameSpacesMap); //add the namespaces
                topLevelSchemaList.add(
                        XmlObject.Factory.parse(
                                getSchemaAsString(schema)
                                , options));

            }

            XmlSchemaCollection extras = new XmlSchemaCollection();
            // add the third party schemas
            //todo perhaps checking the namespaces would be a good idea to
            //make the generated code work efficiently
            for (int i = 0; i < additionalSchemas.length; i++) {
                completeSchemaList.add(extras.read(additionalSchemas[i]));
                topLevelSchemaList.add(XmlObject.Factory.parse(
                        additionalSchemas[i]
                        , null));
            }

            //compile the type system
            Axis2EntityResolver er = new Axis2EntityResolver();
            er.setSchemas((XmlSchema[])completeSchemaList
                    .toArray(new XmlSchema[completeSchemaList.size()]));
            er.setBaseUri(cgconfig.getBaseURI());

            String xsdConfigFile = (String)cgconfig.getProperties().get(XMLBeansExtension.XSDCONFIG_OPTION);

            //-Ejavaversion switch to XmlOptions to generate 1.5 compliant code
            XmlOptions xmlOptions	=	new XmlOptions();
            xmlOptions.setEntityResolver(er);
            //test if javaversion property in CodeGenConfig
            if(null!=cgconfig.getProperty("javaversion")){
            	xmlOptions.put(XmlOptions.GENERATE_JAVA_VERSION,cgconfig.getProperty("javaversion"));
            }
            sts = XmlBeans.compileXmlBeans(
                    // set the STS name; defaults to null, which makes the generated class
                    // include a unique (but random) STS name
                    typeSystemName,
                    null,
                    convertToSchemaArray(topLevelSchemaList),
                    new Axis2BindingConfig(cgconfig.getUri2PackageNameMap(),
                                           xsdConfigFile),
                    XmlBeans.getContextTypeLoader(),
                    new Axis2Filer(cgconfig),
                    xmlOptions);

            // prune the generated schema type system and add the list of base64 types
            cgconfig.putProperty(Constants.BASE_64_PROPERTY_KEY,
                                 findBase64Types(sts));
            cgconfig.putProperty(Constants.PLAIN_BASE_64_PROPERTY_KEY,
                                 findPlainBase64Types(sts));

            SchemaTypeSystem internal = XmlBeans.getBuiltinTypeSystem();
            SchemaType[] schemaTypes = internal.globalTypes();
            for (int j = 0; j < schemaTypes.length; j++) {
                mapper.addTypeMappingName(schemaTypes[j].getName(),
                                          schemaTypes[j].getFullJavaName());

            }

            //get the schematypes and add the document types to the type mapper
            schemaTypes = sts.documentTypes();
            for (int j = 0; j < schemaTypes.length; j++) {
                mapper.addTypeMappingName(schemaTypes[j].getDocumentElementName(),
                                          schemaTypes[j].getFullJavaName());

            }

            //process the unwrapped parameters
            if (!cgconfig.isParametersWrapped()) {
                //figure out the unwrapped operations
                axisServices = cgconfig.getAxisServices();
                for (Iterator servicesIter = axisServices.iterator(); servicesIter.hasNext();) {
                    axisService = (AxisService)servicesIter.next();
                    for (Iterator operations = axisService.getOperations();
                         operations.hasNext();) {
                        AxisOperation op = (AxisOperation)operations.next();

                        if (WSDLUtil.isInputPresentForMEP(op.getMessageExchangePattern())) {
                            AxisMessage message = op.getMessage(
                                    WSDLConstants.MESSAGE_LABEL_IN_VALUE);
                            if (message != null &&
                                    message.getParameter(Constants.UNWRAPPED_KEY) != null) {
                                SchemaGlobalElement xmlbeansElement =
                                        sts.findElement(message.getElementQName());
                                SchemaType sType = xmlbeansElement.getType();

                                SchemaProperty[] elementProperties = sType.getElementProperties();
                                for (int i = 0; i < elementProperties.length; i++) {
                                    SchemaProperty elementProperty = elementProperties[i];

                                    QName partQName =
                                            WSDLUtil.getPartQName(op.getName().getLocalPart(),
                                                                  WSDLConstants.INPUT_PART_QNAME_SUFFIX,
                                                                  elementProperty
                                                                          .getName().getLocalPart());

                                    //this type is based on a primitive type- use the
                                    //primitive type name in this case
                                    String fullJaveName =
                                            elementProperty.getType().getFullJavaName();
                                    if (elementProperty.extendsJavaArray()) {
                                        fullJaveName = fullJaveName.concat("[]");
                                    }
                                    mapper.addTypeMappingName(partQName, fullJaveName);
                                    SchemaType primitiveType =
                                            elementProperty.getType().getPrimitiveType();

                                    if (primitiveType != null) {
                                        mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                                    }
                                    if (elementProperty.extendsJavaArray()) {
                                        mapper.addTypeMappingStatus(partQName,
                                                                    Constants.ARRAY_TYPE);
                                    }
                                }
                            }
                        }

                        if (WSDLUtil.isOutputPresentForMEP(op.getMessageExchangePattern())) {
                            AxisMessage message = op.getMessage(
                                    WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                            if (message != null &&
                                    message.getParameter(Constants.UNWRAPPED_KEY) != null) {
                                SchemaGlobalElement xmlbeansElement =
                                        sts.findElement(message.getElementQName());
                                SchemaType sType = xmlbeansElement.getType();

                                SchemaProperty[] elementProperties = sType.getElementProperties();
                                for (int i = 0; i < elementProperties.length; i++) {
                                    SchemaProperty elementProperty = elementProperties[i];

                                    QName partQName =
                                            WSDLUtil.getPartQName(op.getName().getLocalPart(),
                                                                  WSDLConstants.OUTPUT_PART_QNAME_SUFFIX,
                                                                  elementProperty
                                                                          .getName().getLocalPart());

                                    //this type is based on a primitive type- use the
                                    //primitive type name in this case
                                    String fullJaveName =
                                            elementProperty.getType().getFullJavaName();
                                    if (elementProperty.extendsJavaArray()) {
                                        fullJaveName = fullJaveName.concat("[]");
                                    }
                                    mapper.addTypeMappingName(partQName, fullJaveName);
                                    SchemaType primitiveType =
                                            elementProperty.getType().getPrimitiveType();

                                    if (primitiveType != null) {
                                        mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                                    }
                                    if (elementProperty.extendsJavaArray()) {
                                        mapper.addTypeMappingStatus(partQName,
                                                                    Constants.ARRAY_TYPE);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //return mapper to be set in the config
            return mapper;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Populate the base64 types The algo is to look for simpletypes that have base64 content, and
     * then step out of that onestep and get the element. For now there's an extended check to see
     * whether the simple type is related to the Xmime:contentType!
     *
     * @param sts
     */
    private static List findBase64Types(SchemaTypeSystem sts) {
        List allSeenTypes = new ArrayList();
        List base64ElementQNamesList = new ArrayList();
        SchemaType outerType;
        //add the document types and global types
        allSeenTypes.addAll(Arrays.asList(sts.documentTypes()));
        allSeenTypes.addAll(Arrays.asList(sts.globalTypes()));

        for (int i = 0; i < allSeenTypes.size(); i++) {
            SchemaType sType = (SchemaType)allSeenTypes.get(i);

            if (sType.getContentType() == SchemaType.SIMPLE_CONTENT &&
                    sType.getPrimitiveType() != null) {
                if (org.apache.axis2.namespace.Constants.BASE_64_CONTENT_QNAME
                        .equals(sType.getPrimitiveType().getName())) {
                    outerType = sType.getOuterType();
                    //check the outer type further to see whether it has the contenttype attribute from
                    //XMime namespace
                    SchemaProperty[] properties = sType.getProperties();
                    for (int j = 0; j < properties.length; j++) {
                        if (org.apache.axis2.namespace.Constants.XMIME_CONTENT_TYPE_QNAME
                                .equals(properties[j].getName())) {
                            //add this only if it is a document type ??
                            if (outerType.isDocumentType()) {
                                base64ElementQNamesList.add(outerType.getDocumentElementName());
                            }
                            break;
                        }
                    }
                }
            }
            //add any of the child types if there are any
            allSeenTypes.addAll(Arrays.asList(sType.getAnonymousTypes()));
        }

        return base64ElementQNamesList;
    }

    /**
     * @param sts
     * @return array list
     */
    private static List findPlainBase64Types(SchemaTypeSystem sts) {
        ArrayList allSeenTypes = new ArrayList();

        allSeenTypes.addAll(Arrays.asList(sts.documentTypes()));
        allSeenTypes.addAll(Arrays.asList(sts.globalTypes()));

        ArrayList base64Types = new ArrayList();

        for (Iterator iterator = allSeenTypes.iterator(); iterator.hasNext();) {
            SchemaType stype = (SchemaType)iterator.next();
            findPlainBase64Types(stype, base64Types, new ArrayList());
        }

        return base64Types;
    }

    /**
     * @param stype
     * @param base64Types
     */
    private static void findPlainBase64Types(SchemaType stype,
                                             ArrayList base64Types,
                                             ArrayList processedTypes) {

        SchemaProperty[] elementProperties = stype.getElementProperties();
        QName name;
        SchemaType schemaType;
        for (int i = 0; i < elementProperties.length; i++) {
            schemaType = elementProperties[i].getType();
            name = elementProperties[i].getName();
            if (!base64Types.contains(name) && !processedTypes.contains(schemaType.getName())) {
                processedTypes.add(stype.getName());
                if (schemaType.isPrimitiveType()) {
                    SchemaType primitiveType = schemaType.getPrimitiveType();
                    if (org.apache.axis2.namespace.Constants.BASE_64_CONTENT_QNAME
                            .equals(primitiveType.getName())) {
                        base64Types.add(name);
                    }

                } else {
                    findPlainBase64Types(schemaType, base64Types, processedTypes);
                }
            }
        }

    }

    /** Private class to generate the filer */
    private static class Axis2Filer implements Filer {

        private File location;
        private boolean flatten = false;
        private String resourceDirName;
        private String srcDirName;
        private static final String JAVA_FILE_EXTENSION = ".java";

        private Axis2Filer(CodeGenConfiguration config) {
            location = config.getOutputLocation();
            flatten = config.isFlattenFiles();
            resourceDirName = config.getResourceLocation();
            srcDirName = config.getSourceLocation();
        }

        public OutputStream createBinaryFile(String typename)
                throws IOException {
            File resourcesDirectory =
                    flatten ?
                            location :
                            new File(location, resourceDirName);

            if (!resourcesDirectory.exists()) {
                resourcesDirectory.mkdirs();
            }
            File file = new File(resourcesDirectory, typename);
            file.getParentFile().mkdirs();
            file.createNewFile();
            return new FileOutputStream(file);
        }

        public Writer createSourceFile(String typename)
                throws IOException {
            typename =
                    typename.replace('.', File.separatorChar);

            File outputDir =
                    flatten ?
                            location :
                            new File(location, srcDirName);

            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            File file = new File(outputDir,
                                 typename + JAVA_FILE_EXTENSION);
            file.getParentFile().mkdirs();
            file.createNewFile();
            return new FileWriter(file);
        }
    }

    /**
     * Convert schema into a String
     *
     * @param schema
     */
    private static String getSchemaAsString(XmlSchema schema) throws IOException {
        StringWriter writer = new StringWriter();
        schema.write(writer);
        return writer.toString();
    }

    /**
     * Custom binding configuration for the code generator. This controls how the namespaces are
     * suffixed/prefixed
     */
    private static class Axis2BindingConfig extends BindingConfig {

        private Map uri2packageMappings = null;
        private XSDConfig xsdConfig = null;

        public Axis2BindingConfig(Map uri2packageMappings, String xsdConfigfile) {
            this.uri2packageMappings = uri2packageMappings;
            if (this.uri2packageMappings == null) {
                //make an empty one to avoid nasty surprises
                this.uri2packageMappings = new HashMap();
            }

            // Do we have an xsdconfig file?
            if (xsdConfigfile != null) {
                xsdConfig = new XSDConfig(xsdConfigfile);
            }
        }

        public String lookupPackageForNamespace(String uri) {
            /* If the xsdconfig file has mappings, we'll use them instead of the -p option.
             * If we have an xsdconfig file but no namespace to package mappings, then we'll
             * defer to the -p option.
             */
            if (xsdConfig != null) {
                if (xsdConfig.hasNamespaceToJavaPackageMappings) {
                    log.debug("RETURNING " + uri + " = " +
                            xsdConfig.getNamespacesToJavaPackages().get(uri));
                    return (String)xsdConfig.getNamespacesToJavaPackages().get(uri);
                }
            }

            if (uri2packageMappings.containsKey(uri)) {
                return (String)uri2packageMappings.get(uri);
            } else {
                return URLProcessor.makePackageName(uri);
            }
        }

        public String lookupJavanameForQName(QName qname) {
            /* The mappings are stored in the format:
            * NAMESPACE:LOCAL_NAME, i.e.
            * urn:weegietech:minerva:moduleType
            */
            if (xsdConfig != null) {
                String key = qname.getNamespaceURI() + ":" + qname.getLocalPart();
                if (xsdConfig.getSchemaTypesToJavaNames().containsKey(key)) {
                    log.debug("RETURNING " + qname.getLocalPart() + " = " +
                            xsdConfig.getSchemaTypesToJavaNames().get(key));
                    return (String)xsdConfig.getSchemaTypesToJavaNames().get(key);
                } else {
                    return null;
                }
            } else {
                return super.lookupJavanameForQName(qname);
            }

        }
    }

    /**
     * Converts a given vector of schemaDocuments to XmlBeans processable schema objects. One
     * drawback we have here is the non-inclusion of untargeted namespaces
     *
     * @param vec
     * @return schema array
     */
    private static SchemaDocument.Schema[] convertToSchemaArray(List vec) {
        SchemaDocument[] schemaDocuments =
                (SchemaDocument[])vec.toArray(new SchemaDocument[vec.size()]);
        //remove duplicates
        Vector uniqueSchemas = new Vector(schemaDocuments.length);
        Vector uniqueSchemaTns = new Vector(schemaDocuments.length);
        SchemaDocument.Schema s;
        for (int i = 0; i < schemaDocuments.length; i++) {
            s = schemaDocuments[i].getSchema();
            if (!uniqueSchemaTns.contains(s.getTargetNamespace())) {
                uniqueSchemas.add(s);
                uniqueSchemaTns.add(s.getTargetNamespace());
            } else if (s.getTargetNamespace() == null) {
                uniqueSchemas.add(s);
            }
        }
        return (SchemaDocument.Schema[])
                uniqueSchemas.toArray(
                        new SchemaDocument.Schema[uniqueSchemas.size()]);
    }

    /** Axis2 specific entity resolver */
    private static class Axis2EntityResolver implements EntityResolver {
        private XmlSchema[] schemas;
        private String baseUri;

        /**
         * @param publicId - this is the target namespace
         * @param systemId - this is the location (value of schemaLocation)
         * @return
         * @see EntityResolver#resolveEntity(String, String)
         */
        public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException {
            if (systemId.startsWith("project://local/")) {
                systemId = systemId.substring("project://local/".length());
            }

            // if the system id has // final system id gives only one / after tokenizing process
            // to avoid this we check whether it is started with http:// or not
            if (!systemId.startsWith("http://")) {
                StringTokenizer pathElements = new StringTokenizer(systemId, "/");
                Stack pathElementStack = new Stack();
                while (pathElements.hasMoreTokens()) {
                    String pathElement = pathElements.nextToken();
                    if (".".equals(pathElement)) {
                    } else if ("..".equals(pathElement)) {
                        if (!pathElementStack.isEmpty())
                            pathElementStack.pop();
                    } else {
                        pathElementStack.push(pathElement);
                    }
                }
                StringBuffer pathBuilder = new StringBuffer();
                for (Iterator iter = pathElementStack.iterator(); iter.hasNext();) {
                    pathBuilder.append(File.separator + iter.next());
                }
                systemId = pathBuilder.toString().substring(1);
            }

            log.info("Resolving schema with publicId [" + publicId + "] and systemId [" + systemId + "]");
            try {
                for (int i = 0; i < schemas.length; i++) {
                    XmlSchema schema = schemas[i];
                    if (schema.getSourceURI() != null &&
                            schema.getSourceURI().endsWith(systemId.replaceAll("\\\\", "/"))) {
                        String path = schema.getSourceURI();
                        File f = getFileFromURI(path);
                        if(f.exists()){
                            InputSource source = new InputSource();
                            source.setSystemId(schema.getSourceURI());
                            return source;
                        } else {
                            return new InputSource(getSchemaAsInputStream(schemas[i]));
                        }
                    }

                }
                for (int i = 0; i < schemas.length; i++) {
                    XmlSchema schema = schemas[i];
                    if (schema.getTargetNamespace() != null &&
                            schema.getTargetNamespace().equals(publicId)) {
                        return new InputSource(getSchemaAsInputStream(schemas[i]));
                    }
                }
                if (systemId.indexOf(':') == -1) {
                    //if the base URI is missing then attache the file:/// to it
                    //if the systemId actually had a scheme then as per the URL
                    //constructor, the context URL scheme should be ignored
                    baseUri = (baseUri == null) ? "file:///" : baseUri;
                    URL url = new URL(baseUri + systemId);
                    InputSource source = new InputSource();
                    source.setSystemId(url.toString());
                    return source;
                }
                return XMLUtils.getEmptyInputSource();
            } catch (Exception e) {
                throw new SAXException(e);
            }
        }

        private File getFileFromURI(String path) {
            if(path.startsWith("file:///")){
                            path = path.substring(8);
            } else if(path.startsWith("file://")){
                path = path.substring(7);
            } else if(path.startsWith("file:/")){
                path = path.substring(6);
            }
            return new File(path);
        }

        public XmlSchema[]  getSchemas() {
            return schemas;
        }

        public void setSchemas(XmlSchema[] schemas) {
            this.schemas = schemas;
        }

        public String getBaseUri() {
            return baseUri;
        }

        public void setBaseUri(String baseUri) {
            this.baseUri = baseUri;
        }

        /**
         * Convert schema into a InputStream
         *
         * @param schema
         */
        private InputStream getSchemaAsInputStream(XmlSchema schema){
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         schema.write(baos);
         return new ByteArrayInputStream(baos.toByteArray());
        }
    }

}


text:
Generates general purpose [docker-compose.yml](https://docs.docker.com/compose/yml/) file automatically for your Drupal 6, 7 and 8 projects.

## Usage

    Usage: drupal-compose

    Options:
      -f, --file FILE   Specify an alternate compose file (default: docker-compose.yml)
      -v, --version     Show version number
      -h, --help        Show help

## Install / Update

    curl -sSL https://raw.githubusercontent.com/dockerizedrupal/drupal-compose/master/install.sh | sudo sh

## Switching to a different PHP version

    drupal-compose service php set version <VERSION>

### Supported versions

    5.2
    5.3
    5.4
    5.5
    5.6
    7.0

## License

**MIT**


text:
//
//  OAuthViewController.m
//  坏境搭载
//
//  Created by Mac on 15/10/31.
//  Copyright (c) 2015年 nini. All rights reserved.
//

#import "OAuthViewController.h"
#import "MBProgressHUD+MJ.h"
#import "AFNetworking.h"
#import "Account.h"
#import "AccountTool.h"
#import "UIWindow+Extension.h"

#define AuthorizeBaseUrl @"https://api.weibo.com/oauth2/authorize"
#define Client_id     @"3759665480"
#define Redirect_uri  @"http://www.baidu.com"
#define Client_secret @"bb6b98826c3d03052b670d8d5c1f029b"

@interface OAuthViewController ()<UIWebViewDelegate>

@end

@implementation OAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //1.创建一个WebView
    UIWebView *webview = [[UIWebView alloc]init];
    webview.frame = self.view.bounds;
    webview.delegate = self;
    [self.view addSubview:webview];

    NSString *baseUrl = @"https://api.weibo.com/oauth2/authorize";
    NSString *client_id = @"3759665480";
    NSString *redirect_uri = @"http://www.baidu.com";
    // 拼接URL字符串

    NSString *urlStr = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",baseUrl,client_id,redirect_uri];

    // 创建URL
    NSURL *url = [NSURL URLWithString:urlStr];

    // 创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 加载请求
    [webview loadRequest:request];

}

#pragma mark -UIWebView代理
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    // 提示用户正在加载...
    [MBProgressHUD showMessage:@"正在加载..."];
}

// webview加载完成的时候调用
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
}

//  webview加载失败的时候调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [MBProgressHUD hideHUD];
}

// 拦截webView请求
// 当Webview需要加载一个请求的时候,就会调用这个方法,询问下是否请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlStr = request.URL.absoluteString;

    // 获取code(RequestToken)
    NSRange range = [urlStr rangeOfString:@"code="];
    if (range.length) { // 有code=

        // code=81524df3190ea6e58e33c9a0eba1ac56
        // 0 + length

        NSString *code = [urlStr substringFromIndex:range.location + range.length];
        // 换取accessToken
        [self accessTokenWithCode:code];

        // 不会去加载回调界面
        return NO;

    }

    return YES;
}
#pragma mark - 换取accessToken
- (void)accessTokenWithCode:(NSString *)code
{
    // 发送Post请求

    // 创建请求管理者:请求和解析
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = Client_id;
    params[@"client_secret"] = Client_secret;
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    params[@"redirect_uri"] = Redirect_uri;

    // 1,发送post请求
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) { // 请求成功的时候调用

    // 2,将返回的账号字典数据 --> 模型,存进沙盒
    Account *account = [Account accountWithDict:responseObject];

    //3,存储账号信息
    [AccountTool saveaAccountTool:account];

    //4.切换控制器
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window switchRootViewController];

       // NSLog(@"%@",responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 请求失败的时候调用

        [MBProgressHUD hideHUD];
        NSLog(@"%@",error);
    }];
}
@end

/*
 必选	类型及范围	说明
 client_id	true	string	申请应用时分配的AppKey。
 client_secret	true	string	申请应用时分配的AppSecret。
 grant_type	true	string	请求的类型,填写authorization_code

 grant_type为authorization_code时
 必选	类型及范围	说明
 code	true	string	调用authorize获得的code值。
 redirect_uri	true	string	回调地址,需需与注册应用里的回调地址一致。

 */


text:
from django.test import TestCase

from backend.models import InvalidPermissionStringError, Client
from backend.models import client_has_permission
from backend.tests.helpers import create_client

class ClientHasPermissionTests(TestCase):
    def test_wrong_permission(self):
        """
        client_has_permission() is to raise InvalidPermissionStringError
        if permission name is other than 'read', 'write', 'delete' and 'vote'
        """
        with self.assertRaises(InvalidPermissionStringError):
            client_has_permission('test', 'asdf')

    def test_create_new_client(self):
        """
        if client_has_permission() is called with a name, not relating to an
        existing client object, a new Client object with that name is to be created
        """
        num_before_count = Client.objects.all().count()
        client_has_permission('test', 'read')
        num_after_count = Client.objects.all().count()
        self.assertEqual(num_before_count + 1, num_after_count)

    def test_query_existing_client(self):
        """
        if client_has_permission() is called with a name, relating to an
        existing client object, the corresponding Client object is to be queried
        """
        client = create_client('test')
        client.read_access = False
        client.save()
        num_before_count = Client.objects.all().count()
        permission = client_has_permission('test', 'read')
        num_after_count = Client.objects.all().count()
        self.assertEqual(num_before_count, num_after_count)
        self.assertFalse(permission)


text:
#include "Streams.h"
#include "BufferStream.h"
#include "test_commons.h"

TEST(InputStream, InputBuffer) {
  // TODO:
}

TEST(OutputStream, OutputBuffer) {
  // TODO:
}