text:
static NSInteger globalVariable = 1;

@interface RXBlockChangeOverTimeMRCObject()
@property (nonatomic, copy) NSInteger(^block)(NSInteger);

@property (nonatomic, assign) NSInteger instanceVariable;
@end

@implementation RXBlockChangeOverTimeMRCObject
- (void)test
{
    NSLog(@"--------RXBlockChangeOverTimeMRCObject--------");
    // 定义几种类型的变量
    self.instanceVariable = 10;
    NSInteger localVariable = 100;
    static NSInteger staticLocalVariable = 99;
    __block NSInteger blockVariable = 1000;

    // 定义分别使用类型变量的block
    NSInteger (^block_noVariable)(NSInteger) = ^(NSInteger m) {
        return m;
    };
    NSInteger (^block_globalVariable)(NSInteger) = ^(NSInteger m) {
        return m + globalVariable;
    };
    // MRC解决循环引用
    __block __typeof(self) weakSelf = self;
    NSInteger (^block_instanceVariable)(NSInteger) = ^(NSInteger m) {
        if (malloc_zone_from_ptr(weakSelf)) {
            return m + weakSelf.instanceVariable;
        } else {
            return m;
        }
    };
    NSInteger (^block_localVariable)(NSInteger) = ^(NSInteger m) {
        return m + localVariable;
    };
    NSInteger (^block_staticLocalVariable)(NSInteger) = ^(NSInteger m) {
        return m + staticLocalVariable;
    };
    NSInteger (^block_blockVariable)(NSInteger) = ^(NSInteger m) {
        blockVariable++;
        return m + blockVariable;
    };
    NSInteger (^block_composedVarialbe)(NSInteger) = ^(NSInteger m) {
        return m + localVariable + staticLocalVariable;
    };
    // 输出定义好的block变量
    [RXPrintUtil printBlockWithPrefix:@"block_noVariable" block:block_noVariable];
    [RXPrintUtil printBlockWithPrefix:@"block_globalVariable" block:block_globalVariable];
    [RXPrintUtil printBlockWithPrefix:@"block_instanceVariable" block:block_instanceVariable];
    [RXPrintUtil printBlockWithPrefix:@"block_localVariable" block:block_localVariable];
    [RXPrintUtil printBlockWithPrefix:@"block_staticLocalVariable" block:block_staticLocalVariable];
    [RXPrintUtil printBlockWithPrefix:@"block_blockVariable" block:block_blockVariable];
    [RXPrintUtil printBlockWithPrefix:@"block_composedVarialbe" block:block_composedVarialbe];

    // 分别设置block
    self.block = block_noVariable;
    [RXPrintUtil printBlockWithPrefix:@"self block_noVariable" block:self.block];

    self.block = block_globalVariable;
    [RXPrintUtil printBlockWithPrefix:@"self block_globalVariable" block:self.block];

    self.block = block_instanceVariable;
    [RXPrintUtil printBlockWithPrefix:@"self block_instanceVariable" block:self.block];

    self.block = block_localVariable;
    [RXPrintUtil printBlockWithPrefix:@"self block_localVariable" block:self.block];

    self.block = block_staticLocalVariable;
    [RXPrintUtil printBlockWithPrefix:@"self block_staticLocalVariable" block:self.block];

    self.block = block_blockVariable;
    [RXPrintUtil printBlockWithPrefix:@"self block_blockVariable" block:self.block];

    self.block = block_composedVarialbe;
    [RXPrintUtil printBlockWithPrefix:@"self block_composedVarialbe" block:self.block];
}
- (void)dealloc
{
    [super dealloc];
    NSLog(@"RXBlockChangeOverTimeMRCObject dealloc");
}
@end


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.encog.ml.graph.BasicNode (Encog Core 3.1.0 API)
</TITLE>

<META NAME="date" CONTENT="2012-04-08">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.encog.ml.graph.BasicNode

Packages that use BasicNode

org.encog.ml.graph

org.encog.ml.graph.search

org.encog.ml.schedule

Uses of BasicNode in org.encog.ml.graph

Subclasses of BasicNode in org.encog.ml.graph

 class
EuclideanNode

Methods in org.encog.ml.graph that return BasicNode

 BasicNode
BasicGraph.connect(BasicNode baseNode,
        BasicNode newNode,
        double cost)

 BasicNode
BasicPath.getDestinationNode()

 BasicNode
BasicEdge.getFrom()

 BasicNode
BasicGraph.getRoot()

 BasicNode
BasicEdge.getTo()

Methods in org.encog.ml.graph that return types with arguments of type BasicNode

 List<BasicNode>
BasicPath.getNodes()

 List<BasicNode>
BasicGraph.getNodes()

Methods in org.encog.ml.graph with parameters of type BasicNode

 BasicNode
BasicGraph.connect(BasicNode baseNode,
        BasicNode newNode,
        double cost)

 void
BasicNode.connect(BasicNode newNode,
        double cost)

 double
BasicNode.getCost(BasicNode node)

Constructors in org.encog.ml.graph with parameters of type BasicNode

BasicEdge(BasicNode from,
          BasicNode to,
          double cost)

BasicGraph(BasicNode rootNode)

BasicPath(BasicNode startingPoint)

BasicPath(BasicPath path,
          BasicNode newNode)

Uses of BasicNode in org.encog.ml.graph.search

Methods in org.encog.ml.graph.search that return BasicNode

 BasicNode
SimpleDestinationGoal.getGoalDestination()

Methods in org.encog.ml.graph.search with parameters of type BasicNode

 boolean
FrontierHolder.containsDestination(BasicNode node)

 double
EuclideanCostEstimator.estimateCost(BasicNode startingNode,
             SearchGoal goal)

 double
CostEstimator.estimateCost(BasicNode startingNode,
             SearchGoal goal)

Constructors in org.encog.ml.graph.search with parameters of type BasicNode

AbstractGraphSearch(BasicGraph theGraph,
                    BasicNode startingPoint,
                    SearchGoal theGoal)

AStarSearch(BasicGraph theGraph,
            BasicNode startingPoint,
            SearchGoal theGoal,
            CostEstimator theEstimator)

BreadthFirstSearch(BasicGraph theGraph,
                   BasicNode startingPoint,
                   SearchGoal theGoal)

DepthFirstSearch(BasicGraph theGraph,
                 BasicNode startingPoint,
                 SearchGoal theGoal)

SimpleDestinationGoal(BasicNode goalDestination)

Uses of BasicNode in org.encog.ml.schedule

Subclasses of BasicNode in org.encog.ml.schedule

 class
ActionNode

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.mapreduce;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.nio.ByteBuffer;

import junit.framework.TestCase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.ResourceMgrDelegate;
import org.apache.hadoop.mapred.YARNRunner;
import org.apache.hadoop.mapreduce.protocol.ClientProtocol;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.yarn.api.ClientRMProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenResponse;
import org.apache.hadoop.yarn.api.records.DelegationToken;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.junit.Test;

public class TestYarnClientProtocolProvider extends TestCase {

  private static final RecordFactory recordFactory = RecordFactoryProvider.
      getRecordFactory(null);

  @Test
  public void testClusterWithYarnClientProtocolProvider() throws Exception {

    Configuration conf = new Configuration(false);
    Cluster cluster = null;

    try {
      cluster = new Cluster(conf);
      fail("Cluster should not be initialized with out any framework name");
    } catch (IOException e) {

    }

    try {
      conf = new Configuration();
      conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME);
      cluster = new Cluster(conf);
      ClientProtocol client = cluster.getClient();
      assertTrue(client instanceof YARNRunner);
    } catch (IOException e) {

    } finally {
      if (cluster != null) {
        cluster.close();
      }
    }
  }

  @Test
  public void testClusterGetDelegationToken() throws Exception {

    Configuration conf = new Configuration(false);
    Cluster cluster = null;
    try {
      conf = new Configuration();
      conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME);
      cluster = new Cluster(conf);
      YARNRunner yrunner = (YARNRunner) cluster.getClient();
      GetDelegationTokenResponse getDTResponse =
          recordFactory.newRecordInstance(GetDelegationTokenResponse.class);
      DelegationToken rmDTToken = recordFactory.newRecordInstance(
          DelegationToken.class);
      rmDTToken.setIdentifier(ByteBuffer.wrap(new byte[2]));
      rmDTToken.setKind("Testclusterkind");
      rmDTToken.setPassword(ByteBuffer.wrap("testcluster".getBytes()));
      rmDTToken.setService("0.0.0.0:8032");
      getDTResponse.setRMDelegationToken(rmDTToken);
      ClientRMProtocol cRMProtocol = mock(ClientRMProtocol.class);
      when(cRMProtocol.getDelegationToken(any(
          GetDelegationTokenRequest.class))).thenReturn(getDTResponse);
      ResourceMgrDelegate rmgrDelegate = new ResourceMgrDelegate(
          new YarnConfiguration(conf), cRMProtocol);
      yrunner.setResourceMgrDelegate(rmgrDelegate);
      Token t = cluster.getDelegationToken(new Text(" "));
      assertTrue("Testclusterkind".equals(t.getKind().toString()));
    } finally {
      if (cluster != null) {
        cluster.close();
      }
    }
  }

}


text:
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

declare var jQuery: any;

@Component({

    moduleId: module.id,
    selector: 'adf-notification-modal',
    templateUrl: './notification-component.html',
    styleUrls: ['./notification-component.css']
})
export class NotificationComponent implements OnInit, AfterViewInit {

    @ViewChild('notificationModalTag') notificationModalRef: ElementRef;

    notificationFilters: any [] = [];
    currentNotificationFilter = {
            name: '',
            count: 0
        };

    notificationModal: any;
    modalHeader: string;

    constructor() {
        this.notificationFilters.push({name: 'Unacknowledged', count: 4});
        this.notificationFilters.push({name: 'All Notifications', count: 4});
        this.notificationFilters.push({name: 'Area Widget', count: 4});
        this.notificationFilters.push({name: 'CPU Widget', count: 0});
        this.setSelectedNotificationFilter({name: 'Unacknowledged', count: 4});
    }

    ngOnInit() {
    }

    ngAfterViewInit() {
        this.notificationModal = jQuery(this.notificationModalRef.nativeElement);
    }

    setSelectedNotificationFilter(item) {
        this.currentNotificationFilter = item;
    }

    showNotificationModal(header: string) {

        this.modalHeader = header;
        this.notificationModal.modal('show');
    }

    hideMessageModal() {
        this.modalHeader = '';
        this.notificationModal.modal('hide');
    }
}


text:
@implementation EXBrightness

RCT_EXPORT_MODULE(ExponentBrightness);

RCT_EXPORT_METHOD(setBrightnessAsync:
                  (float)brightnessValue
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  [EXUtil performSynchronouslyOnMainThread:^{
    [UIScreen mainScreen].brightness = brightnessValue;
  }];
  resolve(nil);
}

RCT_REMAP_METHOD(getBrightnessAsync,
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  __block float result = 0;
  [EXUtil performSynchronouslyOnMainThread:^{
    result = [UIScreen mainScreen].brightness;
  }];
  resolve(@(result));
}

@end


text:
import os
import sys
import argparse
import binwalk.core.idb
import binwalk.core.filter
import binwalk.core.common
import binwalk.core.display
import binwalk.core.settings
from binwalk.core.compat import *
from binwalk.core.module import Module, Option, Kwarg, show_help

class General(Module):

    TITLE = "General"
    ORDER = 0

    DEFAULT_DEPENDS = []

    CLI = [
        Option(long='length',
               short='l',
               type=int,
               kwargs={'length' : 0},
               description='Number of bytes to scan'),
        Option(long='offset',
               short='o',
               type=int,
               kwargs={'offset' : 0},
               description='Start scan at this file offset'),
        Option(long='block',
               short='K',
               type=int,
               kwargs={'block' : 0},
               description='Set file block size'),
        Option(long='continue',
               short='k',
               kwargs={'keep_going' : True},
               description="Don't stop at the first match"),
        Option(long='swap',
               short='g',
               type=int,
               kwargs={'swap_size' : 0},
               description='Reverse every n bytes before scanning'),
        Option(short='I',
               long='invalid',
               kwargs={'show_invalid' : True},
               description='Show results marked as invalid'),
        Option(short='x',
               long='exclude',
               kwargs={'exclude_filters' : []},
               type=list,
               dtype=str.__name__,
               description='Exclude results that match <str>'),
        Option(short='y',
               long='include',
               kwargs={'include_filters' : []},
               type=list,
               dtype=str.__name__,
               description='Only show results that match <str>'),
        Option(long='log',
               short='f',
               type=argparse.FileType,
               kwargs={'log_file' : None},
               description='Log results to file'),
        Option(long='csv',
               short='c',
               kwargs={'csv' : True},
               description='Log results to file in CSV format'),
        Option(long='term',
               short='t',
               kwargs={'format_to_terminal' : True},
               description='Format output to fit the terminal window'),
        Option(long='quiet',
               short='q',
               kwargs={'quiet' : True},
               description='Suppress output to stdout'),
        Option(long='verbose',
               short='v',
               kwargs={'verbose' : True},
               description='Enable verbose output'),
        Option(short='h',
               long='help',
               kwargs={'show_help' : True},
               description='Show help output'),
        Option(long=None,
               short=None,
               type=binwalk.core.common.BlockFile,
               kwargs={'files' : []}),
    ]

    KWARGS = [
        Kwarg(name='length', default=0),
        Kwarg(name='offset', default=0),
        Kwarg(name='block', default=0),
        Kwarg(name='swap_size', default=0),
        Kwarg(name='show_invalid', default=False),
        Kwarg(name='include_filters', default=[]),
        Kwarg(name='exclude_filters', default=[]),
        Kwarg(name='log_file', default=None),
        Kwarg(name='csv', default=False),
        Kwarg(name='format_to_terminal', default=False),
        Kwarg(name='quiet', default=False),
        Kwarg(name='verbose', default=False),
        Kwarg(name='files', default=[]),
        Kwarg(name='show_help', default=False),
        Kwarg(name='keep_going', default=False),
    ]

    PRIMARY = False

    def load(self):
        self.target_files = []

        # Order is important with these two methods
        self._open_target_files()
        self._set_verbosity()

        #self.filter = binwalk.core.filter.Filter(self._display_invalid)
        self.filter = binwalk.core.filter.Filter(self.show_invalid)

        # Set any specified include/exclude filters
        for regex in self.exclude_filters:
            self.filter.exclude(regex)
        for regex in self.include_filters:
            self.filter.include(regex)

        self.settings = binwalk.core.settings.Settings()
        self.display = binwalk.core.display.Display(log=self.log_file,
                                                    csv=self.csv,
                                                    quiet=self.quiet,
                                                    verbose=self.verbose,
                                                    filter=self.filter,
                                                    fit_to_screen=self.format_to_terminal)

        if self.show_help:
            show_help()
            if not binwalk.core.idb.LOADED_IN_IDA:
                sys.exit(0)

    def reset(self):
        for fp in self.target_files:
            fp.reset()

    def __del__(self):
        self._cleanup()

    def __exit__(self, a, b, c):
        self._cleanup()

    def _cleanup(self):
        if hasattr(self, 'target_files'):
            for fp in self.target_files:
                fp.close()

    def _set_verbosity(self):
        '''
        Sets the appropriate verbosity.
        Must be called after self._test_target_files so that self.target_files is properly set.
        '''
        # If more than one target file was specified, enable verbose mode; else, there is
        # nothing in some outputs to indicate which scan corresponds to which file.
        if len(self.target_files) > 1 and not self.verbose:
            self.verbose = True

    def open_file(self, fname, length=None, offset=None, swap=None, block=None, peek=None):
        '''
        Opens the specified file with all pertinent configuration settings.
        '''
        if length is None:
            length = self.length
        if offset is None:
            offset = self.offset
        if swap is None:
            swap = self.swap_size

        return binwalk.core.common.BlockFile(fname, length=length, offset=offset, swap=swap, block=block, peek=peek)

    def _open_target_files(self):
        '''
        Checks if the target files can be opened.
        Any files that cannot be opened are removed from the self.target_files list.
        '''
        # Validate the target files listed in target_files
        for tfile in self.files:
            # Ignore directories.
            if not os.path.isdir(tfile):
                # Make sure we can open the target files
                try:
                    self.target_files.append(self.open_file(tfile))
                except KeyboardInterrupt as e:
                    raise e
                except Exception as e:
                    self.error(description="Cannot open file : %s" % str(e))


text:
package org.scalastyle.scalariform

import scala.Option.option2Iterable

import org.scalastyle.scalariform.VisitorHelper.Clazz
import org.scalastyle.PositionError
import org.scalastyle.ScalariformChecker
import org.scalastyle.ScalastyleError

import scalariform.lexer.Tokens.INTEGER_LITERAL
import scalariform.lexer.Tokens.VAL
import scalariform.lexer.Token
import scalariform.parser.CompilationUnit
import scalariform.parser.Expr
import scalariform.parser.ExprElement
import scalariform.parser.GeneralTokens
import scalariform.parser.PatDefOrDcl
import scalariform.parser.PrefixExprElement

class MagicNumberChecker extends ScalariformChecker {
  val DefaultIgnore = "-1,0,1,2"
  val errorKey = "magic.number"

  def verify(ast: CompilationUnit): List[ScalastyleError] = {
    val ignores = getString("ignore", DefaultIgnore).split(",").toSet

    val intList = for {
      t <- localvisit(ast.immediateChildren(0));
      f <- traverse(t);
      if (matches(f, ignores))
    } yield {
      f
    }

    val valList = (for {
      t <- localvisitVal(ast.immediateChildren(0));
      f <- traverseVal(t);
      g <- toOption(f)
    } yield {
      g
    }).map( d => d match {
      case Expr(List(t: Expr)) => t
      case _ => d
    })

    intList.filter(t => !valList.contains(t.t)).map(t => PositionError(t.position)).toList
  }

  case class ExprVisit(t: Expr, position: Int, contents: List[ExprVisit]) extends Clazz[Expr]()

  private def traverse(t: ExprVisit): List[ExprVisit] = t :: t.contents.map(traverse(_)).flatten

  private def matches(t: ExprVisit, ignores: Set[String]) = {
    toIntegerLiteralExprElement(t.t.contents) match {
      case Some(x) => !ignores.contains(x)
      case None => false
    }
  }

  private def toIntegerLiteralExprElement(list: List[ExprElement]): Option[String] = {
    list match {
      case List(Expr(List(PrefixExprElement(t), GeneralTokens(gtList)))) => toIntegerLiteral(t, toIntegerLiteralToken(gtList))
      case List(PrefixExprElement(t), GeneralTokens(gtList)) => toIntegerLiteral(t, toIntegerLiteralToken(gtList))
      case List(GeneralTokens(gtList)) => toIntegerLiteralToken(gtList)
      case _ => None
    }
  }

  private def toIntegerLiteral(prefixExpr: Token, intLiteral: Option[String]): Option[String] = {
    (prefixExpr.text, intLiteral) match {
      case ("+", Some(i)) => Some(i)
      case ("-", Some(i)) => Some("-" + i)
      case _ => None
    }
  }

  private def toIntegerLiteralToken(list: List[Token]): Option[String] = {
    list match {
      case List(Token(tokenType, text, start, end)) if (tokenType == INTEGER_LITERAL) => Some(text.replaceAll("[Ll]", ""))
      case _ => None
    }
  }

  private def localvisit(ast: Any): List[ExprVisit] = ast match {
    case Expr(List(t: Expr)) => List(ExprVisit(t, t.firstToken.offset, localvisit(t.contents)))
    case t: Expr => List(ExprVisit(t, t.firstToken.offset, localvisit(t.contents)))
    case t: Any => VisitorHelper.visit(t, localvisit)
  }

  case class PatDefOrDclVisit(t: PatDefOrDcl, valOrVarToken: Token, pattern: List[PatDefOrDclVisit], otherPatterns: List[PatDefOrDclVisit],
                              equalsClauseOption: List[PatDefOrDclVisit])

  private def localvisitVal(ast: Any): List[PatDefOrDclVisit] = ast match {
    case t: PatDefOrDcl => List(PatDefOrDclVisit(t, t.valOrVarToken, localvisitVal(t.pattern),
                                    localvisitVal(t.otherPatterns), localvisitVal(t.equalsClauseOption)))
    case t: Any => VisitorHelper.visit(t, localvisitVal)
  }

  private def traverseVal(t: PatDefOrDclVisit): List[PatDefOrDclVisit] = t :: t.equalsClauseOption.map(traverseVal(_)).flatten

  private def toOption(t: PatDefOrDclVisit): Option[Expr] = {
    t.t.equalsClauseOption match {
      case Some((equals: Token, expr: Expr)) if (t.t.valOrVarToken.tokenType == VAL && toIntegerLiteralExprElement(expr.contents).isDefined) => Some(expr)
      case _ => None
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. trimest. Soc. mycol. Fr. 97(3): 268 (1981)

#### Original name
Cortinarius isabellae Rob. Henry

### Remarks
null


text:
using ApiTest.Data.Entities;
using Dapper.FluentMap.Dommel.Mapping;
using Dapper.FluentMap.Mapping;

namespace ApiTest.Data.Mappings
{
    public class ProductMap : DommelEntityMap<Product>
    {
        public ProductMap()
        {
            ToTable("SalesLT.Product");
        }
    }
}


text:
package xitrum.routing

import org.apache.commons.lang3.text.WordUtils

import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods

import xitrum.{Action, FutureAction, Config}
import xitrum.annotation.{First, DELETE, GET, PATCH, POST, PUT, SOCKJS, WEBSOCKET}
import xitrum.annotation.{Swagger, SwaggerArg}
import xitrum.view.DocType

case class ApiMethod(method: String, route: String)

/** https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md */
object SwaggerJson {
  val SWAGGER_VERSION = "1.2"
  val NONAME_RESOURCE = "noname"

  /** Maybe called multiple times in development mode when reloading routes. */
  var resources = groupByResource()

  def groupByResource(): Map[Option[Swagger.Resource], Map[Class[_ <: Action], Swagger]] = {
    Config.routes.swaggerMap.groupBy { case (klass, swagger) =>
      val swaggerArgs = swagger.swaggerArgs
      swaggerArgs.find(_.isInstanceOf[Swagger.Resource]).asInstanceOf[Option[Swagger.Resource]]
    }
  }

  //----------------------------------------------------------------------------

  def resourcesJson(apiVersion: String): String = {
    val apis = SwaggerJson.resources.keys.map {
      case None =>
        ("path" -> ("/" + NONAME_RESOURCE)) ~ ("description" -> "APIs without named resource")

      case Some(resource) =>
        val path = if (resource.path.startsWith("/")) resource.path else "/" + resource.path
        ("path" -> path) ~ ("description" -> resource.desc)
    }

    val json =
      ("swaggerVersion" -> SWAGGER_VERSION) ~
      ("apiVersion"     -> apiVersion) ~
      ("apis"           -> apis)
    JsonMethods.pretty(JsonMethods.render(json))
  }

  def resourceJson(apiVersion: String, basePath: String, resourcePatho: Option[String]): Option[String] = {
    val keyo = resourcePatho match {
      case None =>
        Some(None)

      case Some(path) =>
        resources.keys.find { ro => ro.isDefined && (ro.get.path == path || ro.get.path == "/" + path) }
    }

    keyo match {
      case None =>
        None

      case Some(key) =>
        resources.get(key).map { swaggerMap =>
          val resourcePath = resourcePatho.getOrElse(NONAME_RESOURCE)
          val path         = if (resourcePath.startsWith("/")) resourcePath else "/" + resourcePath
          val json         =
            ("swaggerVersion" -> SWAGGER_VERSION) ~
            ("apiVersion"     -> apiVersion) ~
            ("basePath"       -> basePath) ~
            ("resourcePath"   -> path) ~
            ("apis"           -> loadApis(swaggerMap))
          JsonMethods.pretty(JsonMethods.render(json))
        }
    }
  }

  //----------------------------------------------------------------------------

  private def loadApis(swaggerMap: Map[Class[_ <: Action], Swagger]): Seq[JObject] = for {
    route   <- Config.routes.all.flatten
    swagger <- swaggerMap.get(route.klass)
  } yield swagger2Json(route, swagger)

  private def swagger2Json(route: Route, swagger: Swagger): JObject = {
    val swaggerArgs = swagger.swaggerArgs

    val routePath = RouteCompiler.decompile(route.compiledPattern, true)

    val nickname  = swaggerArgs.find(_.isInstanceOf[Swagger.Nickname]).map(_.asInstanceOf[Swagger.Nickname].nickname).getOrElse(WordUtils.uncapitalize(route.klass.getSimpleName))
    val produces  = swaggerArgs.filter(_.isInstanceOf[Swagger.Produces]).asInstanceOf[Seq[Swagger.Produces]].flatMap(_.contentTypes).distinct
    val consumes  = swaggerArgs.filter(_.isInstanceOf[Swagger.Consumes]).asInstanceOf[Seq[Swagger.Consumes]].flatMap(_.contentTypes).distinct
    val summary   = swaggerArgs.find(_.isInstanceOf[Swagger.Summary]).asInstanceOf[Option[Swagger.Summary]].map(_.summary).getOrElse("")
    val notes     = swaggerArgs.filter(_.isInstanceOf[Swagger.Note]).asInstanceOf[Seq[Swagger.Note]].map(_.note).mkString(" ")
    val responses = swaggerArgs.filter(_.isInstanceOf[Swagger.Response]).asInstanceOf[Seq[Swagger.Response]].map(response2Json)

    val params = swaggerArgs.filterNot { arg =>
      arg.isInstanceOf[Swagger.Resource] ||
      arg.isInstanceOf[Swagger.Nickname] ||
      arg.isInstanceOf[Swagger.Produces] ||
      arg.isInstanceOf[Swagger.Consumes] ||
      arg.isInstanceOf[Swagger.Summary]  ||
      arg.isInstanceOf[Swagger.Note]     ||
      arg.isInstanceOf[Swagger.Response]
    }.sortBy(
      _.toString.indexOf("Opt")  // Required params first, optional params later
    ).map(
      param2Json
    )

    val cacheNote  = cache(route)
    val finalNotes =
      if (cacheNote.isEmpty)
        notes
      else if (notes.isEmpty)
        cacheNote
      else
        notes + " " + cacheNote

    val operations = Seq[JObject](
      ("httpMethod"       -> route.httpMethod.toString) ~
      ("summary"          -> summary) ~
      ("notes"            -> finalNotes) ~
      ("nickname"         -> nickname) ~
      ("type"             -> "string") ~  // FIXME: Support models
      ("parameters"       -> params.toSeq) ~
      ("responseMessages" -> responses.toSeq) ~
      ("produces"         -> produces) ~
      ("consumes"         -> consumes))

    ("path" -> routePath) ~ ("operations" -> operations)
  }

  private def param2Json(param: SwaggerArg): JObject = {
    // Use class name to extract paramType, valueType, and required
    // See Swagger.scala

    val klass          = param.getClass
    val className      = klass.getName            // Ex: xitrum.annotation.Swagger$OptBytePath
    val shortClassName = className.split('$')(1)  // Ex: OptBytePath

    val paramType =
           if (shortClassName.endsWith("Path"))   "path"
      else if (shortClassName.endsWith("Query"))  "query"
      else if (shortClassName.endsWith("Body"))   "body"
      else if (shortClassName.endsWith("Header")) "header"
      else                                        "form"

    val required = !shortClassName.startsWith("Opt")

    val valueType =
      if (required)
        shortClassName.substring(0, shortClassName.length - paramType.length).toLowerCase
      else
        shortClassName.substring("Opt".length, shortClassName.length - paramType.length).toLowerCase

    // Use reflection to extract name and desc

    val nameMethod = klass.getMethod("name")
    val name       = nameMethod.invoke(param).asInstanceOf[String]

    val descMethod = klass.getMethod("desc")
    val desc       = descMethod.invoke(param).asInstanceOf[String]

    ("name"        -> name) ~
    ("paramType"   -> paramType) ~
    ("type"        -> valueType) ~
    ("description" -> desc) ~
    ("required"    -> required)
  }

  private def response2Json(response: Swagger.Response): JObject = {
    ("code"    -> response.code) ~
    ("message" -> response.desc)
  }

  private def annotation2Method(annotation: Any): Seq[ApiMethod] = annotation match {
    case method: GET       => method.paths.map(ApiMethod("GET",       _))
    case method: POST      => method.paths.map(ApiMethod("POST",      _))
    case method: PUT       => method.paths.map(ApiMethod("PUT",       _))
    case method: PATCH     => method.paths.map(ApiMethod("PATCH",     _))
    case method: DELETE    => method.paths.map(ApiMethod("DELETE",    _))
    case method: SOCKJS    => method.paths.map(ApiMethod("SOCKJS",    _))
    case method: WEBSOCKET => method.paths.map(ApiMethod("WEBSOCKET", _))
    case _                 => Seq()
  }

  private def cache(route: Route): String = {
    val secs = route.cacheSecs
    if (route.cacheSecs == 0)
      ""
    else if (secs > 0)
      s"(Page cache: ${route.cacheSecs} [sec])"
    else
      s"(Action cache: ${-route.cacheSecs} [sec])"
  }
}

//------------------------------------------------------------------------------

/** Swagger resource listing: https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md */
@First
@GET("xitrum/swagger")
class SwaggerResources extends FutureAction {
  def execute() {
    val apiVersion = Config.xitrum.swaggerApiVersion.get
    val json       = SwaggerJson.resourcesJson(apiVersion)
    respondJsonText(json)
  }
}

/** Swagger API declaration: https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md */
@First
@GET("xitrum/swagger/:*")
class SwaggerResource extends FutureAction {
  def execute() {
    val apiVersion    = Config.xitrum.swaggerApiVersion.get
    val resourcePath  = param("*")
    val resourcePatho = if (resourcePath == SwaggerJson.NONAME_RESOURCE) None else Some(resourcePath)
    SwaggerJson.resourceJson(apiVersion, absUrlPrefix, resourcePatho) match {
      case Some(json) =>
        respondJsonText(json)
      case None =>
        respond404Page()
    }
  }
}

//------------------------------------------------------------------------------
// Swagger UI

/**
 * Easy-to-remember path to Swagger UI:
 * http(s)://host[:port]/xitrum/swagger
 */
@First
@GET("xitrum/swagger-ui")
class SwaggerUi extends FutureAction {
  def execute() {
    redirectTo[SwaggerUiVersioned]()
  }
}

/**
 * Not-so-easy-to-remember path to Swagger UI. The path is longer because the
 * directory must be at the same level with other Swagger UI files.
 */
@First
@GET("webjars/swagger-ui/2.0.24/index")
class SwaggerUiVersioned extends FutureAction {
  def execute() {
    val swaggerResourcesUrl = url[SwaggerResources]

    // Need to update everytime a new Swagger UI version is released
    val html =

  {antiCsrfMeta}
  <title>Swagger UI</title>
  <link href='//fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'/>
  <link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
  <link href='css/screen.css' media='print' rel='stylesheet' type='text/css'/>

    swagger
    <form id='api_selector'>

<input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/>

<input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/>

Explore

    </form>

    respondHtml(DocType.html5(html))
  }
}


text:
package biz.lci.stockfighter;

/**
 * Created by tlanders on 4/16/2016.
 */
public class Order {
//    public enum Direction {buy, sell};
//    public enum OrderType {limit, market};

    private String account;
    private String venue;
    private String stock;
    private int price;
    private int qty;
    private Direction direction;
    private OrderType orderType;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getVenue() {
        return venue;
    }

    public void setVenue(String venue) {
        this.venue = venue;
    }

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public OrderType getOrderType() {
        return orderType;
    }

    public void setOrderType(OrderType orderType) {
        this.orderType = orderType;
    }

    @Override
    public String toString() {
        return "Order{" +
                "account='" + account + '\'' +
                ", venue='" + venue + '\'' +
                ", stock='" + stock + '\'' +
                ", price=" + price +
                ", qty=" + qty +
                ", direction=" + direction +
                ", orderType=" + orderType +
                '}';
    }
}


text:
package com.avos.avoscloud.PushDemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.*;

public class PushDemo extends Activity {
  /**
   * Called when the activity is first created.
   */

  View customPushButton;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    PushService.setDefaultPushCallback(this, PushDemo.class);
    PushService.subscribe(this, "public", PushDemo.class);
    PushService.subscribe(this, "private", Callback1.class);
    PushService.subscribe(this, "protected", Callback2.class);

    final Context context = this;

    final TextView t = (TextView) this.findViewById(R.id.mylabel);
    t.setText("id: " + AVInstallation.getCurrentInstallation().getInstallationId());
    AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
      @Override
      public void done(AVException e) {
        PushService.unsubscribe(context, "protected");
        AVInstallation.getCurrentInstallation().saveInBackground();
      }
    });
    customPushButton = this.findViewById(R.id.customPush);
    customPushButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        AVPush push = new AVPush();

        AVQuery<AVInstallation> query = AVInstallation.getQuery();
        query.whereEqualTo("installationId", AVInstallation.getCurrentInstallation()
            .getInstallationId());
        push.setQuery(query);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action", "com.pushdemo.action");
        jsonObject.put("alert", "Here is the Custom Push Message");

        push.setData(jsonObject);
        push.setPushToAndroid(true);
        push.sendInBackground(new SendCallback() {
          @Override
          public void done(AVException e) {
            Toast.makeText(getApplicationContext(), "send successfully", Toast.LENGTH_SHORT);
          }
        });
      }
    });
  }
}


text:
package util;

public class DataGenerator {
	private int numOfUsers;
	private int numOfItems;
	private int numOfRatings;

	public DataGenerator(int numOfUsers, int numOfItems, int numOfRatings) {
		this.numOfItems = numOfItems;
		this.numOfRatings = numOfRatings;
		this.numOfUsers = numOfUsers;
	}

}


text:
/**
 * \addtogroup message
 * @{
 */

#ifndef __M2ETIS_MESSAGE_INFO_ROUTINGINFO_H__
#define __M2ETIS_MESSAGE_INFO_ROUTINGINFO_H__

#include "boost/shared_ptr.hpp"

namespace m2etis {
namespace message {

    template<class NetworkType>
	struct RoutingInfo {
        typedef boost::shared_ptr<RoutingInfo<NetworkType>> Ptr;

        enum class RoutingType : uint8_t {
        	NONE,
        	ACK,
        	REDIRECT,
        	STOP
        };

        RoutingType action = RoutingType::NONE;

		RoutingInfo() {}
        virtual ~RoutingInfo() {}

    private:
        friend class boost::serialization::access;

		template<typename Archive>
		void serialize(Archive & ar, const unsigned int /*version*/) {
			ar & action;
		}
	};

} /* namespace message */
} /* namespace m2etis */

#endif /* __M2ETIS_MESSAGE_INFO_ROUTINGINFO_H__ */

/**
 * @}
 */


text:
@interface PodsDummy_Pods_Shopmium_Box : NSObject
@end
@implementation PodsDummy_Pods_Shopmium_Box
@end


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class User_login extends CI_Controller {

	public function index() {
        $data = array();
        $data['header'] = $this->load->view('common/header');
        $data['header'] = $this->load->view('common/navigation');

        $data['main-content'] = $this->load->view('main-content');
        $data['footer'] = $this->load->view('common/footer');
        $this->load->view('home', $data);
    }
}


text:
<?php
namespace Deepdivedylan\DylanAndTonyFiesta\Test;

use Deepdivedylan\DylanAndTonyFiesta\{Message, Media, Profile};

require_once(dirname(__DIR__) . "/autoload.php");

class MessageTest extends DylanAndTonyFiestaTest {
	/**
	 * valid message id to use
	 * @var string $VALID_MESSAGEID
	 **/
	protected $VALID_MESSAGEID = "848649042821341185";
	/**
	 * valid message content to use
	 * @var string $VALID_MESSAGECONTENT
	 **/
	protected $VALID_MESSAGECONTENT = "Senator Arlo endorses this marriage and can't wait to get drunk off Romulan ale at #dylanandtonyfiesta";
	/**
	 * valid message date and time to use
	 * @var \DateTime $VALID_MESSAGEDATETIME
	 **/
	protected $VALID_MESSAGEDATETIME = null;
	/**
	 * profile to own test message
	 * @var Profile $profile
	 **/
	protected $profile = null;

	/**
	 * setup parent objects
	 **/
	public function setUp() {
		$this->profile = new Profile("847297430630522880", "SenatorArlo", "T");
		$this->profile->insert($this->getPDO());
		$this->VALID_MESSAGEDATETIME = new \DateTime();
	}

	/**
	 * test inserting a valid message
	 **/
	public function testInsertValidMessage() : void {
		// count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("message");

		$message = new Message($this->VALID_MESSAGEID, $this->profile->getProfileId(), $this->VALID_MESSAGECONTENT, $this->VALID_MESSAGEDATETIME);
		$message->insert($this->getPDO());

		// grab the data from mySQL and enforce the fields match our expectations
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("message"));
		$pdoMessage = Message::getMessageByMessageId($this->getPDO(), $this->VALID_MESSAGEID);
		$this->assertEquals($pdoMessage->getMessageId(), $message->getMessageId());
		$this->assertEquals($pdoMessage->getMessageProfileId(), $message->getMessageProfileId());
		$this->assertEquals($pdoMessage->getMessageContent(), $message->getMessageContent());
		$this->assertEquals($pdoMessage->getMessageDateTime(), $message->getMessageDateTime());
	}

	/**
	 * tests getting messages by message profile id
	 **/
	public function testGetMessageByMessageProfileId() : void {
		// count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("message");

		$message = new Message($this->VALID_MESSAGEID, $this->profile->getProfileId(), $this->VALID_MESSAGECONTENT, $this->VALID_MESSAGEDATETIME);
		$message->insert($this->getPDO());

		$messages = Message::getMessageByMessageProfileId($this->getPDO(), $this->profile->getProfileId());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("message"));
		$this->assertCount(1, $messages);
		$this->assertContainsOnlyInstancesOf("Deepdivedylan\\DylanAndTonyFiesta\\Message", $messages);

		// grab the data from mySQL and enforce the fields match our expectations
		$pdoMessage = $messages[0];
		$this->assertEquals($pdoMessage->getMessageId(), $message->getMessageId());
		$this->assertEquals($pdoMessage->getMessageProfileId(), $message->getMessageProfileId());
		$this->assertEquals($pdoMessage->getMessageContent(), $message->getMessageContent());
		$this->assertEquals($pdoMessage->getMessageDateTime(), $message->getMessageDateTime());
	}

	/**
	 * tests beaming out the away team
	 **/
	public function testBeamOutMessages() : void {
		// count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("message");

		$message = new Message($this->VALID_MESSAGEID, $this->profile->getProfileId(), $this->VALID_MESSAGECONTENT, $this->VALID_MESSAGEDATETIME);
		$message->insert($this->getPDO());

		$media = new Media("817277825208094720", $message->getMessageId(), "image/jpeg", "https://pbs.twimg.com/media/C8cBt21UwAEPdmt.jpg");
		$media->insert($this->getPDO());

		$awayTeam = Message::emergencyBeamOut($this->getPDO());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("message"));
		$this->assertCount(1, $awayTeam);

		foreach($awayTeam as $pdoMessage) {
			$this->assertEquals($pdoMessage->getMessageId(), $message->getMessageId());
			$this->assertEquals($pdoMessage->getMessageProfileId(), $message->getMessageProfileId());
			$this->assertEquals($pdoMessage->getMessageContent(), $message->getMessageContent());
			$this->assertEquals($pdoMessage->getMessageDateTime(), $message->getMessageDateTime());

			$this->assertCount(2, $awayTeam[$pdoMessage]);
			$this->assertInstanceOf("Deepdivedylan\\DylanAndTonyFiesta\\Profile", $awayTeam[$pdoMessage]["profile"]);
			$this->assertInstanceOf("Deepdivedylan\\DylanAndTonyFiesta\\Media", $awayTeam[$pdoMessage]["media"]);
		}
	}

	/**
	 * tests getting all messages
	 **/
	public function testGetAllMessages() : void {
		// count the number of rows and save it for later
		$numRows = $this->getConnection()->getRowCount("message");

		$message = new Message($this->VALID_MESSAGEID, $this->profile->getProfileId(), $this->VALID_MESSAGECONTENT, $this->VALID_MESSAGEDATETIME);
		$message->insert($this->getPDO());

		$messages = Message::getAllMessages($this->getPDO());
		$this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("message"));
		$this->assertCount(1, $messages);
		$this->assertContainsOnlyInstancesOf("Deepdivedylan\\DylanAndTonyFiesta\\Message", $messages);

		// grab the data from mySQL and enforce the fields match our expectations
		$pdoMessage = $messages[0];
		$this->assertEquals($pdoMessage->getMessageId(), $message->getMessageId());
		$this->assertEquals($pdoMessage->getMessageProfileId(), $message->getMessageProfileId());
		$this->assertEquals($pdoMessage->getMessageContent(), $message->getMessageContent());
		$this->assertEquals($pdoMessage->getMessageDateTime(), $message->getMessageDateTime());
	}
}


text:
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

using Draft.Endpoints;
using Draft.Responses.Statistics;

using Flurl.Http;

namespace Draft.Requests.Statistics
{
    internal class GetSelfStatisticsRequest : BaseRequest, IGetServerStatisticsRequest
    {

        public GetSelfStatisticsRequest(IEtcdClient etcdClient, EndpointPool endpointPool, params string[] pathParts) : base(etcdClient, endpointPool, pathParts) {}

        public async Task<IServerStatistics> Execute()
        {
            try
            {
                return await TargetUrl
                    .GetAsync()
                    .ReceiveJson<ServerStatistics>();
            }
            catch (FlurlHttpException e)
            {
                throw e.ProcessException();
            }
        }

        public TaskAwaiter<IServerStatistics> GetAwaiter()
        {
            return Execute().GetAwaiter();
        }

    }
}


text:
<?php

define('TEST_SERVICES', dirname(__FILE__) . '/testservices');

/**
 * Tests for the dependency injector
 *
 * Note that these are SS conversions of the existing Simpletest unit tests
 *
 * @author marcus@silverstripe.com.au
 * @license BSD License http://silverstripe.org/bsd-license/
 */
class InjectorTest extends SapphireTest {

	protected $nestingLevel = 0;

	public function setUp() {
		parent::setUp();

		$this->nestingLevel = 0;
	}

	public function tearDown() {

		while($this->nestingLevel > 0) {
			$this->nestingLevel--;
			Config::unnest();
		}

		parent::tearDown();
	}

	public function testCorrectlyInitialised() {
		$injector = Injector::inst();
		$this->assertTrue($injector->getConfigLocator() instanceof SilverStripeServiceConfigurationLocator,
			'Failure most likely because the injector has been referenced BEFORE being initialised in Core.php');
	}

	public function testBasicInjector() {
		$injector = new Injector();
		$injector->setAutoScanProperties(true);
		$config = array(array('src' => TEST_SERVICES . '/SampleService.php',));

		$injector->load($config);
		$this->assertTrue($injector->hasService('SampleService') == 'SampleService');

		$myObject = new TestObject();
		$injector->inject($myObject);

		$this->assertEquals(get_class($myObject->sampleService), 'SampleService');
	}

	public function testConfiguredInjector() {
		$injector = new Injector();
		$services = array(
			array(
				'src' => TEST_SERVICES . '/AnotherService.php',
				'properties' => array('config_property' => 'Value'),
			),
			array(
				'src' => TEST_SERVICES . '/SampleService.php',
			)
		);

		$injector->load($services);
		$this->assertTrue($injector->hasService('SampleService') == 'SampleService');
		// We expect a false because the 'AnotherService' is actually
		// just a replacement of the SampleService
		$this->assertTrue($injector->hasService('AnotherService') == 'AnotherService');

		$item = $injector->get('AnotherService');

		$this->assertEquals('Value', $item->config_property);
	}

	public function testIdToNameMap() {
		$injector = new Injector();
		$services = array(
			'FirstId' => 'AnotherService',
			'SecondId' => 'SampleService',
		);

		$injector->load($services);

		$this->assertTrue($injector->hasService('FirstId') == 'FirstId');
		$this->assertTrue($injector->hasService('SecondId') == 'SecondId');

		$this->assertTrue($injector->get('FirstId') instanceof AnotherService);
		$this->assertTrue($injector->get('SecondId') instanceof SampleService);
	}

	public function testReplaceService() {
		$injector = new Injector();
		$injector->setAutoScanProperties(true);

		$config = array(array('src' => TEST_SERVICES . '/SampleService.php'));

		// load
		$injector->load($config);

		// inject
		$myObject = new TestObject();
		$injector->inject($myObject);

		$this->assertEquals(get_class($myObject->sampleService), 'SampleService');

		// also tests that ID can be the key in the array
		$config = array('SampleService' => array('src' => TEST_SERVICES . '/AnotherService.php'));
		// , 'id' => 'SampleService'));
		// load
		$injector->load($config);

		$injector->inject($myObject);
		$this->assertEquals('AnotherService', get_class($myObject->sampleService));
	}

	public function testUpdateSpec() {
		$injector = new Injector();
		$services = array(
			'AnotherService' => array(
				'src' => TEST_SERVICES . '/AnotherService.php',
				'properties' => array(
					'filters' => array(
						'One',
						'Two',
					)
				),
			)
		);

		$injector->load($services);

		$injector->updateSpec('AnotherService', 'filters', 'Three');
		$another = $injector->get('AnotherService');

		$this->assertEquals(3, count($another->filters));
		$this->assertEquals('Three', $another->filters[2]);
	}

	public function testAutoSetInjector() {
		$injector = new Injector();
		$injector->setAutoScanProperties(true);
		$injector->addAutoProperty('auto', 'somevalue');
		$config = array(array('src' => TEST_SERVICES . '/SampleService.php',));
		$injector->load($config);

		$this->assertTrue($injector->hasService('SampleService') == 'SampleService');
		// We expect a false because the 'AnotherService' is actually
		// just a replacement of the SampleService

		$myObject = new TestObject();

		$injector->inject($myObject);

		$this->assertEquals(get_class($myObject->sampleService), 'SampleService');
		$this->assertEquals($myObject->auto, 'somevalue');
	}

	public function testSettingSpecificProperty() {
		$injector = new Injector();
		$config = array('AnotherService');
		$injector->load($config);
		$injector->setInjectMapping('TestObject', 'sampleService', 'AnotherService');
		$testObject = $injector->get('TestObject');

		$this->assertEquals(get_class($testObject->sampleService), 'AnotherService');
	}

	public function testSettingSpecificMethod() {
		$injector = new Injector();
		$config = array('AnotherService');
		$injector->load($config);
		$injector->setInjectMapping('TestObject', 'setSomething', 'AnotherService', 'method');

		$testObject = $injector->get('TestObject');

		$this->assertEquals(get_class($testObject->sampleService), 'AnotherService');
	}

	public function testInjectingScopedService() {
		$injector = new Injector();

		$config = array(
			'AnotherService',
			'AnotherService.DottedChild'	=> 'SampleService',
		);

		$injector->load($config);

		$service = $injector->get('AnotherService.DottedChild');
		$this->assertEquals(get_class($service), 'SampleService');

		$service = $injector->get('AnotherService.Subset');
		$this->assertEquals(get_class($service), 'AnotherService');

		$injector->setInjectMapping('TestObject', 'sampleService', 'AnotherService.Geronimo');
		$testObject = $injector->create('TestObject');
		$this->assertEquals(get_class($testObject->sampleService), 'AnotherService');

		$injector->setInjectMapping('TestObject', 'sampleService', 'AnotherService.DottedChild.AnotherDown');
		$testObject = $injector->create('TestObject');
		$this->assertEquals(get_class($testObject->sampleService), 'SampleService');

	}

	public function testInjectUsingConstructor() {
		$injector = new Injector();
		$config = array(array(
				'src' => TEST_SERVICES . '/SampleService.php',
				'constructor' => array(
					'val1',
					'val2',
				)
				));

		$injector->load($config);
		$sample = $injector->get('SampleService');
		$this->assertEquals($sample->constructorVarOne, 'val1');
		$this->assertEquals($sample->constructorVarTwo, 'val2');

		$injector = new Injector();
		$config = array(
			'AnotherService',
			array(
				'src' => TEST_SERVICES . '/SampleService.php',
				'constructor' => array(
					'val1',
					'%$AnotherService',
				)
			)
		);

		$injector->load($config);
		$sample = $injector->get('SampleService');
		$this->assertEquals($sample->constructorVarOne, 'val1');
		$this->assertEquals(get_class($sample->constructorVarTwo), 'AnotherService');

		$injector = new Injector();
		$config = array(array(
				'src' => TEST_SERVICES . '/SampleService.php',
				'constructor' => array(
					'val1',
					'val2',
				)
				));

		$injector->load($config);
		$sample = $injector->get('SampleService');
		$this->assertEquals($sample->constructorVarOne, 'val1');
		$this->assertEquals($sample->constructorVarTwo, 'val2');

		// test constructors on prototype
		$injector = new Injector();
		$config = array(array(
			'type'	=> 'prototype',
			'src' => TEST_SERVICES . '/SampleService.php',
			'constructor' => array(
				'val1',
				'val2',
			)
		));

		$injector->load($config);
		$sample = $injector->get('SampleService');
		$this->assertEquals($sample->constructorVarOne, 'val1');
		$this->assertEquals($sample->constructorVarTwo, 'val2');

		$again = $injector->get('SampleService');
		$this->assertFalse($sample === $again);

		$this->assertEquals($sample->constructorVarOne, 'val1');
		$this->assertEquals($sample->constructorVarTwo, 'val2');
	}

	public function testInjectUsingSetter() {
		$injector = new Injector();
		$injector->setAutoScanProperties(true);
		$config = array(array('src' => TEST_SERVICES . '/SampleService.php',));

		$injector->load($config);
		$this->assertTrue($injector->hasService('SampleService') == 'SampleService');

		$myObject = new OtherTestObject();
		$injector->inject($myObject);

		$this->assertEquals(get_class($myObject->s()), 'SampleService');

		// and again because it goes down a different code path when setting things
		// based on the inject map
		$myObject = new OtherTestObject();
		$injector->inject($myObject);

		$this->assertEquals(get_class($myObject->s()), 'SampleService');
	}

	// make sure we can just get any arbitrary object - it should be created for us
	public function testInstantiateAnObjectViaGet() {
		$injector = new Injector();
		$injector->setAutoScanProperties(true);
		$config = array(array('src' => TEST_SERVICES . '/SampleService.php',));

		$injector->load($config);
		$this->assertTrue($injector->hasService('SampleService') == 'SampleService');

		$myObject = $injector->get('OtherTestObject');
		$this->assertEquals(get_class($myObject->s()), 'SampleService');

		// and again because it goes down a different code path when setting things
		// based on the inject map
		$myObject = $injector->get('OtherTestObject');
		$this->assertEquals(get_class($myObject->s()), 'SampleService');
	}

	public function testCircularReference() {
		$services = array('CircularOne', 'CircularTwo');
		$injector = new Injector($services);
		$injector->setAutoScanProperties(true);

		$obj = $injector->get('NeedsBothCirculars');

		$this->assertTrue($obj->circularOne instanceof CircularOne);
		$this->assertTrue($obj->circularTwo instanceof CircularTwo);
	}

	public function testPrototypeObjects() {
		$services = array('CircularOne', 'CircularTwo', array('class' => 'NeedsBothCirculars', 'type' => 'prototype'));
		$injector = new Injector($services);
		$injector->setAutoScanProperties(true);
		$obj1 = $injector->get('NeedsBothCirculars');
		$obj2 = $injector->get('NeedsBothCirculars');

		// if this was the same object, then $obj1->var would now be two
		$obj1->var = 'one';
		$obj2->var = 'two';

		$this->assertTrue($obj1->circularOne instanceof CircularOne);
		$this->assertTrue($obj1->circularTwo instanceof CircularTwo);

		$this->assertEquals($obj1->circularOne, $obj2->circularOne);
		$this->assertNotEquals($obj1, $obj2);
	}

	public function testSimpleInstantiation() {
		$services = array('CircularOne', 'CircularTwo');
		$injector = new Injector($services);

		// similar to the above, but explicitly instantiating this object here
		$obj1 = $injector->create('NeedsBothCirculars');
		$obj2 = $injector->create('NeedsBothCirculars');

		// if this was the same object, then $obj1->var would now be two
		$obj1->var = 'one';
		$obj2->var = 'two';

		$this->assertEquals($obj1->circularOne, $obj2->circularOne);
		$this->assertNotEquals($obj1, $obj2);
	}

	public function testCreateWithConstructor() {
		$injector = new Injector();
		$obj = $injector->create('CircularTwo', 'param');
		$this->assertEquals($obj->otherVar, 'param');
	}

	public function testSimpleSingleton() {
		$injector = new Injector();

		$one = $injector->create('CircularOne');
		$two = $injector->create('CircularOne');

		$this->assertFalse($one === $two);

		$one = $injector->get('CircularTwo');
		$two = $injector->get('CircularTwo');

		$this->assertTrue($one === $two);
	}

	public function testOverridePriority() {
		$injector = new Injector();
		$injector->setAutoScanProperties(true);
		$config = array(
			array(
				'src' => TEST_SERVICES . '/SampleService.php',
				'priority' => 10,
			)
		);

		// load
		$injector->load($config);

		// inject
		$myObject = new TestObject();
		$injector->inject($myObject);

		$this->assertEquals(get_class($myObject->sampleService), 'SampleService');

		$config = array(
			array(
				'src' => TEST_SERVICES . '/AnotherService.php',
				'id' => 'SampleService',
				'priority' => 1,
			)
		);
		// load
		$injector->load($config);

		$injector->inject($myObject);
		$this->assertEquals('SampleService', get_class($myObject->sampleService));
	}

	/**
	 * Specific test method to illustrate various ways of setting a requirements backend
	 */
	public function testRequirementsSettingOptions() {
		$injector = new Injector();
		$config = array(
			'OriginalRequirementsBackend',
			'NewRequirementsBackend',
			'DummyRequirements' => array(
				'constructor' => array(
					'%$OriginalRequirementsBackend'
				)
			)
		);

		$injector->load($config);

		$requirements = $injector->get('DummyRequirements');
		$this->assertEquals('OriginalRequirementsBackend', get_class($requirements->backend));

		// just overriding the definition here
		$injector->load(array(
			'DummyRequirements' => array(
				'constructor' => array(
					'%$NewRequirementsBackend'
				)
			)
		));

		// requirements should have been reinstantiated with the new bean setting
		$requirements = $injector->get('DummyRequirements');
		$this->assertEquals('NewRequirementsBackend', get_class($requirements->backend));
	}

	/**
	 * disabled for now
	 */
	public function testStaticInjections() {
		$injector = new Injector();
		$config = array(
			'NewRequirementsBackend',
		);

		$injector->load($config);

		$si = $injector->get('TestStaticInjections');
		$this->assertEquals('NewRequirementsBackend', get_class($si->backend));
	}

	public function testCustomObjectCreator() {
		$injector = new Injector();
		$injector->setObjectCreator(new SSObjectCreator($injector));
		$config = array(
			'OriginalRequirementsBackend',
			'DummyRequirements' => array(
				'class' => 'DummyRequirements(\'%$OriginalRequirementsBackend\')'
			)
		);
		$injector->load($config);

		$requirements = $injector->get('DummyRequirements');
		$this->assertEquals('OriginalRequirementsBackend', get_class($requirements->backend));
	}

	public function testInheritedConfig() {
		$injector = new Injector(array('locator' => 'SilverStripeServiceConfigurationLocator'));
		Config::inst()->update('Injector', 'MyParentClass', array('properties' => array('one' => 'the one')));
		$obj = $injector->get('MyParentClass');
		$this->assertEquals($obj->one, 'the one');

		$obj = $injector->get('MyChildClass');
		$this->assertEquals($obj->one, 'the one');
	}

	public function testSameNamedSingeltonPrototype() {
		$injector = new Injector();

		// get a singleton object
		$object = $injector->get('NeedsBothCirculars');
		$object->var = 'One';

		$again = $injector->get('NeedsBothCirculars');
		$this->assertEquals($again->var, 'One');

		// create a NEW instance object
		$new = $injector->create('NeedsBothCirculars');
		$this->assertNull($new->var);

		// this will trigger a problem below
		$new->var = 'Two';

		$again = $injector->get('NeedsBothCirculars');
		$this->assertEquals($again->var, 'One');
	}

	public function testConvertServicePropertyOnCreate() {
		// make sure convert service property is not called on direct calls to create, only on configured
		// declarations to avoid un-needed function calls
		$injector = new Injector();
		$item = $injector->create('ConstructableObject', '%$TestObject');
		$this->assertEquals('%$TestObject', $item->property);

		// do it again but have test object configured as a constructor dependency
		$injector = new Injector();
		$config = array(
			'ConstructableObject' => array(
				'constructor' => array(
					'%$TestObject'
				)
			)
		);

		$injector->load($config);
		$item = $injector->get('ConstructableObject');
		$this->assertTrue($item->property instanceof TestObject);

		// and with a configured object defining TestObject to be something else!
		$injector = new Injector(array('locator' => 'InjectorTestConfigLocator'));
		$config = array(
			'ConstructableObject' => array(
				'constructor' => array(
					'%$TestObject'
				)
			),
		);

		$injector->load($config);
		$item = $injector->get('ConstructableObject');
		$this->assertTrue($item->property instanceof ConstructableObject);

		$this->assertInstanceOf('OtherTestObject', $item->property->property);
	}

	public function testNamedServices() {
		$injector = new Injector();
		$service  = new stdClass();

		$injector->registerNamedService('NamedService', $service);
		$this->assertEquals($service, $injector->get('NamedService'));
	}

	public function testCreateConfiggedObjectWithCustomConstructorArgs() {
		// need to make sure that even if the config defines some constructor params,
		// that we take our passed in constructor args instead
		$injector = new Injector(array('locator' => 'InjectorTestConfigLocator'));

		$item = $injector->create('ConfigConstructor', 'othervalue');
		$this->assertEquals($item->property, 'othervalue');
	}

	/**
	 * Tests creating a service with a custom factory.
	 */
	public function testCustomFactory() {
		$injector = new Injector(array(
			'service' => array('factory' => 'factory', 'constructor' => array(1, 2, 3))
		));

		$factory = $this->getMock('SilverStripe\\Framework\\Injector\\Factory');
		$factory
			->expects($this->once())
			->method('create')
			->with($this->equalTo('service'), $this->equalTo(array(1, 2, 3)))
			->will($this->returnCallback(function($args) {
				return new TestObject();
			}));

		$injector->registerService($factory, 'factory');

		$this->assertInstanceOf('TestObject', $injector->get('service'));
	}

	/**
	 * Test nesting of injector
	 */
	public function testNest() {

		// Outer nest to avoid interference with other
		Injector::nest();
		$this->nestingLevel++;

		// Test services
		$config = array(
			'NewRequirementsBackend',
		);
		Injector::inst()->load($config);
		$si = Injector::inst()->get('TestStaticInjections');
		$this->assertInstanceOf('TestStaticInjections', $si);
		$this->assertInstanceOf('NewRequirementsBackend', $si->backend);
		$this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
		$this->assertInstanceOf('MyChildClass', Injector::inst()->get('MyChildClass'));

		// Test that nested injector values can be overridden
		Injector::nest();
		$this->nestingLevel++;
		Injector::inst()->unregisterAllObjects();
		$newsi = Injector::inst()->get('TestStaticInjections');
		$newsi->backend = new OriginalRequirementsBackend();
		Injector::inst()->registerService($newsi, 'TestStaticInjections');
		Injector::inst()->registerService(new MyChildClass(), 'MyParentClass');

		// Check that these overridden values are retrievable
		$si = Injector::inst()->get('TestStaticInjections');
		$this->assertInstanceOf('TestStaticInjections', $si);
		$this->assertInstanceOf('OriginalRequirementsBackend', $si->backend);
		$this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
		$this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyChildClass'));

		// Test that unnesting restores expected behaviour
		Injector::unnest();
		$this->nestingLevel--;
		$si = Injector::inst()->get('TestStaticInjections');
		$this->assertInstanceOf('TestStaticInjections', $si);
		$this->assertInstanceOf('NewRequirementsBackend', $si->backend);
		$this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
		$this->assertInstanceOf('MyChildClass', Injector::inst()->get('MyChildClass'));

		// Test reset of cache
		Injector::inst()->unregisterAllObjects();
		$si = Injector::inst()->get('TestStaticInjections');
		$this->assertInstanceOf('TestStaticInjections', $si);
		$this->assertInstanceOf('NewRequirementsBackend', $si->backend);
		$this->assertInstanceOf('MyParentClass', Injector::inst()->get('MyParentClass'));
		$this->assertInstanceOf('MyChildClass', Injector::inst()->get('MyChildClass'));

		// Return to nestingLevel 0
		Injector::unnest();
		$this->nestingLevel--;
	}

}

class InjectorTestConfigLocator extends SilverStripeServiceConfigurationLocator implements TestOnly {
	public function locateConfigFor($name) {
		if ($name == 'TestObject') {
			return array('class' => 'ConstructableObject', 'constructor' => array('%$OtherTestObject'));
		}

		if ($name == 'ConfigConstructor') {
			return array('class' => 'ConstructableObject', 'constructor' => array('value'));
		}

		return parent::locateConfigFor($name);
	}
}

class ConstructableObject implements TestOnly {
	public $property;

	public function __construct($prop) {
		$this->property = $prop;
	}
}

class TestObject implements TestOnly {

	public $sampleService;

	public function setSomething($v) {
		$this->sampleService = $v;
	}

}

class OtherTestObject implements TestOnly {

	private $sampleService;

	public function setSampleService($s) {
		$this->sampleService = $s;
	}

	public function s() {
		return $this->sampleService;
	}

}

class CircularOne implements TestOnly {

	public $circularTwo;

}

class CircularTwo implements TestOnly {

	public $circularOne;

	public $otherVar;

	public function __construct($value = null) {
		$this->otherVar = $value;
	}
}

class NeedsBothCirculars implements TestOnly{

	public $circularOne;
	public $circularTwo;
	public $var;

}

class MyParentClass implements TestOnly {
	public $one;
}

class MyChildClass extends MyParentClass implements TestOnly {

}

class DummyRequirements implements TestOnly {

	public $backend;

	public function __construct($backend) {
		$this->backend = $backend;
	}

	public function setBackend($backend) {
		$this->backend = $backend;
	}

}

class OriginalRequirementsBackend implements TestOnly {

}

class NewRequirementsBackend implements TestOnly {

}

class TestStaticInjections implements TestOnly {

	public $backend;
	/** @config */
	private static $dependencies = array(
		'backend' => '%$NewRequirementsBackend'
	);

}

/**
 * An example object creator that uses the SilverStripe class(arguments) mechanism for
 * creating new objects
 *
 * @see https://github.com/silverstripe/sapphire
 */
class SSObjectCreator extends InjectionCreator {
	private $injector;

	public function __construct($injector) {
		$this->injector = $injector;
	}

	public function create($class, array $params = array()) {
		if (strpos($class, '(') === false) {
			return parent::create($class, $params);
		} else {
			list($class, $params) = Object::parse_class_spec($class);
			$params = $this->injector->convertServiceProperty($params);
			return parent::create($class, $params);
		}
	}
}


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
             xmlns:m="urn:import:gwt.material.design.client.ui"
             xmlns:demo="urn:import:gwt.material.design.demo.client.ui">

  <m:MaterialRow>
    <m:MaterialRow addStyleNames="code">
      <m:MaterialTitle title="Check Box" description="Checkboxes"/>
      <m:MaterialRow>
        <m:MaterialColumn grid="l2">
          <m:MaterialCheckBox text="Blue" value="true" />
          <m:MaterialCheckBox text="Red" />
          <m:MaterialCheckBox text="Cyan" value="true" type="FILLED"/>
          <m:MaterialCheckBox text="Green" value="true" enabled="false"/>
          <m:MaterialCheckBox text="Brown" enabled="false"/>
          <m:MaterialCheckBox ui:field="cbBox" text="CheckBox 1: true" value="true" type="FILLED"/>
        </m:MaterialColumn>
        <m:MaterialColumn grid="l2">
          <m:MaterialCheckBox ui:field="cbBoxAll" text="Check all" type="FILLED"/>
          <m:MaterialCheckBox ui:field="cbBlue" text="Blue" type="FILLED" />
          <m:MaterialCheckBox ui:field="cbRed" text="Red" type="FILLED"/>
          <m:MaterialCheckBox ui:field="cbCyan" text="Cyan" type="FILLED"/>
          <m:MaterialCheckBox ui:field="cbGreen" text="Green" type="FILLED"/>
          <m:MaterialCheckBox ui:field="cbBrown" text="Brown" type="FILLED"/>
        </m:MaterialColumn>
      </m:MaterialRow>

      <demo:PrettyPre addStyleNames="lang-xml">
         <m:MaterialCheckBox text="Blue" value="true" />

        <m:MaterialCheckBox text="Red" />

        <m:MaterialCheckBox text="Cyan" value="true" type="FILLED"/>

        <m:MaterialCheckBox text="Green" value="true" enabled="false"/>

        <m:MaterialCheckBox text="Brown" enabled="false"/>

        <m:MaterialCheckBox ui:field="cbBox" text="CheckBox 1: true" value="true" type="FILLED"/>

      </demo:PrettyPre>

      <demo:PrettyPre addStyleNames="lang-xml">
         <m:MaterialCheckBox ui:field="cbBoxAll" text="Check all" type="FILLED"/>

        <m:MaterialCheckBox ui:field="cbBlue" text="Blue" type="FILLED" />

        <m:MaterialCheckBox ui:field="cbRed" text="Red" type="FILLED"/>

        <m:MaterialCheckBox ui:field="cbCyan" text="Cyan" type="FILLED"/>

        <m:MaterialCheckBox ui:field="cbGreen" text="Green" type="FILLED"/>

        <m:MaterialCheckBox ui:field="cbBrown" text="Brown" type="FILLED"/>

      </demo:PrettyPre>
    </m:MaterialRow>

    <m:MaterialRow addStyleNames="code">
      <m:MaterialBadge text="FEATURE UPDATE" textColor="AMBER" shadow="1" layoutPosition="RELATIVE" float="RIGHT" backgroundColor="AMBER_LIGHTEN_5" />
      <m:MaterialTitle title="CheckBox : setValue(value, fireEvents)"/>
      <m:MaterialCheckBox ui:field="cbValue" text="CheckBox"/>

      <m:MaterialRow>
        <m:MaterialButton text="Set Value" ui:field="btnCbValue" marginRight="20" />
        <m:MaterialButton text="Set Value with Event" ui:field="btnCbValueEvent" />
      </m:MaterialRow>
      <demo:PrettyPre addStyleNames="lang-java">
         // Set Value with firing the value change event

        checkBox.setValue(true, true);

        // Set Value without firing the value change event

        checkBox.setValue(false);

        checkBox.setValue(false, false);
      </demo:PrettyPre>
    </m:MaterialRow>
  </m:MaterialRow>
</ui:UiBinder>


text:
module.exports = function(config) {
	config.set({
		browsers: ['PhantomJS'],
		frameworks: ['jasmine']
	});
};


text:
from chardet.universaldetector import UniversalDetector
from codecs import getreader
import csv
from xlrd import (
    error_text_from_code, xldate_as_tuple, XL_CELL_DATE, XL_CELL_ERROR,
)
from worksheet import Worksheet

class DirigibleImportError(Exception):
    pass

def worksheet_from_csv(
    worksheet, csv_file, start_column, start_row, excel_encoding
):

    def autodetect_encoding(csv_file):
        detector = UniversalDetector()
        for line in csv_file.readlines():
            detector.feed(line)
            if detector.done: break
        detector.close()
        csv_file.seek(0)
        encoding = detector.result['encoding']

        if not encoding:
            raise DirigibleImportError('could not recognise encoding')

        return encoding

    def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
        # csv.py doesn't do Unicode; encode temporarily as UTF-8:
        csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                                dialect=dialect, **kwargs)
        for row in csv_reader:
            # decode UTF-8 back to Unicode, cell by cell:
            yield [unicode(cell, 'utf-8') for cell in row]

    def utf_8_encoder(unicode_csv_data):
        for line in unicode_csv_data:
            yield line.encode('utf-8')

    if excel_encoding:
        encoding = 'windows-1252'
    else:
        encoding = autodetect_encoding(csv_file)
    unicode_translated_csv_file = getreader(encoding)(csv_file)

    row = start_row
    try:
        for csv_row in unicode_csv_reader(unicode_translated_csv_file):
            column = start_column
            for csv_cell in csv_row:
                worksheet[column, row].formula = unicode(csv_cell)
                column += 1
            row += 1
    except Exception, e:
        raise DirigibleImportError(unicode(e))

    return worksheet

def worksheet_from_excel(excel_sheet):
    worksheet = Worksheet()
    for col in range(excel_sheet.ncols):
        for row in range(excel_sheet.nrows):
            cell = excel_sheet.cell(row, col)
            if cell.ctype == XL_CELL_ERROR:
                formula = '=%s' % (error_text_from_code[cell.value], )
            elif cell.ctype == XL_CELL_DATE:
                formula = '=DateTime(%s, %s, %s, %s, %s, %s)' % xldate_as_tuple(
                    cell.value, excel_sheet.book.datemode)
            else:
                formula = unicode(excel_sheet.cell(row, col).value)
            worksheet[col + 1, row + 1].formula = formula
    return worksheet


text:
package org.gradoop.flink.model.impl.operators.matching.single.cypher.operators.expand;

import com.google.common.collect.Lists;
import org.apache.flink.api.java.DataSet;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.utils.ExpandDirection;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.operators.PhysicalOperatorTest;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.gradoop.flink.model.impl.operators.matching.single.cypher.common.pojos.EmbeddingTestUtils.*;
import static org.junit.Assert.assertEquals;

public abstract class ExpandEmbeddingsTest extends PhysicalOperatorTest {
  //define some vertices
  private final GradoopId a = GradoopId.get();
  private final GradoopId b = GradoopId.get();
  private final GradoopId c = GradoopId.get();
  private final GradoopId d = GradoopId.get();
  private final GradoopId m = GradoopId.get();
  private final GradoopId n = GradoopId.get();

  //define some edges
  private final GradoopId e0 = GradoopId.get();
  private final GradoopId e1 = GradoopId.get();
  private final GradoopId e2 = GradoopId.get();
  private final GradoopId e3 = GradoopId.get();

  @Test
  public void testOutputFormat() throws Exception {
    DataSet<Embedding> input = getExecutionEnvironment().fromElements(
      createEmbedding(m, e0, n)
    );

    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(n, e1, a),
      createEmbedding(a, e2, b),
      createEmbedding(b, e3, c)
    );

    DataSet<Embedding> result = getOperator(
      input, candidateEdges, 2, 1, 3,
      ExpandDirection.OUT, new ArrayList<>(), new ArrayList<>(), -1
    ).evaluate();

    assertEquals(3, result.count());

    assertEveryEmbedding(result, embedding -> {
      assertEquals(5, embedding.size());
      embedding.getIdList(3);
    });

    assertEmbeddingExists(
      result,
      embedding -> (embedding.getIdList(3)).size() == 1
    );

    assertEmbeddingExists(
      result,
      embedding -> (embedding.getIdList(3)).size() == 3
    );

    assertEmbeddingExists(
      result,
      embedding -> (embedding.getIdList(3)).size() == 5
    );
  }

  @Test
  public void testResultForOutExpansion() throws Exception {
    DataSet<Embedding> input = createEmbeddings(getExecutionEnvironment(), 1, a);

    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(a, e1, b),
      createEmbedding(b, e2, c),
      createEmbedding(c, e3, d)
    );

    DataSet<Embedding> result = getOperator(
      input, candidateEdges, 0, 2, 4,
      ExpandDirection.OUT, new ArrayList<>(), new ArrayList<>(), -1
    ).evaluate();

    assertEquals(2, result.count());
    assertEmbeddingExists(result, a, e1, b, e2, c);
    assertEmbeddingExists(result, a, e1, b, e2, c, e3, d);
  }

  @Test
  public void testResultForInExpansion() throws Exception {
    DataSet<Embedding> input = createEmbeddings(getExecutionEnvironment(), 1, a);

    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(b, e1, a),
      createEmbedding(c, e2, b),
      createEmbedding(d, e3, c)
    );

    DataSet<Embedding> result = getOperator(
      input, candidateEdges, 0, 2, 4,
      ExpandDirection.IN, new ArrayList<>(), new ArrayList<>(), -1
    ).evaluate();

    assertEquals(2, result.count());
    assertEmbeddingExists(result, a, e1, b, e2, c);
    assertEmbeddingExists(result, a, e1, b, e2, c, e3, d);
  }

  @Test
  public void testUpperBoundRequirement() throws Exception {
    DataSet<Embedding> input = createEmbeddings(getExecutionEnvironment(), 1, a);

    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(a, e1, b),
      createEmbedding(b, e2, c),
      createEmbedding(c, e3, d)
    );

    DataSet<Embedding> result = getOperator(
      input, candidateEdges, 0, 2, 2,
      ExpandDirection.OUT, new ArrayList<>(), new ArrayList<>(), -1
    ).evaluate();

    assertEveryEmbedding(result, (embedding) -> {
      assertEquals(3, embedding.getIdList(1).size());
    });
  }

  @Test
  public void testLowerBoundRequirement() throws Exception {
    DataSet<Embedding> input = createEmbeddings(getExecutionEnvironment(), 1, a);

    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(a, e1, b),
      createEmbedding(b, e2, c)
    );

    DataSet<Embedding> result = getOperator(
      input, candidateEdges, 0, 2, 2,
      ExpandDirection.OUT, new ArrayList<>(), new ArrayList<>(), -1
    ).evaluate();

    assertEveryEmbedding(result, (embedding) -> assertEquals(3, embedding.getIdList(1).size()));
  }

  @Test
  public void testLowerBound0() throws Exception {
    DataSet<Embedding> input = createEmbeddings(getExecutionEnvironment(), 1, a);

    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(a, e1, b)
    );

    DataSet<Embedding> result = getOperator(
      input, candidateEdges, 0, 0, 3,
      ExpandDirection.OUT, new ArrayList<>(), new ArrayList<>(), -1
    ).evaluate();

    assertEquals(2, result.count());

    assertEmbeddingExists(result, (embedding) ->
      embedding.getId(0).equals(embedding.getId(2)) &&
      embedding.getIdList(1).size() == 0
    );
  }

  @Test
  public void testFilterDistinctVertices() throws Exception {
    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(a, e1, b),
      createEmbedding(b, e2, a)
    );

    DataSet<Embedding> input = getExecutionEnvironment().fromElements(
      createEmbedding(a, e0, b)
    );

    ExpandEmbeddings op = getOperator(
      input, candidateEdges,
      2, 2, 3,
      ExpandDirection.OUT,
      Lists.newArrayList(0, 2),
      new ArrayList<>(), -1
    );

    DataSet<Embedding> result = op.evaluate();

    assertEquals(0, result.count());
  }

  @Test
  public void testFilterDistinctEdges() throws Exception {
    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(a, e0, b),
      createEmbedding(b, e1, a)
    );

    DataSet<Embedding> input = getExecutionEnvironment().fromElements(
      createEmbedding(a, e0, b)
    );

    ExpandEmbeddings op = getOperator(
      input, candidateEdges,
      2, 1, 2,
      ExpandDirection.OUT,
      new ArrayList<>(),
      Lists.newArrayList(1, 2), -1
    );

    DataSet<Embedding> result = op.evaluate();

    assertEquals(1, result.count());
    assertEmbeddingExists(result, a, e0, b, e1, a);
  }

  @Test
  public void testCircleCondition() throws Exception {
    DataSet<Embedding> candidateEdges = getExecutionEnvironment().fromElements(
      createEmbedding(b, e1, c),
      createEmbedding(b, e2, a)
    );

    DataSet<Embedding> input = getExecutionEnvironment().fromElements(
      createEmbedding(a, e0, b)
    );

    ExpandEmbeddings op = getOperator(
      input, candidateEdges,
      2, 1, 2,
      ExpandDirection.OUT,
      new ArrayList<>(),
      new ArrayList<>(),
      0
    );

    DataSet<Embedding> result = op.evaluate();

    assertEquals(1, result.count());
    assertEmbeddingExists(result, a, e0, b, e2, a);
  }

  protected abstract ExpandEmbeddings getOperator(
    DataSet<Embedding> input, DataSet<Embedding> candidateEdges,
    int expandColumn, int lowerBound, int upperBound, ExpandDirection direction,
    List<Integer> distinctVertexColumns, List<Integer> distinctEdgeColumns, int closingColumn);

}


text:
package com.github.groupsky.nexus4callfixer;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class CallReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, CallMonitorService.class);
        startWakefulService(context, service);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Transformation</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Fusion 2.1">
<link rel="up" href="../algorithm.html" title="Algorithm">
<link rel="prev" href="query/metafunctions/count_if.html" title="count_if">
<link rel="next" href="transformation/functions.html" title="Functions">

Home
Libraries
People
FAQ
More

Transformation

Functions

Metafunctions

        The transformation algorithms create new sequences out of existing sequences
        by performing some sort of transformation. In reality the new sequences are
        views onto the data in the original sequences.

Note

          As the transformation algorithms return views onto their input arguments,
          it is important that the lifetime of the input arguments is greater than
          the period during which you wish to use the results.

        Header

#include <boost/fusion/algorithm/transformation.hpp>
#include <boost/fusion/include/transformation.hpp>

Copyright © 2001-2006, 2011, 2012 Joel de Guzman,
      Dan Marsden, Tobias Schwinger

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
layout: post
title: Vimeo Privacy by Website Domain Bypass
date: 2016-05-10 12:00:00
categories: articles
en: true
comments: true
description: Report how to bypass and access a video secret by website domain from Vimeo
pt: /articles/bypass-privacidade-do-vimeo/
description_pt: Relato de como bypassar o acesso a vídeo privativo por domínio do site no Vimeo
keywords: bypass, hacking, vimeo, video, movie, privacy, privado
authors:
    - gjuniioor
    - userx
---

> **OBS:** Você pode ler esse post em português em [{{ site.baseurl }}{{ page.pt }}]({{ page.pt }})
>
> **NOTE:** You can read this post in portuguese in [{{ site.baseurl }}{{ page.pt }}]({{ page.pt }})

# Summary
{:.no_toc}

* toc
{:toc}

# Intrudoction

On [#ViradaHacker][virada-hacker] on the first day of April was [descrybed a way][relato-do-bypass] [^0] to watch a private vimeo video. That was a fast and resumed approach about that matter, however, through the page on [facebook do LampiãoSec][facebook-do-lampiao], e-mail and telegram, we have received some requests and incentives to make a more detailed post, to show the theory behind the scenes of the whole process. So, as response to this people and our own will to help the community how ever we can, it took time but here it goes.

## Motivation
{:id="motivation"}

To show and to help you understand how the solution was thought is important, both, for those who are stating on this matter, once that this way they start to see how the process was thought and stuff like that, and for the community itself, once that it's one how-to less creating *facebook hackers* around.

## The Issue

What would happen is the following: We wanted a friend of ours to see a video hosted on Vimeo but that video was configured to be shown only through a particula site, and this friend hasn't access to it. So, was thought: if vimeo let only one site to show the video content, let's then pretend that my machine is this site. After some tests, everything worked very well and you can see this report, originally, on #ViradaHacker [^0].

# Theory

Basically, when we talk about web, we talk about HTTP (Hipertext Transfer protocol). Therefore, for better understanding the procedure, is good to have some knowledge, even basic, of this protocol behavior. If you need an reinforcement, we recommend the free e-book HTTP Succinctly [^1], once and explanation about HTTP is far beyond the scope of this post.

But let's remember somethings to keep the focus: remember that HTTP stands for a text protocol, then every management is easly done. Another thing that must be remembered is HTTP headers and its parameters. The most important of them to our scope now is the field **Referer**[^2]. This field informs to server from where the user got the reference (suspect name isn't?) to access certain resource. In other words, if you click on some link, the server in which the site refered by the link will know from where you came. Ergo, if you access any link you saw here, but typing the address, the destiny server won't be able to know this info.

And it's through this field (**referer**) that vimeo make its verification. Take a look at this sample:
E é justamente por esse campo que o Vimeo faz a verificação. Veja exemplo:

![Cabeçalho HTTP de requisição ao Vimeo]({{ site.baseurl }}/assets/img/posts/vimeo/01.png){:class="imghalf"}

And that's whole theory we need to know and understand this hack. Let's practice!

# Practice
{:id="practice"}

Knowing that it's by this way that Vimeo make its verification if the domain on the Referer [^2] field is the same that is informed by user on video settings, we can then manipulate the request, informing on this field what Vimeo wants to know. All we need is to edit the HTTP request to player.vimeo.com. We can do this by a lot of ways: Web proxy, criating your own request or generating a new one as we need. Let's show some ways to do that but do not limit yourself to this ways. And if there's any other way to do that, please, share it with us, be our guest to comment or contact us to add your contribution here.

## Changing DNS

The first method to be shown will be the one originally tested, and already shown on the post [^0], on [#ViradaHacker][virada-hacker]. On this method, we create a local server, to assign the domain we want and done.

### First Step: Creating the server

Firstly, we need to create our own server. We can do this by several means, but the choosen one here was with python module, once that it comes already installed by default on the most linux distributions. So, just run the command below, modifying some fields:

~~~
$ sudo python -m http.server --bind your_ip_address 80
~~~

* Change the field your_ip_address, as you may guess, the ip address of your computer. You can discover what it is by using the command ip addr ;
* `sudo` was necessary because  we're using the low port 80 to easy the access.

### Second Step: Creating a video page

On the same directory that you runned the server, create an index.html file (or, ofcourse, any other html file :] ) with an widget video. To easy your work, you can copy and paste it if you wish:

~~~
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vimeo Privacy Bypass :: LampiãoSec</title>
</head>
<body>
	<iframe style="width: 100%; height: 500px;" src="https://player.vimeo.com/video/109727604" frameborder="0" allowfullscreen></iframe>
</body>
</html>
~~~

> **NOTE:** The above video belongs to [Cybrary]. We're using it as example once that it's a nice project and with free access, therefore, no one gets hurt. =-D

If you make the request now, you'll notice that you can't see the video, it's blocked. And if you debug the communication header, you'll see that a 403 was returned, just because of the **referer** field that is diferent from the allowed.

![Request that doesn't show the video]({{ site.baseurl }}/assets/img/posts/vimeo/02.png){:class="imghalf"}

### Third: Informing the necessary referer

Now we need to show to Vimeo that we're Cybrary (faking it). How can we do this? With this method we can change the Cybrary response address, in the way that when we access cybrary.ti on the browser, it returns the page we want.

To do this, we change the DNS answer, informing that now our ip answers as cybrary.it. We could do this by building our own DNS server doing a Cache poisioning, but to easy the process, let's just modify our /etc/hosts. For this, insert the following field to the file:

~~~
your_ip	 allowed_domain	allowed_domain
~~~

> Of course, modifying the it properly to fit your configuration, like editing your_ip field and so on.

Done! Now if we request again we can se that we'll get a valid response and taking a look at the **referer**, we can notice that it's now changed:

![Request shown the video]({{ site.baseurl }}/assets/img/posts/vimeo/03.png){:class="imghalf"}

# Another methods
{:id="another-methods"}

Exploining the way we get to the results, let's do this by other ways, with other tools so we are not stuck in a single idea. The major goal here is that you learn the technique than simply execute it, alright?!

## Modifying the HTTP request through BurpSuite

Let's show you how to do this by means of editing HTTP request header. Firstly, we need to open Burp Suite and configure your browser. Once you have done it, let's make a request to player.vimeo.com informing the video ID. So, the address will be:

~~~
https://player.vimeo.com/video/109727604
~~~

Ergo on the first request captured by our Burp Suite proxy, let's make our modification:

~~~
Referer: https://cybrary.it
~~~

Do not forget that we put http://cybrary.it because that's the domain that the video is configure to work on, you need to make it fit to your case.

![Modified header from HTTP request through BurpSuite]({{ site.baseurl }}/assets/img/posts/vimeo/04.png){:class="imghalf"}

## Make the request through cURL & wget

In all moments we need to directly interact with several programs to make this modification, basically, for each moment we want to see a video. Once that the video page is already loaded we can download it so we won't need to worry to make it all again anymore. With `curl` or `wget` this is a lot easier. Take a look:

* cURL

~~~
$ curl --referer https://cybrary.it -o curl.html https://player.vimeo.com/video/109727604
~~~

* wget

~~~
$ wget --referer https://cybrary.it -O wget.html https://player.vimeo.com/video/109727604
~~~

Note that what's different from on command to another  is the first parameter to the filename to be saved. Both will modify the `referer` the same way. That makes it easy if you want to make a script for something :)

## Building the request with ncat from the scratch

Now, let's practice what was seen by creating the request from the scratch with ncat instead of using some tool that automates it.

*- But why ncat instead of netcat?* - he asked.

*- Because we need SSL on this request* - we answered (rs')

It's easy:

~~~
$ ncat --ssl player.vimeo.com 443 | grep -i "doctype" > ncat.html
	GET /video/109727604 HTTP/1.1
	Referer: https://cybrary.it
	Host: player.vimeo.com
	User-Agent: LampiãoSec
	Connection: close
~~~

**OBS:** We have used TAB on some lines indicating that this lines will be writing inside ncat.

Based on everything explained, we believe that this request is understandable. But if you have some question, feel free to contact us.

# Conclusion

Let us be succints now: **Find out to where goes the rabbit role**.

# Referencies
{:id="referencies"}

[^0]: [Bypass report](https://lampiaosec.github.io/virada-hacker/2016/04/02/diario-de-bordo/#ver-vdeo-privado-do-vimeo-localmente)
[^1]: [HTTP Succinctly Review](https://gjuniioor.github.io/books/http-succinctly/)
[^2]: [Referer Field](https://tools.ietf.org/html/rfc2616#section-14.36)

[virada-hacker]: https://lampiaosec.github.io/virada-hacker/
[relato-do-bypass]: https://lampiaosec.github.io/virada-hacker/2016/04/02/diario-de-bordo/#ver-vdeo-privado-do-vimeo-localmente
[facebook-do-lampiao]: https://facebook.com/lampiaosec
[cybrary]: https://cybrary.it


text:
package io.crate.metadata.shard;

import io.crate.common.collections.MapBuilder;
import io.crate.exceptions.ResourceUnknownException;
import io.crate.exceptions.UnhandledServerException;
import io.crate.execution.engine.collect.NestableCollectExpression;
import io.crate.expression.NestableInput;
import io.crate.expression.reference.ReferenceResolver;
import io.crate.expression.reference.StaticTableReferenceResolver;
import io.crate.expression.reference.sys.shard.ShardRowContext;
import io.crate.metadata.ColumnIdent;
import io.crate.metadata.IndexParts;
import io.crate.metadata.MapBackedRefResolver;
import io.crate.metadata.PartitionName;
import io.crate.metadata.Reference;
import io.crate.metadata.RelationName;
import io.crate.metadata.Schemas;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.metadata.sys.SysShardsTableInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.index.Index;

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

import static io.crate.execution.engine.collect.NestableCollectExpression.constant;

public class ShardReferenceResolver implements ReferenceResolver<NestableInput<?>> {

    private static final Logger LOGGER = LogManager.getLogger(ShardReferenceResolver.class);
    private static final StaticTableReferenceResolver<ShardRowContext> SHARD_REFERENCE_RESOLVER_DELEGATE =
        new StaticTableReferenceResolver<>(SysShardsTableInfo.create().expressions());
    private static final ReferenceResolver<NestableInput<?>> EMPTY_RESOLVER =
        new MapBackedRefResolver(Collections.emptyMap());

    private static ReferenceResolver<NestableInput<?>> createPartitionColumnResolver(Index index, Schemas schemas) {
        PartitionName partitionName;
        try {
            partitionName = PartitionName.fromIndexOrTemplate(index.getName());
        } catch (IllegalArgumentException e) {
            throw new UnhandledServerException(String.format(Locale.ENGLISH,
                "Unable to load PARTITIONED BY columns from partition %s", index.getName()), e);
        }
        RelationName relationName = partitionName.relationName();
        MapBuilder<ColumnIdent, NestableInput> builder = MapBuilder.newMapBuilder();
        try {
            DocTableInfo info = schemas.getTableInfo(relationName);
            assert info.isPartitioned() : "table must be partitioned";
            int i = 0;
            int numPartitionedColumns = info.partitionedByColumns().size();

            List<String> partitionValue = partitionName.values();
            assert partitionValue.size() ==
                   numPartitionedColumns : "invalid number of partitioned columns";
            for (Reference partitionedInfo : info.partitionedByColumns()) {
                builder.put(
                    partitionedInfo.column(),
                    constant(partitionedInfo.valueType().implicitCast(partitionValue.get(i)))
                );
                i++;
            }
        } catch (ResourceUnknownException e) {
            LOGGER.error("Orphaned partition '{}' with missing table '{}' found", index, relationName.fqn());
        }
        return new MapBackedRefResolver(builder.immutableMap());
    }

    private final ShardRowContext shardRowContext;
    private final ReferenceResolver<NestableInput<?>> partitionColumnResolver;

    public ShardReferenceResolver(Schemas schemas, ShardRowContext shardRowContext) {
        this.shardRowContext = shardRowContext;
        IndexParts indexParts = shardRowContext.indexParts();
        if (indexParts.isPartitioned()) {
            partitionColumnResolver = createPartitionColumnResolver(
                shardRowContext.indexShard().shardId().getIndex(), schemas);
        } else {
            partitionColumnResolver = EMPTY_RESOLVER;
        }
    }

    @Override
    public NestableInput<?> getImplementation(Reference ref) {
        NestableInput<?> partitionColImpl = partitionColumnResolver.getImplementation(ref);
        if (partitionColImpl != null) {
            return partitionColImpl;
        }
        NestableCollectExpression<ShardRowContext, ?> impl = SHARD_REFERENCE_RESOLVER_DELEGATE.getImplementation(ref);
        impl.setNextRow(shardRowContext);
        return impl;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.li.coolweather"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/weather1"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.li.coolweather.activity.ChooseAreaActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.li.coolweather.activity.WeatherActivity" >
        </activity>

        <receiver android:name="com.li.coolweather.receiver.AutoUpdateReceiver" >
        </receiver>

        <service android:name="com.li.coolweather.service.AutoUpdateService" >
        </service>
    </application>

</manifest>