text:
import TranslationsProvider from '../../_locales/_provider';

global.TranslationProvider = new TranslationsProvider();

if (global.HTMLSpanElement) {
  const createTranslationElement = (originalElement, elementTag) => {
    const TranslationProto = Object.create(originalElement.prototype);

    TranslationProto.createdCallback = function createdCallback() {
      this._key = this.textContent;
      this.innerHTML = TranslationProvider.query(this.textContent);
    };
    TranslationProto.setKey = function setKey(newKey) {
      this._key = newKey;
      this.innerHTML = TranslationProvider.query(newKey);
    };
    TranslationProto.getKey = function getKey() {
      return this._key;
    };

    window.ThumbImage = document.registerElement(`translation-key${elementTag === 'span' ? '' : `-${elementTag}`}`, {
      prototype: TranslationProto,
      extends: elementTag,
    });
  };

  createTranslationElement(HTMLSpanElement, 'span');
  createTranslationElement(HTMLParagraphElement, 'p');
  createTranslationElement(HTMLHeadingElement, 'h4');
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import _ from 'lodash';
import cx from 'classnames';
import moment from 'moment-timezone';
import { translate, Trans } from 'react-i18next';

const JS_DATE_FORMAT = 'YYYY-MM-DD';

export default translate()(class Export extends Component {
  static propTypes = {
    api: React.PropTypes.object.isRequired,
    patient: React.PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);

    const endDate = moment().format(JS_DATE_FORMAT);
    this.state = {
      allTime: false,
      endDate,
      startDate: moment(endDate)
        .subtract(30, 'd')
        .format(JS_DATE_FORMAT),
      anonymizeData: false,
      format: 'json',
      extraExpanded: false,
      error: false,
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.toggleOptions = this.toggleOptions.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    this.setState({ error: null });
    let options = _.pick(this.state, [
      'endDate',
      'startDate',
      'anonymizeData',
      'format',
    ]);
    if (this.state.allTime) {
      options = _.omit(options, ['endDate', 'startDate']);
    } else {
      options.endDate = moment.utc(this.state.endDate).toISOString();
      options.startDate = moment.utc(this.state.startDate).toISOString();
    }

    this.props.api.tidepool.getExportDataURL(
      this.props.patient.userid,
      options,
      (err, url) => {
        if (err) {
          this.setState({ error: err });
          return;
        }
        let a = document.createElement('a');
        a.style = 'display: none';
        document.body.appendChild(a);
        a.href = url;
        a.click();
        a.remove();
      }
    );
  }

  handleInputChange(event) {
    const target = event.target;
    let value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    if (name === 'startDate') {
      if (moment(value).isAfter(this.state.endDate)) {
        value = this.state.endDate;
      }
    }
    if (name === 'endDate') {
      if (moment(value).isBefore(this.state.startDate)) {
        value = this.state.startDate;
      }
      if (moment(value).isAfter(moment())) {
        value = moment().format(JS_DATE_FORMAT);
      }
    }

    this.setState({
      [name]: value
    });
  }

  toggleOptions() {
    this.setState({
      extraExpanded: !this.state.extraExpanded
    });
  }

  setDateRange(range) {
    const endDate = moment().format(JS_DATE_FORMAT);
    const startDate = moment(endDate)
      .subtract(range, 'd')
      .format(JS_DATE_FORMAT);
    this.setState({
      allTime: false,
      endDate,
      startDate,
    });
  }

  render() {
    /* TODO: for upcoming export service support of anonymization
    const extraClassnames = cx({
      hidden: !this.state.extraExpanded,
      'Export-optionEntry': true
    });
    const norgieClasses = cx({
      norgie: true,
      opened: this.state.extraExpanded,
    });
    */

    let errDisplay = null;
    if (this.state.error) {
      errDisplay = (

            An error occured attempting to export your data. This may be
            temporary and you can try the export again. If the error continues,
            please contact support.

            Details:{' '}
            {this.state.error.message
              ? this.state.error.message
              : this.state.error.toString()}

      );
    }
    return (

        <form onSubmit={this.handleSubmit}>

Export my data from:

            <input
              name="startDate"
              type="date"
              disabled={this.state.allTime}
              value={this.state.startDate}
              onChange={this.handleInputChange}
            />

 to

            <input
              name="endDate"
              type="date"
              disabled={this.state.allTime}
              value={this.state.endDate}
              onChange={this.handleInputChange}
            />

             this.setState({ allTime: true })}>All Data |
             this.setDateRange(90)}>Last 90 Days |
             this.setDateRange(30)}>Last 30 Days |
             this.setDateRange(14)}>Last 14 Days

            File type:
            <input
              name="format"
              type="radio"
              value="excel"
              checked={this.state.format === 'excel'}
              onChange={this.handleInputChange}
            />{' '}
            Excel
            <input
              name="format"
              type="radio"
              value="json"
              checked={this.state.format === 'json'}
              onChange={this.handleInputChange}
            />{' '}
            JSON

          {/* TODO: for upcoming export service support of anonymization

            Optional export settings

                <input
                  name="anonymizeData"
                  type="checkbox"
                  checked={this.state.anonymizeData}
                  onChange={this.handleInputChange}
                />
                Anonymize my exported diabetes data

This will remove personally identifying information as well as any device make, model, and serial number from the export.

          */}

            <input className="btn btn-primary" type="submit" value="Export" />

        </form>
        {errDisplay}

    );
  }
});


text:
namespace android.webkit
{
	[global::MonoJavaBridge.JavaInterface(typeof(global::android.webkit.UrlInterceptHandler_))]
	public partial interface UrlInterceptHandler  : global::MonoJavaBridge.IJavaObject
	{
		global::android.webkit.CacheManager.CacheResult service(java.lang.String arg0, java.util.Map arg1);
		global::android.webkit.PluginData getPluginData(java.lang.String arg0, java.util.Map arg1);
	}

	[global::MonoJavaBridge.JavaProxy(typeof(global::android.webkit.UrlInterceptHandler))]
	internal sealed partial class UrlInterceptHandler_ : java.lang.Object, UrlInterceptHandler
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		internal UrlInterceptHandler_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		global::android.webkit.CacheManager.CacheResult android.webkit.UrlInterceptHandler.service(java.lang.String arg0, java.util.Map arg1)
		{
			return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.webkit.UrlInterceptHandler_.staticClass, "service", "(Ljava/lang/String;Ljava/util/Map;)Landroid/webkit/CacheManager$CacheResult;", ref global::android.webkit.UrlInterceptHandler_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.webkit.CacheManager.CacheResult;
		}
		private static global::MonoJavaBridge.MethodId _m1;
		global::android.webkit.PluginData android.webkit.UrlInterceptHandler.getPluginData(java.lang.String arg0, java.util.Map arg1)
		{
			return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.webkit.PluginData>(this, global::android.webkit.UrlInterceptHandler_.staticClass, "getPluginData", "(Ljava/lang/String;Ljava/util/Map;)Landroid/webkit/PluginData;", ref global::android.webkit.UrlInterceptHandler_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.webkit.PluginData;
		}
		static UrlInterceptHandler_()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.webkit.UrlInterceptHandler_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/UrlInterceptHandler"));
		}
	}
}


text:
/**
 * ```ts
 * interface IO<A> {
 *   (): A
 * }
 * ```
 *
 * `IO<A>` represents a non-deterministic synchronous computation that can cause side effects, yields a value of
 * type `A` and **never fails**.
 *
 * If you want to represent a synchronous computation that may fail, please see `IOEither`.
 * If you want to represent a synchronous computation that may yield nothing, please see `IOOption`.
 *
 * @since 2.0.0
 */
import { Applicative1, getApplicativeMonoid } from './Applicative'
import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_, getApplySemigroup } from './Apply'
import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain'
import { ChainRec1 } from './ChainRec'
import { FromIO1 } from './FromIO'
import { constant, identity } from './function'
import { let as let__, bindTo as bindTo_, flap as flap_, Functor1 } from './Functor'
import * as _ from './internal'
import { Monad1 } from './Monad'
import { MonadIO1 } from './MonadIO'
import { Monoid } from './Monoid'
import { NonEmptyArray } from './NonEmptyArray'
import { Pointed1 } from './Pointed'
import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray'
import { Semigroup } from './Semigroup'

// -------------------------------------------------------------------------------------
// model
// -------------------------------------------------------------------------------------

/**
 * @category model
 * @since 2.0.0
 */
export interface IO<A> {
  (): A
}

const _map: Monad1<URI>['map'] = (ma, f) => () => f(ma())
const _ap: Monad1<URI>['ap'] = (mab, ma) => () => mab()(ma())
const _chain: Monad1<URI>['chain'] = (ma, f) => () => f(ma())()
const _chainRec: ChainRec1<URI>['chainRec'] = (a, f) => () => {
  let e = f(a)()
  while (e._tag === 'Left') {
    e = f(e.left)()
  }
  return e.right
}

/**
 * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types
 * use the type constructor `F` to represent some computational context.
 *
 * @category mapping
 * @since 2.0.0
 */
export const map: <A, B>(f: (a: A) => B) => (fa: IO<A>) => IO<B> = (f) => (fa) => _map(fa, f)

/**
 * @since 2.0.0
 */
export const ap: <A>(fa: IO<A>) => <B>(fab: IO<(a: A) => B>) => IO<B> = (fa) => (fab) => _ap(fab, fa)

/**
 * @category constructors
 * @since 2.0.0
 */
export const of: <A>(a: A) => IO<A> = constant

/**
 * Composes computations in sequence, using the return value of one computation to determine the next computation.
 *
 * @category sequencing
 * @since 2.0.0
 */
export const chain: <A, B>(f: (a: A) => IO<B>) => (ma: IO<A>) => IO<B> = (f) => (ma) => _chain(ma, f)

/**
 * @category sequencing
 * @since 2.0.0
 */
export const flatten: <A>(mma: IO<IO<A>>) => IO<A> = /*#__PURE__*/ chain(identity)

/**
 * @category type lambdas
 * @since 2.0.0
 */
export const URI = 'IO'

/**
 * @category type lambdas
 * @since 2.0.0
 */
export type URI = typeof URI

declare module './HKT' {
  interface URItoKind<A> {
    readonly [URI]: IO<A>
  }
}

/**
 * @category instances
 * @since 2.7.0
 */
export const Functor: Functor1<URI> = {
  URI,
  map: _map
}

/**
 * @category mapping
 * @since 2.10.0
 */
export const flap = /*#__PURE__*/ flap_(Functor)

/**
 * @category instances
 * @since 2.10.0
 */
export const Pointed: Pointed1<URI> = {
  URI,
  of
}

/**
 * @category instances
 * @since 2.10.0
 */
export const Apply: Apply1<URI> = {
  URI,
  map: _map,
  ap: _ap
}

/**
 * Combine two effectful actions, keeping only the result of the first.
 *
 * @since 2.0.0
 */
export const apFirst = /*#__PURE__*/ apFirst_(Apply)

/**
 * Combine two effectful actions, keeping only the result of the second.
 *
 * @since 2.0.0
 */
export const apSecond = /*#__PURE__*/ apSecond_(Apply)

/**
 * @category instances
 * @since 2.7.0
 */
export const Applicative: Applicative1<URI> = {
  URI,
  map: _map,
  ap: _ap,
  of
}

/**
 * @category instances
 * @since 2.10.0
 */
export const Chain: Chain1<URI> = {
  URI,
  map: _map,
  ap: _ap,
  chain: _chain
}

/**
 * @category instances
 * @since 2.7.0
 */
export const Monad: Monad1<URI> = {
  URI,
  map: _map,
  ap: _ap,
  of,
  chain: _chain
}

/**
 * Composes computations in sequence, using the return value of one computation to determine the next computation and
 * keeping only the result of the first.
 *
 * @category sequencing
 * @since 2.0.0
 */
export const chainFirst: <A, B>(f: (a: A) => IO<B>) => (first: IO<A>) => IO<A> = /*#__PURE__*/ chainFirst_(Chain)

/**
 * @category zone of death
 * @since 2.7.0
 * @deprecated
 */
export const fromIO: <A>(fa: IO<A>) => IO<A> = identity

/**
 * @category instances
 * @since 2.7.0
 */
export const MonadIO: MonadIO1<URI> = {
  URI,
  map: _map,
  ap: _ap,
  of,
  chain: _chain,
  fromIO
}

/**
 * @category instances
 * @since 2.7.0
 */
export const ChainRec: ChainRec1<URI> = {
  URI,
  map: _map,
  ap: _ap,
  chain: _chain,
  chainRec: _chainRec
}

/**
 * @category instances
 * @since 2.10.0
 */
export const FromIO: FromIO1<URI> = {
  URI,
  fromIO: identity
}

// -------------------------------------------------------------------------------------
// do notation
// -------------------------------------------------------------------------------------

/**
 * @category do notation
 * @since 2.9.0
 */
export const Do: IO<{}> = /*#__PURE__*/ of(_.emptyRecord)

/**
 * @category do notation
 * @since 2.8.0
 */
export const bindTo = /*#__PURE__*/ bindTo_(Functor)

const let_ = /*#__PURE__*/ let__(Functor)

export {
  /**
   * @category do notation
   * @since 2.13.0
   */
  let_ as let
}

/**
 * @category do notation
 * @since 2.8.0
 */
export const bind = /*#__PURE__*/ bind_(Chain)

/**
 * @category do notation
 * @since 2.8.0
 */
export const apS = /*#__PURE__*/ apS_(Apply)

/**
 * @since 2.11.0
 */
export const ApT: IO<readonly []> = /*#__PURE__*/ of(_.emptyReadonlyArray)

// -------------------------------------------------------------------------------------
// array utils
// -------------------------------------------------------------------------------------

/**
 * Equivalent to `ReadonlyNonEmptyArray#traverseWithIndex(Applicative)`.
 *
 * @category traversing
 * @since 2.11.0
 */
export const traverseReadonlyNonEmptyArrayWithIndex =
  <A, B>(f: (index: number, a: A) => IO<B>) =>
  (as: ReadonlyNonEmptyArray<A>): IO<ReadonlyNonEmptyArray<B>> =>
  () => {
    const out: NonEmptyArray<B> = [f(0, _.head(as))()]
    for (let i = 1; i < as.length; i++) {
      out.push(f(i, as[i])())
    }
    return out
  }

/**
 * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.
 *
 * @category traversing
 * @since 2.11.0
 */
export const traverseReadonlyArrayWithIndex = <A, B>(
  f: (index: number, a: A) => IO<B>
): ((as: ReadonlyArray<A>) => IO<ReadonlyArray<B>>) => {
  const g = traverseReadonlyNonEmptyArrayWithIndex(f)
  return (as) => (_.isNonEmpty(as) ? g(as) : ApT)
}

/**
 * Equivalent to `ReadonlyArray#traverseWithIndex(Applicative)`.
 *
 * @category traversing
 * @since 2.9.0
 */
export const traverseArrayWithIndex: <A, B>(
  f: (index: number, a: A) => IO<B>
) => (as: ReadonlyArray<A>) => IO<ReadonlyArray<B>> = traverseReadonlyArrayWithIndex

/**
 * Equivalent to `ReadonlyArray#traverse(Applicative)`.
 *
 * @category traversing
 * @since 2.9.0
 */
export const traverseArray = <A, B>(f: (a: A) => IO<B>): ((as: ReadonlyArray<A>) => IO<ReadonlyArray<B>>) =>
  traverseReadonlyArrayWithIndex((_, a) => f(a))

/**
 * Equivalent to `ReadonlyArray#sequence(Applicative)`.
 *
 * @category traversing
 * @since 2.9.0
 */
export const sequenceArray: <A>(arr: ReadonlyArray<IO<A>>) => IO<ReadonlyArray<A>> =
  /*#__PURE__*/ traverseArray(identity)

// -------------------------------------------------------------------------------------
// deprecated
// -------------------------------------------------------------------------------------

/**
 * This instance is deprecated, use small, specific instances instead.
 * For example if a function needs a `Functor` instance, pass `IO.Functor` instead of `IO.io`
 * (where `IO` is from `import IO from 'fp-ts/IO'`)
 *
 * @category zone of death
 * @since 2.0.0
 * @deprecated
 */
export const io: Monad1<URI> & MonadIO1<URI> & ChainRec1<URI> = {
  URI,
  map: _map,
  of,
  ap: _ap,
  chain: _chain,
  fromIO,
  chainRec: _chainRec
}

/**
 * Use [`getApplySemigroup`](./Apply.ts.html#getapplysemigroup) instead.
 *
 * @category zone of death
 * @since 2.0.0
 * @deprecated
 */
export const getSemigroup: <A>(S: Semigroup<A>) => Semigroup<IO<A>> = /*#__PURE__*/ getApplySemigroup(Apply)

/**
 * Use [`getApplicativeMonoid`](./Applicative.ts.html#getapplicativemonoid) instead.
 *
 * @category zone of death
 * @since 2.0.0
 * @deprecated
 */
export const getMonoid: <A>(M: Monoid<A>) => Monoid<IO<A>> = /*#__PURE__*/ getApplicativeMonoid(Applicative)


text:
using content::BrowserThread;

namespace policy {

namespace {

#if defined(OS_MACOSX)
base::FilePath GetManagedPolicyPath() {
  CFBundleRef bundle(CFBundleGetMainBundle());
  if (!bundle)
    return base::FilePath();

  CFStringRef bundle_id = CFBundleGetIdentifier(bundle);
  if (!bundle_id)
    return base::FilePath();

  return policy::PolicyLoaderMac::GetManagedPolicyPath(bundle_id);
}
#endif  // defined(OS_MACOSX)

}  // namespace

ChromeBrowserPolicyConnector::ChromeBrowserPolicyConnector()
    : BrowserPolicyConnector(base::Bind(&BuildHandlerList)) {
  ConfigurationPolicyProvider* platform_provider = CreatePlatformProvider();
  if (platform_provider)
    SetPlatformPolicyProvider(make_scoped_ptr(platform_provider));
}

ChromeBrowserPolicyConnector::~ChromeBrowserPolicyConnector() {}

void ChromeBrowserPolicyConnector::Init(
    PrefService* local_state,
    scoped_refptr<net::URLRequestContextGetter> request_context) {
  // Initialization of some of the providers requires the FILE thread; make
  // sure that threading is ready at this point.
  DCHECK(BrowserThread::IsThreadInitialized(BrowserThread::FILE));

  scoped_ptr<DeviceManagementService::Configuration> configuration(
      new DeviceManagementServiceConfiguration(
          BrowserPolicyConnector::GetDeviceManagementUrl()));
  scoped_ptr<DeviceManagementService> device_management_service(
      new DeviceManagementService(std::move(configuration)));
  device_management_service->ScheduleInitialization(
      kServiceInitializationStartupDelay);

  InitInternal(local_state, std::move(device_management_service));
}

ConfigurationPolicyProvider*
    ChromeBrowserPolicyConnector::CreatePlatformProvider() {
#if defined(OS_WIN)
  scoped_ptr<AsyncPolicyLoader> loader(PolicyLoaderWin::Create(
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
      kRegistryChromePolicyKey));
  return new AsyncPolicyProvider(GetSchemaRegistry(), loader.Pass());
#elif defined(OS_MACOSX)
  scoped_ptr<AsyncPolicyLoader> loader(new PolicyLoaderMac(
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
      GetManagedPolicyPath(),
      new MacPreferences()));
  return new AsyncPolicyProvider(GetSchemaRegistry(), std::move(loader));
#elif defined(OS_POSIX) && !defined(OS_ANDROID)
  base::FilePath config_dir_path;
  if (PathService::Get(chrome::DIR_POLICY_FILES, &config_dir_path)) {
    scoped_ptr<AsyncPolicyLoader> loader(new ConfigDirPolicyLoader(
        BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
        config_dir_path,
        POLICY_SCOPE_MACHINE));
    return new AsyncPolicyProvider(GetSchemaRegistry(), std::move(loader));
  } else {
    return NULL;
  }
#elif defined(OS_ANDROID)
  return new policy::android::AndroidCombinedPolicyProvider(
      GetSchemaRegistry());
#else
  return NULL;
#endif
}

}  // namespace policy


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mikol. Fitopatol. 13(2): 108 (1979)

#### Original name
Cicinobolus heraclei Dejeva

### Remarks
null


text:
package io.grpc.okhttp;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.grpc.internal.ClientStreamListener.RpcProgress.PROCESSED;

import com.google.common.io.BaseEncoding;
import io.grpc.Attributes;
import io.grpc.CallOptions;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.internal.AbstractClientStream;
import io.grpc.internal.Http2ClientStreamTransportState;
import io.grpc.internal.StatsTraceContext;
import io.grpc.internal.TransportTracer;
import io.grpc.internal.WritableBuffer;
import io.grpc.okhttp.internal.framed.ErrorCode;
import io.grpc.okhttp.internal.framed.Header;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
import javax.annotation.concurrent.GuardedBy;
import okio.Buffer;

/**
 * Client stream for the okhttp transport.
 */
class OkHttpClientStream extends AbstractClientStream {

  private static final Buffer EMPTY_BUFFER = new Buffer();

  public static final int ABSENT_ID = -1;

  private final MethodDescriptor<?, ?> method;

  private final String userAgent;
  private final StatsTraceContext statsTraceCtx;
  private String authority;
  private Object outboundFlowState;
  private volatile int id = ABSENT_ID;
  private final TransportState state;
  private final Sink sink = new Sink();
  private final Attributes attributes;

  private boolean useGet = false;

  OkHttpClientStream(
      MethodDescriptor<?, ?> method,
      Metadata headers,
      AsyncFrameWriter frameWriter,
      OkHttpClientTransport transport,
      OutboundFlowController outboundFlow,
      Object lock,
      int maxMessageSize,
      int initialWindowSize,
      String authority,
      String userAgent,
      StatsTraceContext statsTraceCtx,
      TransportTracer transportTracer,
      CallOptions callOptions) {
    super(
        new OkHttpWritableBufferAllocator(),
        statsTraceCtx,
        transportTracer,
        headers,
        callOptions,
        method.isSafe());
    this.statsTraceCtx = checkNotNull(statsTraceCtx, "statsTraceCtx");
    this.method = method;
    this.authority = authority;
    this.userAgent = userAgent;
    // OkHttpClientStream is only created after the transport has finished connecting,
    // so it is safe to read the transport attributes.
    // We make a copy here for convenience, even though we can ask the transport.
    this.attributes = transport.getAttributes();
    this.state =
        new TransportState(
            maxMessageSize,
            statsTraceCtx,
            lock,
            frameWriter,
            outboundFlow,
            transport,
            initialWindowSize);
  }

  @Override
  protected TransportState transportState() {
    return state;
  }

  @Override
  protected Sink abstractClientStreamSink() {
    return sink;
  }

  /**
   * Returns the type of this stream.
   */
  public MethodDescriptor.MethodType getType() {
    return method.getType();
  }

  public int id() {
    return id;
  }

  /**
   * Returns whether the stream uses GET. This is not known until after {@link Sink#writeHeaders} is
   * invoked.
   */
  boolean useGet() {
    return useGet;
  }

  @Override
  public void setAuthority(String authority) {
    this.authority = checkNotNull(authority, "authority");
  }

  @Override
  public Attributes getAttributes() {
    return attributes;
  }

  class Sink implements AbstractClientStream.Sink {
    @SuppressWarnings("BetaApi") // BaseEncoding is stable in Guava 20.0
    @Override
    public void writeHeaders(Metadata metadata, byte[] payload) {
      String defaultPath = "/" + method.getFullMethodName();
      if (payload != null) {
        useGet = true;
        defaultPath += "?" + BaseEncoding.base64().encode(payload);
      }
      synchronized (state.lock) {
        state.streamReady(metadata, defaultPath);
      }
    }

    @Override
    public void writeFrame(
        WritableBuffer frame, boolean endOfStream, boolean flush, int numMessages) {
      Buffer buffer;
      if (frame == null) {
        buffer = EMPTY_BUFFER;
      } else {
        buffer = ((OkHttpWritableBuffer) frame).buffer();
        int size = (int) buffer.size();
        if (size > 0) {
          onSendingBytes(size);
        }
      }

      synchronized (state.lock) {
        state.sendBuffer(buffer, endOfStream, flush);
        getTransportTracer().reportMessageSent(numMessages);
      }
    }

    @Override
    public void request(final int numMessages) {
      synchronized (state.lock) {
        state.requestMessagesFromDeframer(numMessages);
      }
    }

    @Override
    public void cancel(Status reason) {
      synchronized (state.lock) {
        state.cancel(reason, true, null);
      }
    }
  }

  class TransportState extends Http2ClientStreamTransportState {
    private final int initialWindowSize;
    private final Object lock;
    @GuardedBy("lock")
    private List<Header> requestHeaders;
    /**
     * Null iff {@link #requestHeaders} is null.  Non-null iff neither {@link #cancel} nor
     * {@link #start(int)} have been called.
     */
    @GuardedBy("lock")
    private Queue<PendingData> pendingData = new ArrayDeque<PendingData>();
    @GuardedBy("lock")
    private boolean cancelSent = false;
    @GuardedBy("lock")
    private int window;
    @GuardedBy("lock")
    private int processedWindow;
    @GuardedBy("lock")
    private final AsyncFrameWriter frameWriter;
    @GuardedBy("lock")
    private final OutboundFlowController outboundFlow;
    @GuardedBy("lock")
    private final OkHttpClientTransport transport;

    public TransportState(
        int maxMessageSize,
        StatsTraceContext statsTraceCtx,
        Object lock,
        AsyncFrameWriter frameWriter,
        OutboundFlowController outboundFlow,
        OkHttpClientTransport transport,
        int initialWindowSize) {
      super(maxMessageSize, statsTraceCtx, OkHttpClientStream.this.getTransportTracer());
      this.lock = checkNotNull(lock, "lock");
      this.frameWriter = frameWriter;
      this.outboundFlow = outboundFlow;
      this.transport = transport;
      this.window = initialWindowSize;
      this.processedWindow = initialWindowSize;
      this.initialWindowSize = initialWindowSize;
    }

    @GuardedBy("lock")
    public void start(int streamId) {
      checkState(id == ABSENT_ID, "the stream has been started with id %s", streamId);
      id = streamId;
      state.onStreamAllocated();

      if (pendingData != null) {
        // Only happens when the stream has neither been started nor cancelled.
        frameWriter.synStream(useGet, false, id, 0, requestHeaders);
        statsTraceCtx.clientOutboundHeaders();
        requestHeaders = null;

        boolean flush = false;
        while (!pendingData.isEmpty()) {
          PendingData data = pendingData.poll();
          outboundFlow.data(data.endOfStream, id, data.buffer, false);
          if (data.flush) {
            flush = true;
          }
        }
        if (flush) {
          outboundFlow.flush();
        }
        pendingData = null;
      }
    }

    @GuardedBy("lock")
    @Override
    protected void onStreamAllocated() {
      super.onStreamAllocated();
      getTransportTracer().reportLocalStreamStarted();
    }

    @GuardedBy("lock")
    @Override
    protected void http2ProcessingFailed(Status status, boolean stopDelivery, Metadata trailers) {
      cancel(status, stopDelivery, trailers);
    }

    @Override
    @GuardedBy("lock")
    public void deframeFailed(Throwable cause) {
      http2ProcessingFailed(Status.fromThrowable(cause), true, new Metadata());
    }

    @Override
    @GuardedBy("lock")
    public void bytesRead(int processedBytes) {
      processedWindow -= processedBytes;
      if (processedWindow <= initialWindowSize * Utils.DEFAULT_WINDOW_UPDATE_RATIO) {
        int delta = initialWindowSize - processedWindow;
        window += delta;
        processedWindow += delta;
        frameWriter.windowUpdate(id(), delta);
      }
    }

    @Override
    @GuardedBy("lock")
    public void deframerClosed(boolean hasPartialMessage) {
      onEndOfStream();
      super.deframerClosed(hasPartialMessage);
    }

    @Override
    @GuardedBy("lock")
    public void runOnTransportThread(final Runnable r) {
      synchronized (lock) {
        r.run();
      }
    }

    /**
     * Must be called with holding the transport lock.
     */
    @GuardedBy("lock")
    public void transportHeadersReceived(List<Header> headers, boolean endOfStream) {
      if (endOfStream) {
        transportTrailersReceived(Utils.convertTrailers(headers));
      } else {
        transportHeadersReceived(Utils.convertHeaders(headers));
      }
    }

    /**
     * Must be called with holding the transport lock.
     */
    @GuardedBy("lock")
    public void transportDataReceived(okio.Buffer frame, boolean endOfStream) {
      // We only support 16 KiB frames, and the max permitted in HTTP/2 is 16 MiB. This is verified
      // in OkHttp's Http2 deframer. In addition, this code is after the data has been read.
      int length = (int) frame.size();
      window -= length;
      if (window < 0) {
        frameWriter.rstStream(id(), ErrorCode.FLOW_CONTROL_ERROR);
        transport.finishStream(
            id(),
            Status.INTERNAL.withDescription(
                "Received data size exceeded our receiving window size"),
            PROCESSED, false, null, null);
        return;
      }
      super.transportDataReceived(new OkHttpReadableBuffer(frame), endOfStream);
    }

    @GuardedBy("lock")
    private void onEndOfStream() {
      if (!isOutboundClosed()) {
        // If server's end-of-stream is received before client sends end-of-stream, we just send a
        // reset to server to fully close the server side stream.
        transport.finishStream(id(),null, PROCESSED, false, ErrorCode.CANCEL, null);
      } else {
        transport.finishStream(id(), null, PROCESSED, false, null, null);
      }
    }

    @GuardedBy("lock")
    private void cancel(Status reason, boolean stopDelivery, Metadata trailers) {
      if (cancelSent) {
        return;
      }
      cancelSent = true;
      if (pendingData != null) {
        // stream is pending.
        transport.removePendingStream(OkHttpClientStream.this);
        // release holding data, so they can be GCed or returned to pool earlier.
        requestHeaders = null;
        for (PendingData data : pendingData) {
          data.buffer.clear();
        }
        pendingData = null;
        transportReportStatus(reason, true, trailers != null ? trailers : new Metadata());
      } else {
        // If pendingData is null, start must have already been called, which means synStream has
        // been called as well.
        transport.finishStream(
            id(), reason, PROCESSED, stopDelivery, ErrorCode.CANCEL, trailers);
      }
    }

    @GuardedBy("lock")
    private void sendBuffer(Buffer buffer, boolean endOfStream, boolean flush) {
      if (cancelSent) {
        return;
      }
      if (pendingData != null) {
        // Stream is pending start, queue the data.
        pendingData.add(new PendingData(buffer, endOfStream, flush));
      } else {
        checkState(id() != ABSENT_ID, "streamId should be set");
        // If buffer > frameWriter.maxDataLength() the flow-controller will ensure that it is
        // properly chunked.
        outboundFlow.data(endOfStream, id(), buffer, flush);
      }
    }

    @GuardedBy("lock")
    private void streamReady(Metadata metadata, String path) {
      requestHeaders = Headers.createRequestHeaders(metadata, path, authority, userAgent, useGet);
      transport.streamReadyToStart(OkHttpClientStream.this);
    }
  }

  void setOutboundFlowState(Object outboundFlowState) {
    this.outboundFlowState = outboundFlowState;
  }

  Object getOutboundFlowState() {
    return outboundFlowState;
  }

  private static class PendingData {
    Buffer buffer;
    boolean endOfStream;
    boolean flush;

    PendingData(Buffer buffer, boolean endOfStream, boolean flush) {
      this.buffer = buffer;
      this.endOfStream = endOfStream;
      this.flush = flush;
    }
  }
}


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { CourseListComponent } from './course-list.component';

describe('Component: CourseListComponent', () => {
  it('should create an instance', () => {
    let component = new CourseListComponent(null);
    expect(component).toBeTruthy();
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace Elders.Cronus.EventStore
{
    [DataContract(Namespace = "cronus", Name = "f69daa12-171c-43a1-b049-be8a93ff137f")]
    public class AggregateCommit : IMessage
    {
        AggregateCommit()
        {
            Events = new List<IEvent>();
            PublicEvents = new List<IPublicEvent>();
        }

        public AggregateCommit(IBlobId aggregateId, int revision, List<IEvent> events) : this(aggregateId.RawId, revision, events, new List<IPublicEvent>()) { }
        public AggregateCommit(byte[] aggregateRootId, int revision, List<IEvent> events) : this(aggregateRootId, revision, events, new List<IPublicEvent>(), DateTime.UtcNow.ToFileTimeUtc()) { }

        public AggregateCommit(IBlobId aggregateId, int revision, List<IEvent> events, List<IPublicEvent> publicEvents) : this(aggregateId.RawId, revision, events, publicEvents) { }
        public AggregateCommit(byte[] aggregateRootId, int revision, List<IEvent> events, List<IPublicEvent> publicEvents) : this(aggregateRootId, revision, events, publicEvents, DateTime.UtcNow.ToFileTimeUtc()) { }

        public AggregateCommit(byte[] aggregateRootId, int revision, List<IEvent> events, List<IPublicEvent> publicEvents, long timestamp)
        {
            AggregateRootId = aggregateRootId;
            Revision = revision;
            Events = events;
            PublicEvents = publicEvents;
            Timestamp = timestamp;
        }

        [DataMember(Order = 1)]
        public byte[] AggregateRootId { get; private set; }

        [Obsolete]
        [DataMember(Order = 2)]
        string BoundedContext { get; set; }

        [DataMember(Order = 3)]
        public int Revision { get; private set; }

        [DataMember(Order = 4)]
        public List<IEvent> Events { get; set; }

        [DataMember(Order = 6)]
        public List<IPublicEvent> PublicEvents { get; set; }

        [DataMember(Order = 5)]
        public long Timestamp { get; private set; }

        public override string ToString()
        {
            StringBuilder commitInfoBuilder = new StringBuilder();
            commitInfoBuilder.AppendLine("AggregateCommit details:");

            commitInfoBuilder.Append("RootId:");
            commitInfoBuilder.AppendLine(Encoding.UTF8.GetString(AggregateRootId));

            commitInfoBuilder.Append("Revision:");
            commitInfoBuilder.AppendLine(Revision.ToString());

            commitInfoBuilder.Append("Events:");
            commitInfoBuilder.AppendLine(string.Join(Environment.NewLine, Events.Select(e => "\t" + e.ToString())));

            commitInfoBuilder.Append("PublicEvents:");
            commitInfoBuilder.AppendLine(string.Join(Environment.NewLine, PublicEvents.Select(e => "\t" + e.ToString())));

            return commitInfoBuilder.ToString();
        }
    }
}


text:
{% extends "WPSsite/header.html" %}

{% block content %}

{% load staticfiles %}

<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

				  Predicting the future to help improve the present

Peter Jupp, Lead Website Developer and Data Analyst

We can predict rainfall, temperature and even hurricanes, what's stopping us from predicting wildfires as well?

Vishal Soomaney, Lead Backend Developer and Senior Data Analyst

				  Fires are bad

Flinn Dolman, Algorithm Design And Implementation

 News

OREGON, UNITED STATES
 Wildfires close Pacific Crest Trail at Crater Lake, evacuation warning

OREGONLIVE Article [06/08/17]

FRANCE
 Thousands evacuated after wildfire on France's Mediterranean coast

Guardian Article [26/07/17]

WASHINGTON, UNITED STATES
 Wildfire prompts Level 2 evacuation notice in Naches

KING5 Article [03/07/17]

For more wildfire news, click here

 Updates

Development Updates: Infoboxes are live! Hover over a placemark on the app to see more info!

[28/07/17]

Development Updates: Filter system has been added - you can now filter by fire likelihood!

[21/07/17]

Development Updates: New UI upgrades include a legend and select a day functions!

[17/07/17]

Media Updates: AWARE now has a Twitter account. Make sure to follow us!

[08/07/17]

Tweets by TwitterDev

{% endblock %}


text: Capyable API Client Package


text:
/****************************************************************************
 * lib/libc/wchar/lib_wcstod.c
 *
 *   Copyright (c)1999 Citrus Project,
 *   All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <stdlib.h>
#include <wchar.h>

#ifdef CONFIG_LIBC_WCHAR

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: wcstod
 *
 * Description:
 *   The wcstod() function is the wide-character equivalent of the strtod()
 *   function. It converts a wchar string to long long value.
 *
 ****************************************************************************/

double wcstod(FAR const wchar_t *nptr, FAR wchar_t **endptr)
{
	return strtod((FAR const char *)nptr, (FAR char **)endptr);
}

#endif							/* CONFIG_LIBC_WCHAR */


text:
const Promise = require(`bluebird`)
const os = require(`os`)
const HJSON = require(`hjson`)

const { onCreateNode } = require(`../gatsby-node`)

describe(`Process HJSON nodes correctly`, () => {
  const node = {
    name: `nodeName`,
    id: `whatever`,
    parent: null,
    children: [],
    internal: {
      contentDigest: `whatever`,
      mediaType: `application/hjson`,
      name: `test`,
    },
  }

  // Make some fake functions its expecting.
  const loadNodeContent = node => Promise.resolve(node.content)

  it(`correctly creates nodes from HJSON which is an array of objects`, async () => {
    const data = [
      { id: `foo`, blue: true, funny: `yup` },
      { blue: false, funny: `nope` },
    ]
    node.content = HJSON.stringify(data)

    const createNode = jest.fn()
    const createParentChildLink = jest.fn()
    const actions = { createNode, createParentChildLink }
    const createNodeId = jest.fn()
    createNodeId.mockReturnValue(`uuid-from-gatsby`)
    const createContentDigest = jest.fn().mockReturnValue(`contentDigest`)

    await onCreateNode({
      node,
      loadNodeContent,
      actions,
      createNodeId,
      createContentDigest,
    }).then(() => {
      expect(createNode.mock.calls).toMatchSnapshot()
      expect(createParentChildLink.mock.calls).toMatchSnapshot()
      expect(createNode).toHaveBeenCalledTimes(2)
      expect(createParentChildLink).toHaveBeenCalledTimes(2)
    })
  })

  it(`correctly creates a node from HJSON which is a single object`, async () => {
    const data = { id: `foo`, blue: true, funny: `yup` }
    node.content = HJSON.stringify(data)
    node.dir = `${os.tmpdir()}/foo/`

    const createNode = jest.fn()
    const createParentChildLink = jest.fn()
    const actions = { createNode, createParentChildLink }
    const createNodeId = jest.fn()
    createNodeId.mockReturnValue(`uuid-from-gatsby`)
    const createContentDigest = jest.fn().mockReturnValue(`contentDigest`)

    await onCreateNode({
      node,
      loadNodeContent,
      actions,
      createNodeId,
      createContentDigest,
    }).then(() => {
      expect(createNode.mock.calls).toMatchSnapshot()
      expect(createParentChildLink.mock.calls).toMatchSnapshot()
      expect(createNode).toHaveBeenCalledTimes(1)
      expect(createParentChildLink).toHaveBeenCalledTimes(1)
    })
  })
})


text:
package com.dianping.cat.consumer.heartbeat;

import com.dianping.cat.Cat;
import com.dianping.cat.analysis.AbstractMessageAnalyzer;
import com.dianping.cat.analysis.MessageAnalyzer;
import com.dianping.cat.config.server.ServerFilterConfigManager;
import com.dianping.cat.consumer.heartbeat.model.entity.HeartbeatReport;
import com.dianping.cat.consumer.heartbeat.model.entity.Machine;
import com.dianping.cat.consumer.heartbeat.model.entity.Period;
import com.dianping.cat.message.Heartbeat;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.report.DefaultReportManager.StoragePolicy;
import com.dianping.cat.report.ReportManager;
import com.dianping.cat.status.model.StatusInfoHelper;
import com.dianping.cat.status.model.entity.*;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.unidal.lookup.annotation.Inject;
import org.unidal.lookup.annotation.Named;

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

@Named(type = MessageAnalyzer.class, value = HeartbeatAnalyzer.ID, instantiationStrategy = Named.PER_LOOKUP)
public class HeartbeatAnalyzer extends AbstractMessageAnalyzer<HeartbeatReport> implements LogEnabled {
	public static final String ID = "heartbeat";

	@Inject(ID)
	private ReportManager<HeartbeatReport> m_reportManager;

	@Inject
	private ServerFilterConfigManager m_serverFilterConfigManager;

	private Period buildHeartBeatInfo(Machine machine, Heartbeat heartbeat, long timestamp) {
		String xml = (String) heartbeat.getData();
		StatusInfo info;

		try {
			info = StatusInfoHelper.fromXml(xml);
			RuntimeInfo runtime = info.getRuntime();

			if (runtime != null) {
				machine.setClasspath(runtime.getJavaClasspath());
			} else {
				machine.setClasspath("");
			}

			translateHeartbeat(info);
		} catch (Exception e) {
			return null;
		}

		try {
			long current = timestamp / 1000 / 60;
			int minute = (int) (current % (60));
			Period period = new Period(minute);

			for (Entry<String, Extension> entry : info.getExtensions().entrySet()) {
				String id = entry.getKey();
				Extension ext = entry.getValue();
				com.dianping.cat.consumer.heartbeat.model.entity.Extension extension = period.findOrCreateExtension(id);
				Map<String, ExtensionDetail> details = ext.getDetails();

				for (Entry<String, ExtensionDetail> detail : details.entrySet()) {
					ExtensionDetail extensionDetail = detail.getValue();

					extension.findOrCreateDetail(extensionDetail.getId()).setValue(extensionDetail.getValue());
				}
			}
			return period;
		} catch (Exception e) {
			Cat.logError(e);
			return null;
		}
	}

	@Override
	public synchronized void doCheckpoint(boolean atEnd) {
		if (atEnd && !isLocalMode()) {
			m_reportManager.storeHourlyReports(getStartTime(), StoragePolicy.FILE_AND_DB, m_index);
		} else {
			m_reportManager.storeHourlyReports(getStartTime(), StoragePolicy.FILE, m_index);
		}
	}

	@Override
	public void enableLogging(Logger logger) {
		m_logger = logger;
	}

	@Override
	public HeartbeatReport getReport(String domain) {
		return m_reportManager.getHourlyReport(getStartTime(), domain, false);
	}

	@Override
	public ReportManager<HeartbeatReport> getReportManager() {
		return m_reportManager;
	}

	@Override
	public boolean isEligable(MessageTree tree) {
		return tree.getHeartbeats().size() > 0;
	}

	@Override
	protected void loadReports() {
		m_reportManager.loadHourlyReports(getStartTime(), StoragePolicy.FILE, m_index);
	}

	@Override
	protected void process(MessageTree tree) {
		String domain = tree.getDomain();

		if (m_serverFilterConfigManager.validateDomain(domain)) {
			HeartbeatReport report = m_reportManager.getHourlyReport(getStartTime(), domain, true);
			report.addIp(tree.getIpAddress());
			List<Heartbeat> heartbeats = tree.getHeartbeats();

			for (Heartbeat h : heartbeats) {
				if (h.getType().equalsIgnoreCase("heartbeat")) {
					processHeartbeat(report, h, tree);
				}
			}
		}
	}

	private void processHeartbeat(HeartbeatReport report, Heartbeat heartbeat, MessageTree tree) {
		String ip = tree.getIpAddress();
		Machine machine = report.findOrCreateMachine(ip);
		Period period = buildHeartBeatInfo(machine, heartbeat, heartbeat.getTimestamp());

		if (period != null) {
			List<Period> periods = machine.getPeriods();

			if (periods.size() <= 60) {
				machine.getPeriods().add(period);
			}
		}
	}

	private void translateHeartbeat(StatusInfo info) {
		try {
			MessageInfo message = info.getMessage();

			if (message.getProduced() > 0 || message.getBytes() > 0) {
				Extension catExtension = info.findOrCreateExtension("CatUsage");

				catExtension.findOrCreateExtensionDetail("Produced").setValue(message.getProduced());
				catExtension.findOrCreateExtensionDetail("Overflowed").setValue(message.getOverflowed());
				catExtension.findOrCreateExtensionDetail("Bytes").setValue(message.getBytes());

				Extension system = info.findOrCreateExtension("System");
				OsInfo osInfo = info.getOs();

				system.findOrCreateExtensionDetail("LoadAverage").setValue(osInfo.getSystemLoadAverage());
				system.findOrCreateExtensionDetail("FreePhysicalMemory").setValue(osInfo.getFreePhysicalMemory());
				system.findOrCreateExtensionDetail("FreeSwapSpaceSize").setValue(osInfo.getFreeSwapSpace());

				Extension gc = info.findOrCreateExtension("GC");
				MemoryInfo memory = info.getMemory();
				List<GcInfo> gcs = memory.getGcs();

				if (gcs.size() >= 2) {
					GcInfo newGc = gcs.get(0);
					GcInfo oldGc = gcs.get(1);
					gc.findOrCreateExtensionDetail("ParNewCount").setValue(newGc.getCount());
					gc.findOrCreateExtensionDetail("ParNewTime").setValue(newGc.getTime());
					gc.findOrCreateExtensionDetail("ConcurrentMarkSweepCount").setValue(oldGc.getCount());
					gc.findOrCreateExtensionDetail("ConcurrentMarkSweepTime").setValue(oldGc.getTime());
				}

				Extension thread = info.findOrCreateExtension("FrameworkThread");
				ThreadsInfo threadInfo = info.getThread();

				thread.findOrCreateExtensionDetail("HttpThread").setValue(threadInfo.getHttpThreadCount());
				thread.findOrCreateExtensionDetail("CatThread").setValue(threadInfo.getCatThreadCount());
				thread.findOrCreateExtensionDetail("PigeonThread").setValue(threadInfo.getPigeonThreadCount());
				thread.findOrCreateExtensionDetail("ActiveThread").setValue(threadInfo.getCount());
				thread.findOrCreateExtensionDetail("StartedThread").setValue(threadInfo.getTotalStartedCount());

				Extension disk = info.findOrCreateExtension("Disk");
				List<DiskVolumeInfo> diskVolumes = info.getDisk().getDiskVolumes();

				for (DiskVolumeInfo vinfo : diskVolumes) {
					disk.findOrCreateExtensionDetail(vinfo.getId() + " Free").setValue(vinfo.getFree());
				}
			}
		} catch (Exception ignored) {
			// support new java client
		}

		for (Extension ex : info.getExtensions().values()) {
			Map<String, String> propertis = ex.getDynamicAttributes();

			for (Entry<String, String> entry : propertis.entrySet()) {
				try {
					double value = Double.parseDouble(entry.getValue());

					ex.findOrCreateExtensionDetail(entry.getKey()).setValue(value);
				} catch (Exception e) {
					Cat.logError("StatusExtension can only be double type", e);
				}
			}
		}
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>QDomDocument — PyQt 5.5.1 Reference Guide</title>

    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/logo_tn.ico"/>
    <link rel="top" title="PyQt 5.5.1 Reference Guide" href="../index.html" />
    <link rel="up" title="PyQt5 Class Reference" href="../class_reference.html" />
    <link rel="next" title="QDomDocumentFragment" href="qdomdocumentfragment.html" />
    <link rel="prev" title="QDomComment" href="qdomcomment.html" />

Navigation

          index

          modules |

          next |

          previous |

PyQt 5.5.1 Reference Guide »

PyQt5 Class Reference »

QDomDocument¶

class PyQt5.QtXml.QDomDocument¶

C++ documentation

Previous topic

QDomComment

Next topic

QDomDocumentFragment

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

PyQt 5.5.1 Reference Guide »

PyQt5 Class Reference »

        © Copyright 2015 Riverbank Computing Limited.
      Created using Sphinx 1.3.1.


text:
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';
import { Router } from '@angular/router';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';
import { AppRoutingModule } from '../../app-routing.module';
import { AuthService } from '../shared/auth.service';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule,FormsModule,RouterTestingModule],
      declarations: [ LoginComponent ],
      schemas: [ NO_ERRORS_SCHEMA ],
      providers: [AuthService,{provide: APP_BASE_HREF, useValue: '/'}],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
package org.apache.directory.server.core.operations.move;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;

import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapEntryAlreadyExistsException;
import org.apache.directory.api.ldap.model.exception.LdapOperationErrorException;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.server.core.annotations.ContextEntry;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreateIndex;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.ApacheDSTestExtension;
import org.apache.directory.server.core.integ.IntegrationUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

/**
 * Test the move operation performances
 *
 * @author Apache Directory Project
 * @version $Rev$
 */
@ExtendWith( { ApacheDSTestExtension.class } )
@CreateDS(name = "MovePerfDS",
    partitions =
    {
        @CreatePartition(
            name = "example",
            suffix = "dc=example,dc=com",
            contextEntry =
                @ContextEntry(
                    entryLdif =
                        "dn: dc=example,dc=com\n" +
                        "dc: example\n" +
                        "objectClass: top\n" +
                        "objectClass: domain\n\n"),
            indexes =
            {
                @CreateIndex(attribute = "objectClass"),
                @CreateIndex(attribute = "sn"),
                @CreateIndex(attribute = "cn")
            })
    })
public class MoveIT extends AbstractLdapTestUnit
{
    /**
     * Test a move operation :
     * cn=test,ou=system will be moved to cn=test,ou=users,ou=system
     */
    @Test
    public void testMove() throws Exception
    {
        LdapConnection connection = IntegrationUtils.getAdminConnection( getService() );

        String oldDn = "cn=test,ou=system";
        String newDn = "cn=test,ou=users,ou=system";
        String newSuperior = "ou=users,ou=system";

        Dn dn = new Dn( oldDn );
        Entry entry = new DefaultEntry( getService().getSchemaManager(), dn,
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: TEST",
            "cn: test" );

        connection.add( entry );

        assertNull( connection.lookup( newDn ) );
        assertNotNull( connection.lookup( oldDn ) );

        connection.move( oldDn, newSuperior );

        assertNotNull( connection.lookup( newDn ) );
        assertNull( connection.lookup( oldDn ) );

        connection.close();
    }

    /**
     * Test a move operation :
     * cn=test,ou=system will be moved to cn=test,ou=users,ou=system
     */
    @Test
    public void testMoveWithChildren() throws Exception
    {
        LdapConnection connection = IntegrationUtils.getAdminConnection( getService() );

        Entry test1 = new DefaultEntry( getService().getSchemaManager(), "cn=test1,ou=system",
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: Test1",
            "cn: tes1t" );

        Entry childTest1 = new DefaultEntry( getService().getSchemaManager(), "cn=childTest1,cn=test1,ou=system",
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: child test1",
            "cn: childTest1" );

        Entry test2 = new DefaultEntry( getService().getSchemaManager(), "cn=test2,ou=system",
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: Test2",
            "cn: test2" );

        Entry childTest2 = new DefaultEntry( getService().getSchemaManager(), "cn=childTest2,cn=test2,ou=system",
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: child test2",
            "cn: childTest2" );

        connection.add( test1 );
        connection.add( test2 );
        connection.add( childTest1 );
        connection.add( childTest2 );

        assertNotNull( connection.lookup( "cn=test1,ou=system" ) );
        assertNotNull( connection.lookup( "cn=test2,ou=system" ) );
        assertNotNull( connection.lookup( "cn=childTest1,cn=test1,ou=system" ) );
        assertNotNull( connection.lookup( "cn=childTest2,cn=test2,ou=system" ) );

        connection.move( "cn=test1,ou=system", "cn=test2,ou=system" );

        assertNull( connection.lookup( "cn=test1,ou=system" ) );
        assertNull( connection.lookup( "cn=childTest1,cn=test1,ou=system" ) );
        assertNotNull( connection.lookup( "cn=test2,ou=system" ) );
        assertNotNull( connection.lookup( "cn=childTest2,cn=test2,ou=system" ) );
        assertNotNull( connection.lookup( "cn=test1,cn=test2,ou=system" ) );
        assertNotNull( connection.lookup( "cn=childTest1,cn=test1,cn=test2,ou=system" ) );

        connection.close();
    }

    /**
     * Test a move operation to a non existing parent:
     * cn=test,ou=system will be moved to cn=test,ou=users,ou=system
     */
    @Test
    public void testMoveNonExistingParent() throws Exception
    {
        LdapConnection connection = IntegrationUtils.getAdminConnection( getService() );

        String oldDn = "cn=test,ou=system";
        String newDn = "cn=test,ou=nonExisting,ou=system";
        String newSuperior = "ou=nonExisting,ou=system";

        Dn dn = new Dn( oldDn );
        Entry entry = new DefaultEntry( getService().getSchemaManager(), dn,
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: TEST",
            "cn: test" );

        connection.add( entry );

        assertNull( connection.lookup( newDn ) );
        assertNotNull( connection.lookup( oldDn ) );

        try
        {
            connection.move( oldDn, newSuperior );
            fail();
        }
        catch ( LdapOperationErrorException loee )
        {
            assertEquals( ResultCodeEnum.OPERATIONS_ERROR, loee.getResultCode() );
        }

        assertNull( connection.lookup( newDn ) );
        assertNotNull( connection.lookup( oldDn ) );

        connection.close();
    }

    /**
     * Test a move operation on an existing location:
     * cn=test,ou=system will be moved to cn=test,ou=users,ou=system, which already exists
     */
    @Test
    public void testMoveExistingTarget() throws Exception
    {
        LdapConnection connection = IntegrationUtils.getAdminConnection( getService() );

        String oldDn = "cn=test,ou=system";
        String newDn = "cn=test,ou=users,ou=system";
        String newSuperior = "ou=users,ou=system";
        String targetDnStr = "cn=test,ou=users,ou=system";

        Dn dn = new Dn( oldDn );
        Entry entry = new DefaultEntry( getService().getSchemaManager(), dn,
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: TEST",
            "cn: test" );

        connection.add( entry );

        Dn targetDn = new Dn( targetDnStr );
        Entry target = new DefaultEntry( getService().getSchemaManager(), targetDn,
            "ObjectClass: top",
            "ObjectClass: person",
            "sn: TEST",
            "cn: test" );

        connection.add( target );

        assertNotNull( connection.lookup( oldDn ) );

        try
        {
            connection.move( oldDn, newSuperior );
            fail();
        }
        catch ( LdapEntryAlreadyExistsException leaee )
        {
            assertNotNull( connection.lookup( newDn ) );
            assertNotNull( connection.lookup( oldDn ) );
        }

        connection.close();
    }
}


text:
<?php

class OutputTableGenerator extends InterfaceGenerator {

   public $showRowLabel = false;
   public $statFieldType = null;

   public function generate($package, $extraClasses = "") {
      $rows = $package[$this->fieldName];
      if (!is_array($rows)) {
         $rows = array($rows);
      }

      $formatter = new ItemStoreGeneralFormatter();
      if ($this->statFieldType) {
         $formatter->statFieldCombiner = new $this->statFieldType();
      }

      $data = $formatter->formatByTimePeriod(
         $rows,
         TimePeriod::all_time_periods(),
         new PrimitiveFieldFormatter('amount'),  // How to render the field
         new EntrySumCombiner()  // How to distill the entries to a single field
      );

      $tableGenerator = new TableGenerator();
      return $this->assemble(
         "output-table " . $extraClasses,
         $this->buildContent(
            $tableGenerator->buildTable($data, $this->showRowLabel, null)
         )
      );
   }

   protected function loadSpecialized($config) {
      $this->showRowLabel = $this->field($config, 'rowLabel', false);
      $this->statFieldType = $this->field($config, 'statField', null);
   }
}


text:
const CONFIG = arguments[0] || {};

function navigateBack() {
  const { goBack } = CONFIG.navigation;
  goBack();
}

exports.navigationOptions = {
  window: {
    title: 'Profile'
  },
  navBar: {
    title: 'Profile'
  }
};


text:
namespace _03DependencyInversion
{
    using _03.DependencyInversion.Contracts;

    class PrimitiveCalculator
    {
        private IStrategy strategy;

        public PrimitiveCalculator(IStrategy strategy)
        {
            this.strategy = strategy;
        }

        public void changeStrategy(IStrategy strategy)
        {
            this.strategy = strategy;
        }

        public int performCalculation(int firstOperand, int secondOperand)
        {
            return this.strategy.Calculate(firstOperand, secondOperand);
        }
    }
}


text:
/**
 * @file   BaseGLWindow.h
 * @author Sebastian Maisch <sebastian.maisch@googlemail.com>
 * @date   2013.12.19
 *
 * @brief  Contains the base class for all OpenGL windows and definitions needed.
 */

#ifndef BASEGLWINDOW_H
#define BASEGLWINDOW_H

#include "gfx/glrenderer/GLRenderTarget.h"
#include "gfx/glrenderer/FrameBuffer.h"

namespace cgu {

    class TextureManager;
    class MaterialLibManager;
    class ShaderManager;
    class GPUProgramManager;
    class ShaderBufferBindingPoints;

    /**
     * @brief The base class for all OpenGL windows.
     *
     * @author Sebastian Maisch <sebastian.maisch@googlemail.com>
     * @date   2013.12.19
     */
    class BaseGLWindow : public GLRenderTarget
    {
    public:
        BaseGLWindow(unsigned int w, unsigned int h);
        virtual ~BaseGLWindow();

        /**
         * Shows a question message box.
         * @param title the message boxes title
         * @param content the message boxes content
         * @return returns true if the user pressed 'yes' false if 'no'
         */
        virtual bool MessageBoxQuestion(const std::string& title, const std::string& content) = 0;
        /** Swaps buffers and shows the content rendered since last call of Present(). */
        virtual void Present() = 0;
        /** Closes the window. */
        virtual void CloseWindow() = 0;

        /** Returns the windows width. */
        unsigned int GetWidth() const
        {
            return width;
        };

        /** Returns the windows height. */
        unsigned int GetHeight() const
        {
            return height;
        };

        unsigned int GetMouseButtonState(unsigned int btn) const { return mouseButtonState & btn; };
        glm::vec2 GetMouseRelative() const { return mouseRelative; };
        glm::vec2 GetMouseAbsolute() const { return mouseAbsolute; };
        glm::vec3 GetMouseAbsoluteNDC() const;
        unsigned int GetKeyboardModState(unsigned int modKey) const { return keyboardModState & modKey; };
        bool HadPositionUpdate() const { return hadPositionUpdate; };
        void HandledPositionUpdate() { hadPositionUpdate = false; };

        /*TextureManager* GetTextureManager() const;
        MaterialLibManager* GetMaterialLibManager() const;
        ShaderManager* GetShaderManager() const;
        GPUProgramManager* GetGPUProgramaManager() const;
        ShaderBufferBindingPoints* GetUBOBindingPoints() const;*/

    protected:
        /** Holds the texture manager. */
        TextureManager* texManager;
        /** Holds the material lib manager. */
        MaterialLibManager* matManager;
        /** Holds the shader manager. */
        ShaderManager* shaderManager;
        /** Holds the GPU program manager. */
        GPUProgramManager* programManager;
        /** Holds the uniform binding points. */
        ShaderBufferBindingPoints* uboBindingPoints;
        /** holds the current mouse button state. */
        unsigned int mouseButtonState;
        /** holds the current relative mouse position. */
        glm::vec2 mouseRelative;
        /** holds the current absolute mouse position. */
        glm::vec2 mouseAbsolute;
        /** holds the state of keyboard modificators (shift, ctrl, alt). */
        unsigned int keyboardModState;
        /** holds whether there was an update to the absolute position. */
        bool hadPositionUpdate;
    };
}
#endif /* BASEGLWINDOW_H */


text:
@interface PAPImageView ()

@property (nonatomic, strong) PFFile *currentFile;
@property (nonatomic, strong) NSString *url;

@end

@implementation PAPImageView

@synthesize currentFile,url;
@synthesize placeholderImage;

#pragma mark - PAPImageView

- (void) setFile:(PFFile *)file {
    UIImageView *border = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ShadowsProfilePicture-43.png"]];
    [self addSubview:border];

    NSString *requestURL = file.url; // Save copy of url locally (will not change in block)
    [self setUrl:file.url]; // Save copy of url on the instance

    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        if (!error) {
            UIImage *image = [UIImage imageWithData:data];
            if ([requestURL isEqualToString:self.url]) {
                [self setImage:image];
                [self setNeedsDisplay];
            }
        } else {
            NSLog(@"Error on fetching file");
        }
    }];
}

@end


text:
class Admin::PaymentsController < Admin::BaseController
  before_filter :load_data
  before_filter :load_amount, :except => :country_changed
  resource_controller
  belongs_to :order
  ssl_required

  def create
    build_object
    load_object

    begin

      unless object.save
        response_for :create_fails
        return
      end

      if @order.checkout.state == "complete"
        object.process!
        set_flash :create
        redirect_to collection_path
      else
        #This is the first payment (admin created order)
        until @order.checkout.state == "complete"
          @order.checkout.next!
        end
        self.notice = t('new_order_completed')
        redirect_to admin_order_url(@order)
      end

    rescue Spree::GatewayError => e
      flash[:error] = "#{e.message}"
      @payment.destroy
      redirect_to new_object_path
    end
  end

  def fire
    # TODO - possible security check here
    load_object
    return unless event = params[:e] and @payment.source

    if @payment.source.send("can_#{event}?", @payment)
      Payment.transaction do
        @payment.source.send("#{event}", @payment)
      end
      self.notice = t('payment_updated')
    else
      flash[:error] = t('cannot_perform_requested_transition')
    end
  rescue Spree::GatewayError => ge
    flash[:error] = "#{ge.message}"
  ensure
    redirect_to collection_path
  end

  def finalize
    object.finalize!
    redirect_to collection_path
  end

  private

  def object
    @object ||= Payment.find(param) unless param.nil?
    @object
  end

  def object_params
    if params[:payment] and params[:payment_source] and source_params = params.delete(:payment_source)[params[:payment][:payment_method_id]]
      params[:payment][:source_attributes] = source_params
    end
    params[:payment]
  end

  def load_data
    load_object
    @payment_methods = PaymentMethod.available(:back_end)
    if object and object.payment_method
      @payment_method = object.payment_method
    else
      @payment_method = @payment_methods.first
    end
    @previous_cards = @order.creditcards.with_payment_profile
    @countries = Country.find(:all).sort
    @shipping_countries = Checkout.countries.sort
    if current_user && current_user.bill_address
      default_country = current_user.bill_address.country
    else
      default_country = Country.find Spree::Config[:default_country_id]
    end
    @states = default_country.states.sort
  end

  def load_amount
    @amount = params[:amount] || @order.total
  end

  def build_object
    @object = model.new(object_params)
    @object.payable = parent_object.checkout
    @payment = @object
    if @object.payment_method.is_a?(Gateway) and @object.payment_method.payment_profiles_supported? and params[:card].present? and params[:card] != 'new'
      @object.source = Creditcard.find_by_id(params[:card])
    end
    @object
  end

end


text:
/**
    * Centralized logging implementation. Will add more streams later. Also need to make it Debug mode specific.
    * Author: Skylar Payne
    * Date: 6/8/2013
    * File: Entity.h
**/

#pragma once

#include <string>
#include <cstring>

class Logger
{
private:
    //later implement stream information here.
public:
    Logger& operator<<(const char* c);
    Logger& operator<<(const int i);
    Logger& operator<<(const unsigned int i);
    Logger& operator<<(const float f);

    void flush();
};

extern Logger g_Logger;


text:
<?php

class Clockworkgeek_Futureslider_Model_Resource_Slide extends Mage_Catalog_Model_Resource_Abstract
{

    protected function _construct()
    {
        $this->setType('futureslider_slide');
        $this->setConnection('core_read', 'core_write');
    }

    public function afterLoad(Mage_Core_Model_Abstract $object)
    {
        return $this->_afterLoad($object);
    }
}


text:
class NatureOpensearch < Source
  def get_query_url(work, options = {})
    query_string = get_query_string(work)
    return {} unless query_string.present?

    start_record = options[:start_record] || 1

    url % { query_string: query_string, start_record: start_record }
  end

  def get_data(work, options={})
    query_url = get_query_url(work, options)
    return query_url.extend Hashie::Extensions::DeepFetch if query_url.is_a?(Hash)

    result = get_result(query_url, options)

    # make sure we return a hash
    result = { 'data' => result } unless result.is_a?(Hash)

    total = (result.fetch("feed", {}).fetch("opensearch:totalResults", nil)).to_i

    if total > rows
      # walk through paginated results
      total_pages = (total.to_f / rows).ceil

      (2..total_pages).each do |page|
        options[:start_record] = page * 25 + 1
        query_url = get_query_url(work, options)
        paged_result = get_result(query_url, options)
        result["feed"]["entry"] = result["feed"]["entry"] | paged_result.fetch("feed", {}).fetch("entry", [])
      end
    end

    # extend hash fetch method to nested hashes
    result.extend Hashie::Extensions::DeepFetch
  end

  def parse_data(result, work, options={})
    return result if result[:error]

    related_works = get_related_works(result, work)
    total = related_works.length
    events_url = total > 0 ? get_events_url(work) : nil

    { works: related_works,
      events: {
        source: name,
        work: work.pid,
        total: total,
        events_url: events_url,
        days: get_events_by_day(related_works, work),
        months: get_events_by_month(related_works) } }
  end

  def get_related_works(result, work)
    # result.deep_fetch("sru:recordData", "pam:message", "pam:article", "xhtml:head") { nil }
    result.fetch("feed", {}).fetch("entry", []).map do |item|
      item.extend Hashie::Extensions::DeepFetch
      item = item.deep_fetch("sru:recordData", "pam:message", "pam:article", "xhtml:head") { {} }

      doi = item.fetch("prism:doi", nil)
      url = item.fetch("prism:url", nil)
      author_string = item.fetch("authorString", "").chomp(".")
      timestamp = item.fetch("prism:publicationDate", nil)
      timestamp = "#{timestamp}T00:00:00Z"

      { "author" => get_authors(item.fetch("dc:creator", [])),
        "title" => item.fetch("dc:title", ""),
        "container-title" => item.fetch("prism:publicationName", nil),
        "issued" => get_date_parts(timestamp),
        "timestamp" => timestamp,
        "DOI" => doi,
        "URL" => url,
        "type" => "article-journal",
        "tracked" => tracked,
        "related_works" => [{ "related_work" => work.pid,
                              "source" => name,
                              "relation_type" => "cites" }] }
    end
  end

  def config_fields
    [:url, :events_url]
  end

  def url
    "http://www.nature.com/opensearch/request?query=%{query_string}&httpAccept=application/json&startRecord=%{start_record}"
  end

  def events_url
    "http://www.nature.com/search?q=%{query_string}"
  end

  def rate_limiting
    config.rate_limiting || 25000
  end

  def rows
    25
  end
end


text:
import React from 'react'
import './styles.css'

const Container = ({ children }) => (
  <div className="Container">
    {children}
  </div>
)

export default Container


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibMinecraft.Server;
using LibMinecraft.Model.Entities;

namespace LibMinecraft.Model.Blocks
{
    /// <summary>
    /// A Grass block (ID = 2)
    /// </summary>
    /// <remarks></remarks>
    public class GrassBlock : Block
    {
        static Block[] AdjacentBlocks = new Block[24]; // Maximum number of applicable blocks

        /// <summary>
        /// The Block ID for this block (2)
        /// </summary>
        /// <remarks></remarks>
        public override byte BlockID
        {
            get { return 0x02; }
        }

        public override void BlockUpdate(World world, Vector3 position)
        {
            ScheduleUpdate(MultiplayerServer.Random.Next(100, 1000), position, world);
            base.BlockUpdate(world, position);
        }

        public override void ScheduledUpdate(World world, Vector3 position)
        {
            Block b = world.GetBlock(position + Vector3.Up);
            if (b.Transparent == BlockOpacity.Opaque || b.Transparent == BlockOpacity.CubeSolid)
                world.SetBlock(position, new DirtBlock());
        }
    }
}


text:
package org.redisson.reactive;

import java.util.Map;
import java.util.Map.Entry;

import org.reactivestreams.Publisher;
import org.redisson.RedissonMap;
import org.redisson.api.RMapCache;

import reactor.core.publisher.Flux;

/**
 *
 * @author Nikita Koksharov
 *
 * @param <K> key
 * @param <V> value
 */
public class RedissonMapCacheReactive<K, V> {

    private final RMapCache<K, V> mapCache;

    public RedissonMapCacheReactive(RMapCache<K, V> mapCache) {
        this.mapCache = mapCache;
    }

    public Publisher<Map.Entry<K, V>> entryIterator() {
        return entryIterator(null);
    }

    public Publisher<Map.Entry<K, V>> entryIterator(int count) {
        return entryIterator(null, count);
    }

    public Publisher<Map.Entry<K, V>> entryIterator(String pattern) {
        return entryIterator(pattern, 10);
    }

    public Publisher<Map.Entry<K, V>> entryIterator(String pattern, int count) {
        return Flux.create(new MapReactiveIterator<K, V, Map.Entry<K, V>>((RedissonMap<K, V>) mapCache, pattern, count));
    }

    public Publisher<V> valueIterator() {
        return valueIterator(null);
    }

    public Publisher<V> valueIterator(String pattern) {
        return valueIterator(pattern, 10);
    }

    public Publisher<V> valueIterator(int count) {
        return valueIterator(null, count);
    }

    public Publisher<V> valueIterator(String pattern, int count) {
        return Flux.create(new MapReactiveIterator<K, V, V>((RedissonMap<K, V>) mapCache, pattern, count) {
            @Override
            V getValue(Entry<Object, Object> entry) {
                return (V) entry.getValue();
            }
        });
    }

    public Publisher<K> keyIterator() {
        return keyIterator(null);
    }

    public Publisher<K> keyIterator(String pattern) {
        return keyIterator(pattern, 10);
    }

    public Publisher<K> keyIterator(int count) {
        return keyIterator(null, count);
    }

    public Publisher<K> keyIterator(String pattern, int count) {
        return Flux.create(new MapReactiveIterator<K, V, K>((RedissonMap<K, V>) mapCache, pattern, count) {
            @Override
            K getValue(Entry<Object, Object> entry) {
                return (K) entry.getKey();
            }
        });
    }

            }


text:
// open request
var request = new XMLHttpRequest();

// get the copy
request.open('GET', 'http://thecatapi.com/api/images/get?format=xml&results_per_page=12');

/**
 * Check when the request is done
 */
request.onreadystatechange = function() {

	// when the request in done show everything
	if ((request.readyState === 4) && (request.status === 200)) {

		// parse JSON
		var items = request.responseXML.getElementsByTagName('url');

		for (var i = 0; i < items.length; i++) {

			// write into the DOM
			document.getElementById('cats').innerHTML += '

';
		}

	}
}

// send the request
request.send();


text:
Godaften!

For et år siden stod verden ansigt til ansigt med en ufattelig katastrofe. Over 200.000 mennesker mistede livet under flodbølgen i Sydøstasien.

I oktober blev Pakistan ramt af et forfærdende jordskælv, som kostede over 70.000 mennesker livet.

Mange her i landet mistede familiemedlemmer eller nære venner under flodbølgen eller jordskælvet. Vore tanker og vor medfølelse går til alle, som så tragisk har mistet nogle af deres kære.

* * *

For Danmark blev 2005 et godt år. Vi har i dag én af Europas stærkeste økonomier. Langt de fleste danskere har mærket fremgangen på den ene eller den anden måde.

I løbet af 2005 kom der flere internationale vurderinger af Danmark med topkarakterer. Én af dem kårede Danmark til at have verdens bedste erhvervsklima. En anden udpegede Danmark til at have den samlet set bedste internationale bistand i verden.

De fortæller to vigtige ting om Danmark: Vi har orden i økonomien. Og vi har overskud til at tænke på andre end os selv.

Det gælder, når vi bidrager til at bringe fattige lande på fode. Først og fremmest i Afrika. Men også andre steder.

Det gælder, når danske nødhjælpsarbejdere ved hurtig og resolut indsats hjælper med at afbøde virkninger af naturkatastrofer. Som efter flodbølgen for et år siden. Og senest efter jordskælvet i Pakistan.

Og når danske soldater og politifolk deltager i fredsskabende og fredsbevarende aktioner. I Kosovo. I Afghanistan. I Irak. I Darfur. Og i andre af verdens brændpunkter.

De danskere, vi har sendt ud, gør en dygtig og engageret indsats. Vi kan være stolte over deres bidrag til at bevæge verden i den rigtige retning.

Jeg vil gerne sige en varm tak til hver og én af jer.

Vore soldater i Irak yder en prisværdig indsats med at hjælpe irakerne til at leve i frihed, fred og fremgang.

Det er et vanskeligt arbejde. For fanatiske grupper prøver med terror og trusler at blokere vejen frem til demokrati.

Men den irakiske befolkning har tre gange demonstreret, at den afviser terroristerne. Første gang ved at stemme i stort tal ved valget i januar. Dernæst ved folkeafstemningen om en ny forfatning i oktober. Og nu senest ved i meget stort tal at stemme ved parlamentsvalget i december.

For første gang træffer irakerne på demokratisk vis beslutninger om fremtiden for deres eget land. Det er opløftende.

Vi skal hjælpe det irakiske folk med at opbygge et frit og demokratisk Irak. Vi skal hjælpe den nye irakiske regering til selv at overtage ansvaret for Iraks sikkerhed.

Målet er, at de internationale tropper skal ud af Irak. Det gælder også de danske soldater. Vi skal ikke være der én dag længere, end det er nødvendigt.

Men det skal være folkevalgte politikere, der bestemmer. Ikke terrorister.

* * *

Her i Danmark oplever vi vækst og velstand. Beskæftigelsen stiger. Arbejdsløsheden falder. På mindre end to år er ledigheden faldet med omkring 35.000. Vi har nu den laveste reelle ledighed siden 1979.

I et par år var der bekymring for stigende ledighed. Nu er der bekymring for mangel på arbejdskraft. Lad os udnytte det offensivt. Nu har vi chancen for, at mennesker, der har haft rigtig svært ved at få arbejde, kan få fodfæste på arbejdsmarkedet.

Vi har overskud. På de offentlige budgetter. Og på betalingsbalancen. Udlandsgælden bliver støt og roligt bragt ned. Om et par år er den helt væk.

Tidligere steg skatter og afgifter år for år. Nu har vi skattestop. Og skatten på arbejde er sænket med omkring 10 mia. kr. For en typisk familie har det betydet en gevinst på over 10.000 kr. årligt.

Og boligejerne behøver ikke leve i frygt for, at de skal betale mere i skat, hver gang deres bolig stiger i værdi.

Så jo, det går godt i Danmark.

Og det er netop, når det går allerbedst, at vi skal træffe de nødvendige beslutninger, som er afgørende for landets fremtid. For det er på den måde, at vi kan gøre de gode tider langtidsholdbare. Træffer vi beslutningerne i god tid, kan vi med velovervejede justeringer få ganske store virkninger på længere sigt. Det vil ikke kun vi få glæde af, men også de kommende generationer.

I fremtiden bliver vi flere ældre -- og færre på arbejdsmarkedet.

Samtidig lever vi længere. Og det er jo positivt.

Men det giver også nogle udfordringer. For samtidig med, at vi lever længere, bruger vi mindre tid på arbejdsmarkedet.

Fortsætter den udvikling, så bliver der flere og flere, som vil trække på det offentlige. Og færre og færre til at betale skat. Det siger sig selv, at det ikke hænger sammen.

Derfor siger jeg: Vi bliver nødt til gradvist at udsætte det tidspunkt, hvor vi normalt trækker os tilbage fra arbejdslivet.

Det betyder, at vi må se på reglerne om efterløn og pension.

Heldigvis er vi i en gunstig situation. Vi behøver ikke et kriseindgreb over hals og hoved. Med den sunde økonomi kan vi gennemføre de nødvendige ændringer gradvist over en længere årrække. Så den enkelte i god tid kan nå at indrette sig på de nye forhold. Og selvfølgelig så skal der fortsat være mulighed for, at de, som er nedslidte, kan trække sig tilbage før tid.

Vi skal værne om den tryghed, vi har i dag. Men verden omkring os er i forandring. Derfor skal vi forny os, hvis vi også i fremtiden skal være blandt de rigeste og socialt bedst fungerende lande i verden. For tryghed i fremtiden kræver, at vi bliver bedre til at skabe ny viden og nye idéer. Bedre til at omsætte nye idéer til produktion og arbejdspladser. Bedre til at sætte nye ting i gang. Bedre til at opnå en god uddannelse for alle unge. Og bedre til at forny vores uddannelse gennem hele livet. Så vi hver især bliver bedre til at omstille os.

Alle skal med. En god uddannelse til alle er den vigtigste forudsætning for, at vi kan opretholde et samfund uden store økonomiske og sociale skel. Et samfund, der hænger sammen.

I slutningen af februar kommer regeringen med udspil til reformer. Reformer, som bl.a. betyder, at vi fremover bliver nogle år mere på arbejdsmarkedet og får flere indvandrere i arbejde.

Og reformer, som ruster Danmark stærkere til at klare den internationale konkurrence. Gennem kraftig satsning på forskning og udvikling. Uddannelse til alle unge. Voksen- og efteruddannelse. Bedre forhold for iværksættere. Det er dét, der i fremtiden skal gøre os bedre til at skabe nye arbejdspladser. Det, der vil skabe grundlag for tryghed.

Vi vil indbyde alle Folketingets partier til forhandlinger. Sigtet er en bred politisk aftale og lovgivning i 2006.

Vi skal træffe de nødvendige beslutninger nu. Så også vore børn og børnebørn kan leve i et godt, et trygt og et fremgangsrigt samfund.

* * *

Der har i det forløbne år været en heftig debat om ytringsfriheden og dens grænser. Og der er nogle, som mener, at tonen i debatten er blevet for grov.

Lad mig sige meget klart: Jeg fordømmer enhver udtalelse, handling eller tilkendegivelse, som forsøger at dæmonisere grupper af mennesker på baggrund af deres religion eller etniske baggrund.

Den slags hører ikke hjemme i et samfund, som netop bygger på respekten for det enkelte menneske.

Vi har en god tradition i Danmark for en vidtgående ytringsfrihed. Vi skal tale frit og sige vores mening ligeud til hinanden. Men det skal foregå i gensidig respekt og forståelse. Og i en ordentlig tone.

Og heldigvis så er tonen i den danske debat i almindelighed både ordentlig og redelig. Der har været enkelte eksempler på utilladeligt krænkende ytringer. Og de er såmænd kommet fra mere end én side i debatten. Dem må vi tage klart afstand fra.

Men de få eksempler må ikke overskygge den kendsgerning, at debatten og hele situationen i Danmark er langt fredeligere end i en række andre lande.

Vi har i Danmark en sund tradition for at stille kritiske spørgsmål til alle autoriteter, hvad enten de er politiske eller religiøse. Vi bruger humor. Vi bruger satire. Ja, vi har i det hele taget et lidt afslappet forhold til autoriteterne.

Og for nu at sige det ligeud: Det er denne tradition for manglende autoritetstro, det er denne trang til at sætte spørgsmålstegn ved det bestående, det er denne tilbøjelighed til at sætte alt til kritisk debat, som har skabt fremskridtet i vores samfund.

For det er i den proces, at nye horisonter bliver åbnet, nye opdagelser bliver gjort, nye idéer bliver født. Mens gamle systemer og forældede tankesæt falder.

Derfor er ytringsfriheden så afgørende. Og ytringsfriheden kan ikke gradbøjes. Den er ikke til forhandling.

Men vi har hver især et ansvar for at forvalte den på en sådan måde, at vi ikke opildner til had og ikke splintrer det fællesskab, som er én af Danmarks stærke sider.

Det er en betydelig styrke for det danske samfund, at vi i reglen er ret gode til at snakke os til rette om tingene. Fordi vi generelt set viser hensyn og har tillid til hinanden. Tillid til samfundets institutioner. Tillid til et sæt bærende principper for vort samfund.

Vi har bygget vort samfund på respekten for det enkelte menneskes liv og frihed, ytringsfrihed, ligestilling mellem kvinder og mænd, sondring mellem politik og religion. Vi tager udgangspunkt i, at mennesker er frie, selvstændige, ligeværdige og ansvarlige. Det skal vi værne om.

For det er nogle af de bånd, der giver samhørighed. Vi har derfor let ved at samarbejde. Let ved at løse fælles opgaver. Og derfor også lettere ved at klare nye udfordringer.

Lad os stå sammen om et samfund, hvor der er frihed til forskellighed. Og et samfund, hvor der er et stærkt fællesskab om grundlæggende værdier.

Et Danmark, som ikke blot har en stærk konkurrencekraft. Men også en stærk sammenhængskraft.

Godt nytår!


text:
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var path = require('path');

module.exports = yeoman.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);

    // add option to skip install
    this.option('skip-install');
  },
  initializing: function() {
    this.pkg = require('../../package.json');
    this.props = {};
  },
  prompting: {
    dirname: function () {
      this.log(yosay(
        'Welcome to the myun ' + chalk.red('generator-myun-vue ') + chalk.blue(this.pkg.version) + ' generator!'
      ));

      var done = this.async();
      var prompts = [
        {
          type: 'input',
          name: 'projectName',
          message: 'What is the project\'s name?'
        },
        {
          type: 'input',
          name: 'description',
          message: 'Enter project description'
        },
        {
          type: 'input',
          name: 'author',
          message: 'Enter project author name'
        },
        {
          type: 'input',
          name: 'version',
          message: 'Enter project version',
          default: 'v0.0.1'
        }
      ];

      this.prompt(prompts).then(function (answers) {
        this.projectName = answers.projectName;
        this.projectDes = answers.description;
        this.projectAuthor = answers.author;
        this.projectVersion = answers.version;
        this.props = answers;
        done();
      }.bind(this));
    }
  },
  defaults: function () {
    if (path.basename(this.destinationPath()) !== this.props.projectName) {
      this.log(
        'Your generator must be inside a folder named ' + this.props.projectName + '\n' +
        'I\'ll automatically create this folder.'
      );
      mkdirp(this.props.projectName);
      this.destinationRoot(this.destinationPath(this.props.projectName));
    }
  },
  writing: {
    packageJson: function () {
      this._copyTpl('_package.json', 'package.json', {
        projectName: this.projectName,
        projectDes: this.projectDes,
        projectAuthor: this.projectAuthor,
        projectVersion: this.projectVersion
      });
    },
    babel:function(){
      this._copy('_babelrc', '.babelrc');
    },
    editorconfig:function(){
      this._copy('_editorconfig', '.editorconfig');
    },
    eslint: function() {
      this._copy('_eslintrc.js', '.eslintrc.js');
    },
    gitattributes:function(){
      this._copy('_gitattributes', '.gitattributes');
    },
    gitignore: function() {
      this._copy('_gitignore', '.gitignore');
    },
    webpack: function() {
      mkdirp(this.destinationPath('./build'));
      this._copy('build/build.js', './build/build.js');
      this._copy('build/dev-client.js', './build/dev-client.js');
      this._copy('build/dev-server.js', './build/dev-server.js');
      this._copy('build/css-loaders.js', './build/css-loaders.js');
      this._copy('build/webpack.base.conf.js', './build/webpack.base.conf.js');
      this._copy('build/webpack.dev.conf.js', './build/webpack.dev.conf.js');
      this._copy('build/webpack.prod.conf.js', './build/webpack.prod.conf.js');
      mkdirp(this.destinationPath('./config'));
      this._copy('config/dev.env.js', './config/dev.env.js');
      this._copy('config/index.js', './config/index.js');
      this._copy('config/prod.env.js', './config/prod.env.js');
    },
    common: function() {
      mkdirp(this.destinationPath('./common'));
      this._copy('common/api.conf.js', './common/api.conf.js');
      this._copy('common/config.js', './common/config.js');
      this._copy('common/oss.conf.js', './common/oss.conf.js');
      this._copy('common/wx.conf.js', './common/wx.conf.js');
    },
    assets: function() {
      mkdirp(this.destinationPath('./src/assets'));
      this._copy('src/assets/pcd.js', './src/assets/pcd.js');
      this._copy('src/assets/config.js', './src/assets/config.js');
      this._copy('src/assets/function.js', './src/assets/function.js');
      this._copy('src/assets/lib.js', './src/assets/lib.js');
      this._copy('src/assets/myun.css', './src/assets/myun.css');
      mkdirp(this.destinationPath('./src/assets/font'));
      this._copy('src/assets/font/_gitkeep', './src/assets/font/.gitkeep');
      mkdirp(this.destinationPath('./src/assets/images'));
      this._copy('src/assets/images/_gitkeep', './src/assets/images/.gitkeep');
    },
    components: function() {
      mkdirp(this.destinationPath('./src/components'));
      this._copy('src/components/_gitkeep', './src/components/.gitkeep');
    },
    module: function() {
      mkdirp(this.destinationPath('./src/module/index'));
      this._copy('src/module/index/app.vue', './src/module/index/app.vue');
      this._copy('src/module/index/index.html', './src/module/index/index.html');
      this._copy('src/module/index/index.js', './src/module/index/index.js');
      mkdirp(this.destinationPath('./src/module/error'));
      this._copy('src/module/error/error.html', './src/module/error/error.html');
    },
    static: function() {
      mkdirp(this.destinationPath('./static'));
      this._copy('static/_gitkeep', './static/.gitkeep');
    },
    route: function() {
      mkdirp(this.destinationPath('./routes'));
      this._copy('routes/index.js', './routes/index.js');
    },
    bin: function() {
      mkdirp(this.destinationPath('./bin'));
      this._copy('bin/www', './bin/www');
    },
    app: function () {
      this._copy('_app.js', './app.js');
    },
    log: function () {
      mkdirp(this.destinationPath('./logs'));
      this._copy('logs/_gitkeep', './logs/.gitkeep');
      this._copy('_logger.js', './logger.js');
    }
  },
  _copy: function(from, to) {
    this.fs.copy(this.templatePath(from), this.destinationPath(to))
  },

  _copyTpl: function(from, to, params) {
    this.fs.copyTpl(this.templatePath(from), this.destinationPath(to), params)
  },
  install: function () {
    if (!this.options['skip-install']) this.installDependencies();
  }
});


text:
using System;
using System.ComponentModel;
using Prism.Regions;

namespace Prism.Wpf.Tests.Mocks
{
    class MockPresentationRegion : IRegion
    {
        public MockViewsCollection MockViews = new MockViewsCollection();
        public MockViewsCollection MockActiveViews = new MockViewsCollection();

        public MockPresentationRegion()
        {
            Behaviors = new MockRegionBehaviorCollection();
        }
        public IRegionManager Add(object view)
        {
            MockViews.Items.Add(view);

            return null;
        }

        public void Remove(object view)
        {
            MockViews.Items.Remove(view);
            MockActiveViews.Items.Remove(view);
        }

        public void Activate(object view)
        {
            MockActiveViews.Items.Add(view);
        }

        public IRegionManager Add(object view, string viewName)
        {
            throw new NotImplementedException();
        }

        public IRegionManager Add(object view, string viewName, bool createRegionManagerScope)
        {
            throw new NotImplementedException();
        }

        public object GetView(string viewName)
        {
            throw new NotImplementedException();
        }

        public IRegionManager RegionManager { get; set; }

        public IRegionBehaviorCollection Behaviors { get; set; }

        public IViewsCollection Views
        {
            get { return MockViews; }
        }

        public IViewsCollection ActiveViews
        {
            get { return MockActiveViews; }
        }

        public void Deactivate(object view)
        {
            MockActiveViews.Items.Remove(view);
        }

        private object context;
        public object Context
        {
            get { return context; }
            set
            {
                context = value;
                OnPropertyChange("Context");
            }
        }

        public NavigationParameters NavigationParameters
        {
            get { throw new System.NotImplementedException(); }
            set { throw new System.NotImplementedException(); }
        }

        private string name;
        public string Name
        {
            get { return this.name; }
            set
            {
                this.name = value;
                this.OnPropertyChange("Name");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public bool Navigate(Uri source)
        {
            throw new NotImplementedException();
        }

        public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback)
        {
            throw new NotImplementedException();
        }

        public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
        {
            throw new NotImplementedException();
        }

        public void RemoveAll()
        {
            throw new NotImplementedException();
        }

        public IRegionNavigationService NavigationService
        {
            get { throw new NotImplementedException(); }
            set { throw new System.NotImplementedException(); }
        }

        public Comparison<object> SortComparison
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
namespace TeleimotBg.Data
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using Models;

    public interface ITeleimotBgDbContext
    {
        IDbSet<User> Users { get; set; }

        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

        DbSet<TEntity> Set<TEntity>() where TEntity : class;

        int SaveChanges();

        void Dispose();
    }
}