text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import './diagnostics_card.js';
import './diagnostics_shared_css.js';
import './text_badge.js';

import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {RoutineResult, RoutineType, StandardRoutineResult} from './diagnostics_types.js';
import {getRoutineFailureMessage} from './diagnostics_utils.js';
import {RoutineGroup} from './routine_group.js';
import {ExecutionProgress, ResultStatusItem} from './routine_list_executor.js';
import {BadgeType} from './text_badge.js';

/**
 * Resolves a routine name to its corresponding localized string name.
 * @param {!RoutineType} routineType
 * @return {string}
 */
export function getRoutineType(routineType) {
  switch (routineType) {
    case RoutineType.kBatteryCharge:
      return loadTimeData.getString('batteryChargeRoutineText');
    case RoutineType.kBatteryDischarge:
      return loadTimeData.getString('batteryDischargeRoutineText');
    case RoutineType.kCaptivePortal:
      return loadTimeData.getString('captivePortalRoutineText');
    case RoutineType.kCpuCache:
      return loadTimeData.getString('cpuCacheRoutineText');
    case RoutineType.kCpuStress:
      return loadTimeData.getString('cpuStressRoutineText');
    case RoutineType.kCpuFloatingPoint:
      return loadTimeData.getString('cpuFloatingPointAccuracyRoutineText');
    case RoutineType.kCpuPrime:
      return loadTimeData.getString('cpuPrimeSearchRoutineText');
    case RoutineType.kDnsLatency:
      return loadTimeData.getString('dnsLatencyRoutineText');
    case RoutineType.kDnsResolution:
      return loadTimeData.getString('dnsResolutionRoutineText');
    case RoutineType.kDnsResolverPresent:
      return loadTimeData.getString('dnsResolverPresentRoutineText');
    case RoutineType.kGatewayCanBePinged:
      return loadTimeData.getString('gatewayCanBePingedRoutineText');
    case RoutineType.kHasSecureWiFiConnection:
      return loadTimeData.getString('hasSecureWiFiConnectionRoutineText');
    case RoutineType.kHttpFirewall:
      return loadTimeData.getString('httpFirewallRoutineText');
    case RoutineType.kHttpsFirewall:
      return loadTimeData.getString('httpsFirewallRoutineText');
    case RoutineType.kHttpsLatency:
      return loadTimeData.getString('httpsLatencyRoutineText');
    case RoutineType.kLanConnectivity:
      return loadTimeData.getString('lanConnectivityRoutineText');
    case RoutineType.kMemory:
      return loadTimeData.getString('memoryRoutineText');
    case RoutineType.kSignalStrength:
      return loadTimeData.getString('signalStrengthRoutineText');
    case RoutineType.kArcHttp:
      return loadTimeData.getString('arcHttpRoutineText');
    case RoutineType.kArcPing:
        return loadTimeData.getString('arcPingRoutineText');
    case RoutineType.kArcDnsResolution:
      return loadTimeData.getString('arcDnsResolutionRoutineText');
    default:
      // Values should always be found in the enum.
      assert(false);
      return '';
  }
}

/**
 * @param {!RoutineResult} result
 * @return {?StandardRoutineResult}
 */
export function getSimpleResult(result) {
  if (!result) {
    return null;
  }

  if (result.hasOwnProperty('simpleResult')) {
    // Ideally we would just return assert(result.simpleResult) but enum
    // value 0 fails assert.
    return /** @type {!StandardRoutineResult} */ (result.simpleResult);
  }

  if (result.hasOwnProperty('powerResult')) {
    return /** @type {!StandardRoutineResult} */ (
        result.powerResult.simpleResult);
  }

  assertNotReached();
  return null;
}

/**
 * @fileoverview
 * 'routine-result-entry' shows the status of a single test routine or group.
 */
Polymer({
  is: 'routine-result-entry',

  _template: html`{__html_template__}`,

  properties: {
    /**
     * Added to support testing of announce behavior.
     * @private
     * @type {string}
     */
    announcedText_: {
      type: String,
      value: '',
    },

    /** @type {RoutineGroup|ResultStatusItem} */
    item: {
      type: Object,
    },

    /** @private */
    routineType_: {
      type: String,
      computed: 'getRunningRoutineString_(item.*)',
    },

    /** @protected {!BadgeType} */
    badgeType_: {
      type: String,
      value: BadgeType.QUEUED,
    },

    /** @protected {string} */
    badgeText_: {
      type: String,
      value: '',
    },

    /** @protected {boolean} */
    testCompleted_: {
      type: Boolean,
      value: false,
    },

    /** @type {boolean} */
    hideVerticalLines: {
      type: Boolean,
      value: false,
    },

    /** @type {boolean} */
    usingRoutineGroups: {
      type: Boolean,
      value: false,
    },
  },

  observers: ['entryStatusChanged_(item.*)'],

  /** @override */
  attached() {
    IronA11yAnnouncer.requestAvailability();
  },

  /**
   * Get the localized string name for the routine.
   * @return {string}
   */
  getRunningRoutineString_() {
    if (this.usingRoutineGroups) {
      return loadTimeData.getString(this.item.groupName);
    }

    return loadTimeData.getStringF(
        'routineEntryText', getRoutineType(this.item.routine));
  },

  /**
   * @private
   */
  entryStatusChanged_() {
    switch (this.item.progress) {
      case ExecutionProgress.kNotStarted:
        this.setBadgeTypeAndText_(
            BadgeType.QUEUED, loadTimeData.getString('testQueuedBadgeText'));
        break;
      case ExecutionProgress.kRunning:
        this.setBadgeTypeAndText_(
            BadgeType.RUNNING, loadTimeData.getString('testRunningBadgeText'));
        this.announceRoutineStatus_();
        break;
      case ExecutionProgress.kCancelled:
        this.setBadgeTypeAndText_(
            BadgeType.STOPPED, loadTimeData.getString('testStoppedBadgeText'));
        break;
      case ExecutionProgress.kCompleted:
        this.testCompleted_ = true;
        // Prevent warning state from being overridden.
        if (this.item.inWarningState) {
          this.setBadgeTypeAndText_(
              BadgeType.WARNING,
              loadTimeData.getString('testWarningBadgeText'));
          return;
        }

        const testPassed = this.usingRoutineGroups ?
            !this.item.failedTest :
            (this.item.result &&
             getSimpleResult(this.item.result) ===
                 StandardRoutineResult.kTestPassed);
        const badgeType = testPassed ? BadgeType.SUCCESS : BadgeType.ERROR;
        const badgeText = loadTimeData.getString(
            testPassed ? 'testSucceededBadgeText' : 'testFailedBadgeText');
        this.setBadgeTypeAndText_(badgeType, badgeText);
        if (!testPassed) {
          this.announceRoutineStatus_();
        }
        break;
      case ExecutionProgress.kSkipped:
        this.setBadgeTypeAndText_(
            BadgeType.SKIPPED, loadTimeData.getString('testSkippedBadgeText'));
        break;
      case ExecutionProgress.kWarning:
        this.setBadgeTypeAndText_(
            BadgeType.WARNING, loadTimeData.getString('testWarningBadgeText'));
        break;
      default:
        assertNotReached();
    }
  },

  /**
   * @param {!BadgeType} badgeType
   * @param {string} badgeText
   * @private
   */
  setBadgeTypeAndText_(badgeType, badgeText) {
    this.setProperties({badgeType_: badgeType, badgeText_: badgeText});
  },

  /** @override */
  created() {},

  /** @private */
  announceRoutineStatus_() {
    this.announcedText_ = this.routineType_ + ' - ' + this.badgeText_;
    this.fire('iron-announce', {text: `${this.announcedText_}`});
  },

  /**
   * @protected
   * @return {string}
   */
  getLineClassName_(num) {
    if (!this.badgeType_) {
      return '';
    }

    let lineColor = '';
    switch (this.badgeType_) {
      case BadgeType.RUNNING:
      case BadgeType.SUCCESS:
        lineColor = 'green';
        break;
      case BadgeType.ERROR:
        lineColor = 'red';
        break;
      case BadgeType.WARNING:
        lineColor = 'yellow';
        break;
      case BadgeType.STOPPED:
      case BadgeType.QUEUED:
        return '';
    }
    return `line animation-${num} ${lineColor}`;
  },

  /**
   * @protected
   * @return {boolean}
   */
  shouldHideLines_() {
    return this.hideVerticalLines || !this.testCompleted_;
  },

  /**
   * @protected
   * @return {string}
   */
  computeFailedTestText_() {
    if (!this.usingRoutineGroups || !this.item.failedTest) {
      return '';
    }

    return getRoutineFailureMessage(this.item.failedTest);
  },
});


text:
<?php

namespace Symfony\Component\Security\Guard\Tests\Authenticator;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;

class AbstractFormLoginAuthenticatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @group legacy
     */
    public function testLegacyWithLoginUrl()
    {
        $request = new Request();
        $request->setSession($this->getMock('Symfony\Component\HttpFoundation\Session\Session'));

        $authenticator = new LegacyFormLoginAuthenticator();
        /** @var RedirectResponse $actualResponse */
        $actualResponse = $authenticator->onAuthenticationSuccess(
            $request,
            $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'),
            'provider_key'
        );

        $this->assertEquals('/default_url', $actualResponse->getTargetUrl());
    }
}

class LegacyFormLoginAuthenticator extends AbstractFormLoginAuthenticator
{
    protected function getDefaultSuccessRedirectUrl()
    {
        return '/default_url';
    }

    protected function getLoginUrl()
    {
    }

    public function getCredentials(Request $request)
    {
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
#nullable enable

namespace SkiaSharp.Views.Maui.Controls
{
	partial class SKImageImageSource : ISKImageImageSource
	{
	}

	partial class SKBitmapImageSource : ISKBitmapImageSource
	{
	}

	partial class SKPixmapImageSource : ISKPixmapImageSource
	{
	}

	partial class SKPictureImageSource : ISKPictureImageSource
	{
	}
}


text:
package org.eclipse.jetty.continuation;

import org.eclipse.jetty.servlets.ProxyServlet;
import org.junit.Ignore;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.FilterHolder;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.servlet.ServletHolder;

@Ignore("Not a test case")
public class TestProxyServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
        SelectChannelConnector selectChannelConnector = new SelectChannelConnector();
        server.setConnectors(new Connector[]{ selectChannelConnector });
        selectChannelConnector.setPort(8080);

        Context servletContext = new Context(Context.NO_SECURITY|Context.NO_SESSIONS);
        server.setHandler(servletContext);
        ServletHandler servletHandler=servletContext.getServletHandler();

        ServletHolder proxy=new ServletHolder(ProxyServlet.Transparent.class);
        servletHandler.addServletWithMapping(proxy,"/ws/*");
        proxy.setInitParameter("ProxyTo","http://www.webtide.com");
        proxy.setInitParameter("Prefix","/ws");

        FilterHolder filter=servletHandler.addFilterWithMapping(ContinuationFilter.class,"/*",0);
        filter.setInitParameter("debug","true");

        server.start();
        server.join();
    }
}


text:
package org.apache.storm.kafka;

import org.junit.Test;

import static org.junit.Assert.*;

public class ExponentialBackoffMsgRetryManagerTest {

  private static final Long TEST_OFFSET = 101L;
  private static final Long TEST_OFFSET2 = 102L;
  private static final Long TEST_OFFSET3 = 105L;
  private static final Long TEST_NEW_OFFSET = 103L;

  @Test
  public void testImmediateRetry() throws Exception {

    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.failed(TEST_OFFSET);
    Long next = manager.nextFailedMessageToRetry();
    assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
    assertTrue("message should be ready for retry immediately",
        manager.shouldReEmitMsg(TEST_OFFSET));

    manager.retryStarted(TEST_OFFSET);

    manager.failed(TEST_OFFSET);
    next = manager.nextFailedMessageToRetry();
    assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
    assertTrue("message should be ready for retry immediately",
        manager.shouldReEmitMsg(TEST_OFFSET));
  }

  @Test
  public void testSingleDelay() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(100, 1d, 1000, Integer.MAX_VALUE);
    manager.failed(TEST_OFFSET);
    Thread.sleep(5);
    Long next = manager.nextFailedMessageToRetry();
    assertNull("expect no message ready for retry yet", next);
    assertFalse("message should not be ready for retry yet", manager.shouldReEmitMsg(TEST_OFFSET));

    Thread.sleep(100);
    next = manager.nextFailedMessageToRetry();
    assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
    assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));
  }

  @Test
  public void testExponentialBackoff() throws Exception {
    final long initial = 10;
    final double mult = 2d;
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(initial, mult, initial * 10, Integer.MAX_VALUE);

    long expectedWaitTime = initial;
    for (long i = 0L; i < 3L; ++i) {
      manager.failed(TEST_OFFSET);

      Thread.sleep((expectedWaitTime + 1L) / 2L);
      assertFalse("message should not be ready for retry yet",
          manager.shouldReEmitMsg(TEST_OFFSET));

      Thread.sleep((expectedWaitTime + 1L) / 2L);
      Long next = manager.nextFailedMessageToRetry();
      assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
      assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));

      manager.retryStarted(TEST_OFFSET);
      expectedWaitTime *= mult;
    }
  }

  @Test
  public void testRetryOrder() throws Exception {
    final long initial = 10;
    final double mult = 2d;
    final long max = 20;
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(initial, mult, max, Integer.MAX_VALUE);

    manager.failed(TEST_OFFSET);
    Thread.sleep(initial);

    manager.retryStarted(TEST_OFFSET);
    manager.failed(TEST_OFFSET);
    manager.failed(TEST_OFFSET2);

    // although TEST_OFFSET failed first, it's retry delay time is longer b/c this is the second
    // retry so TEST_OFFSET2 should come first

    Thread.sleep(initial * 2);
    assertTrue("message " + TEST_OFFSET + "should be ready for retry",
        manager.shouldReEmitMsg(TEST_OFFSET));
    assertTrue("message " + TEST_OFFSET2 + "should be ready for retry",
        manager.shouldReEmitMsg(TEST_OFFSET2));

    Long next = manager.nextFailedMessageToRetry();
    assertEquals("expect first message to retry is " + TEST_OFFSET2, TEST_OFFSET2, next);

    Thread.sleep(initial);

    // haven't retried yet, so first should still be TEST_OFFSET2
    next = manager.nextFailedMessageToRetry();
    assertEquals("expect first message to retry is " + TEST_OFFSET2, TEST_OFFSET2, next);
    manager.retryStarted(next);

    // now it should be TEST_OFFSET
    next = manager.nextFailedMessageToRetry();
    assertEquals("expect message to retry is now " + TEST_OFFSET, TEST_OFFSET, next);
    manager.retryStarted(next);

    // now none left
    next = manager.nextFailedMessageToRetry();
    assertNull("expect no message to retry now", next);
  }

  @Test
  public void testQueriesAfterRetriedAlready() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.failed(TEST_OFFSET);
    Long next = manager.nextFailedMessageToRetry();
    assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
    assertTrue("message should be ready for retry immediately",
        manager.shouldReEmitMsg(TEST_OFFSET));

    manager.retryStarted(TEST_OFFSET);
    next = manager.nextFailedMessageToRetry();
    assertNull("expect no message ready after retried", next);
    assertFalse("message should not be ready after retried", manager.shouldReEmitMsg(TEST_OFFSET));
  }

  @Test(expected = IllegalStateException.class)
  public void testRetryWithoutFail() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.retryStarted(TEST_OFFSET);
  }

  @Test(expected = IllegalStateException.class)
  public void testFailRetryRetry() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.failed(TEST_OFFSET);
    try {
      manager.retryStarted(TEST_OFFSET);
    } catch (IllegalStateException ise) {
      fail("IllegalStateException unexpected here: " + ise);
    }

    assertFalse("message should not be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));
    manager.retryStarted(TEST_OFFSET);
  }

  @Test
  public void testMaxBackoff() throws Exception {
    final long initial = 100;
    final double mult = 2d;
    final long max = 2000;
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(initial, mult, max, Integer.MAX_VALUE);

    long expectedWaitTime = initial;
    for (long i = 0L; i < 4L; ++i) {
      manager.failed(TEST_OFFSET);

      Thread.sleep((expectedWaitTime + 1L) / 2L);
      assertFalse("message should not be ready for retry yet",
          manager.shouldReEmitMsg(TEST_OFFSET));

      Thread.sleep((expectedWaitTime + 1L) / 2L);
      Long next = manager.nextFailedMessageToRetry();
      assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
      assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));

      manager.retryStarted(TEST_OFFSET);
      expectedWaitTime = Math.min((long) (expectedWaitTime * mult), max);
    }
  }

  @Test
  public void testFailThenAck() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.failed(TEST_OFFSET);
    assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));

    manager.acked(TEST_OFFSET);

    Long next = manager.nextFailedMessageToRetry();
    assertNull("expect no message ready after acked", next);
    assertFalse("message should not be ready after acked", manager.shouldReEmitMsg(TEST_OFFSET));
  }

  @Test
  public void testAckThenFail() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.acked(TEST_OFFSET);
    assertFalse("message should not be ready after acked", manager.shouldReEmitMsg(TEST_OFFSET));

    manager.failed(TEST_OFFSET);

    Long next = manager.nextFailedMessageToRetry();
    assertEquals("expect test offset next available for retry", TEST_OFFSET, next);
    assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));
  }

  @Test
  public void testClearInvalidMessages() throws Exception {
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(0, 0d, 0, Integer.MAX_VALUE);
    manager.failed(TEST_OFFSET);
    manager.failed(TEST_OFFSET2);
    manager.failed(TEST_OFFSET3);

    assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET));
    assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET2));
    assertTrue("message should be ready for retry", manager.shouldReEmitMsg(TEST_OFFSET3));

    manager.clearOffsetsBefore(TEST_NEW_OFFSET);

    Long next = manager.nextFailedMessageToRetry();
    assertEquals("expect test offset next available for retry", TEST_OFFSET3, next);

    manager.acked(TEST_OFFSET3);
    next = manager.nextFailedMessageToRetry();
    assertNull("expect no message ready after acked", next);
  }

  @Test
  public void testMaxRetry() throws Exception {
    final long initial = 100;
    final double mult = 2d;
    final long max = 2000;
    final int maxRetries = 2;
    ExponentialBackoffMsgRetryManager manager =
        buildExponentialBackoffMsgRetryManager(initial, mult, max, maxRetries);
    assertTrue(manager.retryFurther(TEST_OFFSET));
    manager.failed(TEST_OFFSET);

    assertTrue(manager.retryFurther(TEST_OFFSET));
    manager.failed(TEST_OFFSET);

    assertFalse(manager.retryFurther(TEST_OFFSET));
  }

  private ExponentialBackoffMsgRetryManager buildExponentialBackoffMsgRetryManager(
      long retryInitialDelayMs,
      double retryDelayMultiplier,
      long retryDelayMaxMs,
      int retryLimit) {
    SpoutConfig spoutConfig = new SpoutConfig(null, null, null, null);
    spoutConfig.retryInitialDelayMs = retryInitialDelayMs;
    spoutConfig.retryDelayMultiplier = retryDelayMultiplier;
    spoutConfig.retryDelayMaxMs = retryDelayMaxMs;
    spoutConfig.retryLimit = retryLimit;
    ExponentialBackoffMsgRetryManager exponentialBackoffMsgRetryManager =
        new ExponentialBackoffMsgRetryManager();
    exponentialBackoffMsgRetryManager.prepare(spoutConfig, null);
    return exponentialBackoffMsgRetryManager;
  }
}


text:
- added link to coding standards in READ ME
- fixed variable declaration (#45)

## 0.6.0

- refactored promise code to make it work with changes that were made to angular 1.3.0-beta.18
- added .editorconfig file
- added main property to bower.json file (#44)

## 0.5.0

- coding standards update and other general code cleanup
- fixed issue where extending model data was not calling custom setter functions for the model properties (#42)
- added installation section to README (#35)
- fixed issue that would have the url include a trailing ? when there are no query string variables
- refactored parameters for repository's find() method
- added support for passing query string data (#41)
- added quick start guide to README
- update to used external data validation library

## 0.3.6
- added support for defining inherited methods in schema definitions (#28)

## 0.3.5
- fixed bug where model sync was not using full route

## 0.3.4
- added support for data validation (#3)

## 0.3.3
- added support for custom getters/setters for modal properties
- removed ES5 Shim since we are no longer support IE 8 (#20)
- added ability to mapping incoming data to different property names within the model (#22)
- fixed bug where base url was not being accounted for (#24)
- ModelFactory.create() now properly normalizes initail data( #25)
- Misc changes and clean up

## 0.3.0

- IE 8 support dropped
- Completely rewrote the foundation for models/repositories (backward compatible broken)
- Karma configuration file update (phantom configurations now include code coverage)
- Flatten url logic now accounts for the base url
- Added strict mode configuration though not being used anywhere yet

## 0.2.3

- Config values are now using a provider that can be configured in a module.config() instead of using .values()
- Added logic for flattenItemRoute property in schema definition for better support when using model.getRelation()
- Added logic for flatten for property are part of relation config in schema definition for better support when using model.getRelation()
- Added Karma configuration files for PhantomJS

## 0.2.2

- Added logic for isArray property in schema definition
- Added forceIsArray to model/repository instances

## 0.2.1

- Fixed typo where parseData was being used instead parsedData
- Move lodash into dev dependencies

## 0.2.0

- Initial Commit


text:
package hudson.model.queue;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.ExtensionList;
import hudson.model.Action;
import hudson.model.Executor;
import hudson.model.ExecutorListener;
import hudson.model.Queue;
import hudson.model.Queue.BuildableItem;
import hudson.model.Queue.Task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

/**
 * Holds the information shared between {@link WorkUnit}s created from the same {@link Task}.
 *
 * @author Kohsuke Kawaguchi
 */
public final class WorkUnitContext {

    private static final Logger LOGGER = Logger.getLogger(WorkUnitContext.class.getName());

    public final BuildableItem item;

    public final Task task;

    /**
     * Once the execution starts and completes, update this future object with the outcome.
     */
    public final FutureImpl future;

    /**
     * Associated parameters to the build.
     */
    public final List<Action> actions;

    private final Latch startLatch, endLatch;

    private List<WorkUnit> workUnits = new ArrayList<>();

    /**
     * If the execution is aborted, set to non-null that indicates where it was aborted.
     */
    private volatile Throwable aborted;

    public WorkUnitContext(BuildableItem item) {
        this.item = item;
        this.task = item.task;
        this.future = (FutureImpl) item.getFuture();
        // JENKINS-51584 do not use item.getAllActions() here.
        this.actions = new ArrayList<>(item.getActions());
        // +1 for the main task
        int workUnitSize = task.getSubTasks().size();
        startLatch = new Latch(workUnitSize) {
            @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "TODO needs triage")
            @Override
            protected void onCriteriaMet() {
                // on behalf of the member Executors,
                // the one that executes the main thing will send notifications
                // Unclear if this will work with AsynchronousExecution; it *seems* this is only called from synchronize which is only called from synchronizeStart which is only called from an executor thread.
                Executor e = Executor.currentExecutor();
                if (e.getCurrentWorkUnit().isMainWork()) {
                    e.getOwner().taskAccepted(e, task);
                    for (ExecutorListener listener : ExtensionList.lookup(ExecutorListener.class)) {
                        try {
                            listener.taskAccepted(e, task);
                        } catch (RuntimeException x) {
                            LOGGER.log(Level.WARNING, null, x);
                        }
                    }
                }
            }
        };

        endLatch = new Latch(workUnitSize);
    }

    /**
     * Called within the queue maintenance process to create a {@link WorkUnit} for the given {@link SubTask}
     */
    public WorkUnit createWorkUnit(SubTask execUnit) {
        WorkUnit wu = new WorkUnit(this, execUnit);
        workUnits.add(wu);
        return wu;
    }

    public List<WorkUnit> getWorkUnits() {
        return Collections.unmodifiableList(workUnits);
    }

    public WorkUnit getPrimaryWorkUnit() {
        return workUnits.get(0);
    }

    /**
     * All the {@link Executor}s that jointly execute a {@link Task} call this method to synchronize on the start.
     */
    @Restricted(NoExternalUse.class)
    public void synchronizeStart() throws InterruptedException {
        // Let code waiting for the start (future.start.get()) finishes when there is a faulty SubTask by setting the
        // future always.
        try {
            startLatch.synchronize();
        } finally {
            // the main thread will send a notification
            Executor e = Executor.currentExecutor();
            WorkUnit wu = e.getCurrentWorkUnit();
            if (wu.isMainWork()) {
                future.start.set(e.getCurrentExecutable());
                for (ExecutorListener listener : ExtensionList.lookup(ExecutorListener.class)) {
                    try {
                        listener.taskStarted(e, task);
                    } catch (RuntimeException x) {
                        LOGGER.log(Level.WARNING, null, x);
                    }
                }
            }
        }
    }

    @Deprecated
    public void synchronizeEnd(Queue.Executable executable, Throwable problems, long duration) throws InterruptedException {
        synchronizeEnd(Executor.currentExecutor(), executable, problems, duration);
    }

    /**
     * All the {@link Executor}s that jointly execute a {@link Task} call this method to synchronize on the end of the task.
     *
     * @throws InterruptedException
     *      If any of the member thread is interrupted while waiting for other threads to join, all
     *      the member threads will report {@link InterruptedException}.
     */
    @Restricted(NoExternalUse.class)
    public void synchronizeEnd(Executor e, Queue.Executable executable, Throwable problems, long duration) throws InterruptedException {
        // Let code waiting for the build to finish (future.get()) finishes when there is a faulty SubTask by setting
        // the future always.
        try {
            endLatch.synchronize();
        } finally {
            // the main thread will send a notification
            WorkUnit wu = e.getCurrentWorkUnit();
            if (wu.isMainWork()) {
                if (problems == null) {
                    future.set(executable);
                    e.getOwner().taskCompleted(e, task, duration);
                    for (ExecutorListener listener : ExtensionList.lookup(ExecutorListener.class)) {
                        try {
                            listener.taskCompleted(e, task, duration);
                        } catch (RuntimeException x) {
                            LOGGER.log(Level.WARNING, null, x);
                        }
                    }
                } else {
                    future.set(problems);
                    e.getOwner().taskCompletedWithProblems(e, task, duration, problems);
                    for (ExecutorListener listener : ExtensionList.lookup(ExecutorListener.class)) {
                        try {
                            listener.taskCompletedWithProblems(e, task, duration, problems);
                        } catch (RuntimeException x) {
                            LOGGER.log(Level.WARNING, null, x);
                        }
                    }
                }
            }
        }
    }

    /**
     * When one of the work unit is aborted, call this method to abort all the other work units.
     */
    public synchronized void abort(Throwable cause) {
        if (cause == null)        throw new IllegalArgumentException();
        if (aborted != null)      return; // already aborted
        aborted = cause;
        startLatch.abort(cause);
        endLatch.abort(cause);

        Thread c = Thread.currentThread();
        for (WorkUnit wu : workUnits) {
            Executor e = wu.getExecutor();
            if (e != null && e != c)
                e.interrupt();
        }
    }
}


text:
Amazon arora zero downtime patching

https://aws.amazon.com/blogs/aws/amazon-aurora-update-spatial-indexing-and-zero-downtime-patching/


text:
package org.opencb.opencga.app.migrations.v2_2_1.catalog;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptorFactory;
import org.opencb.opencga.catalog.migration.Migration;
import org.opencb.opencga.catalog.migration.MigrationTool;

import java.util.Collections;

@Migration(id = "init_shared_project",
        description = "Initialise sharedProjects #TASK-702", version = "2.2.1",
        language = Migration.MigrationLanguage.JAVA,
        domain = Migration.MigrationDomain.CATALOG,
        date = 20220502)
public class InitSharedProjectField extends MigrationTool {

    @Override
    protected void run() throws Exception {
        MongoCollection<Document> collection = getMongoCollection(MongoDBAdaptorFactory.USER_COLLECTION);
        Bson query = Filters.or(
            Filters.exists("sharedProjects", false),
            Filters.eq("sharedProjects", null)
        );
        Bson update = Updates.set("sharedProjects", Collections.emptyList());

        collection.updateMany(query, update);
    }
}


text:
package com.squarespace.template;

import java.util.HashMap;

public class StringViewMap<K, V> extends HashMap<K, V> {

  public StringViewMap(int numBuckets) {
    super(numBuckets);
  }

  /**
   * Dump the structure of the map to debug and tune the layout. I'd prefer to switch to a
   * compiled DFA-based replacement, which will eliminate need for a HashMap and calling
   * hashCode() on StringViews -- it will match incrementally, char-by-char.
   */
  public String dump() throws Exception {
    StringBuilder buf = new StringBuilder();
    /* TEMPORARILY DISABLED - phensley

    Field field = HashMap.class.getDeclaredField("table");
    field.setAccessible(true);

    Map.Entry<K, V>[] table = (Map.Entry<K, V>[])field.get(this);

    Class<?> hashMapEntryClass = null;
    for (Class<?> c : HashMap.class.getDeclaredClasses()) {
      if ("java.util.HashMap.Entry".equals(c.getCanonicalName())) {
        hashMapEntryClass = c;
      }
    }

    Field nextField = hashMapEntryClass.getDeclaredField("next");
    nextField.setAccessible(true);

    for (int i = 0, len = table.length; i < len; i++) {
      buf.append("Bucket ").append(i).append(":\n");
      Map.Entry<K, V> entry = table[i];

      int num = 0;
      while (entry != null) {
        num++;
        buf.append(entry.getKey()).append(' ');
        entry = (Map.Entry<K, V>)nextField.get(entry);
      }
      if (num > 0) {
        buf.append('(').append(num).append(')');
      }
      buf.append('\n');
    }
    */
    return buf.toString();
  }

}


text:
DEFINE_TEST_MODULE_REGISTER_FUNCTION_BODY(GameWorldLoaderTest)

namespace {
    const char* TEST_WORLD_PATH = "Worlds/World.json";
}

GameWorldLoaderTest::GameWorldLoaderTest() {
}

GameWorldLoaderTest::~GameWorldLoaderTest() {
}

void GameWorldLoaderTest::SetUp() {
    gameApp.reset(new TestGameApplication);
    ASSERT_TRUE(gameApp);
    ASSERT_TRUE(gameApp->initialize());

    world.reset(new GameWorld());
    ASSERT_TRUE(world);

    loader.reset(new GameWorldLoader(*world));
    ASSERT_TRUE(loader);
}

void GameWorldLoaderTest::TearDown() {
    loader.reset();
    world.reset();
    gameApp.reset();
}

TEST_F(GameWorldLoaderTest, TestWorldDescription) {
    ASSERT_TRUE(loader->loadWorld(TEST_WORLD_PATH));
    ASSERT_EQ(world->getName(), TEST_WORLD_PATH);
}


text:
import {
    takeLatest
} from 'redux-saga'
import {
    fork,
    put,
    call
} from 'redux-saga/effects'
import {
    message
} from 'antd'
import {
    getUserList, sendCaptcha, setAlipay, getMoney
} from '../services/user.js'

function* watchGetMoney() {
    yield* takeLatest('user/deposit', function* (action) {
        try {
            yield call(getMoney, action.payload)
            yield put({
                type: 'user/deposit/success'
            })
            yield call(action.meta.resolve)
        } catch (error) {
            yield put({
                type: 'user/deposit/failure'
            })
            yield call(action.meta.reject, error)
        }
    })
}

function* watchSetAlipay() {
    yield* takeLatest('user/alipay/set', function*(action) {
        try {
            yield call(setAlipay, action.payload.params)
            if (action.payload.resolve) {
                action.payload.resolve()
            }
            yield put({
                type: 'user/alipay/set/success',
                payload: action.payload.params
            })
        } catch (error) {
            if (action.payload.reject) {
                action.payload.reject(error)
            }
            yield put({
                type: 'user/alipay/set/failure'
            })
        }
    })
}

function* watchSendCaptcha() {
    yield* takeLatest('captcha/send', function* (action) {
        try {
            yield call(sendCaptcha, action.payload)
            yield put({
                type: 'captcha/send/success'
            })
            if (action.meta.resolve) {
                action.meta.resolve()
            }
        } catch (error) {
            yield put({
                type: 'captcha/send/failure'
            })
            if (action.meta.reject) {
                action.meta.reject()
            }
        }
    })
}

function* handleUserList(action) {
    try {
        const result = yield call(getUserList, action.payload)
        yield put({
            type: 'user/list/success',
            payload: {
                list: result.list
            }
        })
    } catch (error) {
        message.error(error)
        yield put({
            type: 'user/list/failure'
        })
    }
}

function* watchUserList() {
    yield * takeLatest('user/list', handleUserList)
}

export default function*() {
    yield * [
        fork(watchUserList),
        fork(watchSetAlipay),
        fork(watchSendCaptcha),
        fork(watchGetMoney)
    ]
}


text:
(function (window) {
    "use strict";

    class ReversibleMap extends Map {

        constructor() {

            super();

            this.uniques = new Set();
            this.reverseMap = new Map();

        }

        set(key, value) {

            // console.log("ReversibleMap.set");

            //Grab our old value (to manage unique tables)
            let oldValue = super.get(key);

            //If the new value matches the old, do nothing
            if (value === oldValue) return;

            //Set the key to the new value
            super.set(key, value);

            //Make sure the new value is in our list of uniques
            this.uniques.add(value);

            //Grab the set of things that point at the new value
            let reverseSet = this.reverseMap.get(value);

            //But first create a new set of it doesn't yet exist...
            if (!reverseSet) {
                reverseSet = new Set();
                this.reverseMap.set(value, reverseSet);
            }

            //Add the key to the set of things that point at the new value
            reverseSet.add(key);

            //Grab the set of things that pointed at the old value
            if (reverseSet = this.reverseMap.get(oldValue))

                //If the old set is now empty, kill the set and remove it from the uniques
                if (reverseSet.size === 1) {
                    this.reverseMap.delete(oldValue);
                    this.uniques.delete(oldValue);

                //Otherwise just update that set of things to indicate the key no longer points at it
                } else reverseSet.delete(key);

        }

        delete(key) {

            // console.log("ReversibleMap.delete");

            let value = super.get(key);
            super.delete(key);

            let reverseSet = this.reverseMap.get(value);
            if (!reverseSet) return;

            reverseSet.delete(key);

            if (reverseSet.size) this.reverseMap.set(value, reverseSet);
            else {
                this.reverseMap.delete(value);
                this.uniques.delete(value);
            }

        }

        reverse(value) {
            return this.reverseMap.get(value) || [];
        }

        get values() {
            return this.uniques;
        }

    }

    window.ReversibleMap = ReversibleMap;

}(window));


text:
class Catchmouse < Cask
  version 'latest'
  sha256 :no_check

  url 'http://ftnew.com/files/CatchMouse.zip'
  homepage 'http://ftnew.com/catchmouse.html'

  link 'CatchMouse.app'
end


text:
#include <OpenSim/OpenSim.h>

main() {
    // A study is the top level component that contains the model and other
    // computational components. It maintains "results" as data tables.
    // It is a replacement for Tool and the system and storgae owning
    // elements of the model
    Study muscleStudy;

    Model model("subject_02.osim");
    // the exact states trajectory generated by an OpenSim simulation
    StatesTrajectory states("states.ost");
    OutputReporter muscleReporter;
    muscleReporter.addOutput("/muscles/vasti_r/fiber_length");
    muscleReporter.addOutputs("/muscles/*/passive_fiber_force");
    muscleReporter.addOutputs("muscles/*/moment_arm");

    // Add the model to the study
    muscleStudy.addComponent(model);
    // Add reporters to the Study a NOT a Model
    muscleStudy.addReporter(muscleReporter);

    // initialize the Study and underlying system
    muscleStudy.initSystem();

    // realize the study to the reporting stage (time->pos->vel->acc->report)
    // so that all associated reporters can be evaluated
    for (const auto& state : states)
        muscleStudy.realizeReport(state);

    // in memory results to be used for further processing
    TimeSeriesTable results = muscleReporter.getReport();
    // or write it to file
    FileAdapter fileAdapter;
    fileAdapter.write("muscleResults.csv", results);
}


text:
using System;
using System.Net;
using System.Windows;
using System.Runtime.Serialization.Json;
using System.IO;
using Alexis.WindowsPhone.Social.Helper;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Alexis.WindowsPhone.Social.Renren;
using Alexis.WindowsPhone.Social.Resources;
using System.Windows.Media.Imaging;

namespace Alexis.WindowsPhone.Social
{
    public enum SocialType
    {
        /// <summary>
        /// sina weibo
        /// </summary>
        Weibo,
        /// <summary>
        /// tencent weibo
        /// </summary>
        Tencent,
        /// <summary>
        /// renren
        /// </summary>
        Renren,
        /// <summary>
        /// douban
        /// </summary>
        Douban,
        /// <summary>
        /// 163
        /// </summary>
        Net,
        /// <summary>
        /// Sohu.com
        /// </summary>
        Sohu,
        /// <summary>
        /// QQ空间
        /// </summary>
        QZone,
        /// <summary>
        /// twitter
        /// </summary>
        Twitter,
        /// <summary>
        /// facebook
        /// </summary>
        Facebook
    }

    public class SocialAPI
    {
        #region Public

        public static string ShareStatus { get; set; }

        public static SocialType CurrentSocialType { get; set; }

        public static string ShareImagePath { get; set; }

        public static bool IsLoginGoBack { get; set; }

        public static WriteableBitmap PreviewImage { get; set; }
        #endregion

        public const string SHARE_IMAGE_NAME = "share.jpg";
        public const string ACCESS_TOKEN_PREFIX = "accesstoken_{0}.json";
        static object _obj = new object();

        #region Property
        private static AccessToken _weiboAccessToken;
        public static AccessToken WeiboAccessToken
        {
            get
            {
                if (_weiboAccessToken == null)
                {
                    string path = string.Format(ACCESS_TOKEN_PREFIX, SocialType.Weibo);
                    _weiboAccessToken = JsonHelper.LoadJson<AccessToken>(path) as AccessToken;
                }
                return _weiboAccessToken;
            }
            set
            {
                _weiboAccessToken = value;
            }
        }

        private static AccessToken _tencentAccessToken;
        public static AccessToken TencentAccessToken
        {
            get
            {
                if (_tencentAccessToken == null)
                {
                    string path = string.Format(ACCESS_TOKEN_PREFIX, SocialType.Tencent);
                    _tencentAccessToken = JsonHelper.LoadJson<AccessToken>(path) as AccessToken;
                }
                return _tencentAccessToken;
            }
            set
            {
                _tencentAccessToken = value;
            }
        }

        private static AccessToken _renrenAccessToken;
        public static AccessToken RenrenAccessToken
        {
            get
            {
                if (_renrenAccessToken == null)
                {
                    string path = string.Format(ACCESS_TOKEN_PREFIX, SocialType.Renren);
                    _renrenAccessToken = JsonHelper.LoadJson<AccessToken>(path) as AccessToken;
                }
                return _renrenAccessToken;
            }
            set
            {
                _renrenAccessToken = value;
            }
        }

        private static AccessToken _qzoneAccessToken;
        public static AccessToken QZoneAccessToken
        {
            get
            {
                if (_qzoneAccessToken == null)
                {
                    string path = string.Format(ACCESS_TOKEN_PREFIX, SocialType.QZone);
                    _qzoneAccessToken = JsonHelper.LoadJson<AccessToken>(path) as AccessToken;
                }
                return _qzoneAccessToken;
            }
            set
            {
                _qzoneAccessToken = value;
            }
        }

        public static ClientInfo Client { get; set; }
        #endregion

        /// <summary>
        /// account logout, delete local cache and clear accesstoken
        /// </summary>
        /// <param name="type">social type</param>
        public static void LogOff(SocialType type)
        {
            if (MessageBox.Show(LangResource.LogOffConfirm, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
                return;
            }
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string path = string.Format(ACCESS_TOKEN_PREFIX, type);
                if (store.FileExists(path))
                {
                    store.DeleteFile(path);
                }
                if (type == SocialType.Weibo)
                {
                    WeiboAccessToken = null;
                }
                else if (type == SocialType.Tencent)
                {
                    TencentAccessToken = null;
                }
                else if (type == SocialType.Renren)
                {
                    RenrenAccessToken = null;
                }
                else if (type == SocialType.QZone)
                {
                    QZoneAccessToken = null;
                }
            }
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                MessageBox.Show(LangResource.LogOffSuccess);
            });
        }

        /// <summary>
        /// send status with image
        /// </summary>
        /// <param name="type">social type</param>
        /// <param name="status">text to send</param>
        /// <param name="imgPath">imgPath in IsoStore</param>
        /// <param name="action">send complete callback</param>
        public static void UploadStatusWithPic(SocialType type, string status, string imgPath, Action<bool, Exception> action)
        {
            HttpUploader uploader = new HttpUploader();
            uploader.parameters = new Dictionary<string, object>();
            switch (type)
            {
                case SocialType.Weibo:
                    {
                        uploader.url = "https://api.weibo.com/2/statuses/upload.json";
                        uploader.parameters.Add("status", status);
                        uploader.parameters.Add("access_token", WeiboAccessToken.Token);
                    }
                    break;
                case SocialType.Tencent:
                    {
                        uploader.url = "https://open.t.qq.com/api/t/add_pic";
                        uploader.parameters.Add("oauth_consumer_key", Client.ClientId);
                        uploader.parameters.Add("access_token", TencentAccessToken.Token);
                        uploader.parameters.Add("openid", TencentAccessToken.OpenId);
                        uploader.parameters.Add("oauth_version", "2.a");
                        uploader.parameters.Add("scope", "all");
                        uploader.parameters.Add("format", "json");
                        uploader.parameters.Add("content", status);
                    }
                    break;
                case SocialType.Renren:
                    {
                        uploader.url = "http://api.renren.com/restserver.do";
                        uploader.parameters.Add("method", "photos.upload");
                        uploader.parameters.Add("v", "1.0");
                        uploader.parameters.Add("access_token", RenrenAccessToken.Token);
                        uploader.parameters.Add("format", "JSON");
                        uploader.parameters.Add("caption", status);
                        uploader.parameters.Add("aid", "0");

                        List<APIParameter> para = new List<APIParameter>();
                        para.Add(new APIParameter("access_token", RenrenAccessToken.Token));
                        para.Add(new APIParameter("method", "photos.upload"));
                        para.Add(new APIParameter("v", "1.0"));
                        para.Add(new APIParameter("format", "JSON"));
                        para.Add(new APIParameter("caption", status));
                        para.Add(new APIParameter("aid", "0"));
                        uploader.parameters.Add("sig", CalSig(para));
                    }
                    break;
                case SocialType.QZone:
                    {
                        uploader.url = "https://graph.qq.com/share/add_share";
                        uploader.parameters.Add("title", status);
                        uploader.parameters.Add("oauth_consumer_key", Client.ClientId);
                        uploader.parameters.Add("format", "json");
                    }
                    break;
                case SocialType.Twitter:
                    {
                        uploader.url = "https://api.twitter.com/1.1/statuses/update_with_media";
                        uploader.parameters.Add("status", status);

                    }
                    break;
                case SocialType.Facebook:
                    {

                    }
                    break;
                case SocialType.Douban:
                    break;
                case SocialType.Net:
                    break;
                case SocialType.Sohu:
                    break;
                default:
                    break;
            }

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(imgPath))
                {
                    using (var stream = store.OpenFile(imgPath, FileMode.Open, FileAccess.Read))
                    {
                        byte[] bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, bytes.Length);
                        if (type == SocialType.Renren)
                        {
                            uploader.parameters.Add("upload", bytes);
                        }
                        else
                        {
                            uploader.parameters.Add("pic", bytes);
                        }
                    }
                }
                else
                {
                    //image do not exists
                    //TODO
                }
            }
            uploader.Submit();
            uploader.UploadCompleted += (e1, e2) =>
            {
                if (e1 is string && e1.ToString() == "ok")
                {
                    action(true, null);
                }
                else
                {
                    action(false, e1 as Exception);
                }
            };
        }

        /// <summary>
        /// 发送不带图片的微博
        /// 史坤
        /// 2012.7.4
        /// </summary>
        /// <param name="type">social type</param>
        /// <param name="status">text to send</param>
        /// <param name="action">send complete callback</param>
        public static void UpdateStatus(SocialType type, string status, Action<bool, Exception> action)
        {
            HttpUpdate uploader = new HttpUpdate();
            uploader.Type = type;
            uploader.parameters = new Dictionary<string, object>();
            switch (type)
            {
                case SocialType.Weibo:
                    {
                        uploader.url = "https://api.weibo.com/2/statuses/update.json";
                        uploader.parameters.Add("status", status);
                        uploader.parameters.Add("access_token", WeiboAccessToken.Token);
                    }
                    break;
                case SocialType.Tencent:
                    {
                        uploader.url = "https://open.t.qq.com/api/t/add";
                        uploader.parameters.Add("oauth_consumer_key", Client.ClientId);
                        uploader.parameters.Add("access_token", TencentAccessToken.Token);
                        uploader.parameters.Add("openid", TencentAccessToken.OpenId);
                        uploader.parameters.Add("oauth_version", "2.a");
                        uploader.parameters.Add("scope", "all");
                        uploader.parameters.Add("format", "json");
                        uploader.parameters.Add("content", status);
                    }
                    break;
                case SocialType.Renren:
                    {
                        uploader.url = "http://api.renren.com/restserver.do";
                        uploader.parameters.Add("method", "feed.publishFeed");
                        uploader.parameters.Add("v", "1.0");
                        uploader.parameters.Add("access_token", RenrenAccessToken.Token);
                        uploader.parameters.Add("format", "JSON");
                        uploader.parameters.Add("name", " ");
                        uploader.parameters.Add("message", status);
                        uploader.parameters.Add("description", " ");
                        uploader.parameters.Add("url", " ");

                        List<APIParameter> para = new List<APIParameter>();
                        para.Add(new APIParameter("access_token", RenrenAccessToken.Token));
                        para.Add(new APIParameter("method", "feed.publishFeed"));
                        para.Add(new APIParameter("v", "1.0"));
                        para.Add(new APIParameter("name", " "));
                        para.Add(new APIParameter("description", " "));
                        para.Add(new APIParameter("message", status));
                        para.Add(new APIParameter("url", " "));
                        para.Add(new APIParameter("format", "JSON"));

                        uploader.parameters.Add("sig", CalSig(para));
                    }
                    break;
                case SocialType.QZone:
                    {
                        // not finished
                        uploader.url = "https://graph.qq.com/share/add_share";
                        uploader.parameters.Add("title", status);
                        uploader.parameters.Add("site", status);
                        uploader.parameters.Add("fromurl", status);
                    }
                    break;
                case SocialType.Twitter:
                    {
                        uploader.url = "https://api.twitter.com/1.1/statuses/update";
                        uploader.parameters.Add("status", status);

                    }
                    break;
                case SocialType.Douban:
                    break;
                case SocialType.Net:
                    break;
                case SocialType.Sohu:
                    break;
                default:
                    break;
            }
            uploader.Submit();

            uploader.UploadCompleted += (e1, e2) =>
            {
                if (e1 is string && e1.ToString() == "ok")
                {
                    action(true, null);
                }
                else
                {
                    action(false, e1 as Exception);
                }
            };
        }

        #region Renren Calculate Sig
        internal static string CalSig(List<APIParameter> parameters)
        {
            parameters.Sort(new ParameterComparer());
            StringBuilder sbList = new StringBuilder();
            foreach (APIParameter para in parameters)
            {
                sbList.AppendFormat("{0}={1}", para.Name, para.Value);
            }
            sbList.Append(Client.ClientSecret);
            return MD5CryptoServiceProvider.GetMd5String((sbList.ToString()));
        }
        #endregion
    }
}


text:
package br.com.cofagra.bi.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Classe utilitaria para arquivos de properties.
 *
 * @author marcelo.borba
 */
public class PropertiesUtil {

     /**
      * Obtem um arquivo de properties a partir do caminho especificado.
      *
      * @param pathFile
      * caminho do arquivo.
      * @return arquivo de properties.
      */
     public Properties obterProperties(String pathFile) {

          InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(pathFile);
          Properties props = new Properties();

          try {

               props.load(inputStream);

          } catch (FileNotFoundException ex) {
               ex.printStackTrace();

          } catch (IOException ex) {
               ex.printStackTrace();
          }

          return props;
     }

}


text:
CREATE TABLE "public"."blog_entries" (
  "id" INTEGER DEFAULT nextval('blog_id_seq'::regclass) NOT NULL,
  "author_id" INTEGER NOT NULL,
  "name" VARCHAR(250) NOT NULL,
  "content" TEXT,
  "view_count" INTEGER DEFAULT 0,
  "modify_count" SMALLINT DEFAULT 0,
  "comment_count" INTEGER DEFAULT 0,
  "new_comment_count" INTEGER DEFAULT 0,
  "created" INTEGER,
  "modified" INTEGER,
  CONSTRAINT "blog_pkey" PRIMARY KEY("id"),
  CONSTRAINT "blog_user_id_fkey" FOREIGN KEY ("author_id")
    REFERENCES "public"."users"("id")
    ON DELETE CASCADE
    ON UPDATE NO ACTION
    NOT DEFERRABLE
) WITHOUT OIDS;

CREATE INDEX "blog_entry_user_id" ON "public"."blog_entries"
  USING btree ("author_id");

CREATE INDEX "blog_new_comment_count" ON "public"."blog_entries"
  USING btree ("new_comment_count");

CREATE INDEX "blog_view_count" ON "public"."blog_entries"
  USING btree ("view_count");


text:
#include <cstdint>
#include <Module.h>
#include <types/Int32.h>
#include <interpreter/at/MachineState.h>
#include <sexpr_parsing/CharacterStream.h>
#include <sexpr_parsing/SExprParser.h>
#include <sexpr_parsing/ModuleParser.h>
#include <assert.h>

using namespace wasm_module;
using namespace wasm_module::sexpr;
using namespace wasmint;

int main() {
    // we will just test some basic programs here to verify that the if_else and unreachable work that are required
    // for the test suite.

    // positive infinite_tests
    {

        MachineState environment;

        Module* positiveModule = ModuleParser::parse("module (func $main (if_else (i32.const 0) (unreachable) ()))");

        environment.useModule(*positiveModule, true);

        InterpreterThread & thread = environment.createThread().startAtFunction(positiveModule->name(), "$main");
        thread.stepUntilFinished();
    }
    {
        MachineState environment;

        Module* positiveModule = ModuleParser::parse("module (func $main (if_else (i32.const 1) () (unreachable)))");

        environment.useModule(*positiveModule, true);

        InterpreterThread & thread = environment.createThread().startAtFunction(positiveModule->name(), "$main");
        thread.stepUntilFinished();
    }
    // negative infinite_tests
    {

        MachineState environment;

        Module* positiveModule = ModuleParser::parse("module (func $main (if_else (i32.const 1) (unreachable) ()))");

        environment.useModule(*positiveModule, true);

        InterpreterThread & thread = environment.createThread().startAtFunction(positiveModule->name(), "$main");
        thread.stepUntilFinished();
        assert(thread.gotTrap());
    }
    {
        MachineState environment;

        Module* positiveModule = ModuleParser::parse("module (func $main (if_else (i32.const 0) () (unreachable)))");

        environment.useModule(*positiveModule, true);

        InterpreterThread & thread = environment.createThread().startAtFunction(positiveModule->name(), "$main");
        thread.stepUntilFinished();
        assert(thread.gotTrap());
    }
}


text:
require 'rubygems'
require 'happymapper'
require 'nokogiri'

require 'ext/nokogiri_skip_instruct'
require 'ext/ordered_hash'

require 'ext/happymapper_builder'

require "columbo/base"

require "columbo/family_name"
require "columbo/name"
require "columbo/id_value"

require "columbo/delivery_address"
require "columbo/address"
require "columbo/government_id"

require "columbo/client_references"

require "columbo/demographic_detail"

require "columbo/screening"
require "columbo/screenings"

require "columbo/contact_method"
require "columbo/personal_data"

require "columbo/background_check"

require "columbo/background_report"


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>ForeignExceptionListener (HBase 0.98.8-hadoop2 API)</title>
<meta name="date" content="2014-11-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.hadoop.hbase.errorhandling

Interface ForeignExceptionListener

All Known Implementing Classes:

ForeignExceptionDispatcher, Procedure

@InterfaceAudience.Private
@InterfaceStability.Evolving
public interface ForeignExceptionListener

The ForeignExceptionListener is an interface for objects that can receive a ForeignException.

 Implementations must be thread-safe, because this is expected to be used to propagate exceptions
 from foreign threads.

Method Summary

Methods

Modifier and Type
Method and Description

void
receive(ForeignException e)

Receive a ForeignException.

Method Detail

receive

void receive(ForeignException e)

Receive a ForeignException.

 Implementers must ensure that this method is thread-safe.

Parameters:

e - exception causing the error. Implementations must accept and handle null here.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 The Apache Software Foundation. All rights reserved.


text:
.navbar {
	display: none;
}
.main-navigation{
	display: none;
}
.hidden-print {
	display: none;
}
.breadcrumb {
	display: none;
}
.page-header {
	display: none;
}
.footer {
	display: none;
}
.main-container {
	margin: 0 !important;
	padding: 0 !important;
}
.main-content .container{
	min-height: auto !important;
	border: none !important;
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<org.jenkinsci.plugins.coordinator.model.CoordinatorProject plugin="coordinator">
  <actions/>
  <description></description>
  <logRotator class="hudson.tasks.LogRotator">
    <daysToKeep>-1</daysToKeep>
    <numToKeep>6</numToKeep>
    <artifactDaysToKeep>-1</artifactDaysToKeep>
    <artifactNumToKeep>-1</artifactNumToKeep>
  </logRotator>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <org.jenkinsci.plugins.coordinator.model.CoordinatorBuilder>
      <executionPlan>
        <id>j1_1</id>
        <text>Root_S_breaking</text>
        <type>breaking-serial</type>
        <children>
          <org.jenkinsci.plugins.coordinator.model.TreeNode>
            <id>j1_5</id>
            <text>1_S_non_breaking</text>
            <type>non-breaking-serial</type>
            <children>
              <org.jenkinsci.plugins.coordinator.model.TreeNode>
                <id>j1_9</id>
                <text>12_S_breaking</text>
                <type>breaking-serial</type>
                <children>
                  <org.jenkinsci.plugins.coordinator.model.TreeNode>
                    <id>j1_4</id>
                    <text>121_L_Failure</text>
                    <type>leaf</type>
                    <children/>
                    <state>
                      <opened>false</opened>
                      <disabled>false</disabled>
                      <selected>false</selected>
                      <checked>true</checked>
                      <undetermined>false</undetermined>
                      <breaking>true</breaking>
                      <execPattern>serial</execPattern>
                    </state>
                    <buildNumber>0</buildNumber>
                  </org.jenkinsci.plugins.coordinator.model.TreeNode>
                  <org.jenkinsci.plugins.coordinator.model.TreeNode>
                    <id>j1_10</id>
                    <text>122_S_non_breaking</text>
                    <type>non-breaking-serial</type>
                    <children>
                      <org.jenkinsci.plugins.coordinator.model.TreeNode>
                        <id>j1_11</id>
                        <text>122_L_4s</text>
                        <type>leaf</type>
                        <children/>
                        <state>
                          <opened>false</opened>
                          <disabled>false</disabled>
                          <selected>false</selected>
                          <checked>true</checked>
                          <undetermined>false</undetermined>
                          <breaking>true</breaking>
                          <execPattern>serial</execPattern>
                        </state>
                        <buildNumber>0</buildNumber>
                      </org.jenkinsci.plugins.coordinator.model.TreeNode>
                    </children>
                    <state>
                      <opened>true</opened>
                      <disabled>false</disabled>
                      <selected>true</selected>
                      <checked>true</checked>
                      <undetermined>false</undetermined>
                      <breaking>false</breaking>
                      <execPattern>serial</execPattern>
                    </state>
                    <buildNumber>0</buildNumber>
                  </org.jenkinsci.plugins.coordinator.model.TreeNode>
                </children>
                <state>
                  <opened>true</opened>
                  <disabled>false</disabled>
                  <selected>false</selected>
                  <checked>true</checked>
                  <undetermined>false</undetermined>
                  <breaking>true</breaking>
                  <execPattern>serial</execPattern>
                </state>
                <buildNumber>0</buildNumber>
              </org.jenkinsci.plugins.coordinator.model.TreeNode>
              <org.jenkinsci.plugins.coordinator.model.TreeNode>
                <id>j1_14</id>
                <text>13_S_breaking</text>
                <type>breaking-serial</type>
                <children>
                  <org.jenkinsci.plugins.coordinator.model.TreeNode>
                    <id>j1_2</id>
                    <text>21_L_Failure</text>
                    <type>leaf</type>
                    <children/>
                    <state>
                      <opened>false</opened>
                      <disabled>false</disabled>
                      <selected>false</selected>
                      <checked>true</checked>
                      <undetermined>false</undetermined>
                      <breaking>true</breaking>
                      <execPattern>serial</execPattern>
                    </state>
                    <buildNumber>0</buildNumber>
                  </org.jenkinsci.plugins.coordinator.model.TreeNode>
                </children>
                <state>
                  <opened>true</opened>
                  <disabled>false</disabled>
                  <selected>false</selected>
                  <checked>true</checked>
                  <undetermined>false</undetermined>
                  <breaking>true</breaking>
                  <execPattern>serial</execPattern>
                </state>
                <buildNumber>0</buildNumber>
              </org.jenkinsci.plugins.coordinator.model.TreeNode>
            </children>
            <state>
              <opened>true</opened>
              <disabled>false</disabled>
              <selected>false</selected>
              <checked>true</checked>
              <undetermined>false</undetermined>
              <breaking>false</breaking>
              <execPattern>serial</execPattern>
            </state>
            <buildNumber>0</buildNumber>
          </org.jenkinsci.plugins.coordinator.model.TreeNode>
        </children>
        <state>
          <opened>true</opened>
          <disabled>false</disabled>
          <selected>false</selected>
          <checked>true</checked>
          <undetermined>false</undetermined>
          <breaking>true</breaking>
          <execPattern>serial</execPattern>
        </state>
        <buildNumber>0</buildNumber>
      </executionPlan>
    </org.jenkinsci.plugins.coordinator.model.CoordinatorBuilder>
  </builders>
  <publishers/>
  <buildWrappers/>
</org.jenkinsci.plugins.coordinator.model.CoordinatorProject>


text:
/* eslint-env jest */
import React from 'react'
import { shallow } from 'enzyme'
import { EmptySegmentContainer } from '../EmptySegmentContainer'
import EmptySegment from '../EmptySegment'

describe('EmptySegment', () => {
  it('renders two <EmptySegment /> components of equal width', () => {
    const wrapper = shallow(<EmptySegmentContainer remainingWidth={10} occupiedWidth={40} />)

    expect(wrapper.find(EmptySegment).length).toEqual(2)
    expect(wrapper.find(EmptySegment).at(0).props()).toMatchObject({ width: 5, left: 0 })
    expect(wrapper.find(EmptySegment).at(1).props()).toMatchObject({ width: 5, left: 45 })
  })

  it('renders one <EmptySegment /> component if street is totally empty', () => {
    const wrapper = shallow(<EmptySegmentContainer remainingWidth={50} occupiedWidth={0} />)
    expect(wrapper.find(EmptySegment).length).toEqual(1)
    expect(wrapper.find(EmptySegment).at(0).props()).toMatchObject({ width: 50 })
  })

  it('renders zero <EmptySegment /> components if street is fully occupied', () => {
    const wrapper = shallow(<EmptySegmentContainer remainingWidth={0} occupiedWidth={50} />)
    expect(wrapper.find(EmptySegment).length).toEqual(0)
  })

  it('renders zero <EmptySegment /> components if street is over occupied', () => {
    const wrapper = shallow(<EmptySegmentContainer remainingWidth={-10} occupiedWidth={50} />)
    expect(wrapper.find(EmptySegment).length).toEqual(0)
  })
})


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

#nullable disable

namespace StyleCop.Analyzers.ReadabilityRules
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Immutable;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;
    using Microsoft.CodeAnalysis.Diagnostics;
    using StyleCop.Analyzers.Helpers;
    using StyleCop.Analyzers.Settings.ObjectModel;

    /// <summary>
    /// The code uses one of the basic C# types, but does not use the built-in alias for the type.
    /// </summary>
    /// <remarks>
    /// <para>A violation of this rule occurs when one of the following types are used anywhere in the code:
    /// <c>Boolean</c>, <c>Byte</c>, <c>Char</c>, <c>Decimal</c>, <c>Double</c>, <c>Int16</c>, <c>Int32</c>,
    /// <c>Int64</c>, <c>Object</c>, <c>SByte</c>, <c>Single</c>, <c>String</c>, <c>UInt16</c>, <c>UInt32</c>,
    /// <c>UInt64</c>.</para>
    ///
    /// <para>A violation also occurs when any of these types are represented in the code using the full namespace for
    /// the type:
    /// <c>System.Boolean</c>, <c>System.Byte</c>, <c>System.Char</c>, <c>System.Decimal</c>, <c>System.Double</c>,
    /// <c>System.Int16</c>, <c>System.Int32</c>, <c>System.Int64</c>, <c>System.Object</c>, <c>System.SByte</c>,
    /// <c>System.Single</c>, <c>System.String</c>, <c>System.UInt16</c>, <c>System.UInt32</c>,
    /// <c>System.UInt64</c>.</para>
    ///
    /// <para>Rather than using the type name or the fully-qualified type name, the built-in aliases for these types
    /// should always be used: <c>bool</c>, <c>byte</c>, <c>char</c>, <c>decimal</c>, <c>double</c>, <c>short</c>,
    /// <c>int</c>, <c>long</c>, <c>object</c>, <c>sbyte</c>, <c> float</c>, <c>string</c>, <c>ushort</c>, <c>uint</c>,
    /// <c>ulong</c>.</para>
    ///
    /// <para>The following table lists each of these types in all three formats:</para>
    ///
    /// <list type="table">
    /// <listheader>
    ///   <term>Type Alias</term>
    ///   <term>Type</term>
    ///   <term>Fully-Qualified Type</term>
    /// </listheader>
    /// <item>
    ///   <description>bool</description>
    ///   <description>Boolean</description>
    ///   <description>System.Boolean</description>
    /// </item>
    /// <item>
    ///   <description>byte</description>
    ///   <description>Byte</description>
    ///   <description>System.Byte</description>
    /// </item>
    /// <item>
    ///   <description>char</description>
    ///   <description>Char</description>
    ///   <description>System.Char</description>
    /// </item>
    /// <item>
    ///   <description>decimal</description>
    ///   <description>Decimal</description>
    ///   <description>System.Decimal</description>
    /// </item>
    /// <item>
    ///   <description>double</description>
    ///   <description>Double</description>
    ///   <description>System.Double</description>
    /// </item>
    /// <item>
    ///   <description>short</description>
    ///   <description>Int16</description>
    ///   <description>System.Int16</description>
    /// </item>
    /// <item>
    ///   <description>int</description>
    ///   <description>Int32</description>
    ///   <description>System.Int32</description>
    /// </item>
    /// <item>
    ///   <description>long</description>
    ///   <description>Int64</description>
    ///   <description>System.Int64</description>
    /// </item>
    /// <item>
    ///   <description>object</description>
    ///   <description>Object</description>
    ///   <description>System.Object</description>
    /// </item>
    /// <item>
    ///   <description>sbyte</description>
    ///   <description>SByte</description>
    ///   <description>System.SByte</description>
    /// </item>
    /// <item>
    ///   <description>float</description>
    ///   <description>Single</description>
    ///   <description>System.Single</description>
    /// </item>
    /// <item>
    ///   <description>string</description>
    ///   <description>String</description>
    ///   <description>System.String</description>
    /// </item>
    /// <item>
    ///   <description>ushort</description>
    ///   <description>UInt16</description>
    ///   <description>System.UInt16</description>
    /// </item>
    /// <item>
    ///   <description>uint</description>
    ///   <description>UInt32</description>
    ///   <description>System.UInt32</description>
    /// </item>
    /// <item>
    ///   <description>ulong</description>
    ///   <description>UInt64</description>
    ///   <description>System.UInt64</description>
    /// </item>
    /// </list>
    /// </remarks>
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal class SA1121UseBuiltInTypeAlias : DiagnosticAnalyzer
    {
        /// <summary>
        /// The ID for diagnostics produced by the <see cref="SA1121UseBuiltInTypeAlias"/> analyzer.
        /// </summary>
        public const string DiagnosticId = "SA1121";
        private const string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1121.md";
        private static readonly LocalizableString Title = new LocalizableResourceString(nameof(ReadabilityResources.SA1121Title), ReadabilityResources.ResourceManager, typeof(ReadabilityResources));
        private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(ReadabilityResources.SA1121MessageFormat), ReadabilityResources.ResourceManager, typeof(ReadabilityResources));
        private static readonly LocalizableString Description = new LocalizableResourceString(nameof(ReadabilityResources.SA1121Description), ReadabilityResources.ResourceManager, typeof(ReadabilityResources));

        private static readonly DiagnosticDescriptor Descriptor =
            new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.ReadabilityRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink, WellKnownDiagnosticTags.Unnecessary);

        private static readonly Action<CompilationStartAnalysisContext> CompilationStartAction = HandleCompilationStart;

        /// <inheritdoc/>
        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
            ImmutableArray.Create(Descriptor);

        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterCompilationStartAction(CompilationStartAction);
        }

        private static void HandleCompilationStart(CompilationStartAnalysisContext context)
        {
            Analyzer analyzer = new Analyzer(context.Compilation.GetOrCreateUsingAliasCache());
            context.RegisterSyntaxNodeAction(analyzer.HandleIdentifierNameSyntax, SyntaxKind.IdentifierName);
        }

        private sealed class Analyzer
        {
            private readonly ConcurrentDictionary<SyntaxTree, bool> usingAliasCache;

            public Analyzer(ConcurrentDictionary<SyntaxTree, bool> usingAliasCache)
            {
                this.usingAliasCache = usingAliasCache;
            }

            public void HandleIdentifierNameSyntax(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
            {
                IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)context.Node;
                if (identifierNameSyntax.IsVar)
                {
                    return;
                }

                if (identifierNameSyntax.Identifier.IsMissing)
                {
                    return;
                }

                switch (identifierNameSyntax.Identifier.ValueText)
                {
                case "bool":
                case "byte":
                case "char":
                case "decimal":
                case "double":
                case "short":
                case "int":
                case "long":
                case "object":
                case "sbyte":
                case "float":
                case "string":
                case "ushort":
                case "uint":
                case "ulong":
                    return;

                default:
                    break;
                }

                if (identifierNameSyntax.FirstAncestorOrSelf<UsingDirectiveSyntax>() != null
                    && identifierNameSyntax.FirstAncestorOrSelf<TypeArgumentListSyntax>() == null)
                {
                    return;
                }

                // Most source files will not have any using alias directives. Then we don't have to use semantics
                // if the identifier name doesn't match the name of a special type
                if (settings.ReadabilityRules.AllowBuiltInTypeAliases
                    || !identifierNameSyntax.SyntaxTree.ContainsUsingAlias(this.usingAliasCache))
                {
                    switch (identifierNameSyntax.Identifier.ValueText)
                    {
                    case nameof(Boolean):
                    case nameof(Byte):
                    case nameof(Char):
                    case nameof(Decimal):
                    case nameof(Double):
                    case nameof(Int16):
                    case nameof(Int32):
                    case nameof(Int64):
                    case nameof(Object):
                    case nameof(SByte):
                    case nameof(Single):
                    case nameof(String):
                    case nameof(UInt16):
                    case nameof(UInt32):
                    case nameof(UInt64):
                        break;

                    default:
                        return;
                    }
                }

                SemanticModel semanticModel = context.SemanticModel;

                // We go straight to the symbol here. We don't need to check alias information because aliases will fall
                // into one of two categories:
                //
                // 1. The alias to a built-in type matches the name of a built-in type (e.g. using Int32 = Int32;). In
                //    this case, a diagnostic is reported even if allowBuiltInTypeAliases=true.
                // 2. The alias to a built-in type is a different name. In this case, if allowBuiltInTypeAliases is true
                //    then the above code would have already returned due to the renamed symbol not being in the set of
                //    strings checked by the analyzer above.
                INamedTypeSymbol symbol = semanticModel.GetSymbolInfo(identifierNameSyntax, context.CancellationToken).Symbol as INamedTypeSymbol;

                switch (symbol?.SpecialType)
                {
                case SpecialType.System_Boolean:
                case SpecialType.System_Byte:
                case SpecialType.System_Char:
                case SpecialType.System_Decimal:
                case SpecialType.System_Double:
                case SpecialType.System_Int16:
                case SpecialType.System_Int32:
                case SpecialType.System_Int64:
                case SpecialType.System_Object:
                case SpecialType.System_SByte:
                case SpecialType.System_Single:
                case SpecialType.System_String:
                case SpecialType.System_UInt16:
                case SpecialType.System_UInt32:
                case SpecialType.System_UInt64:
                    break;

                default:
                    return;
                }

                SyntaxNode locationNode = identifierNameSyntax;
                if (identifierNameSyntax.Parent is QualifiedNameSyntax)
                {
                    locationNode = identifierNameSyntax.Parent;
                }
                else if ((identifierNameSyntax.Parent as MemberAccessExpressionSyntax)?.Name == identifierNameSyntax)
                {
                    // this "weird" syntax appears for qualified references within a nameof expression
                    locationNode = identifierNameSyntax.Parent;
                }
                else if (identifierNameSyntax.Parent is NameMemberCrefSyntax && identifierNameSyntax.Parent.Parent is QualifiedCrefSyntax)
                {
                    locationNode = identifierNameSyntax.Parent.Parent;
                }

                // Allow nameof
                if (IsNameInNameOfExpression(identifierNameSyntax))
                {
                    return;
                }

                // Use built-in type alias
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, locationNode.GetLocation()));
            }

            private static bool IsNameInNameOfExpression(IdentifierNameSyntax identifierNameSyntax)
            {
                // The only time a type name can appear as an argument is for the invocation expression created for the
                // nameof keyword. This assumption is the foundation of the following simple analysis algorithm.

                // This covers the case nameof(Int32)
                if (identifierNameSyntax.Parent is ArgumentSyntax)
                {
                    return true;
                }

                // This covers the case nameof(System.Int32)
                if (identifierNameSyntax.Parent is MemberAccessExpressionSyntax simpleMemberAccess)
                {
                    // This final check ensures that we don't consider nameof(System.Int32.ToString) the same as
                    // nameof(System.Int32)
                    return identifierNameSyntax.Parent.Parent.IsKind(SyntaxKind.Argument)
                        && simpleMemberAccess.Name == identifierNameSyntax;
                }

                return false;
            }
        }
    }
}


text:
require 'spec_helper'

module TestItemx

  describe TestItemx::TestSamplesController do

    before(:each) do
      #the following recognizes that there is a before filter without execution of it.
      controller.should_receive(:require_signin)
      controller.should_receive(:require_employee)
      #controller.should_receive(:session_timeout)
    end

    render_views

    describe "'show'" do
      it "should be successful for everyone" do
        ugrp = FactoryGirl.create(:authentify_sys_user_group, :user_group_name => 'eng')
        ul = FactoryGirl.create(:authentify_user_level, :sys_user_group_id => ugrp.id )
        u = FactoryGirl.create(:authentify_user, :user_levels => [ul])
        session[:user_id] = u.id
        session[:user_privilege] = Authentify::UserPrivilegeHelper::UserPrivilege.new(u.id)

        m = FactoryGirl.create(:manufacturer)
        rfq = FactoryGirl.create(:rfq, :emc_eng_id => u.id)
        q = FactoryGirl.create(:quote, :rfq_id => rfq.id)
        tl = FactoryGirl.create(:test_plan, :quote_id => q.id)
        ts = FactoryGirl.create(:test_sample, :test_plan_id => tl.id, :manufacturer_id => m.id)
        get 'show', {:use_route => :test_items, :id => ts.id, :test_plan_id => tl.id }
        response.should be_success
      end
    end

    describe "'new'" do

      it "should be successful" do
        ugrp = FactoryGirl.create(:authentify_sys_user_group, :user_group_name => 'eng')
        action = FactoryGirl.create(:authentify_sys_action_on_table, :action => 'create', :table_name => 'test_itemx_test_samples')
        right = FactoryGirl.create(:authentify_sys_user_right, :sys_user_group_id => ugrp.id, :sys_action_on_table_id => action.id)
        ul = FactoryGirl.create(:authentify_user_level, :sys_user_group_id => ugrp.id )
        u = FactoryGirl.create(:authentify_user, :user_levels => [ul])
        session[:user_id] = u.id
        session[:user_privilege] = Authentify::UserPrivilegeHelper::UserPrivilege.new(u.id)

        m = FactoryGirl.create(:manufacturer)
        prod = FactoryGirl.create(:productx_emc_it_product)
        rfq = FactoryGirl.create(:rfq, :emc_eng_id => u.id,:product_id => prod.id)
        q = FactoryGirl.create(:quote, :rfq_id => rfq.id)
        tl = FactoryGirl.create(:test_plan, :quote_id => q.id)
        ts = FactoryGirl.attributes_for(:test_sample, :test_plan_id => tl.id, :manufacturer_id => m.id)
        get 'new', {:use_route => :test_items, :test_plan_id => tl.id  }
        response.should be_success
      end

      it "should reject for those without rights" do
        ugrp = FactoryGirl.create(:authentify_sys_user_group, :user_group_name => 'eng')
        ul = FactoryGirl.create(:authentify_user_level, :sys_user_group_id => ugrp.id )
        u = FactoryGirl.create(:authentify_user, :user_levels => [ul])
        session[:user_id] = u.id
        session[:user_privilege] = Authentify::UserPrivilegeHelper::UserPrivilege.new(u.id)

        m = FactoryGirl.create(:manufacturer)
        prod = FactoryGirl.create(:productx_emc_it_product)
        rfq = FactoryGirl.create(:rfq, :emc_eng_id => u.id,:product_id => prod.id)
        q = FactoryGirl.create(:quote, :rfq_id => rfq.id)
        tl = FactoryGirl.create(:test_plan, :quote_id => q.id)
        ts = FactoryGirl.attributes_for(:test_sample, :test_plan_id => tl.id, :manufacturer_id => m.id)
        get 'new', {:use_route => :test_items, :test_plan_id => tl.id }
        response.should redirect_to URI.escape("/view_handler?index=0&msg=权限不足!")
      end

    end

    describe "'create'" do
      it "should be successful and sample record increased by -1-" do
        ugrp = FactoryGirl.create(:authentify_sys_user_group, :user_group_name => 'eng')
        action = FactoryGirl.create(:authentify_sys_action_on_table, :action => 'create', :table_name => 'test_itemx_test_samples')
        right = FactoryGirl.create(:authentify_sys_user_right, :sys_user_group_id => ugrp.id, :sys_action_on_table_id => action.id)
        ul = FactoryGirl.create(:authentify_user_level, :sys_user_group_id => ugrp.id )
        u = FactoryGirl.create(:authentify_user, :user_levels => [ul])
        session[:user_id] = u.id
        session[:user_privilege] = Authentify::UserPrivilegeHelper::UserPrivilege.new(u.id)

        m = FactoryGirl.create(:manufacturer)
        prod = FactoryGirl.create(:productx_emc_it_product)
        rfq = FactoryGirl.create(:rfq, :emc_eng_id => u.id,:product_id => prod.id)
        q = FactoryGirl.create(:quote, :rfq_id => rfq.id)
        tl = FactoryGirl.create(:test_plan, :quote_id => q.id)
        ts = FactoryGirl.attributes_for(:test_sample, :test_plan_id => tl.id, :manufacturer_id => m.id)
        lambda do
          get 'create', {:use_route => :test_items, :test_plan_id => tl.id, :test_sample => ts }
          response.should redirect_to quote_test_plan_path(tl.quote_id, tl)
        end.should change(TestSample, :count).by(1)
      end
    end

    describe "'edit'" do
      it "should reject for those without rights" do
        ugrp = FactoryGirl.create(:authentify_sys_user_group, :user_group_name => 'eng')
        ul = FactoryGirl.create(:authentify_user_level, :sys_user_group_id => ugrp.id )
        u = FactoryGirl.create(:authentify_user, :user_levels => [ul])
        session[:user_id] = u.id
        session[:user_privilege] = Authentify::UserPrivilegeHelper::UserPrivilege.new(u.id)

        m = FactoryGirl.create(:manufacturer)
        rfq = FactoryGirl.create(:rfq, :emc_eng_id => u.id)
        q = FactoryGirl.create(:quote, :rfq_id => rfq.id)
        tl = FactoryGirl.create(:test_plan, :quote_id => q.id)
        ts = FactoryGirl.create(:test_sample, :test_plan_id => tl.id, :manufacturer_id => m.id)
        get 'edit', {:use_route => :test_items, :id => ts.id, :test_plan_id => tl.id }
        response.should redirect_to URI.escape("/view_handler?index=0&msg=权限不足!")
      end
    end

    describe "'update'" do
      it "should be OK for those with rights" do
        ugrp = FactoryGirl.create(:authentify_sys_user_group, :user_group_name => 'eng')
        action = FactoryGirl.create(:authentify_sys_action_on_table, :action => 'create', :table_name => 'test_itemx_test_samples')
        right = FactoryGirl.create(:authentify_sys_user_right, :sys_user_group_id => ugrp.id, :sys_action_on_table_id => action.id)
        ul = FactoryGirl.create(:authentify_user_level, :sys_user_group_id => ugrp.id )
        u = FactoryGirl.create(:authentify_user, :user_levels => [ul])
        session[:user_id] = u.id
        session[:user_privilege] = Authentify::UserPrivilegeHelper::UserPrivilege.new(u.id)

        m = FactoryGirl.create(:manufacturer)
        rfq = FactoryGirl.create(:rfq, :emc_eng_id => u.id)
        q = FactoryGirl.create(:quote, :rfq_id => rfq.id)
        tl = FactoryGirl.create(:test_plan, :quote_id => q.id)
        ts = FactoryGirl.create(:test_sample, :test_plan_id => tl.id, :manufacturer_id => m.id)
        lambda do
          get 'update', {:use_route => :test_items, :id => ts.id, :test_plan_id => tl.id, :test_sample => {:return_date => '2012-6-6' }  }
          response.should redirect_to quote_test_plan_path(tl.quote, tl)
          #response.should render_template('edit')
        end.should change(TestSample, :count).by(0)
      end

    end

    describe "'destroy'" do
      it "should be successful" do
        get 'destroy', {:use_route => :test_items}
        response.should be_success
      end
    end

  end
end