text:
import { EventEmitter, ElementRef, Renderer2, ViewContainerRef, Output, ContentChild, TemplateRef, Directive, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
let DeferredLoader = class DeferredLoader {
    constructor(el, renderer, viewContainer) {
        this.el = el;
        this.renderer = renderer;
        this.viewContainer = viewContainer;
        this.onLoad = new EventEmitter();
    }
    ngAfterViewInit() {
        if (this.shouldLoad()) {
            this.load();
        }
        if (!this.isLoaded()) {
            this.documentScrollListener = this.renderer.listen('window', 'scroll', () => {
                if (this.shouldLoad()) {
                    this.load();
                    this.documentScrollListener();
                    this.documentScrollListener = null;
                }
            });
        }
    }
    shouldLoad() {
        if (this.isLoaded()) {
            return false;
        }
        else {
            let rect = this.el.nativeElement.getBoundingClientRect();
            let docElement = document.documentElement;
            let winHeight = docElement.clientHeight;
            return (winHeight >= rect.top);
        }
    }
    load() {
        this.view = this.viewContainer.createEmbeddedView(this.template);
        this.onLoad.emit();
    }
    isLoaded() {
        return this.view != null;
    }
    ngOnDestroy() {
        this.view = null;
        if (this.documentScrollListener) {
            this.documentScrollListener();
        }
    }
};
DeferredLoader.ctorParameters = () => [
    { type: ElementRef },
    { type: Renderer2 },
    { type: ViewContainerRef }
];
__decorate([
    Output()
], DeferredLoader.prototype, "onLoad", void 0);
__decorate([
    ContentChild(TemplateRef, { static: true })
], DeferredLoader.prototype, "template", void 0);
DeferredLoader = __decorate([
    Directive({
        selector: '[pDefer]'
    })
], DeferredLoader);
let DeferModule = class DeferModule {
};
DeferModule = __decorate([
    NgModule({
        imports: [CommonModule],
        exports: [DeferredLoader],
        declarations: [DeferredLoader]
    })
], DeferModule);

/**
 * Generated bundle index. Do not edit.
 */

export { DeferModule, DeferredLoader };
//# sourceMappingURL=primeng-defer.js.map


text:
<!DOCTYPE html>

        <title>removeClass()</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

removeClass()

Heading 2

Heading 3

This is a paragraph.

This is another paragraph.

        <button>Remove class from elements</button>

redpajama_set_name: RedPajamaGithub


text:
package java.util;

/**
 * An ListIterator is used to sequence over a List of objects. ListIterator can
 * move backwards or forwards through the List.
 */
public interface ListIterator<E> extends Iterator<E> {

	/**
	 * Inserts the specified object into the list between next
	 * and previous. The object inserted will be the previous
	 * object.
	 *
	 * @param object
	 *            the object to insert
	 *
	 * @exception UnsupportedOperationException
	 *                when adding is not supported by the list being iterated
	 * @exception ClassCastException
	 *                when the class of the object is inappropriate for the list
	 * @exception IllegalArgumentException
	 *                when the object cannot be added to the list
	 */
	void add(E object);

	/**
	 * Answers if there are more elements to iterate.
	 *
	 * @return true if there are more elements, false otherwise
	 *
	 * @see #next
	 */
	public boolean hasNext();

	/**
	 * Answers if there are previous elements to iterate.
	 *
	 * @return true if there are previous elements, false otherwise
	 *
	 * @see #previous
	 */
	public boolean hasPrevious();

	/**
	 * Answers the next object in the iteration.
	 *
	 * @return the next object
	 *
	 * @exception NoSuchElementException
	 *                when there are no more elements
	 *
	 * @see #hasNext
	 */
	public E next();

	/**
	 * Answers the index of the next object in the iteration.
	 *
	 * @return the index of the next object
	 *
	 * @exception NoSuchElementException
	 *                when there are no more elements
	 *
	 * @see #next
	 */
	public int nextIndex();

	/**
	 * Answers the previous object in the iteration.
	 *
	 * @return the previous object
	 *
	 * @exception NoSuchElementException
	 *                when there are no previous elements
	 *
	 * @see #hasPrevious
	 */
	public E previous();

	/**
	 * Answers the index of the previous object in the iteration.
	 *
	 * @return the index of the previous object
	 *
	 * @exception NoSuchElementException
	 *                when there are no previous elements
	 *
	 * @see #previous
	 */
	public int previousIndex();

	/**
	 * Removes the last object returned by next or
	 * previous from the list.
	 *
	 * @exception UnsupportedOperationException
	 *                when removing is not supported by the list being iterated
	 * @exception IllegalStateException
	 *                when next or previous have
	 *                not been called, or remove or
	 *                add have already been called after the last
	 *                call to next or previous
	 */
	public void remove();

	/**
	 * Replaces the last object returned by next or
	 * previous with the specified object.
	 *
	 * @param object
	 *            the object to add
	 *
	 * @exception UnsupportedOperationException
	 *                when adding is not supported by the list being iterated
	 * @exception ClassCastException
	 *                when the class of the object is inappropriate for the list
	 * @exception IllegalArgumentException
	 *                when the object cannot be added to the list
	 * @exception IllegalStateException
	 *                when next or previous have
	 *                not been called, or remove or
	 *                add have already been called after the last
	 *                call to next or previous
	 */
	void set(E object);
}


text:
@interface STHelpers : NSObject

+(void)test;

@end


text:
<?php

/**
 * Class to carry and manage {@link ezcDocumentOdtFormattingProperties}.
 *
 * An instance of this class is used in an {@link ezcDocumentOdtStyle} to carry
 * various formatting properties of class {@link
 * ezcDocumentOdtFormattingProperties}.
 *
 * @package Document
 * @version //autogen//
 * @access private
 */
class ezcDocumentOdtFormattingPropertyCollection
{
    /**
     * Formatting properties.
     *
     * @var array(const=>ezcDocumentOdtFormattingProperties)
     */
    private $properties = array();

    /**
     * Sets the given $properties.
     *
     * If properties of the same type are already set, an exception is thrown.
     * If you don't care if properties are overwriten, use {@link
     * replaceProperties()}. You can check if properties of a certain type are
     * already set using {@link hasProperties()} and retrieve them using {@link
     * getProperties()}.
     *
     * @param ezcDocumentOdtFormattingProperties $properties
     *
     * @throws ezcDocumentOdtFormattingPropertiesAlreadyExistException
     */
    public function setProperties( ezcDocumentOdtFormattingProperties $properties )
    {
        if ( isset( $this->properties[$properties->type] ) )
        {
            throw new ezcDocumentOdtFormattingPropertiesExistException(
                $properties
            );
        }
        $this->replaceProperties( $properties );
    }

    /**
     * Sets the given $properties, even if properties of the same type are
     * already set.
     *
     * Similar to {@link setProperties()} but silently overwrites properties
     * of the same type, if they exist.
     *
     * @param ezcDocumentOdtFormattingProperties $properties
     */
    public function replaceProperties( ezcDocumentOdtFormattingProperties $properties )
    {
        $this->properties[$properties->type] = $properties;
    }

    /**
     * Returns if properties of $type are set.
     *
     * Returns true, if properties of $type are set in this collection,
     * otherwise false. $type must be one of the {@link
     * ezcDocumentOdtFormattingProperties} PROPERTIES_* constants.
     *
     * @param const $type
     * @return bool
     */
    public function hasProperties( $type )
    {
        return isset( $this->properties[$type] );
    }

    /**
     * Returns properties of the given $type.
     *
     * If properties of the given $type are set, the corresponding object is
     * returned. Otherwise null is returned. You can check if properties of a
     * given $type are set using {@link hasProperties()}. $type must be one
     * of the {@link ezcDocumentOdtFormattingProperties} FAMILY_
     * constants.
     *
     * @param const $type
     * @return ezcDocumentOdtFormattingProperties|null
     */
    public function getProperties( $type )
    {
        if ( $this->hasProperties( $type ) )
        {
            return $this->properties[$type];
        }
        return null;
    }
}

?>


text:
<?php

namespace Gregwar\Formidable\Fields;

/**
 * Hidden field
 *
 * @author Grégoire Passault <g.passault@gmail.com>
 */
class HiddenField extends Field
{
    /**
     * Field type
     */
    protected $type = 'hidden';
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Profit
{
    public static function get()
    {
        $profits=array();
        $profits['hand_cash']=Hand_cash::get();
        $profits['product_stock_price']=Product_stock_price::get();
        $profits['bank_cash']=Bank_cash::get();
        $profits['seller_buyer_cash']=Seller_buyer_cash::get();
        $profits['profit']=$profits['hand_cash']+$profits['product_stock_price']-$profits['bank_cash'];
        $profits['profit']=bcsub($profits['profit'],$profits['seller_buyer_cash']);
        return $profits;
    }
}


text:
package handler

import (
	"github.com/jabaraster/webtool"
	"../../model"
	"net/http"
)

func GetAllPropertiesHandler(w http.ResponseWriter, r *http.Request) {
    list := model.GetAllProperties()
    if len(list) == 0 {
        webtool.WriteEmptyArrayJsonResponse(w)
    } else {
        webtool.WriteJsonResponse(list, w)
    }
}


text:
@implementation SwipeCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self) {
        self.leftAreaEnabled = YES;
        self.leftAreaWidth = 100;

        self.rightAreaEnabled = YES;
        self.rightAreaWidth = 150;

        self.rightArea.backgroundColor = [UIColor colorWithRed:1.00f green:0.23f blue:0.19f alpha:1.00f];

        // Adding button
        UIButton *rightButton = [[UIButton alloc] initWithFrame:self.rightArea.bounds];
        // If you plan to use different height cells a resizing mask is recommended.
        rightButton.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [rightButton addTarget:self action:@selector(rightButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [rightButton setTitle:@"Action" forState:UIControlStateNormal];
        [self.rightArea addSubview:rightButton];
    }
    return self;
}

- (void)rightButtonAction {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Action" message:@"Right button was pressed" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
}

@end


text:
extern const AOGridValue AOGridValueWall;

@interface AOAStarResult : NSObject

@property (readonly) AOGridIndex cellCount;

- (AOGridCell)cellAtIndex:(AOGridIndex)index;

@end

@interface AOAStar : NSObject

+ (instancetype)aStarWithGrid:(AOGrid *)grid;

- (instancetype)initWithGrid:(AOGrid *)grid;

- (AOAStarResult *)runFromCell:(AOGridCell)fromCell toCell:(AOGridCell)toCell;

@end


text:
                {% include sns-links.html center=true %}

                    Copyright © {{ site.title }} {{ site.time | date: '%Y' }}

                    Powered by Hux Blog

{% if site.service-worker %}

{% endif %}

{% if page.plchart %}

{% endif %}

{% if page.title == 'Archive' %}

{% endif %}

{% if site.ga_track_id %}

{% endif %}


text:
import base64
import json

from finance import app
from tests.fixtures import setup_user, delete_user

class BaseViewTestCase():
    def get_headers(self, username, password):
        return {
            'Authorization': 'Basic ' + base64.b64encode(
                username + ":" + password
            )
        }

    def open_with_auth(self, url, method, username, password, data=None):
        return self.app.open(
            url,
            method=method,
            headers=self.get_headers(username, password),
            data=json.dumps(data),
            follow_redirects=True,
            content_type='application/json'
        )

    def login(self, username, password):
        data = {
            'username': username,
            'password': password
        }
        return self.app.post(
            "/login",
            data=json.dumps(data),
            follow_redirects=True,
            content_type='application/json'
        )

    def logout(self, auth_token=None):
        return self.app.open(
            "/logout",
            'GET',
            headers={
                'AuthToken': auth_token
            },
            follow_redirects=True
        )

class TestGeneralView(BaseViewTestCase):

    @classmethod
    def setup_class(self):
        self.user, self.username, self.password = setup_user()
        self.app = app.test_client()

    @classmethod
    def teardown_class(self):
        delete_user(self.user)

    def test_version(self):
        """Test version number"""
        rv = self.app.get("/")
        assert 200 == rv.status_code
        assert 'version' in json.loads(rv.data)

    def test_login(self):
        """Test logging in """
        rv = self.login(self.username, self.password)
        assert 200 == rv.status_code
        res = json.loads(rv.data)
        assert "Success" in res.get('message')
        assert 'auth_token' in res

        rv = self.app.open(
            "/accounts",
            'GET',
            headers={
                'AuthToken': res.get('auth_token')
            }
        )
        assert 200 == rv.status_code

        rv = self.app.open(
            "/accounts",
            'GET',
            headers={
                'AuthToken': 'random'
            }
        )
        assert 401 == rv.status_code

    def test_login_fail(self):
        """Test logging in with invalid credentials"""
        rv = self.login('boo', 'hoo')
        assert 400 == rv.status_code
        assert 'Invalid' in json.loads(rv.data).get('message')

    def test_login_invalid(self):
        """Test logging in with invalid form post"""
        rv = self.app.post(
            "/login",
            data=json.dumps({"username": "admin"}),
            follow_redirects=True,
            content_type='application/json'
        )
        assert 400 == rv.status_code
        assert {
            u'password': [u'This field is required.']
        } == json.loads(rv.data)

    def test_logout(self):
        """Test logging out"""
        rv = self.login(self.username, self.password)
        assert 200 == rv.status_code
        auth_token = json.loads(rv.data).get('auth_token')

        rv = self.logout(auth_token)
        assert 200 == rv.status_code
        assert 'Success' in json.loads(rv.data).get('message')

        rv = self.app.open(
            "/accounts",
            'GET',
            headers={
                'AuthToken': auth_token
            }
        )
        assert 401 == rv.status_code


text:
require_relative '../test_helper'

describe DeltacloudVM::Client::Methods::Blob do

  before do
    VCR.insert_cassette(__name__)
    @client = new_client
  end

  after do
    VCR.eject_cassette
  end

  it 'supports #blobs' do
    @client.must_respond_to :blobs
    @client.blobs('bucket1').must_be_kind_of Array
    @client.blobs('bucket1').each { |r| r.must_be_instance_of DeltacloudVM::Client::Blob }
  end

  it 'support #blob' do
    @client.must_respond_to :blob
    result = @client.blob('bucket1', 'blob1')
    result.must_be_instance_of DeltacloudVM::Client::Blob
    lambda { @client.blob('bucket1', 'foo') }.must_raise DeltacloudVM::Client::NotFound
  end

  it 'support #create_blob and #destroy_blob' do
    @client.must_respond_to :create_blob
    result = @client.create_blob('bucket1', 'fooblob123', 'content_of_blob')
    result.must_be_instance_of DeltacloudVM::Client::Blob
    result.bucket_id.must_equal 'bucket1'
    result._id.must_equal 'fooblob123'
    result.content_length.must_equal '15'
    result.content_type.must_equal 'text/plain'
    @client.must_respond_to :destroy_blob
    @client.destroy_blob('bucket1', result._id).must_equal true
  end

  it 'support #create_blob and #destroy_blob with meta_params' do
    @client.must_respond_to :create_blob
    result = @client.create_blob('bucket1', 'fooblob123', 'content', :user_metadata => { :key => :value })
    result.must_be_instance_of DeltacloudVM::Client::Blob
    result.user_metadata.must_be_kind_of Hash
    result.user_metadata['key'].must_equal 'value'
    @client.must_respond_to :destroy_blob
    @client.destroy_blob('bucket1', result._id).must_equal true
  end

end


text:
package org.g4studio.core.mvc.xstruts.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.net.URLEncoder;

/**
 * General purpose utility methods related to generating a servlet response in
 * the Struts controller framework.
 *
 * @version $Rev: 421119 $ $Date: 2005-08-21 14:46:28 -0400 (Sun, 21 Aug 2005) $
 */
public class ResponseUtils {
	// ------------------------------------------------------- Static Variables

	/**
	 * The message resources for this package.
	 */
	protected static MessageResources messages = MessageResources
			.getMessageResources("org.g4studio.core.mvc.xstruts.util.LocalStrings");

	/**
	 * Java 1.4 encode method to use instead of deprecated 1.3 version.
	 */
	private static Method encode = null;

	/**
	 * Commons logging instance.
	 */
	private static final Log log = LogFactory.getLog(ResponseUtils.class);

	/**
	 * Initialize the encode variable with the Java 1.4 method if available.
	 */
	static {
		try {
			// get version of encode method with two String args
			Class[] args = new Class[] { String.class, String.class };

			encode = URLEncoder.class.getMethod("encode", args);
		} catch (NoSuchMethodException e) {
			log.debug("Could not find Java 1.4 encode method.  Using deprecated version.", e);
		}
	}

	// --------------------------------------------------------- Public Methods

	/**
	 * Filter the specified string for characters that are senstive to HTML
	 * interpreters, returning the string with these characters replaced by the
	 * corresponding character entities.
	 *
	 * @param value
	 *            The string to be filtered and returned
	 */
	public static String filter(String value) {
		if ((value == null) || (value.length() == 0)) {
			return value;
		}

		StringBuffer result = null;
		String filtered = null;

		for (int i = 0; i < value.length(); i++) {
			filtered = null;

			switch (value.charAt(i)) {
			case '<':
				filtered = "<";

				break;

			case '>':
				filtered = ">";

				break;

			case '&':
				filtered = "&";

				break;

			case '"':
				filtered = """;

				break;

			case '\'':
				filtered = "'";

				break;
			}

			if (result == null) {
				if (filtered != null) {
					result = new StringBuffer(value.length() + 50);

					if (i > 0) {
						result.append(value.substring(0, i));
					}

					result.append(filtered);
				}
			} else {
				if (filtered == null) {
					result.append(value.charAt(i));
				} else {
					result.append(filtered);
				}
			}
		}

		return (result == null) ? value : result.toString();
	}

	/**
	 * URLencodes a string assuming the character encoding is UTF-8.
	 *
	 * @param url
	 * @return String The encoded url in UTF-8
	 */
	public static String encodeURL(String url) {
		return encodeURL(url, "UTF-8");
	}

	/**
	 * Use the new URLEncoder.encode() method from Java 1.4 if available, else
	 * use the old deprecated version. This method uses reflection to find the
	 * appropriate method; if the reflection operations throw exceptions, this
	 * will return the url encoded with the old URLEncoder.encode() method.
	 *
	 * @param enc
	 *            The character encoding the urlencode is performed on.
	 * @return String The encoded url.
	 */
	public static String encodeURL(String url, String enc) {
		try {
			if ((enc == null) || (enc.length() == 0)) {
				enc = "UTF-8";
			}

			// encode url with new 1.4 method and UTF-8 encoding
			if (encode != null) {
				return (String) encode.invoke(null, new Object[] { url, enc });
			}
		} catch (IllegalAccessException e) {
			log.debug("Could not find Java 1.4 encode method.  Using deprecated version.", e);
		} catch (InvocationTargetException e) {
			log.debug("Could not find Java 1.4 encode method. Using deprecated version.", e);
		}

		return URLEncoder.encode(url);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 62: 141 (1997)

#### Original name
Sporisorium themedae-cymbariae Vánky

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Cdlr\codeBundle\Entity\AutoEcole" table="auto_ecole">
    <indexes>
      <index name="region_id" columns="region_id"/>
    </indexes>
    <id name="autoecoleId" type="integer" column="autoecole_id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="nomAuto" type="string" column="nom_auto" length="30" nullable="false"/>
    <!--<field name="region" type="string" column="region" length="50" nullable="false"/>-->
    <field name="adresse" type="string" column="adresse" length="50" nullable="false"/>
    <field name="tel" type="integer" column="tel" nullable="false"/>
    <many-to-one field="region" target-entity="Regions">
      <join-columns>
        <join-column name="region_id" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
'use strict';

describe('Controller: JobListCtrl', function () {

  // load the controller's module
  beforeEach(module('tbsApp'));

  var JobListCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    JobListCtrl = $controller('JobListCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../鑿/index.html">
<meta http-equiv=refresh content="0; url='../鑿/index.html'">

Redirecting...

Click here if you are not redirected.


text:
.tImageSlideItem {
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  background-size: cover;
}

/*# sourceMappingURL=SlideDemo.css.map */


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.25.128:61616"/>
    </bean>

    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory"
          class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>
    <!--这个是队列目的地,点对点的 -->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>
            <value>spring-queue</value>
        </constructor-arg>
    </bean>
    <!--这个是主题目的地,一对多的 -->
    <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="itemAddTopic"/>
    </bean>

    <!-- 配置测试消息监听 -->
    <bean id="myMessageListener" class="com.fmall.search.message.MyMessageListener"/>
    <!-- 消息监听容器 -->
    <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="queueDestination" />
        <property name="messageListener" ref="myMessageListener" />
    </bean>

    <!-- 配置商品添加消息监听  -->
    <bean id="itemMessageListener" class="com.fmall.search.message.ItemAddMessageListener"/>
    <!--  消息监听容器 -->
    <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer" >
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="topicDestination" />
        <property name="messageListener" ref="itemMessageListener" />
    </bean>

</beans>


text:
set -e
wget -O ydownloader https://raw.githubusercontent.com/pwittchen/ydownloader/master/ydownloader
chmod +x ydownloader
sudo mv ydownloader /usr/local/bin/ydownloader


text:
using PoESkillTree.Utils;

namespace PoESkillTree.Model
{
    public class Options : Notifier
    {
        // Don't set language property! When not set, L10n.Initialize will try to use OS settings.
        private string _language;
        private string _theme = "Dark";
        private string _accent = "Steel";
        private bool _attributesBarOpened;
        private bool _buildsBarOpened;
        private bool _treeComparisonEnabled;
        private bool _changeSummaryEnabled;
        private bool _showAllAscendancyClasses = true;
        private string _nodeSearchHighlightColor = "Red";
        private string _nodeAttrHighlightColor = "LawnGreen";
        private string _nodeHoverHighlightColor = "DodgerBlue";
        private bool _downloadMissingItemImages = true;
        private ResetPreferences _resetPreferences = ResetPreferences.MainTree | ResetPreferences.AscendancyTree;
        private string _buildSavePath;
        private int _loadBuildButtonIndex;

        public string Language
        {
            get { return _language; }
            set { SetProperty(ref _language, value); }
        }

        public string Theme
        {
            get { return _theme; }
            set { SetProperty(ref _theme, value); }
        }

        public string Accent
        {
            get { return _accent; }
            set { SetProperty(ref _accent, value); }
        }

        public bool AttributesBarOpened
        {
            get { return _attributesBarOpened; }
            set { SetProperty(ref _attributesBarOpened, value); }
        }

        public bool BuildsBarOpened
        {
            get { return _buildsBarOpened; }
            set { SetProperty(ref _buildsBarOpened, value); }
        }

        public bool TreeComparisonEnabled
        {
            get { return _treeComparisonEnabled; }
            set { SetProperty(ref _treeComparisonEnabled, value); }
        }

        public bool ChangeSummaryEnabled
        {
            get { return _changeSummaryEnabled; }
            set { SetProperty(ref _changeSummaryEnabled, value); }
        }

        public bool ShowAllAscendancyClasses
        {
            get { return _showAllAscendancyClasses; }
            set { SetProperty(ref _showAllAscendancyClasses, value); }
        }

        public string NodeSearchHighlightColor
        {
            get { return _nodeSearchHighlightColor; }
            set { SetProperty(ref _nodeSearchHighlightColor, value); }
        }

        public string NodeAttrHighlightColor
        {
            get { return _nodeAttrHighlightColor; }
            set { SetProperty(ref _nodeAttrHighlightColor, value); }
        }

        public string NodeHoverHighlightColor
        {
            get { return _nodeHoverHighlightColor; }
            set { SetProperty(ref _nodeHoverHighlightColor, value); }
        }

        public bool DownloadMissingItemImages
        {
            get { return _downloadMissingItemImages; }
            set { SetProperty(ref _downloadMissingItemImages, value); }
        }

        public ResetPreferences ResetPreferences
        {
            get { return _resetPreferences; }
            set { SetProperty(ref _resetPreferences, value); }
        }

        public string BuildsSavePath
        {
            get { return _buildSavePath; }
            set { SetProperty(ref _buildSavePath, value); }
        }

        public int LoadTreeButtonIndex
        {
            get { return _loadBuildButtonIndex; }
            set { SetProperty(ref _loadBuildButtonIndex, value); }
        }
    }
}


text:
//
//  KMToolUtils.h
//  KMToolUtilsDemo
//
//  Created by kumojiang on 16/8/22.
//  Copyright © 2016年 kumo. All rights reserved.
//

#ifndef KMToolUtils_h
#define KMToolUtils_h

// Utils module
#import "ColorUtils.h"
#import "DimensionUtils.h"

// category

#import "UIView+KMToolUtils.h"
#import "UILabel+KMToolUtils.h"
#import "UIImage+KMToolUtils.h"

// KMTemplate
#import "KMTableView.h"

#endif /* KMToolUtils_h */


text:
#ifndef SkSVGTypes_DEFINED
#define SkSVGTypes_DEFINED

enum SkSVGTypes {
    SkSVGType_Circle,
    SkSVGType_ClipPath,
    SkSVGType_Defs,
    SkSVGType_Ellipse,
    SkSVGType_FeColorMatrix,
    SkSVGType_Filter,
    SkSVGType_G,
    SkSVGType_Image,
    SkSVGType_Line,
    SkSVGType_LinearGradient,
    SkSVGType_Mask,
    SkSVGType_Metadata,
    SkSVGType_Path,
    SkSVGType_Polygon,
    SkSVGType_Polyline,
    SkSVGType_RadialGradient,
    SkSVGType_Rect,
    SkSVGType_SVG,
    SkSVGType_Stop,
    SkSVGType_Symbol,
    SkSVGType_Text,
    SkSVGType_Tspan,
	SkSVGType_Unknown,
    SkSVGType_Use
};

#endif // SkSVGTypes_DEFINED


text:
Logger *Logger::GlobalLogger() {
  static Logger logger;
  return &logger;
}

void Logger::VLogF(int priority, const char *format, va_list args) {
  if (priority > verbosity_) {
    return;
  }
  char buffer[4096];
  int length = vsnprintf(buffer, sizeof buffer, format, args);
  if (static_cast<size_t>(length) >= sizeof buffer) {
    length = sizeof buffer;
    buffer[sizeof buffer - 1] = '\n';
  }
  QueueLogLine(new string(buffer, length));
}

void Logger::StartThread() {
  LOGGER_ASSERT(!thread_running_);
  thread_running_ = true;
  LOGGER_ASSERT(0 == pthread_create(&thread_, NULL, &StartRoutine, this));
}

void Logger::StopThread() {
  LOGGER_ASSERT(thread_running_);
  thread_running_ = false;
  LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));
  bool need_cond_signal = queued_lines_.empty();
  queued_lines_.push_back(NULL);
  LOGGER_ASSERT(0 == pthread_mutex_unlock(&queued_lines_mutex_));
  if (need_cond_signal) {
    LOGGER_ASSERT(0 == pthread_cond_signal(&queued_lines_cond_));
  }
  LOGGER_ASSERT(0 == pthread_join(thread_, NULL));
}

Logger::Logger() : verbosity_(20), log_fd_(-1), thread_running_(false) {
  LOGGER_ASSERT(0 == pthread_mutex_init(&queued_lines_mutex_, NULL));
  LOGGER_ASSERT(0 == pthread_cond_init(&queued_lines_cond_, NULL));
  LOGGER_ASSERT(0 == pthread_cond_init(&full_queue_cond_, NULL));
}

Logger::~Logger() {
  LOGGER_ASSERT(0 == pthread_mutex_destroy(&queued_lines_mutex_));
  LOGGER_ASSERT(0 == pthread_cond_destroy(&queued_lines_cond_));
  LOGGER_ASSERT(0 == pthread_cond_destroy(&full_queue_cond_));
}

void Logger::QueueLogLine(string *line) {
  LOGGER_ASSERT(line != NULL);
  LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));
  if (thread_running_) {
    if (queued_lines_.size() >= kMaxQueueSize) {
      LOGGER_ASSERT(0 == pthread_cond_wait(&full_queue_cond_,
                                           &queued_lines_mutex_));
    }
    if (queued_lines_.empty()) {
      LOGGER_ASSERT(0 == pthread_cond_signal(&queued_lines_cond_));
    }
    queued_lines_.push_back(line);
  } else {
    WriteAndDeleteLogLine(line);
  }
  LOGGER_ASSERT(0 == pthread_mutex_unlock(&queued_lines_mutex_));
}

namespace {
void WriteToFile(const string& line, int fd) {
  LOGGER_ASSERT(write(fd, line.data(), line.size()) ==
                static_cast<ssize_t>(line.size()));
}
}

void Logger::WriteAndDeleteLogLine(string *line) {
  LOGGER_ASSERT(line != NULL);
  if (log_fd_ >= 0) {
    WriteToFile(*line, log_fd_);
  }
  WriteToFile(*line, 1);
  delete line;
}

void *Logger::StartRoutine(void *ptr) {
  Logger *self = static_cast<Logger*>(ptr);
  self->ThreadMain();
  return NULL;
}

void Logger::ThreadMain() {
  vector<string*> local_queue;
  LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));

  for (;;) {
    if (queued_lines_.empty()) {
      LOGGER_ASSERT(0 == pthread_cond_wait(&queued_lines_cond_,
                                           &queued_lines_mutex_));
      continue;
    }

    // We move the log lines into a local queue so we can release the lock
    // while writing them to disk, preventing other threads from blocking on
    // our writes.
    local_queue.swap(queued_lines_);
    if (local_queue.size() >= kMaxQueueSize) {
      LOGGER_ASSERT(0 == pthread_cond_broadcast(&full_queue_cond_));
    }

    // Unlock while we process our local queue.
    LOGGER_ASSERT(0 == pthread_mutex_unlock(&queued_lines_mutex_));
    for (vector<string*>::const_iterator it = local_queue.begin();
         it != local_queue.end(); ++it) {
      if (*it == NULL) {
        // NULL is guaranteed to be at the end.
        return;
      }
      WriteAndDeleteLogLine(*it);
    }
    local_queue.clear();
    // We must hold the lock at the start of each iteration of this for loop.
    LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));
  }
}


text:
"""
Change directory to provide relative paths for doctests
   >>> import os
   >>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
   >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
   >>> os.chdir(datadir)
"""
from __future__ import print_function, division, unicode_literals, absolute_import

import os.path as op
import numpy as np
import nibabel as nb
import nibabel.trackvis as nbt

from ... import logging
from ..base import (TraitedSpec, BaseInterfaceInputSpec,
                    File, isdefined, traits)
from .base import DipyBaseInterface
IFLOGGER = logging.getLogger('interface')

class TrackDensityMapInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True,
                   desc='The input TrackVis track file')
    reference = File(exists=True,
                     desc='A reference file to define RAS coordinates space')
    points_space = traits.Enum('rasmm', 'voxel', None, usedefault=True,
                               desc='coordinates of trk file')
    voxel_dims = traits.List(traits.Float, minlen=3, maxlen=3,
                             desc='The size of each voxel in mm.')
    data_dims = traits.List(traits.Int, minlen=3, maxlen=3,
                            desc='The size of the image in voxels.')
    out_filename = File('tdi.nii', usedefault=True,
                        desc='The output filename for the tracks in TrackVis '
                             '(.trk) format')

class TrackDensityMapOutputSpec(TraitedSpec):
    out_file = File(exists=True)

class TrackDensityMap(DipyBaseInterface):

    """
    Creates a tract density image from a TrackVis track file using functions
    from dipy

    Example
    -------

    >>> import nipype.interfaces.dipy as dipy
    >>> trk2tdi = dipy.TrackDensityMap()
    >>> trk2tdi.inputs.in_file = 'converted.trk'
    >>> trk2tdi.run()                                   # doctest: +SKIP

    """
    input_spec = TrackDensityMapInputSpec
    output_spec = TrackDensityMapOutputSpec

    def _run_interface(self, runtime):
        from numpy import min_scalar_type
        from dipy.tracking.utils import density_map

        tracks, header = nbt.read(self.inputs.in_file)
        streams = ((ii[0]) for ii in tracks)

        if isdefined(self.inputs.reference):
            refnii = nb.load(self.inputs.reference)
            affine = refnii.affine
            data_dims = refnii.shape[:3]
            kwargs = dict(affine=affine)
        else:
            IFLOGGER.warn(
                'voxel_dims and data_dims are deprecated as of dipy 0.7.1. Please use reference '
                'input instead')

            if not isdefined(self.inputs.data_dims):
                data_dims = header['dim']
            else:
                data_dims = self.inputs.data_dims
            if not isdefined(self.inputs.voxel_dims):
                voxel_size = header['voxel_size']
            else:
                voxel_size = self.inputs.voxel_dims

            affine = header['vox_to_ras']
            kwargs = dict(voxel_size=voxel_size)

        data = density_map(streams, data_dims, **kwargs)
        data = data.astype(min_scalar_type(data.max()))
        img = nb.Nifti1Image(data, affine)
        out_file = op.abspath(self.inputs.out_filename)
        nb.save(img, out_file)

        IFLOGGER.info(
            'Track density map saved as %s, size=%s, dimensions=%s',
            out_file, img.shape, img.header.get_zooms())

        return runtime

    def _list_outputs(self):
        outputs = self._outputs().get()
        outputs['out_file'] = op.abspath(self.inputs.out_filename)
        return outputs

class StreamlineTractographyInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc=('input diffusion data'))
    in_model = File(exists=True, desc=('input f/d-ODF model extracted from.'))
    tracking_mask = File(exists=True,
                         desc=('input mask within which perform tracking'))
    seed_mask = File(exists=True,
                     desc=('input mask within which perform seeding'))
    in_peaks = File(exists=True, desc=('peaks computed from the odf'))
    seed_coord = File(exists=True,
                      desc=('file containing the list of seed voxel '
                            'coordinates (N,3)'))
    gfa_thresh = traits.Float(0.2, mandatory=True, usedefault=True,
                              desc=('GFA threshold to compute tracking mask'))
    peak_threshold = traits.Float(
        0.5, mandatory=True, usedefault=True,
        desc=('threshold to consider peaks from model'))
    min_angle = traits.Float(25.0, mandatory=True, usedefault=True,
                             desc=('minimum separation angle'))
    multiprocess = traits.Bool(True, mandatory=True, usedefault=True,
                               desc=('use multiprocessing'))
    save_seeds = traits.Bool(False, mandatory=True, usedefault=True,
                             desc=('save seeding voxels coordinates'))
    num_seeds = traits.Int(10000, mandatory=True, usedefault=True,
                           desc=('desired number of tracks in tractography'))
    out_prefix = traits.Str(desc=('output prefix for file names'))

class StreamlineTractographyOutputSpec(TraitedSpec):
    tracks = File(desc='TrackVis file containing extracted streamlines')
    gfa = File(desc=('The resulting GFA (generalized FA) computed using the '
                     'peaks of the ODF'))
    odf_peaks = File(desc=('peaks computed from the odf'))
    out_seeds = File(desc=('file containing the (N,3) *voxel* coordinates used'
                           ' in seeding.'))

class StreamlineTractography(DipyBaseInterface):

    """
    Streamline tractography using EuDX [Garyfallidis12]_.

    .. [Garyfallidis12] Garyfallidis E., "Towards an accurate brain
      tractography", PhD thesis, University of Cambridge, 2012

    Example
    -------

    >>> from nipype.interfaces import dipy as ndp
    >>> track = ndp.StreamlineTractography()
    >>> track.inputs.in_file = '4d_dwi.nii'
    >>> track.inputs.in_model = 'model.pklz'
    >>> track.inputs.tracking_mask = 'dilated_wm_mask.nii'
    >>> res = track.run() # doctest: +SKIP
    """
    input_spec = StreamlineTractographyInputSpec
    output_spec = StreamlineTractographyOutputSpec

    def _run_interface(self, runtime):
        from dipy.reconst.peaks import peaks_from_model
        from dipy.tracking.eudx import EuDX
        from dipy.data import get_sphere
        # import marshal as pickle
        import pickle as pickle
        import gzip

        if (not (isdefined(self.inputs.in_model) or
                 isdefined(self.inputs.in_peaks))):
            raise RuntimeError(('At least one of in_model or in_peaks should '
                                'be supplied'))

        img = nb.load(self.inputs.in_file)
        imref = nb.four_to_three(img)[0]
        affine = img.affine

        data = img.get_data().astype(np.float32)
        hdr = imref.header.copy()
        hdr.set_data_dtype(np.float32)
        hdr['data_type'] = 16

        sphere = get_sphere('symmetric724')

        self._save_peaks = False
        if isdefined(self.inputs.in_peaks):
            IFLOGGER.info('Peaks file found, skipping ODF peaks search...')
            f = gzip.open(self.inputs.in_peaks, 'rb')
            peaks = pickle.load(f)
            f.close()
        else:
            self._save_peaks = True
            IFLOGGER.info('Loading model and computing ODF peaks')
            f = gzip.open(self.inputs.in_model, 'rb')
            odf_model = pickle.load(f)
            f.close()

            peaks = peaks_from_model(
                model=odf_model,
                data=data,
                sphere=sphere,
                relative_peak_threshold=self.inputs.peak_threshold,
                min_separation_angle=self.inputs.min_angle,
                parallel=self.inputs.multiprocess)

            f = gzip.open(self._gen_filename('peaks', ext='.pklz'), 'wb')
            pickle.dump(peaks, f, -1)
            f.close()

        hdr.set_data_shape(peaks.gfa.shape)
        nb.Nifti1Image(peaks.gfa.astype(np.float32), affine,
                       hdr).to_filename(self._gen_filename('gfa'))

        IFLOGGER.info('Performing tractography')

        if isdefined(self.inputs.tracking_mask):
            msk = nb.load(self.inputs.tracking_mask).get_data()
            msk[msk > 0] = 1
            msk[msk < 0] = 0
        else:
            msk = np.ones(imref.shape)

        gfa = peaks.gfa * msk
        seeds = self.inputs.num_seeds

        if isdefined(self.inputs.seed_coord):
            seeds = np.loadtxt(self.inputs.seed_coord)

        elif isdefined(self.inputs.seed_mask):
            seedmsk = nb.load(self.inputs.seed_mask).get_data()
            assert(seedmsk.shape == data.shape[:3])
            seedmsk[seedmsk > 0] = 1
            seedmsk[seedmsk < 1] = 0
            seedps = np.array(np.where(seedmsk == 1), dtype=np.float32).T
            vseeds = seedps.shape[0]
            nsperv = (seeds // vseeds) + 1
            IFLOGGER.info(('Seed mask is provided (%d voxels inside '
                           'mask), computing seeds (%d seeds/voxel).') %
                          (vseeds, nsperv))
            if nsperv > 1:
                IFLOGGER.info(('Needed %d seeds per selected voxel '
                               '(total %d).') % (nsperv, vseeds))
                seedps = np.vstack(np.array([seedps] * nsperv))
                voxcoord = seedps + np.random.uniform(-1, 1, size=seedps.shape)
                nseeds = voxcoord.shape[0]
                seeds = affine.dot(np.vstack((voxcoord.T,
                                              np.ones((1, nseeds)))))[:3, :].T

                if self.inputs.save_seeds:
                    np.savetxt(self._gen_filename('seeds', ext='.txt'), seeds)

        if isdefined(self.inputs.tracking_mask):
            tmask = msk
            a_low = 0.1
        else:
            tmask = gfa
            a_low = self.inputs.gfa_thresh

        eu = EuDX(tmask,
                  peaks.peak_indices[..., 0],
                  seeds=seeds,
                  affine=affine,
                  odf_vertices=sphere.vertices,
                  a_low=a_low)

        ss_mm = [np.array(s) for s in eu]

        trkfilev = nb.trackvis.TrackvisFile(
            [(s, None, None) for s in ss_mm], points_space='rasmm', affine=np.eye(4))
        trkfilev.to_file(self._gen_filename('tracked', ext='.trk'))
        return runtime

    def _list_outputs(self):
        outputs = self._outputs().get()
        outputs['tracks'] = self._gen_filename('tracked', ext='.trk')
        outputs['gfa'] = self._gen_filename('gfa')
        if self._save_peaks:
            outputs['odf_peaks'] = self._gen_filename('peaks', ext='.pklz')
        if self.inputs.save_seeds:
            if isdefined(self.inputs.seed_coord):
                outputs['out_seeds'] = self.inputs.seed_coord
            else:
                outputs['out_seeds'] = self._gen_filename('seeds',
                                                          ext='.txt')

        return outputs

    def _gen_filename(self, name, ext=None):
        fname, fext = op.splitext(op.basename(self.inputs.in_file))
        if fext == '.gz':
            fname, fext2 = op.splitext(fname)
            fext = fext2 + fext

        if not isdefined(self.inputs.out_prefix):
            out_prefix = op.abspath(fname)
        else:
            out_prefix = self.inputs.out_prefix

        if ext is None:
            ext = fext

        return out_prefix + '_' + name + ext


text:
using System;
using System.Data;
using ServiceStack.Text;

namespace ServiceStack.OrmLite
{
    public class ConflictResolution
    {
        public const string Ignore = "IGNORE";
    }

    public static class OrmLiteConflictResolutions
    {
        public static void OnConflictIgnore(this IDbCommand dbCmd) => dbCmd.OnConflict(ConflictResolution.Ignore);

        public static void OnConflict(this IDbCommand dbCmd, string conflictResolution)
        {
            var pos = dbCmd.CommandText?.IndexOf(' ') ?? -1;
            if (pos == -1)
                throw new NotSupportedException("Cannot specify ON CONFLICT resolution on Invalid SQL starting with: " + dbCmd.CommandText.SubstringWithEllipsis(0, 50));

            var sqlConflict = dbCmd.GetDialectProvider().SqlConflict(dbCmd.CommandText, conflictResolution);
            dbCmd.CommandText = sqlConflict;
        }
    }
}


text:
% Filename: RunMCwithcovariates.m
% Author: Andrew Zammit Mangion
% Date: November 2011
% Description: Runs Monte Carlo runs with inferred model (see paper for
% details) to predict AOG activity in 2010.
%
%Requires: Mapping Toolbox
%          Statistical Toolbox
%          LocalisedKernelPhi.m
%          ../AfghanModelHighResWholePrec_Covariates (main data)
%          ../Shapefiles
%          inpolygons.m (available from MATLAB Exchange)
%          multiprod.m (available from MATLAB Exchange)
%          posdist.m (available from MATLAB Exchange)

% Load results from VB-Laplace
studydata = '../AfghanModelHighResWholePrec_Covariates';
load(studydata)
DisturbVar = inv(diag(diag(Thetainfo(m).Meanprecmat))); % Adopt marginal variance (precision is diagonally dominant)

N= 2000;                            % Number of samples
xsample2009 = zeros(Basis.nx,52);   % Samples for 52 weeks, state in 2009
fieldsample2009 = zeros(J,J,52);    % Sample field in 2009
intsample2009 = zeros(J,J,52);      % Sample intensity in 2009
xsample2010 = zeros(Basis.nx,52);   % Sample state in 2010
fieldsample2010 = zeros(J,J,52);    % Sample field in 2010
intsample2010 = zeros(J,J,52);      % Sample intensity in 2010

% Load Provincial Boundaries
Provbounds = shaperead('../Shapefiles/admin2_poly_32.shp','UseGeoCoords',true);

% Setup space
strue1 = s./scale(1) + shift(1);
strue2 = s./scale(2) + shift(2);
[s1true,s2true] = meshgrid(strue1,strue2);

% Provincial masks
Provmask = zeros(J^2,length(Provbounds));
for Pnum = 1:length(Provbounds)
    Provmask(:,Pnum) = inpolygons(s1true(:),s2true(:),Provbounds(Pnum).Lon',Provbounds(Pnum).Lat');
    Provname(Pnum).str = Provbounds(Pnum).PRV_NAME;
end
Provintensity2009 = zeros(length(Provbounds),N);    % Provincial intensity in 2009
Count2009 = zeros(length(Provbounds),N);            % Provincial count in 2009
Provintensity2010 = zeros(length(Provbounds),N);    % Provincial intensity in 2010
Count2010 = zeros(length(Provbounds),N);            % Provincial count in 2010
Growth = zeros(length(Provbounds),N);               % Sample provincial growth

% Find population density
Afg_pop = shaperead('../Shapefiles/afg_population_CSO_2011_2012','UseGeoCoords',true);
Pop_density = zeros(size(s1));
for i = 1:length(Afg_pop)
X = inpolygons(s1true(:),s2true(:),Afg_pop(i).Lon',Afg_pop(i).Lat');
Pop_density(X == 1) = Afg_pop(i).T_P_BS/ Afg_pop(i).AREA_SQKM;
end

% Find distance to city
Afg_cities = shaperead('../Shapefiles/07_03_settlements','UseGeoCoords',true);
Filtered_cities = 0; j =1;
for i = 1:length(Afg_cities)
   if Afg_cities(i).TYPE == 2 ||  Afg_cities(i).TYPE == 3
       Filtered_cities(j,1) = Afg_cities(i).LON;
       Filtered_cities(j,2) = Afg_cities(i).LAT;
       j = j+1;
   end
end
Dist_to_city = zeros(size(s1true));
for i = 1:size(s1true,1)
    for j = 1:size(s1true,2)
        Dist_to_city(i,j) = min(posdist(s1true(1,j),s2true(i,1),Filtered_cities(:,1),Filtered_cities(:,2)));
    end
end

% Fixed effects on intensity field
Covariates = Thetainfo(m).best(1)*Pop_density + Thetainfo(m).varb(1)*Pop_density.^2/2 ...
                 + Thetainfo(m).best(2)*Dist_to_city + Thetainfo(m).varb(2)*Dist_to_city.^2/2;

% Main Monte Carlo routine for intensity in each province
for i = 1:N
    for j = 261:312
        %Sample x
        xsample2009(:,j-260) = mvnrnd(Estinfo(j).xestRTS,diag(diag(Estinfo(j).PRTS)));
        fieldsample2009(:,:,j-260) = sum(multiprod(Basis.phi,reshape(xsample2009(:,j-260),1,1,Basis.nx)),3);
        intsample2009(:,:,j-260) = exp(fieldsample2009(:,:,j-260) + Thetainfo(m).muest + Covariates);
    end
    TotIntensity2009 = sum(intsample2009,3);
    for Pnum = 1:length(Provbounds)
        Provintensity2009(Pnum,i) = sum(sum(reshape(TotIntensity2009(:).*Provmask(:,Pnum),length(s),[])))*ds^2;
        Count2009(Pnum,i) = poissrnd(Provintensity2009(Pnum,i));
    end
    xsample2010(:,1) = xsample2009(:,end);
    fieldsample2010(:,:,1) = fieldsample2009(:,:,end);
    intsample2010(:,:,1) = intsample2009(:,:,end);
    for j = 2:52
        xsample2010(:,j) = xsample2010(:,j-1) + Thetainfo(m).thetaest + mvnrnd(zeros(Basis.nx,1),DisturbVar)';
        fieldsample2010(:,:,j) = sum(multiprod(Basis.phi,reshape(xsample2010(:,j),1,1,Basis.nx)),3);
        intsample2010(:,:,j) = exp(fieldsample2010(:,:,j) + Thetainfo(m).muest +  Covariates);
    end
    TotIntensity2010 = sum(intsample2010,3);
    for Pnum = 1:length(Provbounds)
        Provintensity2010(Pnum,i) = sum(sum(reshape(TotIntensity2010(:).*Provmask(:,Pnum),length(s),[])))*ds^2;
        Count2010(Pnum,i) = poissrnd(Provintensity2010(Pnum,i));
        Growth(Pnum,i) = Count2010(Pnum,i)/Count2009(Pnum,i);
    end
    i
end

% Save results
save('GrowthtrialN2000WholePrecWithDistCovariates')


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Console;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Tester\ApplicationTester;

class ApplicationTest extends TestCase
{
    public function testBundleInterfaceImplementation()
    {
        $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');

        $kernel = $this->getKernel(array($bundle), true);

        $application = new Application($kernel);
        $application->doRun(new ArrayInput(array('list')), new NullOutput());
    }

    public function testBundleCommandsAreRegistered()
    {
        $bundle = $this->createBundleMock(array());

        $kernel = $this->getKernel(array($bundle), true);

        $application = new Application($kernel);
        $application->doRun(new ArrayInput(array('list')), new NullOutput());

        // Calling twice: registration should only be done once.
        $application->doRun(new ArrayInput(array('list')), new NullOutput());
    }

    public function testBundleCommandsAreRetrievable()
    {
        $bundle = $this->createBundleMock(array());

        $kernel = $this->getKernel(array($bundle));

        $application = new Application($kernel);
        $application->all();

        // Calling twice: registration should only be done once.
        $application->all();
    }

    public function testBundleSingleCommandIsRetrievable()
    {
        $command = new Command('example');

        $bundle = $this->createBundleMock(array($command));

        $kernel = $this->getKernel(array($bundle));

        $application = new Application($kernel);

        $this->assertSame($command, $application->get('example'));
    }

    public function testBundleCommandCanBeFound()
    {
        $command = new Command('example');

        $bundle = $this->createBundleMock(array($command));

        $kernel = $this->getKernel(array($bundle));

        $application = new Application($kernel);

        $this->assertSame($command, $application->find('example'));
    }

    public function testBundleCommandCanBeFoundByAlias()
    {
        $command = new Command('example');
        $command->setAliases(array('alias'));

        $bundle = $this->createBundleMock(array($command));

        $kernel = $this->getKernel(array($bundle));

        $application = new Application($kernel);

        $this->assertSame($command, $application->find('alias'));
    }

    public function testBundleCommandsHaveRightContainer()
    {
        $command = $this->getMockForAbstractClass('Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand', array('foo'), '', true, true, true, array('setContainer'));
        $command->setCode(function () {});
        $command->expects($this->exactly(2))->method('setContainer');

        $application = new Application($this->getKernel(array(), true));
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);
        $application->add($command);
        $tester = new ApplicationTester($application);

        // set container is called here
        $tester->run(array('command' => 'foo'));

        // as the container might have change between two runs, setContainer must called again
        $tester->run(array('command' => 'foo'));
    }

    private function getKernel(array $bundles, $useDispatcher = false)
    {
        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');

        if ($useDispatcher) {
            $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
            $dispatcher
                ->expects($this->atLeastOnce())
                ->method('dispatch')
            ;
            $container
                ->expects($this->atLeastOnce())
                ->method('get')
                ->with($this->equalTo('event_dispatcher'))
                ->will($this->returnValue($dispatcher));
        }

        $container
            ->expects($this->once())
            ->method('hasParameter')
            ->with($this->equalTo('console.command.ids'))
            ->will($this->returnValue(true))
        ;
        $container
            ->expects($this->once())
            ->method('getParameter')
            ->with($this->equalTo('console.command.ids'))
            ->will($this->returnValue(array()))
        ;

        $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
        $kernel
            ->expects($this->any())
            ->method('getBundles')
            ->will($this->returnValue($bundles))
        ;
        $kernel
            ->expects($this->any())
            ->method('getContainer')
            ->will($this->returnValue($container))
        ;

        return $kernel;
    }

    private function createBundleMock(array $commands)
    {
        $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
        $bundle
            ->expects($this->once())
            ->method('registerCommands')
            ->will($this->returnCallback(function (Application $application) use ($commands) {
                $application->addCommands($commands);
            }))
        ;

        return $bundle;
    }
}


text:
from oslo_config import cfg
from oslo_log import log as logging

from designate import rpc

LOG = logging.getLogger(__name__)

notify_opts = [
    cfg.BoolOpt('notify_api_faults', default=False,
                help='Send notifications if there\'s a failure in the API.')
]

CONF = cfg.CONF
CONF.register_opts(notify_opts)

def send_api_fault(context, url, status, exception):
    """Send an api.fault notification."""

    if not CONF.notify_api_faults:
        return

    payload = {'url': url, 'exception': str(exception), 'status': status}

    rpc.get_notifier('api').error(context, 'dns.api.fault', payload)


text:
@interface TimeLineCollectionViewCell ()

@property (nonatomic, strong) UILabel *dayLabel;
@property (nonatomic, strong) UILabel *yearLabel;

@end

@implementation TimeLineCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        [self creatUI];
    }
    return self;
}

- (void)creatUI
{
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;

    CGFloat top = 20;
    _dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, top, width-2*10-5, 20)];
    _dayLabel.textAlignment = NSTextAlignmentCenter;
    _dayLabel.font = [UIFont systemFontOfSize:14.0f];
    [self addSubview:_dayLabel];

    _yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, top+20, width-2*10-5, 20)];
    _yearLabel.textAlignment = NSTextAlignmentCenter;
    _yearLabel.font = [UIFont systemFontOfSize:13.0f];
    [self addSubview:_yearLabel];

    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(20, top+19, width-2*20-5, 0.5)];
    line.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:1];
    [self addSubview:line];

    UILabel *vline = [[UILabel alloc] initWithFrame:CGRectMake(width-15, 0, 0.5, height)];
    vline.backgroundColor = [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:1];
    [self addSubview:vline];

}

- (void)layoutSubviews
{
    [super layoutSubviews];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [formatter dateFromString:self.timeString];

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    comps = [calendar components:unitFlags fromDate:date];

    NSInteger year=[ comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    _dayLabel.text = [NSString stringWithFormat:@"%zd日",day];
    _yearLabel.text = [NSString stringWithFormat:@"%zd.%zd",year,month];

}

@end


text:
package org.ovirt.engine.core.bll.scheduling.queries;

import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.bll.scheduling.PolicyUnitImpl;
import org.ovirt.engine.core.bll.scheduling.SchedulingManager;
import org.ovirt.engine.core.common.queries.IdQueryParameters;

public class GetPolicyUnitByIdQuery extends QueriesCommandBase<IdQueryParameters> {
    public GetPolicyUnitByIdQuery(IdQueryParameters parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        PolicyUnitImpl value = SchedulingManager.getInstance()
                .getPolicyUnitsMap()
                .get(getParameters().getId());
        if (value != null) {
            getQueryReturnValue().setReturnValue(value.getPolicyUnit());
        }
    }
}


text:
class Point < ActiveRecord::Base
  def created_ts
    (self.created_at.to_time.to_f * 1000).round
  end
end


text:
package com.google.cloud.aiplatform.v1beta1.stub;

import static com.google.cloud.aiplatform.v1beta1.FeaturestoreOnlineServingServiceClient.ListLocationsPagedResponse;

import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.aiplatform.v1beta1.ReadFeatureValuesRequest;
import com.google.cloud.aiplatform.v1beta1.ReadFeatureValuesResponse;
import com.google.cloud.aiplatform.v1beta1.StreamingReadFeatureValuesRequest;
import com.google.cloud.aiplatform.v1beta1.WriteFeatureValuesRequest;
import com.google.cloud.aiplatform.v1beta1.WriteFeatureValuesResponse;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * Base stub class for the FeaturestoreOnlineServingService service API.
 *
 * <p>This class is for advanced usage and reflects the underlying API directly.
 */
@BetaApi
@Generated("by gapic-generator-java")
public abstract class FeaturestoreOnlineServingServiceStub implements BackgroundResource {

  public UnaryCallable<ReadFeatureValuesRequest, ReadFeatureValuesResponse>
      readFeatureValuesCallable() {
    throw new UnsupportedOperationException("Not implemented: readFeatureValuesCallable()");
  }

  public ServerStreamingCallable<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse>
      streamingReadFeatureValuesCallable() {
    throw new UnsupportedOperationException(
        "Not implemented: streamingReadFeatureValuesCallable()");
  }

  public UnaryCallable<WriteFeatureValuesRequest, WriteFeatureValuesResponse>
      writeFeatureValuesCallable() {
    throw new UnsupportedOperationException("Not implemented: writeFeatureValuesCallable()");
  }

  public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
      listLocationsPagedCallable() {
    throw new UnsupportedOperationException("Not implemented: listLocationsPagedCallable()");
  }

  public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() {
    throw new UnsupportedOperationException("Not implemented: listLocationsCallable()");
  }

  public UnaryCallable<GetLocationRequest, Location> getLocationCallable() {
    throw new UnsupportedOperationException("Not implemented: getLocationCallable()");
  }

  public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() {
    throw new UnsupportedOperationException("Not implemented: setIamPolicyCallable()");
  }

  public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() {
    throw new UnsupportedOperationException("Not implemented: getIamPolicyCallable()");
  }

  public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
      testIamPermissionsCallable() {
    throw new UnsupportedOperationException("Not implemented: testIamPermissionsCallable()");
  }

  @Override
  public abstract void close();
}


text:
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability

class DeviceCpuHourlyRemote(RemoteModel):
    """
    Contains hourly summaries of device CPU statistics.

    |  ``DeviceCpuHourlyID:`` The internal NetMRI identifier for this Device CPU Hourly record.
    |  ``attribute type:`` number

    |  ``DataSourceID:`` The internal NetMRI identifier for the collector NetMRI that collected this data record.
    |  ``attribute type:`` number

    |  ``DeviceID:`` The internal NetMRI identifier for the device from which this record was collected.
    |  ``attribute type:`` number

    |  ``StartTime:`` The starting date/time for the hourly interval.
    |  ``attribute type:`` datetime

    |  ``CpuIndex:`` The CPU number.
    |  ``attribute type:`` number

    |  ``CpuBusyMin:`` The minimum CPU busy reading during the hour.
    |  ``attribute type:`` number

    |  ``CpuBusyAvg:`` The mean CPU busy reading during the hour.
    |  ``attribute type:`` float

    |  ``CpuBusyMax:`` The maximum CPU busy reading during the hour.
    |  ``attribute type:`` number

    """

    properties = ("DeviceCpuHourlyID",
                  "DataSourceID",
                  "DeviceID",
                  "StartTime",
                  "CpuIndex",
                  "CpuBusyMin",
                  "CpuBusyAvg",
                  "CpuBusyMax",
                  )

    @property
    @check_api_availability
    def data_source(self):
        """
        The collector NetMRI that collected this data record.
        ``attribute type:`` model
        """
        return self.broker.data_source(**{"DeviceCpuHourlyID": self.DeviceCpuHourlyID})

    @property
    @check_api_availability
    def device(self):
        """
        The device from which this data was collected.
        ``attribute type:`` model
        """
        return self.broker.device(**{"DeviceCpuHourlyID": self.DeviceCpuHourlyID})

    @property
    @check_api_availability
    def infradevice(self):
        """
        The device from which this data was collected.
        ``attribute type:`` model
        """
        return self.broker.infradevice(**{"DeviceCpuHourlyID": self.DeviceCpuHourlyID})


text:
StartTest(function (t) {
    t.getHarness([
        {
            preload : [
                '../../../extjs-5.1.0/packages/ext-theme-crisp/build/resources/ext-theme-crisp-all.css',
                '../../../extjs-5.1.0/build/ext-all-debug.js'
            ],
            url     : 'testfiles/604_extjs_components.t.js'
        }
    ]);

    t.chain([
        { waitFor : 'harnessReady' },

        { action : "dblclick", target : "#SiestaSelf-testTree => .x-grid-row:nth-child(1) > .x-grid-cell:nth-child(1)" },

        { waitFor : 'HarnessIdle' },

        { action : "click", target : "toolbar => .cmp-inspector" },

        { action : "moveCursorTo", target : ">>#SiestaSelf-resultpanel-domContainer", offset : [42, 20] },

        {
            desc    : 'Inspector box at cursor',
            waitFor :  function () {
                var EXT                 = Ext.query('iframe.tr-iframe')[ 0 ].contentWindow.Ext

                var buttonInInnerTest   = EXT.ComponentQuery.query('[text=Foo]')[0];
                var domContainer        = t.cq1('domcontainer');
                var boxEl               = Ext.getBody().down('.target-inspector-box');

                return t.compareObjects({
                    width       : buttonInInnerTest.el.getWidth() + 5,
                    height      : buttonInInnerTest.getHeight() + 5,
                    x           : buttonInInnerTest.getX(),
                    y           : buttonInInnerTest.getY()
                }, {
                    width       : t.anyNumberApprox(boxEl.getWidth(), 5),
                    height      : t.anyNumberApprox(boxEl.getHeight(), 5),
                    x           : t.anyNumberApprox(boxEl.getX() - domContainer.getX() - 5, 5),
                    y           : t.anyNumberApprox(boxEl.getY() - domContainer.getY() - 5, 5)
                })
            }
        }
    ]);
});


text:
const gulp = require('gulp');
const debug = require('debug')('gulp');

gulp.task('copy-deps', () => {
	if (process.env.NODE_ENV === 'production') {
		debug('In production, nothing to do');
		return;
	}
	const vfs = require('vinyl-fs');
	const merge = require('merge-stream');
	return merge(
		vfs.src('./node_modules/bootstrap/dist/css/**/*.min.*').pipe(gulp.dest('./public/css/bootstrap')),
		vfs.src('./node_modules/bootstrap/dist/fonts/**/*').pipe(gulp.dest('./public/css/fonts')),
		vfs.src('./node_modules/bootstrap/dist/js/**/*.min.*').pipe(gulp.dest('./public/js/bootstrap')),
		vfs.src('./node_modules/jquery/dist/**/*.min.*').pipe(gulp.dest('./public/js/jquery')),
		vfs.src('./node_modules/cldr-data/main/en/numbers.json').pipe(gulp.dest('./controls/cldr-data/main/en')),
		vfs.src('./node_modules/cldr-data/main/vi/numbers.json').pipe(gulp.dest('./controls/cldr-data/main/vi')),
		vfs.src('./node_modules/cldr-data/supplemental/numberingSystems.json').pipe(gulp.dest('./controls/cldr-data/supplemental')),
		vfs.src('./node_modules/cldr-data/supplemental/likelySubtags.json').pipe(gulp.dest('./controls/cldr-data/supplemental'))
	);
});


text:
import { fireEvent, render, screen } from '@testing-library/react';
import { expect } from 'chai';
import { destroy, protect, unprotect } from 'mobx-state-tree';
import * as sinon from 'sinon';

import { URLExt } from '../../libs/utils';
import { Store, StoreProvider } from '../../store';
import { SearchTarget } from '../../store/search_page';
import { SearchPage } from '.';

describe('SearchPage', () => {
  let timer: sinon.SinonFakeTimers;
  beforeEach(() => {
    timer = sinon.useFakeTimers();
  });
  afterEach(() => {
    timer.restore();
    const url = `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
    window.history.replaceState(null, '', url);
  });

  it('should throttle search query updates', () => {
    const store = Store.create({});
    after(() => destroy(store));
    unprotect(store);
    const setSearchQuerySpy = sinon.spy(store.searchPage, 'setSearchQuery');
    protect(store);

    render(
      <StoreProvider value={store}>
        <SearchPage />
      </StoreProvider>
    );

    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'builder' } });
    timer.tick(10);
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'builder-id' } });
    timer.tick(10);
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'builder-id-with-suffix' } });
    timer.tick(300);
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'another-builder' } });
    timer.tick(10);
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'another-builder-id' } });
    timer.runAll();

    expect(setSearchQuerySpy.callCount).to.eq(2);
    expect(setSearchQuerySpy.getCall(0).args).to.deep.eq(['builder-id-with-suffix']);
    expect(setSearchQuerySpy.getCall(1).args).to.deep.eq(['another-builder-id']);
  });

  it('should cancel search query updates when switching search targets', () => {
    const store = Store.create({});
    after(() => destroy(store));
    unprotect(store);
    const setSearchQuerySpy = sinon.spy(store.searchPage, 'setSearchQuery');
    protect(store);

    render(
      <StoreProvider value={store}>
        <SearchPage />
      </StoreProvider>
    );

    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'builder' } });
    timer.tick(10);
    store.searchPage.setSearchTarget(SearchTarget.Tests);
    timer.tick(10);
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'test-id' } });
    timer.runAll();

    expect(setSearchQuerySpy.callCount).to.eq(1);
    expect(setSearchQuerySpy.getCall(0).args).to.deep.eq(['test-id']);
  });

  it('should read params from URL', async () => {
    const url = new URLExt(window.location.href)
      .setSearchParam('t', SearchTarget.Tests)
      .setSearchParam('tp', 'project')
      .setSearchParam('q', 'query');
    window.history.replaceState(null, '', url);

    const store = Store.create({});
    after(() => destroy(store));

    render(
      <StoreProvider value={store}>
        <SearchPage />
      </StoreProvider>
    );

    expect(store.searchPage.searchTarget).to.eq(SearchTarget.Tests);
    expect(store.searchPage.testProject).to.eq('project');
    expect(store.searchPage.searchQuery).to.eq('query');

    // Ensure that the filters are not overwritten after all event hooks are
    // executed.
    await timer.runAllAsync();

    expect(store.searchPage.searchTarget).to.eq(SearchTarget.Tests);
    expect(store.searchPage.testProject).to.eq('project');
    expect(store.searchPage.searchQuery).to.eq('query');
  });

  it('should sync params with URL', async () => {
    const store = Store.create({});
    after(() => destroy(store));

    render(
      <StoreProvider value={store}>
        <SearchPage />
      </StoreProvider>
    );

    expect(window.location.search).to.eq('');
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'query' } });
    store.searchPage.setSearchTarget(SearchTarget.Tests);
    store.searchPage.setTestProject('project');

    await timer.runAllAsync();

    expect(window.location.search).to.eq('?t=TESTS&tp=project&q=query');
  });
});


text:
namespace gsystem { // gsystem

GCriticalSection::GCriticalSection()
{
	Initialize(false, 0);
}

GCriticalSection::GCriticalSection(gbool spin, gsize spin_count)
{
	Initialize(spin, spin_count);
}

GCriticalSection::~GCriticalSection()
{
	Release();
}

gvoid GCriticalSection::Lock()
{
	::EnterCriticalSection((CRITICAL_SECTION*)m_pHandle);
}

gvoid GCriticalSection::Unlock()
{
	::LeaveCriticalSection((CRITICAL_SECTION*)m_pHandle);
}

gvoid GCriticalSection::Initialize(gbool spin, gsize spin_count)
{
	if (spin)
	{
		::InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION*)m_pHandle, spin_count);
	}
	else
	{
		::InitializeCriticalSection((CRITICAL_SECTION*)m_pHandle);
	}
}

gvoid GCriticalSection::Release()
{
	::DeleteCriticalSection((CRITICAL_SECTION*)m_pHandle);
}

} // namespace gsystem


text:
require File.dirname(__FILE__) + "/../lib/timestamped_field"

require 'rubygems'
require 'sqlite3'
require 'active_record'

ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database  => ':memory:'
ActiveRecord::Migration.verbose = false

ActiveRecord::Schema.define do
  create_table :users, :force => true do |t|
    t.boolean  :foo
    t.datetime :foo_changed_at

    t.string :name
    t.datetime :name_changed_at

    t.timestamps
  end
end

class User < ActiveRecord::Base
end


text:
require "climate_control/errors"
require "climate_control/version"
require "monitor"

module ClimateControl
  extend self
  extend Gem::Deprecate

  SEMAPHORE = Monitor.new
  private_constant :SEMAPHORE

  def modify(environment_overrides = {}, &block)
    environment_overrides = environment_overrides.transform_keys(&:to_s)

    SEMAPHORE.synchronize do
      previous = ENV.to_hash

      begin
        copy environment_overrides
      ensure
        middle = ENV.to_hash
      end

      block.call
    ensure
      after = ENV
      (previous.keys | middle.keys | after.keys).each do |key|
        if previous[key] != after[key] && middle[key] == after[key]
          ENV[key] = previous[key]
        end
      end
    end
  end

  def unsafe_modify(environment_overrides = {}, &block)
    environment_overrides = environment_overrides.transform_keys(&:to_s)

    previous = ENV.to_hash

    begin
      copy environment_overrides
    ensure
      middle = ENV.to_hash
    end

    block.call
  ensure
    after = ENV
    (previous.keys | middle.keys | after.keys).each do |key|
      if previous[key] != after[key] && middle[key] == after[key]
        ENV[key] = previous[key]
      end
    end
  end

  def env
    ENV
  end

  deprecate :env, "ENV", 2022, 10

  private

  def copy(overrides)
    overrides.each do |key, value|
      ENV[key] = value
    rescue TypeError => e
      raise UnassignableValueError,
        "attempted to assign #{value} to #{key} but failed (#{e.message})"
    end
  end
end


text:
package net.systran.platform.resources.client.model;

import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty;

@ApiModel(description = "")
public class DictionariesImportResponse  {

  private Integer duplicates = null;
  private Integer inserted = null;
  private Integer total = null;

  /**
   * Number of entries that was already present in the dictionary
   **/
  @ApiModelProperty(value = "Number of entries that was already present in the dictionary")
  @JsonProperty("duplicates")
  public Integer getDuplicates() {
    return duplicates;
  }
  public void setDuplicates(Integer duplicates) {
    this.duplicates = duplicates;
  }

  /**
   * Number of entries succesfully inserted
   **/
  @ApiModelProperty(value = "Number of entries succesfully inserted")
  @JsonProperty("inserted")
  public Integer getInserted() {
    return inserted;
  }
  public void setInserted(Integer inserted) {
    this.inserted = inserted;
  }

  /**
   * Number of entries processed
   **/
  @ApiModelProperty(value = "Number of entries processed")
  @JsonProperty("total")
  public Integer getTotal() {
    return total;
  }
  public void setTotal(Integer total) {
    this.total = total;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class DictionariesImportResponse {\n");

    sb.append("  duplicates: ").append(duplicates).append("\n");
    sb.append("  inserted: ").append(inserted).append("\n");
    sb.append("  total: ").append(total).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
title: Serve static content on Nginx
comments: true
---

This blog is about serving static content on Nginx.

### Configure Nginx config file

Nginx config file located under '/etc/nginx' and you can check this link for full example of nginx configuration file. [Full example of nginx config file](https://www.nginx.com/resources/wiki/start/topics/examples/full/)

{% highlight bash %}
$ sudo vi /etc/nginx/nginx.conf
{% endhighlight %}

and add this under http tag.

server { # simple reverse-proxy
  listen       80;
  server_name  www.utkusonmez.com utkusonmez.com ;

  # serve static files
  location /  {
    root    /var/www/utkusonmez.com/;
    expires 1m;
  }
}

Reload your nginx config.

{% highlight bash %}
$ sudo systemctl reload nginx
{% endhighlight %}

and check your site.


text:
import {log} from './log';
import {timer} from './timer';

let TAG_ = 'retriablePromise';

/**
 * Creates a retriable promise. This promise will retry the work the number of
 * times up to value specified by maxAttempts.
 * @param {!function():!Promise<TYPE>} exec Performs the retriable work and
 *   returns the promise for the attempt.
 * @param {number} maxAttempts Maximum number of attempts to try the execution.
 * @param {number} delay The default delay before the next attempt is made.
 * @param {boolean} backoffFactor The backoff factor for each consequent
 *   attempt.
 * @return {!goog.Promise<TYPE>}
 * @template TYPE
 */
export function retriablePromise(exec, maxAttempts, delay, backoffFactor) {
  return new Promise((resolve, reject) => {
    attempt_(exec, resolve, reject, maxAttempts - 1, delay, backoffFactor);
  });
}

/**
 * @param {!function():!Promise<TYPE>} exec
 * @param {!function(TYPE)} resolve
 * @param {!function(*)} reject
 * @param {number} maxAttempts
 * @param {number} delay
 * @param {boolean} backoffFactor
 * @private
 */
function attempt_(exec, resolve, reject, attemptsLeft, nextDelay,
                  backoffFactor) {
  log.fine(TAG_, 'attempts left: ' + attemptsLeft);
  exec().then((result) => {
    log.fine(TAG_, 'success');
    resolve(result);
  }, (reason) => {
    log.fine(TAG_, 'attempt failed: ' + reason);
    if (attemptsLeft <= 0) {
      log.fine(TAG_, 'out of attempts');
      reject(reason);
    } else {
      // TODO(dvoytenko): not all errors retriable
      var nextNextDelay = (nextDelay * backoffFactor / 2) *
          (1 + Math.random());
      timer.delay(() => {
        attempt_(exec, resolve, reject, attemptsLeft - 1,
            nextNextDelay, backoffFactor);
      }, nextDelay);
    }
  });
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace OneChess
{
    public static class Stage
    {
        public static string user1 = "White", user2 = "Black";
        private static SpriteFont font, Fporcent;
        private static Texture2D Back, porcent, shade, frame, avatar;
        public static List<Texture2D>[] token = new List<Texture2D>[2];
        private static int[,] amount = new int[2, 5];
        private static int[,] Pox = new int[2, 5];
        private static int row;
        private static Texture2D[] shelf;
        public static Viewport view;
        private static char[] cad;
        private static Vector2[] pos;
        private static Vector2 vuser;
        private static Rectangle Fsize, Asize;
        private static Stopwatch count, count2;
        //Variables reservadas
        public static bool New = false, exit = false,
         start = true, check = false, starman = true,
         showturn = true, switchframe = true, style = false,
         showname = true;

        //check
        #region check

        /// <summary>
        /// Inicio de la animación para una cadena cuando ocurra el evento Check o Check Mate
        /// </summary>
        /// <param name="Checkmode">Cadena del  mensaje en un vector de caracteres</param>
        public static void Begin(char[] Checkmode)
        {
            cad = new char[Checkmode.Length];
            pos = new Vector2[Checkmode.Length];

            for (int c = 0; c < Checkmode.Length; c++)
                cad[c] = Checkmode[c];

            for (int i = 0; i < Checkmode.Length; i++)
                pos[i] = new Vector2(820 + (i * 100), 200);

            count = new Stopwatch(); count = Stopwatch.StartNew();
        }
        /// <summary>
        /// Transcurre la animación
        /// </summary>
        public static void Animate_Check()
        {
            for (int i = 0; i < cad.Length; i++) if (pos[i].X > view.Width / 2 - 130 + i * 20)
                    pos[i].X -= 10;

            if (count.Elapsed.Seconds > 2)
            {
                for (int i = 0; i < cad.Length; i++)
                    if (pos[i].X > -30)
                        pos[i].X -= 35.5f / (i + 1);
                if (count.Elapsed.Seconds > 6) check = false;
            }
        }
        /// <summary>
        /// Imprime la animación en la pantalla
        /// </summary>
        /// <param name="spriteBatch">SpriteBatch</param>
        public static void DrawCheck(SpriteBatch spriteBatch)
        {
            for (int i = 0; i < cad.Length; i++)
                spriteBatch.DrawString(font, cad[i].ToString(), pos[i], i % 2 == 0 ? Color.White : Color.Black);
        }
        #endregion

        public static void Tokinst()
        {
            token[0] = new List<Texture2D>();
            token[1] = new List<Texture2D>();
            amount = new int[2, 5];
        }
        public static void LoadComponents(ContentManager Content)
        {
            Tokinst();
            avatar = Ask.White.King.Texture;
            Back = Content.Load<Texture2D>("Back");
            frame = Content.Load<Texture2D>("Frame");
            porcent = shade = Content.Load<Texture2D>("porcent");
            shelf = new Texture2D[2];
            Fporcent = Content.Load<SpriteFont>("Fporcent");
            font = Content.Load<SpriteFont>("Font");
            for (int n = 0; n < 2; n++)
                shelf[n] = Content.Load<Texture2D>("Shelf_" + n);
        }
        public static void Abegin()
        {
            for (int n = 0; n < 2; n++) vuser = new Vector2(-frame.Width + 50, frame.Height / 2 + 15);
            Fsize = new Rectangle(-frame.Width, 0, frame.Width, frame.Height);
            Asize = new Rectangle(-avatar.Width - 20, frame.Height / 10, avatar.Width / 2, avatar.Height / 4);
            count2 = new Stopwatch();
            count2 = Stopwatch.StartNew();
        }
        public static void Animation()
        {
            if (count2.Elapsed.Seconds < 1 && Fsize.X < 0) { Fsize.X += 5; Asize.X += 5; vuser.X += 5; }
            else if (count2.Elapsed.Seconds > 0 && Fsize.X > -Fsize.Width) { Fsize.X -= 5; Asize.X -= 5; vuser.X -= 5; }
        }
        public static void EarnedToken(Texture2D tok, int m)
        {
            if (tracing(tok, row = m)) token[m].Add(tok);
        }
        public static void DrawComponents(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(Ask.Dot.Token.Texture, Ask.Dot.Token.Size, Ask.Dot.Token.Color);
            spriteBatch.Draw(Back, new Rectangle(575, 0, Back.Width - 20, Back.Height), Color.Red);
            for (int n = 0; n < 2; n++) spriteBatch.Draw(shelf[n], new Rectangle(583, 340 + (n * 70), shelf[n].Width, shelf[n].Height), Color.White);
            for (int r = 0; r < 2; r++)
                if (token[r].Count > 0)
                    for (int c = 0; c < token[r].Count; c++)
                        spriteBatch.Draw(token[r][c], new Rectangle(620 + (c * 30), 430 - (r * 70), 20, 37), r == 1 ? Color.LightGoldenrodYellow : Color.Gray);
            Drawamount(spriteBatch);
            spriteBatch.Draw(porcent, new Rectangle(635, 410, 100, porcent.Height - 3), Color.Black);
            spriteBatch.Draw(porcent, new Rectangle(635, 410, (int)Ask.Black.Earn, porcent.Height - 3), Color.Red);
            spriteBatch.Draw(porcent, new Rectangle(635, 410, (int)Ask.White.Earn, porcent.Height - 3), Color.White);
            spriteBatch.Draw(porcent, new Rectangle(635, 341, 100, porcent.Height - 3), Color.Black);
            spriteBatch.Draw(porcent, new Rectangle(635, 341, (int)Ask.White.Earn, porcent.Height - 3), Color.Red);
            spriteBatch.Draw(porcent, new Rectangle(635, 341, (int)Ask.Black.Earn, porcent.Height - 3), Color.White);
            spriteBatch.DrawString(Fporcent, (int)Ask.White.Earn + "%", new Vector2(680, 410), Color.White);
            spriteBatch.DrawString(Fporcent, (int)Ask.Black.Earn + "%", new Vector2(680, 341), Color.White);
            if (showturn)
            {
                spriteBatch.Draw(frame, Fsize, Ask.Turn ? Color.Red : Color.SlateBlue);
                spriteBatch.Draw(avatar, Asize, Ask.Turn ? Color.LightGoldenrodYellow : Color.Gray);
                spriteBatch.DrawString(font, Ask.Turn ? user1 : user2, vuser, Color.White);
            }
        }
        private static void Drawamount(SpriteBatch spriteBatch)
        {
            for (int r = 0; r < 2; r++)
                for (int n = 0; n < token[r].Count; n++)
                    if (amount[r, n] > 0)
                    {
                        spriteBatch.Draw(frame, new Rectangle(635 + (Pox[r, n] * 30), 425 - (r * 70), 14, 13), Color.Black);
                        spriteBatch.DrawString(Fporcent, "x" + (amount[r, n] + 1), new Vector2(635 + (Pox[r, n] * 30), 425 - (r * 70)), Color.White);
                    }
        }
        public static bool tracing(Texture2D tok, int row)
        {
            for (int c = 0; c < token[row].Count; c++)
                if (tok.Equals(token[row][c]))
                {
                    Pox[row, c] = c;
                    amount[row, c]++; return false;
                }
            return true;
        }
    }
}


text:
package handlers

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"

	"github.com/gorilla/csrf"

	"github.com/resourced/resourced-master/libhttp"
	"github.com/resourced/resourced-master/models/cassandra"
)

func GetGraphs(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	currentUser := r.Context().Value("currentUser").(*cassandra.UserRow)

	currentCluster := r.Context().Value("currentCluster").(*cassandra.ClusterRow)

	graphs, err := cassandra.NewGraph(r.Context()).AllByClusterID(currentCluster.ID)
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	data := struct {
		CSRFToken      string
		Addr           string
		CurrentUser    *cassandra.UserRow
		Clusters       []*cassandra.ClusterRow
		CurrentCluster *cassandra.ClusterRow
		Graphs         []*cassandra.GraphRow
	}{
		csrf.Token(r),
		r.Context().Value("Addr").(string),
		currentUser,
		r.Context().Value("clusters").([]*cassandra.ClusterRow),
		currentCluster,
		graphs,
	}

	var tmpl *template.Template

	currentUserPermission := currentCluster.GetLevelByUserID(currentUser.ID)
	if currentUserPermission == "read" {
		tmpl, err = template.ParseFiles("templates/dashboard.html.tmpl", "templates/graphs/list-readonly.html.tmpl")
	} else {
		tmpl, err = template.ParseFiles("templates/dashboard.html.tmpl", "templates/graphs/list.html.tmpl")
	}
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	tmpl.Execute(w, data)
}

func PostGraphs(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	currentCluster := r.Context().Value("currentCluster").(*cassandra.ClusterRow)

	name := r.FormValue("Name")
	description := r.FormValue("Description")
	range_ := r.FormValue("Range")

	data := make(map[string]interface{})
	data["name"] = name
	data["description"] = description
	data["range"] = range_

	_, err := cassandra.NewGraph(r.Context()).Create(currentCluster.ID, data)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	http.Redirect(w, r, "/graphs", 301)
}

func GetPostPutDeleteGraphsID(w http.ResponseWriter, r *http.Request) {
	method := r.FormValue("_method")

	if method == "" || method == "get" {
		GetGraphsID(w, r)
	} else if method == "post" || method == "put" {
		PutGraphsID(w, r)
	} else if method == "delete" {
		DeleteGraphsID(w, r)
	}
}

func GetGraphsID(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	currentUser := r.Context().Value("currentUser").(*cassandra.UserRow)

	currentCluster := r.Context().Value("currentCluster").(*cassandra.ClusterRow)

	id, err := getInt64SlugFromPath(w, r, "id")
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	accessToken, err := getAccessToken(w, r, "read")
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	// -----------------------------------
	// Create channels to receive SQL rows
	// -----------------------------------
	metricsChan := make(chan *cassandra.MetricRowsWithError)
	defer close(metricsChan)

	graphsChan := make(chan *cassandra.GraphRowsWithError)
	defer close(graphsChan)

	// --------------------------
	// Fetch SQL rows in parallel
	// --------------------------
	go func(currentCluster *cassandra.ClusterRow, id int64) {
		graphsWithError := &cassandra.GraphRowsWithError{}
		graphsWithError.Graphs, graphsWithError.Error = cassandra.NewGraph(r.Context()).AllByClusterID(currentCluster.ID)
		graphsChan <- graphsWithError
	}(currentCluster, id)

	go func(currentCluster *cassandra.ClusterRow) {
		metricsWithError := &cassandra.MetricRowsWithError{}
		metricsWithError.Metrics, metricsWithError.Error = cassandra.NewMetric(r.Context()).AllByClusterID(currentCluster.ID)
		metricsChan <- metricsWithError
	}(currentCluster)

	// -----------------------------------
	// Wait for channels to return results
	// -----------------------------------
	hasError := false

	metricsWithError := <-metricsChan
	if metricsWithError.Error != nil {
		libhttp.HandleErrorJson(w, metricsWithError.Error)
		hasError = true
	}

	var currentGraph *cassandra.GraphRow
	graphsWithError := <-graphsChan
	if graphsWithError.Error == nil {
		for _, graph := range graphsWithError.Graphs {
			if graph.ID == id {
				currentGraph = graph
				break
			}
		}
	} else {
		libhttp.HandleErrorJson(w, graphsWithError.Error)
		hasError = true
	}

	if hasError {
		return
	}

	data := struct {
		CSRFToken      string
		Addr           string
		CurrentUser    *cassandra.UserRow
		AccessToken    *cassandra.AccessTokenRow
		Clusters       []*cassandra.ClusterRow
		CurrentCluster *cassandra.ClusterRow
		CurrentGraph   *cassandra.GraphRow
		Graphs         []*cassandra.GraphRow
		Metrics        []*cassandra.MetricRow
	}{
		csrf.Token(r),
		r.Context().Value("Addr").(string),
		currentUser,
		accessToken,
		r.Context().Value("clusters").([]*cassandra.ClusterRow),
		currentCluster,
		currentGraph,
		graphsWithError.Graphs,
		metricsWithError.Metrics,
	}

	var tmpl *template.Template

	currentUserPermission := currentCluster.GetLevelByUserID(currentUser.ID)
	if currentUserPermission == "read" {
		tmpl, err = template.ParseFiles("templates/dashboard.html.tmpl", "templates/graphs/dashboard-readonly.html.tmpl")
	} else {
		tmpl, err = template.ParseFiles("templates/dashboard.html.tmpl", "templates/graphs/dashboard.html.tmpl")
	}
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	tmpl.Execute(w, data)
}

func PutGraphsID(w http.ResponseWriter, r *http.Request) {
	id, err := getInt64SlugFromPath(w, r, "id")
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	err = r.ParseForm()
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	name := r.FormValue("Name")
	description := r.FormValue("Description")
	range_ := r.FormValue("Range")

	data := make(map[string]string)
	if name != "" {
		data["name"] = name
	}
	if description != "" {
		data["description"] = description
	}
	if range_ != "" {
		data["range"] = range_
	}

	metricsJSON := r.FormValue("MetricsWithOrder")
	if metricsJSON != "" {
		data["metrics"] = metricsJSON
	}

	if len(data) > 0 {
		_, err = cassandra.NewGraph(r.Context()).UpdateByID(id, data)
		if err != nil {
			libhttp.HandleErrorHTML(w, err, 500)
			return
		}
	}

	http.Redirect(w, r, fmt.Sprintf("/graphs/%v", id), 301)
}

func DeleteGraphsID(w http.ResponseWriter, r *http.Request) {
	currentCluster := r.Context().Value("currentCluster").(*cassandra.ClusterRow)

	id, err := getInt64SlugFromPath(w, r, "id")
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	err = cassandra.NewGraph(r.Context()).DeleteByClusterIDAndID(currentCluster.ID, id)
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	http.Redirect(w, r, "/graphs", 301)
}

func PutApiGraphsIDMetrics(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	accessTokenRow := r.Context().Value("accessToken").(*cassandra.AccessTokenRow)

	id, err := getInt64SlugFromPath(w, r, "id")
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	dataJSON, err := ioutil.ReadAll(r.Body)
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	row, err := cassandra.NewGraph(r.Context()).UpdateMetricsByClusterIDAndID(accessTokenRow.ClusterID, id, dataJSON)

	rowJSON, err := json.Marshal(row)
	if err != nil {
		libhttp.HandleErrorHTML(w, err, 500)
		return
	}

	w.Write(rowJSON)
}


text:
namespace net {

MappedHostResolver::MappedHostResolver(scoped_ptr<HostResolver> impl)
    : impl_(impl.Pass()) {
}

MappedHostResolver::~MappedHostResolver() {
}

int MappedHostResolver::Resolve(const RequestInfo& original_info,
                                RequestPriority priority,
                                AddressList* addresses,
                                const CompletionCallback& callback,
                                RequestHandle* out_req,
                                const BoundNetLog& net_log) {
  RequestInfo info = original_info;
  int rv = ApplyRules(&info);
  if (rv != OK)
    return rv;

  return impl_->Resolve(info, priority, addresses, callback, out_req, net_log);
}

int MappedHostResolver::ResolveFromCache(const RequestInfo& original_info,
                                         AddressList* addresses,
                                         const BoundNetLog& net_log) {
  RequestInfo info = original_info;
  int rv = ApplyRules(&info);
  if (rv != OK)
    return rv;

  return impl_->ResolveFromCache(info, addresses, net_log);
}

void MappedHostResolver::CancelRequest(RequestHandle req) {
  impl_->CancelRequest(req);
}

void MappedHostResolver::SetDnsClientEnabled(bool enabled) {
  impl_->SetDnsClientEnabled(enabled);
}

HostCache* MappedHostResolver::GetHostCache() {
  return impl_->GetHostCache();
}

base::Value* MappedHostResolver::GetDnsConfigAsValue() const {
  return impl_->GetDnsConfigAsValue();
}

int MappedHostResolver::ApplyRules(RequestInfo* info) const {
  HostPortPair host_port(info->host_port_pair());
  if (rules_.RewriteHost(&host_port)) {
    if (host_port.host() == "~NOTFOUND")
      return ERR_NAME_NOT_RESOLVED;
    info->set_host_port_pair(host_port);
  }
  return OK;
}

}  // namespace net