text:
<?php

final class PhabricatorPasteSearchEngine
  extends PhabricatorApplicationSearchEngine {

  public function buildSavedQueryFromRequest(AphrontRequest $request) {
    $saved = new PhabricatorSavedQuery();
    $saved->setParameter(
      'authorPHIDs',
      array_values($request->getArr('authors')));

    $languages = $request->getStrList('languages');
    if ($request->getBool('noLanguage')) {
      $languages[] = null;
    }
    $saved->setParameter('languages', $languages);

    $saved->setParameter('createdStart', $request->getStr('createdStart'));
    $saved->setParameter('createdEnd', $request->getStr('createdEnd'));

    return $saved;
  }

  public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
    $query = id(new PhabricatorPasteQuery())
      ->needContent(true)
      ->withAuthorPHIDs($saved->getParameter('authorPHIDs', array()))
      ->withLanguages($saved->getParameter('languages', array()));

    $start = $this->parseDateTime($saved->getParameter('createdStart'));
    $end = $this->parseDateTime($saved->getParameter('createdEnd'));

    if ($start) {
      $query->withDateCreatedAfter($start);
    }

    if ($end) {
      $query->withDateCreatedBefore($end);
    }

    return $query;
  }

  public function buildSearchForm(
    AphrontFormView $form,
    PhabricatorSavedQuery $saved_query) {
    $phids = $saved_query->getParameter('authorPHIDs', array());
    $handles = id(new PhabricatorObjectHandleData($phids))
      ->setViewer($this->requireViewer())
      ->loadHandles();
    $author_tokens = mpull($handles, 'getFullName', 'getPHID');

    $languages = $saved_query->getParameter('languages', array());
    $no_language = false;
    foreach ($languages as $key => $language) {
      if ($language === null) {
        $no_language = true;
        unset($languages[$key]);
        continue;
      }
    }

    $form
      ->appendChild(
        id(new AphrontFormTokenizerControl())
          ->setDatasource('/typeahead/common/users/')
          ->setName('authors')
          ->setLabel(pht('Authors'))
          ->setValue($author_tokens))
      ->appendChild(
        id(new AphrontFormTextControl())
          ->setName('languages')
          ->setLabel(pht('Languages'))
          ->setValue(implode(', ', $languages)))
      ->appendChild(
        id(new AphrontFormCheckboxControl())
          ->addCheckbox(
            'noLanguage',
            1,
            pht('Find Pastes with no specified language.'),
            $no_language));

    $this->buildDateRange(
      $form,
      $saved_query,
      'createdStart',
      pht('Created After'),
      'createdEnd',
      pht('Created Before'));

  }

  protected function getURI($path) {
    return '/paste/'.$path;
  }

  public function getBuiltinQueryNames() {
    $names = array(
      'all' => pht('All Pastes'),
    );

    if ($this->requireViewer()->isLoggedIn()) {
      $names['authored'] = pht('Authored');
    }

    return $names;
  }

  public function buildSavedQueryFromBuiltin($query_key) {

    $query = $this->newSavedQuery();
    $query->setQueryKey($query_key);

    switch ($query_key) {
      case 'all':
        return $query;
      case 'authored':
        return $query->setParameter(
          'authorPHIDs',
          array($this->requireViewer()->getPHID()));
    }

    return parent::buildSavedQueryFromBuiltin($query_key);
  }

}


text:
/// <reference path="typedefs/typedefs.ts"/>

/// <reference path="DOMConstants.ts"/>
/// <reference path="CssConstants.ts"/>
/// <reference path="serviceError.ts"/>
/// <reference path="services/build.ts"/>
/// <reference path="services/geoTaggingAnalyzerService.ts"/>
/// <reference path="typedefs/buildConstants.ts"/>
/// <reference path="clientError.ts"/>
/// <reference path="arrayExtensions.ts"/>
/// <reference path="Controls/DomFactory.ts"/>
/// <reference path="Double.ts"/>
/// <reference path="color.ts"/>
/// <reference path="debug.ts"/>
/// <reference path="DragDrop.ts"/>
/// <reference path="Errors.ts"/>
/// <reference path="IStringResourceProvider.ts"/>
/// <reference path="JQueryExtensions.ts"/>
/// <reference path="Lazy.ts"/>
/// <reference path="promise.ts"/>
/// <reference path="Prototype.ts"/>
/// <reference path="ScriptErrorInfo.ts"/>
/// <reference path="Formatting.ts"/>
/// <reference path="services/requires.ts"/>
/// <reference path="services/jqueryPromiseFactory.ts"/>
/// <reference path="services/localStorageService.ts"/>
/// <reference path="services/textMeasurementService.ts"/>
/// <reference path="Utility/ThrottleUtility.ts"/>
/// <reference path="Utility/TimerPromiseFactory.ts"/>
/// <reference path="Utility/Utility.ts"/>
/// <reference path="tracing/traceItem.ts"/>
/// <reference path="Utility/StandaloneUtility.ts"/>
/// <reference path="tracing/trace.ts"/>
/// <reference path="tracing/traceType.ts"/>
/// <reference path="services/dependencies.ts"/>

redpajama_set_name: RedPajamaGithub


text:
require 'puppet/indirector/face'

Puppet::Indirector::Face.define(:catalog, '0.0.1') do
  copyright "Puppet Labs", 2011
  license   "Apache 2 license; see COPYING"

  summary "Compile, save, view, and convert catalogs."
  description <<-'EOT'
    This subcommand deals with catalogs, which are compiled per-node artifacts
    generated from a set of Puppet manifests. By default, it interacts with the
    compiling subsystem and compiles a catalog using the default manifest and
    `certname`, but you can change the source of the catalog with the
    `--terminus` option. You can also choose to print any catalog in 'dot'
    format (for easy graph viewing with OmniGraffle or Graphviz) with
    '--render-as dot'.
  EOT
  short_description <<-'EOT'
    This subcommand deals with catalogs, which are compiled per-node artifacts
    generated from a set of Puppet manifests. By default, it interacts with the
    compiling subsystem and compiles a catalog using the default manifest and
    `certname`; use the `--terminus` option to change the source of the catalog.
  EOT

  get_action(:destroy).summary "Invalid for this subcommand."
  get_action(:search).summary "Invalid for this subcommand."
  find = get_action(:find)
  find.summary "Retrieve the catalog for a node."
  find.arguments "<certname>"
  find.returns <<-'EOT'
    A serialized catalog. When used from the Ruby API, returns a
    Puppet::Resource::Catalog object.
  EOT

  action(:apply) do
    summary "Find and apply a catalog."
    description <<-'EOT'
      Finds and applies a catalog. This action takes no arguments, but
      the source of the catalog can be managed with the `--terminus` option.
    EOT
    returns <<-'EOT'
      Nothing. When used from the Ruby API, returns a
      Puppet::Transaction::Report object.
    EOT
    examples <<-'EOT'
      Apply the locally cached catalog:

      $ puppet catalog apply --terminus yaml

      Retrieve a catalog from the master and apply it, in one step:

      $ puppet catalog apply --terminus rest

      From `secret_agent.rb` (API example):

          # ...
          Puppet::Face[:catalog, '0.0.1'].download
          # (Termini are singletons; catalog.download has a side effect of
          # setting the catalog terminus to yaml)
          report  = Puppet::Face[:catalog, '0.0.1'].apply
          # ...
    EOT

    when_invoked do |options|
      catalog = Puppet::Face[:catalog, "0.0.1"].find(Puppet[:certname]) or raise "Could not find catalog for #{Puppet[:certname]}"
      catalog = catalog.to_ral

      report = Puppet::Transaction::Report.new("apply")
      report.configuration_version = catalog.version
      report.environment = Puppet[:environment]

      Puppet::Util::Log.newdestination(report)

      begin
        benchmark(:notice, "Finished catalog run") do
          catalog.apply(:report => report)
        end
      rescue => detail
        Puppet.log_exception(detail, "Failed to apply catalog: #{detail}")
      end

      report.finalize_report
      report
    end
  end

  action(:download) do
    summary "Download this node's catalog from the puppet master server."
    description <<-'EOT'
      Retrieves a catalog from the puppet master and saves it to the local yaml
      cache. This action always contacts the puppet master and will ignore
      alternate termini.

      The saved catalog can be used in any subsequent catalog action by specifying
      '--terminus yaml' for that action.
    EOT
    returns "Nothing."
    notes <<-'EOT'
      When used from the Ruby API, this action has a side effect of leaving
      Puppet::Resource::Catalog.indirection.terminus_class set to yaml. The
      terminus must be explicitly re-set for subsequent catalog actions.
    EOT
    examples <<-'EOT'
      Retrieve and store a catalog:

      $ puppet catalog download

      From `secret_agent.rb` (API example):

          Puppet::Face[:plugin, '0.0.1'].download
          Puppet::Face[:facts, '0.0.1'].upload
          Puppet::Face[:catalog, '0.0.1'].download
          # ...
    EOT
    when_invoked do |options|
      Puppet::Resource::Catalog.indirection.terminus_class = :rest
      Puppet::Resource::Catalog.indirection.cache_class = nil
      catalog = nil
      retrieval_duration = thinmark do
        catalog = Puppet::Face[:catalog, '0.0.1'].find(Puppet[:certname])
      end
      catalog.retrieval_duration = retrieval_duration
      catalog.write_class_file

      Puppet::Resource::Catalog.indirection.terminus_class = :yaml
      Puppet::Face[:catalog, "0.0.1"].save(catalog)
      Puppet.notice "Saved catalog for #{Puppet[:certname]} to yaml"
      nil
    end
  end
end


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28639_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans19.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Energy Services...

    <p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Surveyor Certification Form

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Survey Company: MS ENERGY SERVICES Surveyors Name: DUSTIN FOWLER
Survey Job Type: RATE GYRO
Customer: EOG RESOURCES, INC.
Well: PARSHALL 92-28H
API: 33-061-03156
Surveyed from: SURFACE TO A DEPTH OF 1944' MD Survey Run Date: 9-1-14
Surface Location: MOUNTRAIL COUNTY, ND

    <p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">I certify that the data is true, correct, and complete and within the limitations of the tool set forth by MS Energy Services; that I am authorized and qualified to make this report; and that l have reviewed this report and find
that it conforms to the principles and procedures as set forth by MS Energy Services.

    <p class="styleSans28.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dustin

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Digitally signed by Dustin Fowler
DN: cn=Dustin Fowler, o=MS Energy Services, ou=MS OW e r Survey, email=dfowler@m5energyservices.com, c=US
Date: 2013.01.02 15:27:29 -O6'OO'

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">MS Directional | MS Guidance | MS Survey | MS Wireline

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">3335 Pollok Drive Conroe, Texas 77303
936.442.2500 (office) 936.442.2599 (fax) www.msenergyservices.com


text:
using System.Text;
using System.Threading.Tasks;
using Hypermedia.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using WebApiHypermediaExtensionsCore.Exceptions;
using WebApiHypermediaExtensionsCore.Hypermedia;
using WebApiHypermediaExtensionsCore.WebApi.RouteResolver;

namespace WebApiHypermediaExtensionsCore.WebApi.Formatter
{
    public class SirenHypermediaFormatter : HypermediaOutputFormatter
    {
        private readonly ISirenHypermediaConverterFactory sirenHypermediaConverterFactory;

        public SirenHypermediaFormatter(
            IRouteResolverFactory routeResolverFactory,
            IRouteKeyFactory routeKeyFactory,
            ISirenHypermediaConverterFactory sirenHypermediaConverterFactory,
            IHypermediaUrlConfig defaultHypermediaUrlConfig)
            : base(routeResolverFactory, routeKeyFactory, defaultHypermediaUrlConfig)
        {
            this.sirenHypermediaConverterFactory = sirenHypermediaConverterFactory;
        }

        public override bool CanWriteResult(OutputFormatterCanWriteContext context)
        {
            if (!(context.Object is HypermediaObject))
            {
                return false;
            }

            var contentType = context.ContentType.ToString();
            if (string.IsNullOrEmpty(contentType))
            {
                return true;
            }

            if (contentType.Contains(DefaultContentTypes.Siren))
            {
                return true;
            }

            return false;
        }

        public override async Task WriteAsync(OutputFormatterWriteContext context)
        {
            var hypermediaObject = context.Object as HypermediaObject;
            if (hypermediaObject == null)
            {
                throw new HypermediaFormatterException("Formatter expected a HypermediaObject but is not.");
            }

            // context influences how routes are resolved
            var routeResolver = CreateRouteResolver(context);
            var converter = sirenHypermediaConverterFactory.CreateSirenConverter(routeResolver);
            var sirenJson = converter.ConvertToString(hypermediaObject);

            var response = context.HttpContext.Response;
            response.ContentType = DefaultContentTypes.Siren;
            await WriteToBody(context, response, sirenJson);
        }

        private static async Task WriteToBody(OutputFormatterWriteContext context, HttpResponse response, string content)
        {
            using (var writer = context.WriterFactory(response.Body, Encoding.UTF8))
            {
                await writer.WriteAsync(content);
                await writer.FlushAsync();
            }
        }
    }
}


text:
package org.marketcetera.photon.internal.strategy.engine.ui.workbench;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.marketcetera.photon.strategy.engine.model.core.test.StrategyEngineCoreTestUtil.assertDeployedStrategy;
import static org.marketcetera.photon.strategy.engine.model.core.test.StrategyEngineCoreTestUtil.createDeployedStrategy;
import static org.marketcetera.photon.strategy.engine.model.core.test.StrategyEngineCoreTestUtil.createEngine;

import java.util.concurrent.CountDownLatch;

import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.results.VoidResult;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotText;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.dialogs.PropertyDialog;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.marketcetera.module.ModuleURN;
import org.marketcetera.photon.commons.ui.JFaceUtilsTest.ErrorDialogFixture;
import org.marketcetera.photon.commons.ui.workbench.ProgressUtilsTest.ProgressDialogFixture;
import org.marketcetera.photon.internal.strategy.engine.ui.workbench.NewPropertyInputDialogTest.NewPropertyInputDialogTestFixture;
import org.marketcetera.photon.strategy.engine.model.core.DeployedStrategy;
import org.marketcetera.photon.strategy.engine.model.core.Strategy;
import org.marketcetera.photon.strategy.engine.model.core.StrategyEngine;
import org.marketcetera.photon.strategy.engine.model.core.StrategyState;
import org.marketcetera.photon.strategy.engine.ui.tests.MockUIConnection;
import org.marketcetera.photon.strategy.engine.ui.workbench.StrategyEngineWorkbenchUI;
import org.marketcetera.photon.test.AbstractUIRunner;
import org.marketcetera.photon.test.ContextMenuHelper;
import org.marketcetera.photon.test.SWTTestUtil;
import org.marketcetera.photon.test.WorkbenchRunner;
import org.marketcetera.photon.test.AbstractUIRunner.ThrowableRunnable;
import org.marketcetera.photon.test.AbstractUIRunner.UI;

import com.google.common.collect.ImmutableMap;

/* $License$ */

/**
 * Tests {@link DeployedStrategyConfigurationPropertyPage}.
 *
 * @author Will Horn
 * @version $Id: DeployedStrategyConfigurationPropertyPageTest.java 16154 2012-07-14 16:34:05Z colin $
 * @since 2.0.0
 */
// see http://bugs.eclipse.org/231619
@SuppressWarnings("restriction")
@RunWith(WorkbenchRunner.class)
public class DeployedStrategyConfigurationPropertyPageTest {

    private static final int WAIT_TIME = 800;
    private final SWTBot mBot = new SWTBot();
    private volatile DeployedStrategy mStrategy;
    private PropertyDialog mDialog;
    private volatile StrategyEngine mEngine;

    @After
    @UI
    public void after() {
        if (mDialog != null) {
            mDialog.close();
        }
    }

    private void openDialog() throws Exception {
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            public void run() throws Throwable {
                mStrategy = createDeployedStrategy("Strategy1");
                mStrategy.setUrn(new ModuleURN("metc:strategy:system:Strategy1"));
                mStrategy.setClassName("Claz");
                mStrategy.setLanguage("Lang");
                mStrategy.setScriptPath("c:\\path");
                mStrategy.setRouteOrdersToServer(true);
                mEngine = createEngine("Engine");
                mEngine.setConnection(new MockUIConnection());
                mEngine.getDeployedStrategies().add(mStrategy);
                mDialog = PropertyDialog
                        .createDialogOn(
                                PlatformUI.getWorkbench()
                                        .getActiveWorkbenchWindow().getShell(),
                                StrategyEngineWorkbenchUI.DEPLOYED_STRATEGY_CONFIGURATION_PROPERTY_PAGE_ID,
                                mStrategy);
                mDialog.setBlockOnOpen(false);
                mDialog.open();
            }
        });
        mBot.shell("Properties for Strategy1 on Engine");
        SWTTestUtil.assertButtonDoesNotExist("Apply");
        SWTTestUtil.assertButtonDoesNotExist("Restore Defaults");
        SWTTestUtil.testReadOnlyText(mBot.textWithLabel("Instance Name:"),
                "Strategy1");
        SWTTestUtil.testReadOnlyText(mBot.textWithLabel("Class:"), "Claz");
        SWTTestUtil.testReadOnlyText(mBot.textWithLabel("Language:"), "Lang");
        SWTTestUtil.testReadOnlyText(mBot.textWithLabel("Script:"), "c:\\path");
    }

    @Test
    public void testChangeProperties() throws Exception {
        openDialog();
        SWTBotCheckBox checkBox = mBot.checkBox("Route orders to server");
        assertThat(checkBox.isChecked(), is(true));
        checkBox.click();
        mBot.button("Add New Property").click();
        new NewPropertyInputDialogTestFixture("key", "value").inputData();
        mBot.button("Add New Property").click();
        new NewPropertyInputDialogTestFixture("key2", "value2").inputData();
        mBot.button("OK").click();
        Thread.sleep(WAIT_TIME);
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            public void run() throws Throwable {
                assertDeployedStrategy(mStrategy, mEngine, StrategyState.STOPPED,
                        "Strategy1", "Claz", "Lang", "c:\\path",
                        false, ImmutableMap.of("key", "value",
                                "key2", "value2"));
            }
        });
    }

    @Test
    public void testDisabledForRunningStrategy() throws Exception {
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            public void run() throws Throwable {
                mStrategy = createDeployedStrategy("Strategy1");
                mStrategy.setClassName("Claz");
                mStrategy.setLanguage("Lang");
                mStrategy.setScriptPath("c:\\path");
                mStrategy.setRouteOrdersToServer(true);
                mStrategy.setState(StrategyState.RUNNING);
                mEngine = createEngine("Engine");
                mEngine.setConnection(new MockUIConnection());
                mEngine.getDeployedStrategies().add(mStrategy);
                mDialog = PropertyDialog
                        .createDialogOn(
                                PlatformUI.getWorkbench()
                                        .getActiveWorkbenchWindow().getShell(),
                                StrategyEngineWorkbenchUI.DEPLOYED_STRATEGY_CONFIGURATION_PROPERTY_PAGE_ID,
                                mStrategy);
                mDialog.setBlockOnOpen(false);
                mDialog.open();
            }
        });
        mBot.shell("Properties for Strategy1 on Engine");
        testDisabled(mBot.textWithLabel("Instance Name:"), "Strategy1");
        testDisabled(mBot.textWithLabel("Class:"), "Claz");
        testDisabled(mBot.textWithLabel("Language:"), "Lang");
        testDisabled(mBot.textWithLabel("Script:"), "c:\\path");
        assertThat(mBot.checkBox("Route orders to server").isEnabled(),
                is(false));
        assertThat(mBot.checkBox("Route orders to server").isChecked(),
                is(true));
        // use index 1 since first tree is property page navigation tree
        assertThat(mBot.tree(1).isEnabled(), is(false));
        assertThat(mBot.button("Add New Property").isEnabled(), is(false));
    }

    private void testDisabled(SWTBotText text, String value) {
        assertThat(text.isEnabled(), is(false));
        assertThat(text.getText(), is(value));
    }

    @Test
    public void testCancelChange() throws Exception {
        openDialog();
        mBot.checkBox("Route orders to server").click();
        mBot.button("Add New Property").click();
        new NewPropertyInputDialogTestFixture("key2", "value2").inputData();
        mBot.button("Cancel").click();
        Thread.sleep(WAIT_TIME);
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            public void run() throws Throwable {
                assertDeployedStrategy(mStrategy, mEngine, StrategyState.STOPPED,
                        "Strategy1", "Claz", "Lang", "c:\\path",
                        true, null);
            }
        });
    }

    @Test
    public void testInlineEditing() throws Exception {
        openDialog();
        mBot.button("Add New Property").click();
        new NewPropertyInputDialogTestFixture("key2", "value2").inputData();
        // use index 1 since first tree is property page navigation tree
        CustomTree tree = new CustomTree(mBot.tree(1).widget);
        tree.click(0, 1);
        mBot.sleep(500);
        mBot.text("value2").setText("value3");
        mBot.button("OK").click();
        Thread.sleep(WAIT_TIME);
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            public void run() throws Throwable {
                assertDeployedStrategy(mStrategy, mEngine, StrategyState.STOPPED,
                        "Strategy1", "Claz", "Lang", "c:\\path",
                        true, ImmutableMap.of("key2", "value3"));
            }
        });
    }

    @Test
    public void testPropertiesContextMenu() throws Exception {
        openDialog();
        // use index 1 since first tree is property page navigation tree
        SWTBotTree tree = mBot.tree(1);
        ContextMenuHelper.clickContextMenu(tree, "Add");
        new NewPropertyInputDialogTestFixture("keyx", "valuex").inputData();
        ContextMenuHelper.clickContextMenu(tree, "Add");
        new NewPropertyInputDialogTestFixture("keyz", "valuez").inputData();
        tree.getTreeItem("keyz").select();
        ContextMenuHelper.clickContextMenu(tree, "Delete");
        tree.unselect();
        // delete should not show up when the selection is empty
        assertThat(SWTTestUtil.getMenuItems(tree).get("Delete"), nullValue());
        mBot.button("OK").click();
        Thread.sleep(WAIT_TIME);
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            public void run() throws Throwable {
                assertDeployedStrategy(mStrategy, mEngine, StrategyState.STOPPED,
                        "Strategy1", "Claz", "Lang", "c:\\path",
                        true, ImmutableMap.of("keyx", "valuex"));
            }
        });
    }

    @Test
    public void testProgressAndErrorReported() throws Exception {
        openDialog();
        final CountDownLatch latch = new CountDownLatch(1);
        try {
            AbstractUIRunner.syncRun(new ThrowableRunnable() {
                @Override
                public void run() throws Throwable {
                    mEngine.setConnection(new MockUIConnection() {
                        @Override
                        public void update(DeployedStrategy strategy,
                                Strategy newConfiguration) throws Exception {
                            latch.await();
                            throw new Exception("Update Failed");
                        }
                    });
                }
            });
            mBot.button("OK").click();
            ProgressDialogFixture fixture = new ProgressDialogFixture();
            fixture.assertTask("Updating strategy configuration on 'Engine'...");
            latch.countDown();
            ErrorDialogFixture errorDialog = new ErrorDialogFixture();
            errorDialog.assertError("Update Failed");
            errorDialog.dismiss();
        } finally {
            latch.countDown();
        }
    }

    /**
     * A tree that lets me click a cell.
     */
    private static class CustomTree extends SWTBotTree {

        public CustomTree(Tree tree) throws WidgetNotFoundException {
            super(tree);
        }

        public void click(final int row, final int column) {
            setFocus();
            select(row);
            asyncExec(new VoidResult() {
                public void run() {
                    TreeItem item = widget.getItem(row);
                    Rectangle cellBounds = item.getBounds(column);
                    clickXY(cellBounds.x + (cellBounds.width / 2), cellBounds.y
                            + (cellBounds.height / 2));
                }
            });
        }

    }

}


text:
<?php
namespace Ice\Frame\Web;
class Request extends \Ice\Frame\Abs\Request {

    protected $_params;
    protected $_gets;
    protected $_posts;
    protected $_cookies;
    protected $_files;
    protected $_body;

    public $uri;
    public $originalUri;

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

        $this->_params   = array();
        $this->_gets     = $_GET;
        $this->_posts    = $_POST;
        $this->_requests = $_REQUEST;
        $this->_cookies  = $_COOKIE;
        $this->_files    = $_FILES;
        $this->_body     = file_get_contents('php://input');

        $this->requestTime = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : \U_Time::now();

        $this->initBaseUri();
    }

    public function __get($name) {
        if ($name == 'id') {
            $this->id = md5(sprintf("%s|%s|%s", gethostname(), posix_getpid(), microtime(TRUE), rand(0, 999999)));
            return $this->id;
        }
        if ($name == 'requests') {
            return $this->getAllRequest();
        }
    }

    public function getParams() {
        return $this->_params;
    }

    public function getQueries() {
        return $this->_gets;
    }

    public function getPosts() {
        return $this->_posts;
    }

    public function getCookies() {
        return $this->_cookies;
    }

    public function getFiles() {
        return $this->_files;
    }

    public function getParam($name, $default = null) {
        return isset($this->_params[$name]) ? $this->_params[$name] : $default;
    }

    public function getQuery($name, $default = null) {
        return isset($this->_gets[$name]) ? $this->_gets[$name] : $default;
    }

    public function getPost($name, $default = null) {
        return isset($this->_posts[$name]) ? $this->_posts[$name] : $default;
    }

    public function getRequest($name, $default = null) {
        return isset($this->_requests[$name]) ? $this->_requests[$name] : $default;
    }

    public function getAllRequest() {
        return $this->_requests;
    }

    public function getCookie($name, $default = null) {
        return isset($this->_cookies[$name]) ? $this->_cookies[$name] : $default;
    }

    public function getFile($name, $default = null) {
        return isset($this->_files[$name]) ? $this->_files[$name] : $default;
    }

    public function getBody() {
        return $this->_body;
    }

    public function setParam($k, $v) {
        $this->_params[$k] = $v;
    }

    protected function initBaseUri() {
        $requestUri     = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
        $this->originalUri = $requestUri;

        // strip repeat "/"
        $requestUri = preg_replace(';/{2,};', '/', $requestUri);
        $requestUri = '/' . trim($requestUri, '/');

        // allow prefix /index.php
        $scriptFilePath = $_SERVER['SCRIPT_FILENAME'];
        $scriptFname    = basename($scriptFilePath);
        if (strpos($requestUri, "/$scriptFname") === 0) {
            $requestUri = '/' . ltrim(strval(substr($requestUri, strlen("/$scriptFname"))), '/');
        }

        // strip query_string and fragment. only remain path
        $comps = parse_url($requestUri);
        $requestUri = $comps['path'];

        // omit $baseUri
        $mainAppConf = \F_Ice::$ins->runner->mainAppConf;
        if (isset($mainAppConf['runner']['frame']['baseUri'])) {
            $baseUri = $mainAppConf['runner']['frame']['baseUri'];
            $baseUri = preg_replace(';/{2,};', '/', $baseUri);
            $baseUri = rtrim($baseUri, '/');

            if (strpos($requestUri, $baseUri . '/') === 0) {
                $requestUri = '/' . ltrim(substr($requestUri, strlen($baseUri)), '/');
            }
        }

        $this->uri = $requestUri;
    }

}


text:
* **Dependency Update**: Updated to the latest SDK module versions

# v1.13.4 (2022-04-25)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.13.3 (2022-03-30)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.13.2 (2022-03-24)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.13.1 (2022-03-23)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.13.0 (2022-03-08)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.12.0 (2022-02-24)

* **Feature**: API client updated
* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options.
* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.11.0 (2022-01-14)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.10.0 (2022-01-07)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.9.0 (2021-12-21)

* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens.

# v1.8.2 (2021-12-02)

* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514))
* **Dependency Update**: Updated to the latest SDK module versions

# v1.8.1 (2021-11-19)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.8.0 (2021-11-12)

* **Feature**: Service clients now support custom endpoints that have an initial URI path defined.

# v1.7.0 (2021-11-06)

* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically.
* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.6.0 (2021-10-21)

* **Feature**: Updated  to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.2 (2021-10-11)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.1 (2021-09-17)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.0 (2021-08-27)

* **Feature**: Updated API model to latest revision.
* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.4.3 (2021-08-19)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.4.2 (2021-08-04)

* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version.
* **Dependency Update**: Updated to the latest SDK module versions

# v1.4.1 (2021-07-15)

* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.4.0 (2021-06-25)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.3.1 (2021-05-20)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.3.0 (2021-05-14)

* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting.
* **Dependency Update**: Updated to the latest SDK module versions


text:
mock_django_orm
===============

Using mock to test django orm

Model Example
=============

```python

class AppOne(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField()

    def get_full_description(self):
        return u'%s / %s' % (self.name, self.description)

    def __unicode__(self):
        return self.name

class AppSecond(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField()

    def __unicode__(self):
        return self.name

class AppThird(models.Model):
    name = models.CharField(max_length=50)
    app_one = models.ForeignKey(AppOne)
    app_second = models.ForeignKey(AppSecond)

    def get_extra(self):
        if self.app_one.name == '1':
            return u'%s-%s' % (self.app_one.name, self.name)
        elif self.app_second.name == '1':
            return u'%s-%s' % (self.app_second.name, self.name)
        elif self.app_one.name == '2' and self.app_second.name == '2':
            return u'%s%s-%s' % (self.app_one.name,
                                 self.app_second.name,
                                 self.name)

```

Test Example
=============

```python

from django.test import TestCase
from app.models import AppOne, AppThird
import mock

class MockingTest(TestCase):

    def setUp(self):
        self.appOneMock = mock.Mock(spec=AppOne)
        self.appOneMock.name = 'Admin'
        self.appOneMock.description = 'Test'

    def test_get_admin_user(self):
        result = AppOne.get_full_description(self.appOneMock)
        self.assertEqual(result, u'Admin / Test')

class MockingThridTest(TestCase):

    def setUp(self):
        self.appThridMock = mock.Mock(spec=AppThird)
        self.appThridMock.name = 'Test'
        self.appThridMock.app_one.name = '1'

    def test_get_extra(self):
        result = AppThird.get_extra(self.appThridMock)
        self.assertEqual(result, u'1-Test')

    def test_get_extra_second(self):
        self.appThridMock.app_one.name = '2'
        self.appThridMock.app_second.name = '2'

        result = AppThird.get_extra(self.appThridMock)
        self.assertEqual(result, u'22-Test')

```


text:
ENV['RAILS_ENV'] ||= 'test'
ENV['MAILER_FROM_EMAIL'] ||= 'public.relations@email.com'
ENV['REQUISITION_BUILDER_EMAIL'] ||= 'ship.builder@email.com'

require File.expand_path('../../config/environment', __FILE__)

require 'simplecov'

if ENV['CIRCLE_ARTIFACTS']
  dir = File.join('..', '..', '..', ENV['CIRCLE_ARTIFACTS'], 'coverage')
  SimpleCov.coverage_dir(dir)
end

SimpleCov.start do
  command_name "requisition_#{ENV['CIRCLE_BUILD_NUM']}_#{ENV['CIRCLE_NODE_INDEX']}"

  add_group 'Models', 'app/models'
  add_group 'Controllers', 'app/controllers'
  add_group 'Mailers', 'app/mailers'
  add_group 'Helpers', 'app/helpers'
  add_group 'Policies', 'app/policies'
  add_group 'Configuration', 'config/'
  add_group 'Libraries', 'lib/'
  add_group 'Test Files', 'test/'

  add_group 'Long files' do |src_file|
    src_file.lines.count > 250
  end

  # get rid of bundled rails/ruby code
  add_filter 'vendor/bundle'

  # make sure we get all results since our tests can take a while
  merge_timeout 60 * 30
end

require 'rails/test_help'

module ActiveSupport
  class TestCase
    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    # Add more helper methods to be used by all tests here...
    def setup
      Rails.cache.clear
    end
  end
end

module ActionController
  class TestCase
    # use the devise test helpers for controller tests
    include Devise::Test::ControllerHelpers

    def teardown
      switch_login nil
      super
    end

    def switch_login(user)
      sign_out @current_user if @current_user.present?
      @current_user = user
      if @current_user
        @current_user.confirm
        sign_in @current_user
      end
    end

    def verify_json(table, json, expected_keys)
      json.keys.sort.must_equal expected_keys
      resource = table.find json['id']
      json.keys.each do |key|
        if resource[key].nil?
          json[key].must_be_nil
        elsif resource[key].respond_to? :iso8601
          json[key].must_equal resource[key].iso8601(3)
        else
          json[key].must_equal resource[key]
        end
      end
    end

    def verify_json_create(table, request, id)
      resource = table.find id
      request.keys.each do |key|
        resource[key].must_equal request[key]
      end
    end
  end
end

module Pundit
  module TestHelpers
    def user_with_abilities(user, kinds)
      user.user_abilities.destroy_all
      kinds.each do |kind|
        user.user_abilities.create! ability: Ability.where(kind: kind).first
      end
    end
  end
end


text:
package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.Category.GUAVA;
import static com.google.errorprone.BugPattern.MaturityLevel.MATURE;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;

import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.lang.model.element.Modifier;

/**
 * Verifies that methods marked {@link com.google.errorprone.annotations.ForOverride} are only
 * called from the defining class.
 *
 * <p>Specifically, all calls to the method have to occur within the context of the outermost class
 * where the method is defined.
 */
@BugPattern(name = "ForOverride",
    summary =
        "Method annotated @ForOverride must be protected or package-private and only invoked from "
        + "declaring class",
    explanation =
        "A method that overrides a @ForOverride method should not be invoked directly. Instead, it"
        + " should be invoked only from the class in which it was declared. For example, if"
        + " overriding Converter.doForward, you should invoke it through Converter.convert."
        + " For testing, factor out the code you want to run to a separate method.",
    category = GUAVA, severity = ERROR, maturity = MATURE)
public class ForOverrideChecker extends BugChecker
    implements MethodInvocationTreeMatcher, MethodTreeMatcher {

  private static final String FOR_OVERRIDE = "com.google.errorprone.annotations.ForOverride";
  private static final String MESSAGE_BASE = "Method annotated @ForOverride ";

  //TODO(user): remove
  private static final String GUAVA_FOR_OVERRIDE = "com.google.common.annotations.ForOverride";

  @Override
  public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    MethodSymbol method = ASTHelpers.getSymbol(tree);
    Type currentClass = getOutermostClass(state);

    if (method.isStatic() || method.isConstructor() || currentClass == null) {
      return Description.NO_MATCH;
    }

    List<MethodSymbol> overriddenMethods = getOverriddenMethods(state, method);

    for (Symbol overriddenMethod : overriddenMethods) {
      Type declaringClass = overriddenMethod.outermostClass().asType();
      if (!declaringClass.equals(currentClass)) {
        String customMessage = MESSAGE_BASE +  "must not be invoked directly "
                    + "(except by the declaring class, " + declaringClass + ")";
        return buildDescription(tree)
            .setMessage(customMessage)
            .build();
      }
    }

    return Description.NO_MATCH;
  }

  @Override
  public Description matchMethod(MethodTree tree, VisitorState state) {
    MethodSymbol method = ASTHelpers.getSymbol(tree);

    if (method.isStatic() || method.isConstructor()) {
      return Description.NO_MATCH;
    }

    if (method.getModifiers().contains(Modifier.PUBLIC)
        || method.getModifiers().contains(Modifier.PRIVATE)) {
      List<MethodSymbol> overriddenMethods = getOverriddenMethods(state, method);

      if (!overriddenMethods.isEmpty()) {
        String customMessage = MESSAGE_BASE + "must have protected or package-private visibility";
        return buildDescription(tree)
            .setMessage(customMessage)
            .build();
      }
    }

    return Description.NO_MATCH;
  }

  /**
   * Get overridden @ForOverride methods.
   *
   * @param state the VisitorState
   * @param method the method to find overrides for
   * @return a list of methods annotated @ForOverride that the method overrides, including the
   * method itself if it has the annotation
   */
  private List<MethodSymbol> getOverriddenMethods(VisitorState state, MethodSymbol method) {
    // Static methods cannot override, only overload.
    if (method.isStatic()) {
      throw new IllegalArgumentException(
          "getOverriddenMethods may not be called on a static method");
    }

    List<MethodSymbol> list = new LinkedList<MethodSymbol>();
    list.add(method);

    // Iterate over supertypes of the type that owns this method, collecting a list of all method
    // symbols with the same name.  We intentionally exclude interface methods because interface
    // methods cannot be annotated @ForOverride.  @ForOverride methods must have protected or
    // package-private visibility, but interface methods have implicit public visibility.
    Type currType = state.getTypes().supertype(method.owner.type);
    while (currType != null
        && !currType.equals(state.getSymtab().objectType)
        && !currType.equals(Type.noType)) {
      Symbol sym = currType.tsym.members().findFirst(method.name);
      if (sym instanceof MethodSymbol) {
        list.add((MethodSymbol) sym);
      }
      currType = state.getTypes().supertype(currType);
    }

    // Remove methods that either don't have the @ForOverride annotation or don't override the
    // method in question.
    Iterator<MethodSymbol> iter = list.iterator();
    while (iter.hasNext()) {
      MethodSymbol member = iter.next();
      if (!(hasAnnotation(FOR_OVERRIDE, member) || hasAnnotation(GUAVA_FOR_OVERRIDE, member))
          // Note that MethodSymbol.overrides() ignores static-ness, but that's OK since we've
          // already checked that this method is not static.
          || !method.overrides(
              member, (TypeSymbol) member.owner, state.getTypes(), true)) {
        iter.remove();
      }
    }

    return list;
  }

  /**
   * Get the outermost class/interface/enum of an element, or null if none.
   */
  private Type getOutermostClass(VisitorState state) {
    TreePath path = state.getPath();
    Type type = null;

    while (path != null) {
      if (path.getLeaf().getKind() == Kind.CLASS
          || path.getLeaf().getKind() == Kind.INTERFACE
          || path.getLeaf().getKind() == Kind.ENUM) {
        type = ASTHelpers.getSymbol(path.getLeaf()).type;
      }
      path = path.getParentPath();
    }
    return type;
  }

  private boolean hasAnnotation(String annotation, Symbol member) {
    for (Attribute.Compound attribute : member.getAnnotationMirrors()) {
      if (annotation.equals(attribute.type.toString())) {
        return true;
      }
    }
    return false;
  }
}


text:
/**
  * This file configures the system clock as follows:
  *-----------------------------------------------------------------------------
  * System clock source                | 1- PLL_HSE_EXTC        | 3- PLL_HSI
  *                                    | (external 8 MHz clock) | (internal 8 MHz)
  *                                    | 2- PLL_HSE_XTAL        |
  *                                    | (external 8 MHz xtal)  |
  *-----------------------------------------------------------------------------
  * SYSCLK(MHz)                        | 72                     | 64
  *-----------------------------------------------------------------------------
  * AHBCLK (MHz)                       | 72                     | 64
  *-----------------------------------------------------------------------------
  * APB1CLK (MHz)                      | 36                     | 32
  *-----------------------------------------------------------------------------
  * APB2CLK (MHz)                      | 72                     | 64
  *-----------------------------------------------------------------------------
  * USB capable (48 MHz precise clock) | NO                     | NO
  *-----------------------------------------------------------------------------
  ******************************************************************************
  */

#include "stm32f1xx.h"

/*!< Uncomment the following line if you need to relocate your vector Table in
     Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET  0x00000000U /*!< Vector Table base offset field.
                                  This value must be a multiple of 0x200. */

/* Select the clock sources (other than HSI) to start with (0=OFF, 1=ON) */
#define USE_PLL_HSE_EXTC (1) /* Use external clock */
#define USE_PLL_HSE_XTAL (1) /* Use external xtal */

#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0)
uint8_t SetSysClock_PLL_HSE(uint8_t bypass);
#endif

uint8_t SetSysClock_PLL_HSI(void);

/**
  * @brief  Setup the microcontroller system
  *         Initialize the Embedded Flash Interface, the PLL and update the
  *         SystemCoreClock variable.
  * @note   This function should be used only after reset.
  * @param  None
  * @retval None
  */
void SystemInit (void)
{
    /* Reset the RCC clock configuration to the default reset state(for debug purpose) */
    /* Set HSION bit */
    RCC->CR |= 0x00000001U;

    /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */
#if !defined(STM32F105xC) && !defined(STM32F107xC)
    RCC->CFGR &= 0xF8FF0000U;
#else
    RCC->CFGR &= 0xF0FF0000U;
#endif /* STM32F105xC */

    /* Reset HSEON, CSSON and PLLON bits */
    RCC->CR &= 0xFEF6FFFFU;

    /* Reset HSEBYP bit */
    RCC->CR &= 0xFFFBFFFFU;

    /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */
    RCC->CFGR &= 0xFF80FFFFU;

#if defined(STM32F105xC) || defined(STM32F107xC)
    /* Reset PLL2ON and PLL3ON bits */
    RCC->CR &= 0xEBFFFFFFU;

    /* Disable all interrupts and clear pending bits  */
    RCC->CIR = 0x00FF0000U;

    /* Reset CFGR2 register */
    RCC->CFGR2 = 0x00000000U;
#elif defined(STM32F100xB) || defined(STM32F100xE)
    /* Disable all interrupts and clear pending bits  */
    RCC->CIR = 0x009F0000U;

    /* Reset CFGR2 register */
    RCC->CFGR2 = 0x00000000U;
#else
    /* Disable all interrupts and clear pending bits  */
    RCC->CIR = 0x009F0000U;
#endif /* STM32F105xC */

#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
#ifdef DATA_IN_ExtSRAM
    SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM */
#endif

#ifdef VECT_TAB_SRAM
    SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#else
    SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
#endif

}

/**
  * @brief  Configures the System clock source, PLL Multiplier and Divider factors,
  *               AHB/APBx prescalers and Flash settings
  * @note   This function should be called only once the RCC clock configuration
  *         is reset to the default reset state (done in SystemInit() function).
  * @param  None
  * @retval None
  */
void SetSysClock(void)
{
    /* 1- Try to start with HSE and external clock */
#if USE_PLL_HSE_EXTC != 0
    if (SetSysClock_PLL_HSE(1) == 0)
#endif
    {
        /* 2- If fail try to start with HSE and external xtal */
#if USE_PLL_HSE_XTAL != 0
        if (SetSysClock_PLL_HSE(0) == 0)
#endif
        {
            /* 3- If fail start with HSI clock */
            if (SetSysClock_PLL_HSI() == 0) {
                while(1) {
                    // [TODO] Put something here to tell the user that a problem occured...
                }
            }
        }
    }

    /* Output clock on MCO1 pin(PA8) for debugging purpose */
    //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_SYSCLK, RCC_MCODIV_1); // 72 MHz or 64 MHz
}

#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0)
/******************************************************************************/
/*            PLL (clocked by HSE) used as System clock source                */
/******************************************************************************/
uint8_t SetSysClock_PLL_HSE(uint8_t bypass)
{
    RCC_ClkInitTypeDef RCC_ClkInitStruct;
    RCC_OscInitTypeDef RCC_OscInitStruct;

    /* Enable HSE oscillator and activate PLL with HSE as source */
    RCC_OscInitStruct.OscillatorType      = RCC_OSCILLATORTYPE_HSE;
    if (bypass == 0) {
        RCC_OscInitStruct.HSEState          = RCC_HSE_ON; /* External 8 MHz xtal on OSC_IN/OSC_OUT */
    } else {
        RCC_OscInitStruct.HSEState          = RCC_HSE_BYPASS; /* External 8 MHz clock on OSC_IN */
    }
    RCC_OscInitStruct.HSEPredivValue      = RCC_HSE_PREDIV_DIV1;
    RCC_OscInitStruct.PLL.PLLState        = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource       = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLMUL          = RCC_PLL_MUL9; // 72 MHz (8 MHz * 9)
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        return 0; // FAIL
    }

    /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */
    RCC_ClkInitStruct.ClockType      = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
    RCC_ClkInitStruct.SYSCLKSource   = RCC_SYSCLKSOURCE_PLLCLK; // 72 MHz
    RCC_ClkInitStruct.AHBCLKDivider  = RCC_SYSCLK_DIV1;         // 72 MHz
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;           // 36 MHz
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;           // 72 MHz
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) {
        return 0; // FAIL
    }

    /* Output clock on MCO1 pin(PA8) for debugging purpose */
    //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_1); // 8 MHz

    return 1; // OK
}
#endif

/******************************************************************************/
/*            PLL (clocked by HSI) used as System clock source                */
/******************************************************************************/
uint8_t SetSysClock_PLL_HSI(void)
{
    RCC_ClkInitTypeDef RCC_ClkInitStruct;
    RCC_OscInitTypeDef RCC_OscInitStruct;

    /* Enable HSI oscillator and activate PLL with HSI as source */
    RCC_OscInitStruct.OscillatorType      = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSIState            = RCC_HSI_ON;
    RCC_OscInitStruct.HSEState            = RCC_HSE_OFF;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState        = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource       = RCC_PLLSOURCE_HSI_DIV2;
    RCC_OscInitStruct.PLL.PLLMUL          = RCC_PLL_MUL16; // 64 MHz (8 MHz/2 * 16)
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        return 0; // FAIL
    }

    /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */
    RCC_ClkInitStruct.ClockType      = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
    RCC_ClkInitStruct.SYSCLKSource   = RCC_SYSCLKSOURCE_PLLCLK; // 64 MHz
    RCC_ClkInitStruct.AHBCLKDivider  = RCC_SYSCLK_DIV1;         // 64 MHz
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;           // 32 MHz
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;           // 64 MHz
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) {
        return 0; // FAIL
    }

    /* Output clock on MCO1 pin(PA8) for debugging purpose */
    //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI, RCC_MCODIV_1); // 8 MHz

    return 1; // OK
}


text:
var BTree = function(order) {
    this.root = new btreeStructure(order);
    this.insert = function(key, value) {
        var result = this.root.insert(key, value);
        if (result instanceof(btreeStructure)) {
            this.root = result;
            return true;
        } else {
            return result;
        }
    };

    this.get = function(key) {
        return this.root.get(key);
    };

    this.remove = function(key) {
        var result = this.root.remove(key);
        if (this.root.keyValuePairs.length == 0) {
            if (this.root.children != null && this.root.children.length != 0)
                this.root = this.root.children[0];
        }
        return result;
    }
};

var btreeStructure = function (order) {
    var KeyValuePair = function(key, value) {
        this.key = key;
        this.value = value;
    };

    this.maxChildren = order;
    this.parent = null;
    this.maxValues = order-1;
    this.minValues = Math.floor(this.maxValues/2);
    this.keyValuePairs = [];
    this.children = null;

    this.insert = function(key, value) {
        var keyPosition = this.find(key);

        // eliminate duplicates
        if (keyPosition.index != null) {
            return false;
        }
        // redirect to the right tree
        return keyPosition.tree.insertValue(key, value);
    };

    this.insertValue = function(key, value) {
        var index;
        for (index = 0; index < this.keyValuePairs.length; ++index) {
            if (key < this.keyValuePairs[index].key) {
                break;
            }
        }
        this.keyValuePairs.splice(index, 0, new KeyValuePair(key, value));

        if (this.keyValuePairs.length > this.maxValues) {
            return this.split();
        }
        return true;
    };

    this.replaceChild = function(keyValuePair, leftChild, rightChild) {
        var index = this.findSpot(keyValuePair.key);
        this.children.splice(index, 1, leftChild, rightChild);
        this.keyValuePairs.splice(index, 0, keyValuePair);
        if (this.keyValuePairs.length > this.maxValues)
            return this.split();
        else
            return true;
    };

    this.findSpot = function(key) {
        for (var i = 0; i < this.keyValuePairs.length; ++i) {
            if (key <= this.keyValuePairs[i].key) {
                return i;
            }
        }
        return i;
    };

    this.find = function(key) {
        for (var i = 0; i < this.keyValuePairs.length; ++i) {
            if (this.keyValuePairs[i].key == key) {
                return { tree: this, index: i };
            } else if (key < this.keyValuePairs[i].key) {
                if (this.children) {
                    return this.children[i].find(key);
                }
            }
        }
        if (this.children) {
            return this.children[i].find(key);
        } else {
            return { tree: this, index: null };
        }
    };

    this.get = function(key) {
        var position = this.find(key);
        if (position.index == null)
            return null;
        else
            return position.tree.keyValuePairs[position.index].value;
    };

    this.split = function() {
        var halfLength = Math.floor(this.keyValuePairs.length/2);

        var leftTree = new btreeStructure(this.maxChildren);
        var rightTree = new btreeStructure(this.maxChildren);

        leftTree.keyValuePairs = this.keyValuePairs.splice(0, halfLength);
        var medianValue = this.keyValuePairs.splice(0,1)[0];
        rightTree.keyValuePairs = this.keyValuePairs.splice(0);

        if (this.children != null) {
            leftTree.children = this.children.splice(0, halfLength + 1);
            rightTree.children = this.children.splice(0);
            for (var i = 0; i < leftTree.children.length; ++i) {
                leftTree.children[i].parent = leftTree;
            }
            for (var i = 0; i < rightTree.children.length; ++i) {
                rightTree.children[i].parent = rightTree;
            }
        }

        if (this.parent == null) {
            // this is the root, we need special treatment
            var newRoot = new btreeStructure(this.maxChildren);
            newRoot.keyValuePairs = [medianValue];
            newRoot.children = [leftTree, rightTree];
            leftTree.parent = rightTree.parent = newRoot;
            return newRoot;
        } else {
            leftTree.parent = rightTree.parent = this.parent;
            return this.parent.replaceChild(medianValue, leftTree, rightTree);
        }
    };

    this.fixChildlessChildUnderflow = function(child, index) {
        var fixed = false;
        if (index != 0) {
            var previousChild = this.children[index - 1];
            if (previousChild.keyValuePairs.length > this.minValues) {
                var lastValue = previousChild.keyValuePairs.splice(previousChild.keyValuePairs.length - 1, 1)[0];
                child.keyValuePairs.unshift(this.keyValuePairs[index - 1]);
                this.keyValuePairs[index - 1] = lastValue;
                fixed = true;
            }
        }

        if (!fixed) {
            if (index != this.keyValuePairs.length) {
                var nextChild = this.children[index + 1];
                if (nextChild.keyValuePairs.length > this.minValues) {
                    var firstValue = nextChild.keyValuePairs.splice(0, 1)[0];
                    child.keyValuePairs.push(this.keyValuePairs[index]);
                    this.keyValuePairs[index] = firstValue;
                    fixed = true;
                }
            }
        }

        if (!fixed) {
            // merge
            if (index != 0) {
                var previousChild = this.children[index-1];
                var separatingValue = this.keyValuePairs.splice(index-1, 1)[0];
                previousChild.keyValuePairs.push(separatingValue);
                previousChild.keyValuePairs = previousChild.keyValuePairs.concat(
                    this.children.splice(index, 1)[0].keyValuePairs);
            } else {
                var nextChild = this.children[index+1];
                var separatingValue = this.keyValuePairs.splice(index, 1)[0];
                nextChild.keyValuePairs.unshift(separatingValue);
                nextChild.keyValuePairs = this.children.splice(index, 1)[0].keyValuePairs.concat(
                    nextChild.keyValuePairs);
            }
            this.fixUnderflow();
        }
    };

    this.fixChildbearingChildUnderflow = function(child, index) {
        var fixed = false;
        if (index != 0) {
            var previousChild = this.children[index-1];
            if (previousChild.keyValuePairs.length > this.minValues) {
                var lastValue = previousChild.keyValuePairs.splice(previousChild.keyValuePairs.length - 1, 1)[0];
                var lastChild = previousChild.children.splice(previousChild.children.length - 1, 1)[0];
                child.keyValuePairs.unshift(this.keyValuePairs[index-1]);
                child.children.unshift(lastChild);
                lastChild.parent = child;
                this.keyValuePairs[index-1] = lastValue;
                fixed = true;
            }
        }

        if (!fixed) {
            if (index != this.keyValuePairs.length) {
                var nextChild = this.children[index + 1];
                if (nextChild.keyValuePairs.length > this.minValues) {
                    var firstValue = nextChild.keyValuePairs.splice(0, 1)[0];
                    var firstChild = nextChild.children.splice(0,1)[0];
                    child.keyValuePairs.push(this.keyValuePairs[index]);
                    child.children.push(firstChild);
                    firstChild.parent = child;
                    this.keyValuePairs[index] = firstValue;
                    fixed = true;
                }
            }
        }

        if (!fixed) {
            // merge
            if (index != 0) {
                var previousChild = this.children[index-1];
                var separatingValue = this.keyValuePairs.splice(index-1, 1)[0];
                previousChild.keyValuePairs.push(separatingValue);
                previousChild.keyValuePairs = previousChild.keyValuePairs.concat(child.keyValuePairs);
                for (var i = 0; i < child.children.length; ++i) {
                    child.children[i].parent = previousChild;
                }
                previousChild.children = previousChild.children.concat(child.children);
            } else {
                var nextChild = this.children[index+1];
                var separatingValue = this.keyValuePairs.splice(index, 1)[0];
                nextChild.keyValuePairs.unshift(separatingValue);
                nextChild.keyValuePairs = child.keyValuePairs.concat(nextChild.keyValuePairs);
                for (var i = 0; i < child.children.length; ++i) {
                    child.children[i].parent = nextChild;
                }
                nextChild.children = child.children.concat(nextChild.children);
            }
            this.children.splice(index, 1);
            this.fixUnderflow();
        }
    };
    this.fixChildUnderflow = function(child) {
        var index;
        for (index = 0; index < this.children.length; ++index) {
            if (this.children[index] == child)
                break;
        }

        if (child.children == null) {
            this.fixChildlessChildUnderflow(child, index);
        } else {
            this.fixChildbearingChildUnderflow(child, index);
        }
    };

    this.fixUnderflow = function() {
        if (this.keyValuePairs.length < this.minValues) {
            if (this.parent != null)
                this.parent.fixChildUnderflow(this);
            else {
                if (this.keyValuePairs.length == 0 && this.children != null && this.children.length != 0) {
                    // new root:
                    this.children[0].parent = null;
                }
            }
        }
    };

    this.findMax = function() {
        var lastValueIndex = this.keyValuePairs.length - 1;
        if (this.children == null) {
            return { keyValuePair: this.keyValuePairs[lastValueIndex], tree: this, index: lastValueIndex };
        } else {
            return this.children[lastValueIndex+1].findMax();
        }
    };

    this.removeItem = function(index) {
        if (this.children == null) {
            this.keyValuePairs.splice(index, 1);
            if (this.keyValuePairs.length < this.minValues)
                this.fixUnderflow();
        } else {
            // If our children don't have children
            if (this.children[0].children == null) {
                if (this.children[index].keyValuePairs.length > this.minValues) {
                    var lastPair = this.children[index].keyValuePairs.splice(this.children[index].keyValuePairs.length-1,1)[0];
                    this.keyValuePairs[index] = lastPair;
                } else if (this.children[index+1].keyValuePairs.length > this.minValues) {
                    var firstPair = this.children[index+1].keyValuePairs.splice(0,1)[0];
                    this.keyValuePairs[index] = firstPair;
                } else {
                    // merge
                    var nextChild = this.children.splice(index+1, 1)[0];
                    this.children[index].keyValuePairs = this.children[index].keyValuePairs.concat(nextChild.keyValuePairs);
                    this.keyValuePairs.splice(index,1);
                    this.fixUnderflow();
                }
            } else {
                var max = this.children[index].findMax();
                this.keyValuePairs[index] = max.keyValuePair;
                max.tree.removeItem(max.index);
            }
        }
    };

    this.remove = function(key) {
        var location = this.find(key);
        if (location.index == null)
            return false;
        return location.tree.removeItem(location.index);
    }
};


text:
'use strict';

module.exports = function randdelay(runtime) {
  var inport = this.openInputPort('IN');
  var intvlport = this.openInputPort('INTVL');
  var outport = this.openOutputPort('OUT');
  var intvl_ip = intvlport.receive();
  var intvl = intvl_ip.contents;
  this.dropIP(intvl_ip);

  while (true) {
    var ip = inport.receive();
    if (ip === null) {
      break;
    }
    runtime.runAsyncCallback(genSleepFun(this, Math.random() * intvl));
    outport.send(ip);
  }
};

function genSleepFun(proc, ms) {
  return function (done) {
    //console.log(proc.name + ' start sleep: ' + Math.round(ms * 100) / 100 + ' msecs');

    setTimeout(function () {
      done();
    }, ms);
  };
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<citations>
	<bibl><title level="m">LiBD-5 2011 – Electrode materials </title>-<pubPlace>Arcachon, France</pubPlace> <biblScope type="pp">12-17</biblScope> <date>Juin 2011</date></bibl>
</citations>


text:
using Cofoundry.Web.Admin.Internal;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Cofoundry.Web.Admin;

[Area(RouteConstants.AdminAreaName)]
[AdminAuthorize]
public class AuthController : Controller
{
    private static readonly string CONTROLLER_NAME = "Auth";

    private readonly IAdvancedContentRepository _contentRepository;
    private readonly IAuthorizedTaskTokenUrlHelper _authorizedTaskTokenUrlHelper;
    private readonly IAdminRouteLibrary _adminRouteLibrary;
    private readonly AdminSettings _adminSettings;

    public AuthController(
        IAdvancedContentRepository contentRepository,
        IAuthorizedTaskTokenUrlHelper authorizedTaskTokenUrlHelper,
        IAdminRouteLibrary adminRouteLibrary,
        AdminSettings adminSettings
        )
    {
        _contentRepository = contentRepository.WithContext<CofoundryAdminUserArea>();
        _authorizedTaskTokenUrlHelper = authorizedTaskTokenUrlHelper;
        _adminRouteLibrary = adminRouteLibrary;
        _adminSettings = adminSettings;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var settings = await _contentRepository.ExecuteQueryAsync(new GetSettingsQuery<InternalSettings>());

        if (!settings.IsSetup)
        {
            context.Result = Redirect(_adminRouteLibrary.Setup.Setup());
        }
        else
        {
            await base.OnActionExecutionAsync(context, next);
        }
    }

    [AllowAnonymous]
    public ActionResult DefaultRedirect()
    {
        return RedirectPermanent(_adminRouteLibrary.Auth.Login());
    }

    [AllowAnonymous]
    public ActionResult Index()
    {
        return RedirectToActionPermanent(nameof(Login));
    }

    [AllowAnonymous]
    public async Task<ActionResult> Login()
    {
        if (await IsLoggedInAsync()) return await GetLoggedInDefaultRedirectActionAsync();

        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(Login));
        var vm = new SignInViewModel();

        return View(viewPath, vm);
    }

    [AllowAnonymous]
    [HttpPost]
    public async Task<ActionResult> Login(string returnUrl, SignInViewModel viewModel)
    {
        var authResult = await _contentRepository
            .WithModelState(this)
            .Users()
            .Authentication()
            .AuthenticateCredentials(new AuthenticateUserCredentialsQuery()
            {
                Username = viewModel.Username,
                Password = viewModel.Password,
                UserAreaCode = CofoundryAdminUserArea.Code,
                PropertyToValidate = nameof(viewModel.Password)
            })
            .ExecuteAsync();

        if (!ModelState.IsValid)
        {
            var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(Login));
            return View(viewPath, viewModel);
        }

        // Support redirect urls from login
        var redirectUrl = RedirectUrlHelper.GetAndValidateReturnUrl(this);

        if (authResult.User.RequirePasswordChange)
        {
            return Redirect(_adminRouteLibrary.Auth.ChangePassword(returnUrl));
        }

        // If no action required, log the user in
        await _contentRepository
            .Users()
            .Authentication()
            .SignInAuthenticatedUserAsync(new SignInAuthenticatedUserCommand()
            {
                UserId = authResult.User.UserId,
                RememberUser = true
            });

        if (redirectUrl != null)
        {
            return Redirect(redirectUrl);
        }

        return await GetLoggedInDefaultRedirectActionAsync();
    }

    public async Task<ActionResult> Logout()
    {
        await _contentRepository
            .Users()
            .Authentication()
            .SignOutAsync();

        return Redirect(_adminRouteLibrary.Auth.Login());
    }

    [AllowAnonymous]
    public async Task<ActionResult> ForgotPassword(string email)
    {
        if (await IsLoggedInAsync()) return await GetLoggedInDefaultRedirectActionAsync();

        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ForgotPassword));
        return View(viewPath, new ForgotPasswordViewModel { Username = email });
    }

    [AllowAnonymous]
    [HttpPost]
    public async Task<ViewResult> ForgotPassword(ForgotPasswordViewModel command)
    {
        await _contentRepository
            .WithModelState(this)
            .Users()
            .AccountRecovery()
            .InitiateAsync(new InitiateUserAccountRecoveryViaEmailCommand()
            {
                UserAreaCode = CofoundryAdminUserArea.Code,
                Username = command.Username
            });

        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ForgotPassword));
        return View(viewPath, command);
    }

    [AllowAnonymous]
    public async Task<ActionResult> ResetPassword()
    {
        if (await IsLoggedInAsync()) return await GetLoggedInDefaultRedirectActionAsync();

        var token = _authorizedTaskTokenUrlHelper.ParseTokenFromQuery(Request.Query);

        var requestValidationResult = await _contentRepository
            .WithModelState(this)
            .Users()
            .AccountRecovery()
            .Validate(new ValidateUserAccountRecoveryByEmailQuery()
            {
                UserAreaCode = CofoundryAdminUserArea.Code,
                Token = token
            })
            .ExecuteAsync();

        if (!ModelState.IsValid)
        {
            var invalidViewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ResetPassword) + "RequestInvalid");
            return View(invalidViewPath, requestValidationResult);
        }

        var vm = new CompleteAccountRecoveryViewModel();
        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ResetPassword));

        return View(viewPath, vm);
    }

    [AllowAnonymous]
    [HttpPost]
    public async Task<ActionResult> ResetPassword(CompleteAccountRecoveryViewModel vm)
    {
        if (await IsLoggedInAsync()) return await GetLoggedInDefaultRedirectActionAsync();

        var token = _authorizedTaskTokenUrlHelper.ParseTokenFromQuery(Request.Query);

        await _contentRepository
            .WithModelState(this)
            .Users()
            .AccountRecovery()
            .CompleteAsync(new CompleteUserAccountRecoveryViaEmailCommand()
            {
                UserAreaCode = CofoundryAdminUserArea.Code,
                Token = token,
                NewPassword = vm.NewPassword
            });

        if (ModelState.IsValid)
        {
            var completeViewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ResetPassword) + "Complete");
            return View(completeViewPath);
        }

        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ResetPassword));
        return View(viewPath, vm);
    }

    [AllowAnonymous]
    public async Task<ActionResult> ChangePassword(string returnUrl)
    {
        var redirectAction = await ValidateChangePasswordRouteAsync();
        if (redirectAction != null) return redirectAction;

        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ChangePassword));
        return View(viewPath, new ChangePasswordViewModel());
    }

    [AllowAnonymous]
    [HttpPost]
    public async Task<ActionResult> ChangePassword(string returnUrl, ChangePasswordViewModel vm)
    {
        var redirectAction = await ValidateChangePasswordRouteAsync();
        if (redirectAction != null) return redirectAction;

        await _contentRepository
            .WithModelState(this)
            .Users()
            .UpdatePasswordByCredentialsAsync(new UpdateUserPasswordByCredentialsCommand()
            {
                UserAreaCode = CofoundryAdminUserArea.Code,
                Username = vm.Username,
                NewPassword = vm.NewPassword,
                OldPassword = vm.OldPassword
            });

        ViewBag.ReturnUrl = RedirectUrlHelper.GetAndValidateReturnUrl(this);

        var viewPath = ViewPathFormatter.View(CONTROLLER_NAME, nameof(ChangePassword));
        return View(viewPath, vm);
    }

    private async Task<ActionResult> ValidateChangePasswordRouteAsync()
    {
        var user = await GetUserContextAsync();
        if (user.UserId.HasValue)
        {
            if (!user.IsPasswordChangeRequired)
            {
                return await GetLoggedInDefaultRedirectActionAsync();
            }

            // The user shouldn't be logged in, but if so, log them out
            await _contentRepository
                .Users()
                .Authentication()
                .SignOutAsync();
        }

        return null;
    }

    private async Task<bool> IsLoggedInAsync()
    {
        var userContext = await GetUserContextAsync();

        return userContext.IsSignedIn();
    }

    private Task<IUserContext> GetUserContextAsync()
    {
        return _contentRepository
            .Users()
            .Current()
            .Get()
            .AsUserContext()
            .ExecuteAsync();
    }

    private async Task<ActionResult> GetLoggedInDefaultRedirectActionAsync()
    {
        var modules = await _contentRepository.ExecuteQueryAsync(new GetPermittedAdminModulesQuery());
        var dashboardModule = modules.FirstOrDefault(m => m.AdminModuleCode == DashboardModuleRegistration.ModuleCode);

        if (dashboardModule == null)
        {
            dashboardModule = modules
                .SetStandardOrdering()
                .FirstOrDefault();
        }

        if (dashboardModule == null)
        {
            throw new InvalidOperationException("No modules available.");
        }

        return Redirect(dashboardModule.Url);
    }
}


text:
/* This is a managed file. Do not delete this comment. */

#include <include/inheritance.h>

/* Simple example that shows how to model and use a struct with inheritance. */

int inheritanceMain(int argc, char *argv[]) {

    /* Create new instance of struct type with inheritance. Notice that the
     * members of the base-struct are automatically added to the Create.
     */
    inheritance_Point3D *p = inheritance_Point3DCreate(10, 20, 30);
    if (!p) {
        goto error;
    }

    /* Members from the base class can be accessed with 'super' */
    corto_info("p->x = %d, p->y = %d, p->z = %d", p->super.x, p->super.y, p->z);

    /* Send update notification for new value */
    inheritance_Point3DUpdate(p, 20, 30, 40);

    /* An alternative way to get members from a base class is with a cast. In
     * debug mode, this cast will perform a type check. If the casted value is
     * not of the specified type, the application will assert. */
    corto_info("p->x = %d, p->y = %d, p->z = %d",
        inheritance_Point(p)->x, inheritance_Point(p)->y, p->z);

    corto_delete(p);

    return 0;
error:
    return -1;
}


text:
Project moved to [charts-d3](https://github.com/mwasiluk/charts-d3)

[Online Demo](https://mwasiluk.github.io/d3-scatterplot-matrix)

## Bower

You can install this package through `Bower` :

    bower install d3-scatterplot-matrix --save

This project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 645860.


text:
alter table SYS_CATEGORY_ATTR add DEFAULT_DECIMAL numeric(36,10)^

alter table SYS_ATTR_VALUE add DECIMAL_VALUE numeric(36,10)^

alter table SYS_CATEGORY_ATTR add ATTRIBUTE_CONFIGURATION_JSON clob^


text:
// Copyright 2013 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.

#include "chrome/browser/chromeos/attestation/platform_verification_flow.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/chromeos/attestation/attestation_ca_client.h"
#include "chrome/browser/chromeos/attestation/attestation_signed_data.pb.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/media/protected_media_identifier_permission_context.h"
#include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/attestation/attestation_flow.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/cryptohome/async_method_caller.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/user_manager/user.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "net/cert/x509_certificate.h"

namespace {

const int kTimeoutInSeconds = 8;
const char kAttestationResultHistogram[] =
    "ChromeOS.PlatformVerification.Result";
const char kAttestationAvailableHistogram[] =
    "ChromeOS.PlatformVerification.Available";
const int kAttestationResultHistogramMax = 10;

// A callback method to handle DBus errors.
void DBusCallback(const base::Callback<void(bool)>& on_success,
                  const base::Closure& on_failure,
                  chromeos::DBusMethodCallStatus call_status,
                  bool result) {
  if (call_status == chromeos::DBUS_METHOD_CALL_SUCCESS) {
    on_success.Run(result);
  } else {
    LOG(ERROR) << "PlatformVerificationFlow: DBus call failed!";
    on_failure.Run();
  }
}

// A helper to call a ChallengeCallback with an error result.
void ReportError(
    const chromeos::attestation::PlatformVerificationFlow::ChallengeCallback&
        callback,
    chromeos::attestation::PlatformVerificationFlow::Result error) {
  UMA_HISTOGRAM_ENUMERATION(kAttestationResultHistogram, error,
                            kAttestationResultHistogramMax);
  callback.Run(error, std::string(), std::string(), std::string());
}
}  // namespace

namespace chromeos {
namespace attestation {

// A default implementation of the Delegate interface.
class DefaultDelegate : public PlatformVerificationFlow::Delegate {
 public:
  DefaultDelegate() {}
  ~DefaultDelegate() override {}

  const GURL& GetURL(content::WebContents* web_contents) override {
    const GURL& url = web_contents->GetLastCommittedURL();
    if (!url.is_valid())
      return web_contents->GetVisibleURL();
    return url;
  }

  const user_manager::User* GetUser(
      content::WebContents* web_contents) override {
    return ProfileHelper::Get()->GetUserByProfile(
        Profile::FromBrowserContext(web_contents->GetBrowserContext()));
  }

  bool IsPermittedByUser(content::WebContents* web_contents) override {
    ProtectedMediaIdentifierPermissionContext* permission_context =
        ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(
            Profile::FromBrowserContext(web_contents->GetBrowserContext()));

    // TODO(xhwang): Using delegate_->GetURL() here is not right. The platform
    // verification may be requested by a frame from a different origin. This
    // will be solved when http://crbug.com/454847 is fixed.
    const GURL& requesting_origin = GetURL(web_contents).GetOrigin();

    GURL embedding_origin = web_contents->GetLastCommittedURL().GetOrigin();

    ContentSetting content_setting = permission_context->GetPermissionStatus(
        requesting_origin, embedding_origin);

    return content_setting == CONTENT_SETTING_ALLOW;
  }

  bool IsInSupportedMode(content::WebContents* web_contents) override {
    Profile* profile =
        Profile::FromBrowserContext(web_contents->GetBrowserContext());
    if (profile->IsOffTheRecord() || profile->IsGuestSession())
      return false;

    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    return !command_line->HasSwitch(chromeos::switches::kSystemDevMode) ||
           command_line->HasSwitch(chromeos::switches::kAllowRAInDevMode);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DefaultDelegate);
};

PlatformVerificationFlow::ChallengeContext::ChallengeContext(
    content::WebContents* web_contents,
    const std::string& service_id,
    const std::string& challenge,
    const ChallengeCallback& callback)
    : web_contents(web_contents),
      service_id(service_id),
      challenge(challenge),
      callback(callback) {}

PlatformVerificationFlow::ChallengeContext::~ChallengeContext() {}

PlatformVerificationFlow::PlatformVerificationFlow()
    : attestation_flow_(NULL),
      async_caller_(cryptohome::AsyncMethodCaller::GetInstance()),
      cryptohome_client_(DBusThreadManager::Get()->GetCryptohomeClient()),
      delegate_(NULL),
      timeout_delay_(base::TimeDelta::FromSeconds(kTimeoutInSeconds)) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  scoped_ptr<ServerProxy> attestation_ca_client(new AttestationCAClient());
  default_attestation_flow_.reset(new AttestationFlow(
      async_caller_,
      cryptohome_client_,
      attestation_ca_client.Pass()));
  attestation_flow_ = default_attestation_flow_.get();
  default_delegate_.reset(new DefaultDelegate());
  delegate_ = default_delegate_.get();
}

PlatformVerificationFlow::PlatformVerificationFlow(
    AttestationFlow* attestation_flow,
    cryptohome::AsyncMethodCaller* async_caller,
    CryptohomeClient* cryptohome_client,
    Delegate* delegate)
    : attestation_flow_(attestation_flow),
      async_caller_(async_caller),
      cryptohome_client_(cryptohome_client),
      delegate_(delegate),
      timeout_delay_(base::TimeDelta::FromSeconds(kTimeoutInSeconds)) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (!delegate_) {
    default_delegate_.reset(new DefaultDelegate());
    delegate_ = default_delegate_.get();
  }
}

PlatformVerificationFlow::~PlatformVerificationFlow() {
}

void PlatformVerificationFlow::ChallengePlatformKey(
    content::WebContents* web_contents,
    const std::string& service_id,
    const std::string& challenge,
    const ChallengeCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!delegate_->GetURL(web_contents).is_valid()) {
    LOG(WARNING) << "PlatformVerificationFlow: Invalid URL.";
    ReportError(callback, INTERNAL_ERROR);
    return;
  }

  // Note: The following two checks are also checked in GetPermissionStatus.
  // Checking them here explicitly to report the correct error type.

  if (!IsAttestationAllowedByPolicy()) {
    VLOG(1) << "Platform verification not allowed by device policy.";
    ReportError(callback, POLICY_REJECTED);
    return;
  }

  // TODO(xhwang): Change to DCHECK when prefixed EME support is removed.
  // See http://crbug.com/249976
  if (!delegate_->IsInSupportedMode(web_contents)) {
    VLOG(1) << "Platform verification denied because it's not supported in the "
            << "current mode.";
    ReportError(callback, PLATFORM_NOT_VERIFIED);
    return;
  }

  if (!delegate_->IsPermittedByUser(web_contents)) {
    VLOG(1) << "Platform verification not permitted by user.";
    ReportError(callback, USER_REJECTED);
    return;
  }

  ChallengeContext context(web_contents, service_id, challenge, callback);
  // Check if the device has been prepared to use attestation.
  BoolDBusMethodCallback dbus_callback =
      base::Bind(&DBusCallback,
                 base::Bind(&PlatformVerificationFlow::OnAttestationPrepared,
                            this, context),
                 base::Bind(&ReportError, callback, INTERNAL_ERROR));
  cryptohome_client_->TpmAttestationIsPrepared(dbus_callback);
}

void PlatformVerificationFlow::OnAttestationPrepared(
    const ChallengeContext& context,
    bool attestation_prepared) {
  UMA_HISTOGRAM_BOOLEAN(kAttestationAvailableHistogram, attestation_prepared);

  if (!attestation_prepared) {
    // This device is not currently able to use attestation features.
    ReportError(context.callback, PLATFORM_NOT_VERIFIED);
    return;
  }

  // Permission allowed. Now proceed to get certificate.
  const user_manager::User* user = delegate_->GetUser(context.web_contents);
  if (!user) {
    ReportError(context.callback, INTERNAL_ERROR);
    LOG(ERROR) << "Profile does not map to a valid user.";
    return;
  }

  GetCertificate(context, user->email(), false /* Don't force a new key */);
}

void PlatformVerificationFlow::GetCertificate(const ChallengeContext& context,
                                              const std::string& user_id,
                                              bool force_new_key) {
  scoped_ptr<base::Timer> timer(new base::Timer(false,    // Don't retain.
                                                false));  // Don't repeat.
  base::Closure timeout_callback = base::Bind(
      &PlatformVerificationFlow::OnCertificateTimeout,
      this,
      context);
  timer->Start(FROM_HERE, timeout_delay_, timeout_callback);

  AttestationFlow::CertificateCallback certificate_callback = base::Bind(
      &PlatformVerificationFlow::OnCertificateReady,
      this,
      context,
      user_id,
      base::Passed(&timer));
  attestation_flow_->GetCertificate(
      PROFILE_CONTENT_PROTECTION_CERTIFICATE,
      user_id,
      context.service_id,
      force_new_key,
      certificate_callback);
}

void PlatformVerificationFlow::OnCertificateReady(
    const ChallengeContext& context,
    const std::string& user_id,
    scoped_ptr<base::Timer> timer,
    bool operation_success,
    const std::string& certificate) {
  // Log failure before checking the timer so all failures are logged, even if
  // they took too long.
  if (!operation_success) {
    LOG(WARNING) << "PlatformVerificationFlow: Failed to certify platform.";
  }
  if (!timer->IsRunning()) {
    LOG(WARNING) << "PlatformVerificationFlow: Certificate ready but call has "
                 << "already timed out.";
    return;
  }
  timer->Stop();
  if (!operation_success) {
    ReportError(context.callback, PLATFORM_NOT_VERIFIED);
    return;
  }
  if (IsExpired(certificate)) {
    GetCertificate(context, user_id, true /* Force a new key */);
    return;
  }
  cryptohome::AsyncMethodCaller::DataCallback cryptohome_callback = base::Bind(
      &PlatformVerificationFlow::OnChallengeReady,
      this,
      context,
      certificate);
  std::string key_name = kContentProtectionKeyPrefix;
  key_name += context.service_id;
  async_caller_->TpmAttestationSignSimpleChallenge(KEY_USER,
                                                   user_id,
                                                   key_name,
                                                   context.challenge,
                                                   cryptohome_callback);
}

void PlatformVerificationFlow::OnCertificateTimeout(
    const ChallengeContext& context) {
  LOG(WARNING) << "PlatformVerificationFlow: Timing out.";
  ReportError(context.callback, TIMEOUT);
}

void PlatformVerificationFlow::OnChallengeReady(
    const ChallengeContext& context,
    const std::string& certificate,
    bool operation_success,
    const std::string& response_data) {
  if (!operation_success) {
    LOG(ERROR) << "PlatformVerificationFlow: Failed to sign challenge.";
    ReportError(context.callback, INTERNAL_ERROR);
    return;
  }
  SignedData signed_data_pb;
  if (response_data.empty() || !signed_data_pb.ParseFromString(response_data)) {
    LOG(ERROR) << "PlatformVerificationFlow: Failed to parse response data.";
    ReportError(context.callback, INTERNAL_ERROR);
    return;
  }
  VLOG(1) << "Platform verification successful.";
  UMA_HISTOGRAM_ENUMERATION(kAttestationResultHistogram, SUCCESS,
                            kAttestationResultHistogramMax);
  context.callback.Run(SUCCESS,
                       signed_data_pb.data(),
                       signed_data_pb.signature(),
                       certificate);
}

bool PlatformVerificationFlow::IsAttestationAllowedByPolicy() {
  // Check the device policy for the feature.
  bool enabled_for_device = false;
  if (!CrosSettings::Get()->GetBoolean(kAttestationForContentProtectionEnabled,
                                       &enabled_for_device)) {
    LOG(ERROR) << "Failed to get device setting.";
    return false;
  }
  if (!enabled_for_device) {
    VLOG(1) << "Platform verification denied because Verified Access is "
            << "disabled for the device.";
    return false;
  }

  return true;
}

bool PlatformVerificationFlow::IsExpired(const std::string& certificate) {
  scoped_refptr<net::X509Certificate> x509(
      net::X509Certificate::CreateFromBytes(certificate.data(),
                                            certificate.length()));
  if (!x509.get() || x509->valid_expiry().is_null()) {
    LOG(WARNING) << "Failed to parse certificate, cannot check expiry.";
    return false;
  }
  return (base::Time::Now() > x509->valid_expiry());
}

}  // namespace attestation
}  // namespace chromeos


text:
from google.cloud import gke_backup_v1

def sample_list_backup_plans():
    # Create a client
    client = gke_backup_v1.BackupForGKEClient()

    # Initialize request argument(s)
    request = gke_backup_v1.ListBackupPlansRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_backup_plans(request=request)

    # Handle the response
    for response in page_result:
        print(response)

# [END gkebackup_v1_generated_BackupForGKE_ListBackupPlans_sync]


text:
<?php

namespace Bootstrap\Components\ClientComponents;
use Bootstrap\Views\BootstrapView;

trait Row {

    /**
     * @param $content array of other objects
     * @param array $parameters selected_state, variable, onclick, style
     * <code>
     * $array = array(
     * 'rightswipeid' => 'item-id-rightswipe',  // this is a compound of item id & action of swipe right
     * 'leftswipeid'   => 'item-id-leftswipe', // this is a compound of item id & action of swipe left
     * 'onclick' => $onclick, // this must be an object or an array of objects
     * 'id' => 'mycustomid',
     * 'swipe_id' => 'swipeareaid' // refers to swipearea in the view
     * );
     * </code>
     * @param array $styles -- please see the link for more information about parameters [link] Bootstrap\Components\ComponentStyles
     * @return \stdClass
     */

    public function getComponentRow(array $content, array $parameters=array(),array $styles=array()) {
        /** @var BootstrapView $this */

		$obj = new \StdClass;
        $obj->type = 'row';
        $obj->row_content = $content;

        $obj = $this->attachStyles($obj,$styles);
        $obj = $this->attachParameters($obj,$parameters);

        return $obj;
	}

}


text:
using System.Threading.Tasks;
using System.Windows.Media;
using MahApps.Metro.Tests.TestHelpers;
using Xunit;

namespace MahApps.Metro.Tests
{
    public class CleanWindowTest : AutomationTestBase
    {
        [Fact]
        [DisplayTestMethodName]
        public async Task DefaultWindowCommandColorIsBlack()
        {
            await TestHost.SwitchToAppThread();

            var window = await WindowHelpers.CreateInvisibleWindowAsync<CleanWindow>();

            var blackBrushColor = ((SolidColorBrush)ThemeManager.GetTheme("Light.Blue").Resources["BlackBrush"]).Color;

            window.AssertWindowCommandsColor(blackBrushColor);
        }
    }
}