text:
package tekton

import (
	"context"
	"fmt"

	pplnv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	fn "knative.dev/func"
	"knative.dev/func/builders"
	"knative.dev/func/buildpacks"
	"knative.dev/func/s2i"
)

func deletePipelines(ctx context.Context, namespaceOverride string, listOptions metav1.ListOptions) (err error) {
	client, namespace, err := NewTektonClientAndResolvedNamespace(namespaceOverride)
	if err != nil {
		return
	}

	return client.Pipelines(namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, listOptions)
}

func deletePipelineRuns(ctx context.Context, namespaceOverride string, listOptions metav1.ListOptions) (err error) {
	client, namespace, err := NewTektonClientAndResolvedNamespace(namespaceOverride)
	if err != nil {
		return
	}

	return client.PipelineRuns(namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, listOptions)
}

func generatePipeline(f fn.Function, labels map[string]string) *pplnv1beta1.Pipeline {

	// -----  General properties
	pipelineName := getPipelineName(f)

	params := []pplnv1beta1.ParamSpec{
		{
			Name:        "gitRepository",
			Description: "Git repository that hosts the function project",
			Default:     pplnv1beta1.NewArrayOrString(f.Build.Git.URL),
		},
		{
			Name:        "gitRevision",
			Description: "Git revision to build",
		},
		{
			Name:        "contextDir",
			Description: "Path where the function project is",
			Default:     pplnv1beta1.NewArrayOrString(""),
		},
		{
			Name:        "imageName",
			Description: "Function image name",
		},
		{
			Name:        "builderImage",
			Description: "Builder image to be used",
		},
		{
			Name:        "buildEnvs",
			Description: "Environment variables to set during build time",
			Type:        "array",
		},
	}

	workspaces := []pplnv1beta1.PipelineWorkspaceDeclaration{
		{Name: "source-workspace", Description: "Directory where function source is located."},
		{Name: "cache-workspace", Description: "Directory where build cache is stored."},
		{Name: "dockerconfig-workspace", Description: "Directory containing image registry credentials stored in `config.json` file.", Optional: true},
	}

	var taskBuild pplnv1beta1.PipelineTask

	// Deploy step that uses an image produced by S2I builds needs explicit reference to the image
	referenceImageFromPreviousTaskResults := false

	var tasks []pplnv1beta1.PipelineTask
	var buildPreReq []string

	if f.Build.Git.URL != "" {
		// If Git is set up create fetch task,
		// otherwise sources have been already uploaded to workspace PVC.
		buildPreReq = []string{taskNameFetchSources}
		tasks = append(tasks, taskFetchSources())
	}

	if f.Build.Builder == builders.Pack {
		// ----- Buildpacks related properties
		taskBuild = taskBuildpacks(buildPreReq)

	} else if f.Build.Builder == builders.S2I {
		// ----- S2I build related properties

		params = append(params, pplnv1beta1.ParamSpec{Name: "s2iImageScriptsUrl", Description: "URL containing the default assemble and run scripts for the builder image.",
			Default: pplnv1beta1.NewArrayOrString("image:///usr/libexec/s2i")})

		taskBuild = taskS2iBuild(buildPreReq)
		referenceImageFromPreviousTaskResults = true
	}

	// ----- Pipeline definition
	tasks = append(tasks, taskBuild, taskDeploy(taskNameBuild, referenceImageFromPreviousTaskResults))

	return &pplnv1beta1.Pipeline{
		ObjectMeta: v1.ObjectMeta{
			Name:        pipelineName,
			Labels:      labels,
			Annotations: f.Deploy.Annotations,
		},
		Spec: pplnv1beta1.PipelineSpec{
			Params:     params,
			Workspaces: workspaces,
			Tasks:      tasks,
		},
	}
}

func generatePipelineRun(f fn.Function, labels map[string]string) *pplnv1beta1.PipelineRun {

	revision := f.Build.Git.Revision
	contextDir := f.Build.Git.ContextDir
	if contextDir == "" && f.Build.Builder == builders.S2I {
		// TODO(lkingland): could instead update S2I to interpret empty string
		// as cwd, such that builder-specific code can be kept out of here.
		contextDir = "."
	}

	buildEnvs := &pplnv1beta1.ArrayOrString{
		Type:     pplnv1beta1.ParamTypeArray,
		ArrayVal: []string{},
	}
	if len(f.Build.BuildEnvs) > 0 {
		var envs []string
		for _, e := range f.Build.BuildEnvs {
			envs = append(envs, e.KeyValuePair())
		}
		buildEnvs.ArrayVal = envs
	} else {
		// need to hack empty BuildEnvs array on Tekton v0.39.0+
		// until https://github.com/tektoncd/pipeline/issues/5149 is resolved and released
		buildEnvs.ArrayVal = append(buildEnvs.ArrayVal, "=")
	}

	params := []pplnv1beta1.Param{
		{
			Name:  "gitRepository",
			Value: *pplnv1beta1.NewArrayOrString(f.Build.Git.URL),
		},
		{
			Name:  "gitRevision",
			Value: *pplnv1beta1.NewArrayOrString(revision),
		},
		{
			Name:  "contextDir",
			Value: *pplnv1beta1.NewArrayOrString(contextDir),
		},
		{
			Name:  "imageName",
			Value: *pplnv1beta1.NewArrayOrString(f.Image),
		},
		{
			Name:  "builderImage",
			Value: *pplnv1beta1.NewArrayOrString(getBuilderImage(f)),
		},
		{
			Name:  "buildEnvs",
			Value: *buildEnvs,
		},
	}

	workspaces := []pplnv1beta1.WorkspaceBinding{
		{
			Name: "source-workspace",
			PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
				ClaimName: getPipelinePvcName(f),
			},
			SubPath: "source",
		},
		{
			Name: "cache-workspace",
			PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
				ClaimName: getPipelinePvcName(f),
			},
			SubPath: "cache",
		},
		{
			Name: "dockerconfig-workspace",
			Secret: &corev1.SecretVolumeSource{
				SecretName: getPipelineSecretName(f),
			},
		},
	}

	if f.Build.Builder == builders.S2I {
		if f.Runtime == "quarkus" {
			params = append(params, pplnv1beta1.Param{Name: "s2iImageScriptsUrl", Value: *pplnv1beta1.NewArrayOrString("image:///usr/local/s2i")})
		}
	}

	// ----- PipelineRun definition
	return &pplnv1beta1.PipelineRun{
		ObjectMeta: v1.ObjectMeta{
			GenerateName: fmt.Sprintf("%s-run-", getPipelineName(f)),
			Labels:       labels,
			Annotations:  f.Deploy.Annotations,
		},
		Spec: pplnv1beta1.PipelineRunSpec{
			PipelineRef: &pplnv1beta1.PipelineRef{
				Name: getPipelineName(f),
			},
			Params:     params,
			Workspaces: workspaces,
		},
	}
}

// guilderImage returns the builder image to use when building the Function
// with the Pack strategy if it can be calculated (the Function has a defined
// language runtime.  Errors are checked elsewhere, so at this level they
// manifest as an inability to get a builder image = empty string.
func getBuilderImage(f fn.Function) (name string) {
	if f.Build.Builder == builders.S2I {
		name, _ = s2i.BuilderImage(f, builders.S2I)
	} else {
		name, _ = buildpacks.BuilderImage(f, builders.Pack)
	}
	return
}

func getPipelineName(f fn.Function) string {
	var source string
	if f.Build.Git.URL == "" {
		source = "upload"
	} else {
		source = "git"
	}
	return fmt.Sprintf("%s-%s-%s-pipeline", f.Name, f.Build.Builder, source)
}

func getPipelineSecretName(f fn.Function) string {
	return fmt.Sprintf("%s-secret", getPipelineName(f))
}

func getPipelinePvcName(f fn.Function) string {
	return fmt.Sprintf("%s-pvc", getPipelineName(f))
}


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

package org.chromium.components.page_info;

import android.graphics.drawable.Drawable;
import android.view.ViewGroup;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;

import org.chromium.base.Callback;
import org.chromium.components.browser_ui.site_settings.SiteSettingsDelegate;
import org.chromium.components.content_settings.CookieControlsBridge;
import org.chromium.components.content_settings.CookieControlsObserver;
import org.chromium.components.omnibox.AutocompleteSchemeClassifier;
import org.chromium.content_public.browser.BrowserContextHandle;
import org.chromium.ui.modaldialog.ModalDialogManager;
import org.chromium.url.GURL;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.function.Consumer;

/**
 *  Provides embedder-level information to PageInfoController.
 */
public abstract class PageInfoControllerDelegate {
    @IntDef({OfflinePageState.NOT_OFFLINE_PAGE, OfflinePageState.TRUSTED_OFFLINE_PAGE,
            OfflinePageState.UNTRUSTED_OFFLINE_PAGE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface OfflinePageState {
        int NOT_OFFLINE_PAGE = 1;
        int TRUSTED_OFFLINE_PAGE = 2;
        int UNTRUSTED_OFFLINE_PAGE = 3;
    }

    private final AutocompleteSchemeClassifier mAutocompleteSchemeClassifier;
    private final VrHandler mVrHandler;
    private final boolean mIsSiteSettingsAvailable;
    private final boolean mCookieControlsShown;
    protected @OfflinePageState int mOfflinePageState;
    protected boolean mIsHttpsImageCompressionApplied;
    protected String mOfflinePageUrl;

    public PageInfoControllerDelegate(AutocompleteSchemeClassifier autocompleteSchemeClassifier,
            VrHandler vrHandler, boolean isSiteSettingsAvailable, boolean cookieControlsShown) {
        mAutocompleteSchemeClassifier = autocompleteSchemeClassifier;
        mVrHandler = vrHandler;
        mIsSiteSettingsAvailable = isSiteSettingsAvailable;
        mCookieControlsShown = cookieControlsShown;
        mIsHttpsImageCompressionApplied = false;

        // These sometimes get overwritten by derived classes.
        mOfflinePageState = OfflinePageState.NOT_OFFLINE_PAGE;
        mOfflinePageUrl = null;
    }
    /**
     * Creates an AutoCompleteClassifier.
     */
    public AutocompleteSchemeClassifier createAutocompleteSchemeClassifier() {
        return mAutocompleteSchemeClassifier;
    }

    /**
     * Whether cookie controls should be shown in Page Info UI.
     */
    public boolean cookieControlsShown() {
        return mCookieControlsShown;
    }

    /**
     * Return the ModalDialogManager to be used.
     */
    public abstract ModalDialogManager getModalDialogManager();

    /**
     * Returns whether LiteMode https image compression was applied on this page
     */
    public boolean isHttpsImageCompressionApplied() {
        return mIsHttpsImageCompressionApplied;
    }

    /**
     * Returns a VrHandler for Page Info UI.
     */
    public VrHandler getVrHandler() {
        return mVrHandler;
    }

    /**
     * Gets the Url of the offline page being shown if any. Returns null otherwise.
     */
    @Nullable
    public String getOfflinePageUrl() {
        return mOfflinePageUrl;
    }

    /**
     * Whether the page being shown is an offline page.
     */
    public boolean isShowingOfflinePage() {
        return mOfflinePageState != OfflinePageState.NOT_OFFLINE_PAGE;
    }

    /**
     * Whether the page being shown is a paint preview.
     */
    public boolean isShowingPaintPreviewPage() {
        return false;
    }

    /**
     * Initialize viewParams with Offline Page UI info, if any.
     * @param viewParams The PageInfoView.Params to set state on.
     * @param runAfterDismiss Used to set "open Online" button callback for offline page.
     */
    public void initOfflinePageUiParams(
            PageInfoView.Params viewParams, Consumer<Runnable> runAfterDismiss) {
        viewParams.openOnlineButtonShown = false;
    }

    /**
     * Return the connection message shown for an offline page, if appropriate.
     * Returns null if there's no offline page.
     */
    @Nullable
    public String getOfflinePageConnectionMessage() {
        return null;
    }

    /**
     * Return the connection message shown for a paint preview page, if appropriate.
     * Returns null if there's no paint preview page.
     */
    @Nullable
    public String getPaintPreviewPageConnectionMessage() {
        return null;
    }

    /**
     * Whether Site settings are available.
     */
    public boolean isSiteSettingsAvailable() {
        return mIsSiteSettingsAvailable;
    }

    /**
     * Show cookie settings.
     */
    public abstract void showCookieSettings();

    /**
     * Show ad personalization settings.
     */
    public abstract void showAdPersonalizationSettings();

    /**
     * Creates Cookie Controls Bridge.
     * @param observer The CookieControlsObserver to create the bridge with.
     * @return the object that facilitates interfacing with native code.
     */
    @NonNull
    public abstract CookieControlsBridge createCookieControlsBridge(
            CookieControlsObserver observer);

    /**
     * Allows the delegate to insert additional {@link PageInfoRowView} views.
     * @return a collection of controllers corresponding to these views.
     */
    @NonNull
    public abstract Collection<PageInfoSubpageController> createAdditionalRowViews(
            PageInfoMainController mainController, ViewGroup rowWrapper);

    /**
     * @return Returns the browser context associated with this dialog.
     */
    @NonNull
    public abstract BrowserContextHandle getBrowserContext();

    /**
     * @return Returns the SiteSettingsDelegate for this page info.
     */
    @NonNull
    public abstract SiteSettingsDelegate getSiteSettingsDelegate();

    /**
     * Fetches a favicon for the current page and passes it to callback.
     * The UI will use a fallback icon if null is supplied.
     */
    public abstract void getFavicon(GURL url, Callback<Drawable> callback);

    /**
     * Checks to see that touch exploration or an accessibility service that can perform gestures
     * is enabled.
     * @return Whether or not accessibility and touch exploration are enabled.
     */
    public abstract boolean isAccessibilityEnabled();

    public abstract FragmentManager getFragmentManager();

    public abstract boolean isIncognito();
}

redpajama_set_name: RedPajamaGithub


text:
Tag-Value Comms System - Python driven multithread communicator

# changelog
- v0.1.7: fix template
- v0.1.6: handle non-registered error, better import error handling, automatic version check
- v0.1.5: add test support
- v0.1.4: add __to_json__
- v0.1.3: fix getInputs copying (del owner info)
- v0.1.2: flag-params support
- v0.1.1: flag support


text:
package net.nurik.roman.formwatchface;

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ConfigComplicationsFragment extends PreferenceFragment {

    public ConfigComplicationsFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_complications);
    }

    public void update() {
        setPreferenceScreen(null);
        addPreferencesFromResource(R.xml.pref_complications);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.prefs_fragment, container, false);
    }
}


text:
require File.dirname(__FILE__) + '/../test_helper'

class BookmarkTest < Test::Unit::TestCase
  context "A Bookmark " do

    setup do
      @user1 = Factory(:user)
      @user2 = Factory(:user)

      @address1 = Factory(:address, :url => 'http://www.toghq.com?' + Time.now.to_i.to_s)
    end

    should "count 1 each time a bookmark is created" do
      assert_equal 0, @address1.bookmarks.size,  "Should have 0 bookmarks"
      bookmark = @address1.add_bookmark(@user1)
      assert_equal 1, @address1.bookmarks.size,  "Should have 1 bookmarks"
      bookmark = @address1.add_bookmark(@user2)
      assert_equal 2, @address1.bookmarks.size,  "Should have 2 bookmarks"
    end

    should "not be added twice for a given user" do
      bookmark = @address1.add_bookmark(@user1)
      assert_equal true, bookmark.is_new?,  "Should be a new bookmark"
      bookmark = @address1.add_bookmark(@user1)
      assert_equal false, bookmark.is_new?,  "Shouldn't be a new bookmark"
    end

    context 'privacy' do
      setup do
        @address2 = Factory(:address, :url => 'http://www.google.com?' + Time.now.to_i.to_s)
        @address3 = Factory(:address, :url => 'http://www.yahoo.com?' + Time.now.to_i.to_s)
        @address1.add_bookmark(@user1, Bookmark::PRIVACY_PRIVATE)
        @address2.add_bookmark(@user1, Bookmark::PRIVACY_NETWORK)
        @address3.add_bookmark(@user1, Bookmark::PRIVACY_PUBLIC)
      end

      should "should hide no public bookmarks" do
        assert_equal 1, @user1.bookmarks.public.size
        assert_equal 2, @user1.bookmarks.network.size
        assert_equal 3, @user1.bookmarks.size
      end

    end

#   context "search" do
#
#      setup do
#        @jaiku = Factory(:addresses, :url => 'http://www.jaiku.com?' + Time.now.to_i.to_s, :title => 'jaiku', :description => 'nanoblog')
#        @twitter = Factory(:addresses, :url => 'http://www.twitter.com?' + Time.now.to_i.to_s, :title => 'twitter', :description => 'nanoblog')
#      end
#
#      should "should find one result" do
#        @bookmark1 = @jaiku.add_bookmark(@user, 'jaiku', 'nanoblog')
#
#        @bookmark2 = @twitter.add_bookmark(@user, 'twitter', 'nanoblog')
#
#        assert_contains Bookmark.site_search('jaiku'), @bookmark1
#        assert_contains Bookmark.site_search('twitter'), @bookmark2
#
#        @bookmarks = Bookmark.site_search('nanoblog')
#
#        assert_contains @bookmarks, @bookmark1
#        assert_contains @bookmarks, @bookmark2
#      end#
#
#    end

  end

end


text:
'use strict';
/**
 * @ngdoc function
 * @name sbAdminApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the sbAdminApp
 */
angular.module('sbAdminApp')
  .controller('PublicCtrl', function($scope, socket, dailyLogService, settingsService, $state) {

    var monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
    ];

    var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

    $scope.displayedCollection = [{'attributes':{'firstName':'Vince', 'lastName': 'Elizaga', 'gender':'Male'}, 'time':'7:43 AM'},
      {'attributes':{'firstName':'Vince', 'lastName': 'Elizaga', 'gender':'Male'}, 'time':'7:43 AM'},
      {'attributes':{'firstName':'Vince', 'lastName': 'Elizaga', 'gender':'Male'}, 'time':'7:43 AM'},
      {'attributes':{'firstName':'Vince', 'lastName': 'Elizaga', 'gender':'Male'}, 'time':'7:43 AM'}
    ];

    $scope.detectedEmployee = {
      'firstName' : '',
      'lastName' : '',
      'position' : '',
      'age' : '',
      'avatar' : '"img/logo/logo_placeholder.png";'
    }

    $scope.isFingerPrintDetected = false;
    $scope.isPublicTable = true;

    startTime();

    getSettings();

    $scope.redirectToLogin = function(){
      $state.go('login');
    }

    $scope.extraLogCheck = function(time){
      if(stringContains(time, 'Extra')){
        return 'log-bold';
      }else{
        return '';
      }
    }

    function getSettings(){
      settingsService.getSetting()
      .then(function(results) {
        // Handle the result

        if(results[0].get('firstBoot')){
          $state.go('guide');
        }

        else{
          $scope.settings = results[0];
          $scope.primaryPhoto = $scope.settings.get('primaryPhoto');
          $scope.secondaryPhoto = $scope.settings.get('secondaryPhoto');
          $scope.cutoffTime = $scope.settings.get('cutoffTime');
          $scope.coverImage = {
            "background-image": "url(" + $scope.settings.get('coverImage') + ")"
          };
        }

        getAll();

      }, function(err) {
        // Error occurred
        console.log(err);
      }, function(percentComplete) {
      });
    };

    function getAll(){
      dailyLogService.getDailyLogs(true)
      .then(function(results) {
        // Handle the result
        var morning = [];
        var afternoon = [];

        angular.forEach(results, function(value, key) {
          var tmp = value.get('time');
          tmp = tmp.split(' ');

          var isPm = stringContains(tmp[1], 'PM');

          tmp = tmp[0];

          tmp = tmp.split(':');

          var h = parseInt(tmp[0]);
          var m = parseInt(tmp[1]);

          if(isPm){
            h = h + 12;
          } else {
            if(h === 12){
              h = 0;
            }
          }

          var timeInDecimals = h + m/100;

          if(timeInDecimals >= $scope.cutoffTime){
            afternoon.push(value);
          }
          else{
            morning.push(value);
          }
        });

        $scope.displayedCollectionAM = morning;
        $scope.displayedCollectionPM = afternoon;

      }, function(err) {
        // Error occurred
        console.log(err);
      }, function(percentComplete) {
      });
    };

    function startTime() {
      var today = new Date();
      var day = today.getDay();
      var dateDay = today.getDate();
      var month = today.getMonth();
      var year = today.getFullYear();

      var h = today.getHours();

      var period = 'PM';

      if(h < 12){
        period = 'AM';
      }

      var m = today.getMinutes();
      var s = today.getSeconds();
      h = checkAMPM(h);
      m = checkTime(m);
      s = checkTime(s);

      $scope.time = h + ":" + m + ":" + s + ' ' + period;
      $scope.currentDate = dayNames[day] + ', ' + monthNames[month] + ' ' + dateDay + ', ' + year;
      $scope.$apply();

      var t = setTimeout(startTime, 1000);

    }

    function checkTime(i) {
      if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
        return i;
    }

    function checkAMPM(h) {
      var tmp;
      if(h > 12){
        h = h - 12;
      }

      if(h === 0){
        h = 12;
      }
      return h;
    }

    function stringContains(data, compare){
      return data.indexOf(compare) > -1;
    }

    socket.on('fromPublicServer', function(data){
      if(typeof data === 'object'){

        $scope.detectedEmployee = {
          'firstName' : data.firstName,
          'lastName' : data.lastName,
          'position' : data.position,
          'avatar' : data.avatarUrl,
          'time' : $scope.time,
          'arrivalAM' : data.departArrive.arrivalAM,
          'departureAM' : data.departArrive.departureAM,
          'arrivalPM' : data.departArrive.arrivalPM,
          'departurePM' : data.departArrive.departurePM
        }
        $scope.isFingerPrintDetected = true;
        getAll();
        setTimeout(function(){
          $scope.isFingerPrintDetected = false;
        },3500);
      }
    });

    $scope.$on("$destroy", function(){
      socket.removeAllListeners("fromPublicServer");
    });
  });


text:
import { module, test } from "qunit";
import Ember from "ember";
import encodeURI from "ember-cpm/macros/encode-uri";

var MyObj = Ember.Object.extend({
  encoded: encodeURI('value')
});

module('encodeURI');

test('returns undefined if the value is undefined', function(assert) {
  assert.equal(MyObj.create().get('encoded'), undefined);
});

test('returns null if the value is null', function(assert) {
  assert.equal(MyObj.create({ value: null }).get('encoded'), null);
});

test('URI-encodes values (as full URIs)', function(assert) {
  var url      = 'http://example.com/one and two';
  var expected = 'http://example.com/one%20and%20two';
  assert.equal(MyObj.create({ value: url }).get('encoded'), expected);
});


text:
quick-foundation
================


text:
<?php

namespace Phospr\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Phospr\DoubleEntryBundle\Model\Account as BaseAccount;
use Phospr\DoubleEntryBundle\Model\AccountInterface;
use JMS\Serializer\Annotation as JMSSerializer;

/**
 * Account
 *
 * @author Tom Haskins-Vaughan <tom@tomhv.uk>
 * @since  0.8.0
 *
 * @ORM\Entity
 * @ORM\Table(name="phospr_account",uniqueConstraints={
 *    @ORM\UniqueConstraint(
 *        name="org_path_idx",
 *        columns={"organization_id", "path"}
 *    ),
 *    @ORM\UniqueConstraint(
 *        name="org_segmentation_idx",
 *        columns={"organization_id", "segmentation"}
 *    ),
 * })
 * @ORM\HasLifecycleCallbacks()
 * @Gedmo\Tree(type="nested")
 * @ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
 *
 * @JMSSerializer\ExclusionPolicy("all")
 */
class Account extends BaseAccount implements AccountInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Gedmo\TreeParent
     * @ORM\ManyToOne(targetEntity="Account", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $parent;

    /**
     * @ORM\ManyToOne(targetEntity="Organization", inversedBy="accounts")
     * @ORM\JoinColumn(name="organization_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $organization;

    /**
     * @ORM\OneToMany(targetEntity="Account", mappedBy="parent", cascade={"persist"})
     * @ORM\OrderBy({"lft" = "ASC"})
     */
    protected $children;

    /**
     * @ORM\OneToMany(targetEntity="Posting", mappedBy="account")
     * @ORM\OrderBy({"date" = "ASC"})
     */
    protected $postings;
}


text:
from __future__ import unicode_literals

import blog.models
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0008_section_img'),
    ]

    operations = [
        migrations.AlterField(
            model_name='section',
            name='img',
            field=models.ImageField(upload_to=blog.models.post_dir_path),
        ),
    ]


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\TblAssetTestPeriods;

/**
 * SearchTblAssetTestPeriods represents the model behind the search form about `common\models\TblAssetTestPeriods`.
 */
class SearchTblAssetTestPeriods extends TblAssetTestPeriods
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['periods'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = TblAssetTestPeriods::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
            'defaultOrder'=>[
                'id'=> SORT_DESC,]
                ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'periods', $this->periods]);

        return $dataProvider;
    }
}


text:
export GRAILS_OPTS="-Xmx4G -Xms512m -Dfile.encoding=UTF-8 -Djava.encoding=UTF-8"
#export GRAILS_OPTS="-Xmx4G -Xms512m -XX:MaxPermSize=512m -Dfile.encoding=UTF-8 -Djava.encoding=UTF-8"

#export LC_ALL=da_DK.UTF-8

## Removes (ugly!) clock char from bash-it theme
export THEME_SHOW_CLOCK_CHAR=false

# Fixes ugly dir color in gnome terminal
## See: https://askubuntu.com/questions/881949/ugly-color-for-directories-in-gnome-terminal
LS_COLORS=$LS_COLORS:'ow=1;34:tw=1;34:' ; export LS_COLORS

PROMPT_COMMAND='echo -en "\033]0; $(pwd) \a"'

PATH=$PATH:~/.dotfiles/local-bin

## clones a git repo and cd into the folder
gitCloneCd() {
    PARAMS=$@
    A=${PARAMS%.*}
    B=${A##*/}

    git clone ${PARAMS} && cd "${B}"
}

openFile() {
    xdg-open $@ &> /dev/null
}

#openSkatVpn() {
#    url="webvpn.skat.dk"
#    group="DevOPS-ext"
#    echo -e '\033]2;SKAT VPN\007'
#    copyq add $SKAT_PASSWORD #add to clipboard
#    sudo openconnect --usergroup=$group --user=$SKAT_WNUMMER $url
#}

##
# Run all codenarc rules.
# Opens the respective reports if they fail.
# Run all tests if codenarc is happy!
# Opens the test report if any test fail.
##
function runCodenarcCleanCheckExitIfFailure() {
    success=true
    gradlewFromParents clean
    if ! gradlewFromParents codenarcMain; then
        xdg-open build/reports/codenarc/main.html &> /dev/null
        success=false
    fi
    if ! gradlewFromParents codenarcTest; then
        xdg-open build/reports/codenarc/test.html &> /dev/null
        success=false
    fi
    if ! gradlewFromParents codenarcIntegrationTest; then
        xdg-open build/reports/codenarc/integrationTest.html &> /dev/null
        success=false
    fi
    # Exit if codenarc has failed
    if ! $success; then
        return 1
    fi
    notify-send 'Codenarc was successful'

    # If all is well run all tests
    if ! gradlewFromParents clean check; then
        xdg-open build/reports/tests/index.html &> /dev/null
        return 1
    else
        notify-send 'BUILD WAS SUCCESSFUL!'
    fi
}

##
# Gets latest grails app from GRAILS APPLICATION FORGE and opens `build.gradle` and `gradle.properties`.
##
function getLatestGrailsAndOpen() {
    TMPDIR=/tmp/latestgrails
    rm -r $TMPDIR
    mkdir $TMPDIR
    curl https://start.grails.org/project.zip -d profile=rest-api -o $TMPDIR/project.zip
    unzip -qq $TMPDIR/project.zip -d $TMPDIR
    xdg-open $TMPDIR/project/build.gradle &> /dev/null
    xdg-open $TMPDIR/project/gradle.properties &> /dev/null
}

function runCleanTest() {
    if ! gradlewFromParents clean test integrationTest; then
        xdg-open build/reports/tests/index.html &> /dev/null
        return 1
    else
        notify-send 'TEST WAS SUCCESSFUL!'
    fi
}

##
# Opens the test report if it exists
##
function openTestReport() {
    UNIT_TEST_REPORT=build/reports/tests/test/index.html
    INTEGRATION_TEST_REPORT=build/reports/tests/index.html
    if [ -f "$INTEGRATION_TEST_REPORT" ]; then
        echo "Opening integration test report..."
        xdg-open $INTEGRATION_TEST_REPORT &> /dev/null
    elif [ -f "$UNIT_TEST_REPORT" ]; then
        echo "Opening unit test report..."
        xdg-open $UNIT_TEST_REPORT &> /dev/null
    else
        echo "No test report found"
    fi
}

##
# bashit gradle-plugin before this commit:  https://github.com/Bash-it/bash-it/commit/7ed12083f26ce95cb9018bf6688fdba2e96514dc
##
function gradlewFromParents() {
  local file="gradlew"
  local curr_path="${PWD}"
  local result="gradle"

  # Search recursively upwards for file.
  until [[ "${curr_path}" == "/" ]]; do
    if [[ -e "${curr_path}/${file}" ]]; then
      result="${curr_path}/${file}"
      break
    else
      curr_path=$(dirname "${curr_path}")
    fi
  done

  # Call gradle
  "${result}" $*
}


text:
========
Progress
========

Progress is a simple Django app that helps you keep track of your
progress in current tasks and rewards you with the green tick mark once
you're done. This app is for my own personal use and unfinished.

Prerequisites
=============

*  Python 3.3.x
*  Django 1.6
*  South 0.8.2 (probably)
*  Sphinx 1.1.3

I use PostgreSQL with the psycopg driver.

*  psycopg version 2.5.1

Quick start
===========

1. Add "progress" (and "django.contrib.humanize") to your INSTALLED_APPS
   setting like this::

      INSTALLED_APPS = (
          ...
          'django.contrib.humanize',
          'progress',
      )

2. Include the progress URLconf in your project urls.py like this::

      url(r'^progress/', include('progress.urls')),

3. Run `python manage.py syncdb` to create the progress models.

4. And you're good to go.


text:
package edu.berkeley.path.beats.control;

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

import edu.berkeley.path.beats.simulator.BeatsException;
import edu.berkeley.path.beats.simulator.Controller;
import edu.berkeley.path.beats.simulator.Sensor;

public class Controller_SIG_Template extends Controller {

	// controller specific variables defined here

	// assign values to your controller-specific variables
	@Override
	protected void populate(Object jaxbobject) {
		super.populate(jaxbobject);
	}

	// validate the controller parameters.
	// use BeatsErrorLog.addError() or BeatsErrorLog.addWarning() to register problems
	@Override
	protected void validate() {
		super.validate();
	}

	// called before simulation starts. Set controller state to initial values.
	@Override
	protected void reset() {
		super.reset();
	}

	// main controller update function, called every controller dt.
	// use this.sensors to get information, and this.actuators to apply the control command.
	@Override
	protected void update() throws BeatsException {
		super.update();

//		ArrayList<Sensor> x = getSensorByUsage("queue_2");
//		AccumulationSensor bla = (AccumulationSensor) x.get(0);
//		ArrayList< time,queue > = bla.getQueueHistory()
//				bla.resetQueueHistory();
//
//		.
//		.
//		.
//		.
//
//		ActuatorSignal act = (ActuatorSignal) = this.actuators.get(0);
//		act.setGreenTimes(List<Double> green_times);

	}

}


text:
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Helmet from "react-helmet"
import { config } from 'config'

export default class Index extends React.Component {
  render () {
    return (

        <Helmet
          title={config.siteTitle}
          meta={[
            {"name": "description", "content": "Dearwish blog"},
            {"name": "keywords", "content": "dearwish, blog, development, react, redux, architecture"},
          ]}
        />

          Hi there! This is my test blog

Let's get started

    )
  }
}


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace QuakeConsole.Samples.HelloPython
{
    public class HelloPythonGame : Game
    {
        private readonly GraphicsDeviceManager _graphics;
        // We need a reference to console to open and close it.
        private readonly ConsoleComponent _console;

        private KeyboardState _previousKeyState;
        private KeyboardState _currentKeyState;

        public HelloPythonGame()
        {
            Window.Title = "Hello Python in MonoGame :)";
            IsMouseVisible = true;
            Window.AllowUserResizing = true;

            _graphics = new GraphicsDeviceManager(this)
            {
                PreferredBackBufferWidth = 1280,
                PreferredBackBufferHeight = 720
            };

            // Create a sample cube component.
            var cube = new CubeComponent(this);
            Components.Add(cube);

            // Create a console component.
            _console = new ConsoleComponent(this);
            Components.Add(_console);

            // Create an interpreter - this will execute the commands typed into console.
            // In this case we are creating a python interpreter which allows python code to be executed.
            var interpreter = new PythonInterpreter();
            // Register the cube and the console itself as objects we can manipulate in-game.
            interpreter.AddVariable("cube", cube);
            interpreter.AddVariable("console", _console);
            // Finally, tell the console to use this interpreter.
            _console.Interpreter = interpreter;

            // Add component for on-screen helper instructions.
            Components.Add(new InstructionsComponent(this));
        }

        public Keys ToggleConsoleKey { get; } = Keys.OemTilde;
        public Color BackgroundColor { get; } = new Color(new Vector3(0.125f));

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            _previousKeyState = _currentKeyState;
            _currentKeyState = Keyboard.GetState();

            // If toggle console key is pressed, toggle the console to open or close.
            if (IsKeyPressed(ToggleConsoleKey))
                _console.ToggleOpenClose();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(BackgroundColor);
            base.Draw(gameTime);
        }

        private bool IsKeyPressed(Keys key) => _previousKeyState.IsKeyUp(key) && _currentKeyState.IsKeyDown(key);
    }
}


text:
<?php
declare(strict_types=1);

namespace Cake\Database\Type;

use Cake\I18n\Date;
use Cake\I18n\FrozenDate;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;

/**
 * Class DateType
 */
class DateType extends DateTimeType
{
    /**
     * Date format for DateTime object
     *
     * @var string|array
     */
    protected $_format = 'Y-m-d';

    /**
     * In this class we want Date objects to  have their time
     * set to the beginning of the day.
     *
     * @var bool
     */
    protected $setToDateStart = true;

    /**
     * Change the preferred class name to the FrozenDate implementation.
     *
     * @return $this
     */
    public function useImmutable()
    {
        $this->_setClassName(FrozenDate::class, DateTimeImmutable::class);

        return $this;
    }

    /**
     * Change the preferred class name to the mutable Date implementation.
     *
     * @return $this
     */
    public function useMutable()
    {
        $this->_setClassName(Date::class, DateTime::class);

        return $this;
    }

    /**
     * Convert request data into a datetime object.
     *
     * @param mixed $value Request data
     * @return \DateTimeInterface|null
     */
    public function marshal($value): ?DateTimeInterface
    {
        $date = parent::marshal($value);
        if ($date instanceof DateTime) {
            $date->setTime(0, 0, 0);
        }

        return $date;
    }

    /**
     * @inheritDoc
     */
    protected function _parseValue(string $value)
    {
        /** @var \Cake\I18n\Time $class */
        $class = $this->_className;

        return $class::parseDate($value, $this->_localeFormat);
    }
}


text:
package com.dci.intellij.dbn.code.common.intention;

import com.dci.intellij.dbn.common.Icons;
import com.dci.intellij.dbn.common.util.DocumentUtil;
import com.dci.intellij.dbn.execution.statement.StatementExecutionManager;
import com.dci.intellij.dbn.language.common.DBLanguageFile;
import com.dci.intellij.dbn.language.common.psi.ExecutablePsiElement;
import com.dci.intellij.dbn.language.common.psi.PsiUtil;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

import javax.swing.Icon;

public class ExecuteStatementIntentionAction extends GenericIntentionAction {
    @NotNull
    public String getText() {
        return "Execute statement";
    }

    @NotNull
    public String getFamilyName() {
        return "Statement execution intentions";
    }

    @Override
    public Icon getIcon(int flags) {
        return Icons.STMT_EXECUTION_RUN;
    }

    public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) {
        if (psiFile instanceof DBLanguageFile) {
            ExecutablePsiElement executable = PsiUtil.lookupExecutableAtCaret(psiFile);

            return  executable != null &&
                    executable.getExecutionProcessor() != null && executable.getExecutionProcessor().canExecute();
        }
        return false;
    }

    public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {
        ExecutablePsiElement executable = PsiUtil.lookupExecutableAtCaret(psiFile);
        StatementExecutionManager executionManager = StatementExecutionManager.getInstance(project);
        executionManager.fireExecution(executable.getExecutionProcessor());
        DocumentUtil.refreshEditorAnnotations(project);
    }

    public boolean startInWriteAction() {
        return false;
    }
}


text:
//
//  EMHTTPResponse.h
//  EMStock
//
//  Created by Ryan Wang on 4/13/15.
//  Copyright (c) 2015 flora. All rights reserved.
//

#import <Foundation/Foundation.h>

enum {MSHTTPResponseStatusOK = 0};

/**
 *  HTTP响应对象
    包含原始数据, 如果是标准格式, 会将status, updatetime, message, data,
    解析后的JSON数据在responseData中, 如果非标准格式, 则responseData为nil
 */

@interface MSHTTPResponse : NSObject {

}

@property (nonatomic, strong) id originData; // 原始数据
@property (nonatomic, strong) id responseData; // 标准JSON返回格式中的data数据, 非标准格式中为nil
@property (nonatomic, assign) NSInteger status; // 状态码, 0为正常
@property (nonatomic, strong) NSDate *updateTime; // 更新时间
@property (nonatomic, strong) NSString *message; // 消息, 一般为错误消息

@property (nonatomic, strong) NSError *error;

/**
 *  创建HTTP响应对象
 *
 *  @param object JSON数据, 格式可能是数组或字典
 *
 *  @return
 */
+ (instancetype)responseWithObject:(id)object;
+ (instancetype)responseWithError:(NSError *)error;

/**
 *  是否是标准的JSON返回格式, 包含status, updatetime, data
 *
 *  @param responseObject JSON数据
 *
 *  @return 是否
 */
+ (BOOL)isStandardResponse:(id)responseObject;

@end


text:
function val = sceGet(sceP,parm,varargin)
% val = sceGet(sceP,parm,varargin)
%
% Get function for Stiles-Crawford effect parameters
%
% Example:
%   sceGet(sceP,'xo')
%   sceGet(sceP,'wavelengths')
%   sceGet(sceP,'rho',550)
%
% See also sceCreate
%
% (c) Wavefront Toolbox Team, 2012

if ~exist('sceP','var') || isempty(sceP), error('sceP must be defined.'); end
if ~exist('parm','var') || isempty(parm), error('Parameter must be defined.'); end

% Default is empty when the parameter is not yet defined.
val = [];

parm = ieParamFormat(parm);

switch parm
    case 'xo'
        val = sceP.xo;
    case 'yo'
        val = sceP.yo;
    case {'wave','wavelengths'}
        val = sceP.wavelengths;
    case 'rho'
        if isempty(varargin)
            val = sceP.rho;
            return
        else
            wList = varargin{1};
            [l, loc] = ismember(wList,sceP.wavelengths); %#ok<ASGLU>
            val = sceP.rho(loc);
        end
    otherwise
        error('Unknown parameter %s\n',parm);
end

return


text:
using testing::InSequence;
using testing::IsNull;
using testing::StrictMock;

namespace v8 {
namespace platform {

namespace {

struct MockTask : public Task {
  virtual ~MockTask() { Die(); }
  MOCK_METHOD0(Run, void());
  MOCK_METHOD0(Die, void());
};

}  // namespace

TEST(WorkerThreadTest, Basic) {
  static const size_t kNumTasks = 10;

  TaskQueue queue;
  for (size_t i = 0; i < kNumTasks; ++i) {
    InSequence s;
    StrictMock<MockTask>* task = new StrictMock<MockTask>;
    EXPECT_CALL(*task, Run());
    EXPECT_CALL(*task, Die());
    queue.Append(task);
  }

  WorkerThread thread1(&queue);
  WorkerThread thread2(&queue);

  // TaskQueue DCHECKS that it's empty in its destructor.
  queue.Terminate();
}

TEST(WorkerThreadTest, PostSingleTask) {
  TaskQueue queue;
  WorkerThread thread1(&queue);
  WorkerThread thread2(&queue);

  InSequence s;
  StrictMock<MockTask>* task = new StrictMock<MockTask>;
  EXPECT_CALL(*task, Run());
  EXPECT_CALL(*task, Die());
  queue.Append(task);

  // The next call should not time out.
  queue.BlockUntilQueueEmptyForTesting();
  queue.Terminate();
}

}  // namespace platform
}  // namespace v8


text:
"""
Distributed trial test runner tests.
"""


text:
<?php

declare(strict_types=1);

namespace Gpupo\CommonSchema;

class TranslatorException extends \RuntimeException
{
}


text:
/**
 * Classes related to the gRPC (global) server interceptors and their discovery.
 */

package net.devh.boot.grpc.server.interceptor;


text:
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package org.mozc.android.inputmethod.japanese;

import org.mozc.android.inputmethod.japanese.CandidateView.ConversionCandidateWordView;
import org.mozc.android.inputmethod.japanese.resources.R;
import org.mozc.android.inputmethod.japanese.ui.ConversionCandidateLayouter;
import com.google.common.base.Preconditions;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ToggleButton;

/**
 * A container (ViewGroup) of candidate word view and input frame fold button.
 *
 * The fold button should be laid out based on candidate word view's internal state
 * (candidate layouter), which is determined at layout flow.
 * The initial implementation sets the button's layout parameter from onLayout method
 * but setting layout parameter on layout flow (e.g. in onLayout() and onSizeChanged())
 * causes unexpected behavior (e.g. infinite loop).
 * This class is introduced to solve this issue.
 *
 * This class is a simple ViewGroup. The layout algorithm is fixed (layout .xml file doesn't affect
 * anything) so {@link #onMeasure(int, int)} is omitted.
 * First, candidate word view fills all the view.
 * Second, input frame fold button is laid out based on ConversionCandidateLayouter's state
 * (which cannot be accessed from standard view layouters. This is the reason why this class is
 * introduced).
 * The layout flow descibed above doesn't depend on {@link android.view.ViewGroup.LayoutParams}
 * we can avoid from unexpected behavior.
 */
public class ConversionCandidateWordContainerView extends ViewGroup {

  private float foldingIconSize;

  public ConversionCandidateWordContainerView(
      Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public ConversionCandidateWordContainerView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public ConversionCandidateWordContainerView(Context context) {
    super(context);
  }

  void setCandidateTextDimension(float candidateTextSize) {
    Preconditions.checkArgument(candidateTextSize > 0);

    foldingIconSize = getResources().getDimension(R.dimen.candidate_fold_icon_width);
  }

  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    // Note: Don't use getMeasuredHeight/Width for this and children because #onMeasure
    //       is omitted so they return invalid value.
    ConversionCandidateWordView candidateWordView =
        ConversionCandidateWordView.class.cast(findViewById(R.id.candidate_word_view));
    candidateWordView.layout(left, top, right, bottom);
    ToggleButton inputFrameFoldButton =
        ToggleButton.class.cast(findViewById(R.id.input_frame_fold_button));
    if (inputFrameFoldButton.getVisibility() != VISIBLE) {
      return;
    }

    ConversionCandidateLayouter layouter = candidateWordView.getCandidateLayouter();
    float topMargin = (layouter.getRowHeight() - foldingIconSize) / 2;
    float rightMargin = (layouter.getChunkWidth() - foldingIconSize) / 2;
    inputFrameFoldButton.layout((int) (right - rightMargin - foldingIconSize),
                                (int) (top + topMargin),
                                (int) (right - rightMargin),
                                (int) (top + topMargin + foldingIconSize));
  }
}


text:
require 'helper'

describe T::Delete do

  before do
    rcfile = RCFile.instance
    rcfile.path = fixture_path + "/.trc"
    @delete = T::Delete.new
    @old_stderr = $stderr
    $stderr = StringIO.new
    @old_stdout = $stdout
    $stdout = StringIO.new
  end

  after do
    $stderr = @old_stderr
    $stdout = @old_stdout
  end

  describe "#block" do
    before do
      @delete.options = @delete.options.merge("profile" => fixture_path + "/.trc")
      stub_delete("/1/blocks/destroy.json").
        with(:query => {:screen_name => "sferik"}).
        to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end
    it "should request the correct resource" do
      @delete.block("sferik")
      a_delete("/1/blocks/destroy.json").
        with(:query => {:screen_name => "sferik"}).
        should have_been_made
    end
    it "should have the correct output" do
      @delete.block("sferik")
      $stdout.string.should =~ /^@testcli unblocked 1 user\.$/
    end
    context "--id" do
      before do
        @delete.options = @delete.options.merge("id" => true)
        stub_delete("/1/blocks/destroy.json").
          with(:query => {:user_id => "7505382"}).
          to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      end
      it "should request the correct resource" do
        @delete.block("7505382")
        a_delete("/1/blocks/destroy.json").
          with(:query => {:user_id => "7505382"}).
          should have_been_made
      end
    end
  end

  describe "#dm" do
    before do
      @delete.options = @delete.options.merge("profile" => fixture_path + "/.trc")
      stub_get("/1/direct_messages/show/1773478249.json").
        to_return(:body => fixture("direct_message.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      stub_delete("/1/direct_messages/destroy/1773478249.json").
        to_return(:body => fixture("direct_message.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end
    it "should request the correct resource" do
      $stdout.should_receive(:print).with("Are you sure you want to permanently delete the direct message to @pengwynn: \"Creating a fixture for the Twitter gem\"? [y/N] ")
      $stdin.should_receive(:gets).and_return("yes")
      @delete.dm("1773478249")
      a_get("/1/direct_messages/show/1773478249.json").
        should have_been_made
      a_delete("/1/direct_messages/destroy/1773478249.json").
        should have_been_made
    end
    context "yes" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete the direct message to @pengwynn: \"Creating a fixture for the Twitter gem\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("yes")
        @delete.dm("1773478249")
        $stdout.string.chomp.should == "@testcli deleted the direct message sent to @pengwynn: \"Creating a fixture for the Twitter gem\""
      end
    end
    context "no" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete the direct message to @pengwynn: \"Creating a fixture for the Twitter gem\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("no")
        @delete.dm("1773478249")
        $stdout.string.chomp.should be_empty
      end
    end
    context "--force" do
      before do
        @delete.options = @delete.options.merge("force" => true)
      end
      it "should request the correct resource" do
        @delete.dm("1773478249")
        a_delete("/1/direct_messages/destroy/1773478249.json").
          should have_been_made
      end
      it "should have the correct output" do
        @delete.dm("1773478249")
        $stdout.string.chomp.should == "@testcli deleted the direct message sent to @pengwynn: \"Creating a fixture for the Twitter gem\""
      end
    end
  end

  describe "#favorite" do
    before do
      @delete.options = @delete.options.merge("profile" => fixture_path + "/.trc")
      stub_get("/1/statuses/show/28439861609.json").
        with(:query => {:include_my_retweet => "false", :trim_user => "true"}).
        to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      stub_delete("/1/favorites/destroy/28439861609.json").
        to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end
    it "should request the correct resource" do
      $stdout.should_receive(:print).with("Are you sure you want to remove @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\" from your favorites? [y/N] ")
      $stdin.should_receive(:gets).and_return("yes")
      @delete.favorite("28439861609")
      a_get("/1/statuses/show/28439861609.json").
        with(:query => {:include_my_retweet => "false", :trim_user => "true"}).
        should have_been_made
      a_delete("/1/favorites/destroy/28439861609.json").
        should have_been_made
    end
    context "yes" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to remove @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\" from your favorites? [y/N] ")
        $stdin.should_receive(:gets).and_return("yes")
        @delete.favorite("28439861609")
        $stdout.string.should =~ /^@testcli unfavorited @sferik's status: "The problem with your code is that it's doing exactly what you told it to do\."$/
      end
    end
    context "no" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to remove @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\" from your favorites? [y/N] ")
        $stdin.should_receive(:gets).and_return("no")
        @delete.favorite("28439861609")
        $stdout.string.chomp.should be_empty
      end
    end
    context "--force" do
      before do
        @delete.options = @delete.options.merge("force" => true)
      end
      it "should request the correct resource" do
        @delete.favorite("28439861609")
        a_delete("/1/favorites/destroy/28439861609.json").
          should have_been_made
      end
      it "should have the correct output" do
        @delete.favorite("28439861609")
        $stdout.string.should =~ /^@testcli unfavorited @sferik's status: "The problem with your code is that it's doing exactly what you told it to do\."$/
      end
    end
  end

  describe "#list" do
    before do
      @delete.options = @delete.options.merge("profile" => fixture_path + "/.trc")
      stub_get("/1/account/verify_credentials.json").
        to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      stub_get("/1/lists/show.json").
        with(:query => {:owner_screen_name => "sferik", :slug => 'presidents'}).
        to_return(:body => fixture("list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      stub_delete("/1/lists/destroy.json").
        with(:query => {:owner_screen_name => "sferik", :list_id => "8863586"}).
        to_return(:body => fixture("list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end
    it "should request the correct resource" do
      $stdout.should_receive(:print).with("Are you sure you want to permanently delete the list \"presidents\"? [y/N] ")
      $stdin.should_receive(:gets).and_return("yes")
      @delete.list("presidents")
      a_get("/1/account/verify_credentials.json").
        should have_been_made
      a_delete("/1/lists/destroy.json").
        with(:query => {:owner_screen_name => "sferik", :list_id => "8863586"}).
        should have_been_made
    end
    context "yes" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete the list \"presidents\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("yes")
        @delete.list("presidents")
        $stdout.string.chomp.should == "@testcli deleted the list \"presidents\"."
      end
    end
    context "no" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete the list \"presidents\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("no")
        @delete.list("presidents")
        $stdout.string.chomp.should be_empty
      end
    end
    context "--force" do
      before do
        @delete.options = @delete.options.merge("force" => true)
      end
      it "should request the correct resource" do
        @delete.list("presidents")
        a_get("/1/account/verify_credentials.json").
          should have_been_made
        a_delete("/1/lists/destroy.json").
          with(:query => {:owner_screen_name => "sferik", :list_id => "8863586"}).
          should have_been_made
      end
      it "should have the correct output" do
        @delete.list("presidents")
        $stdout.string.chomp.should == "@testcli deleted the list \"presidents\"."
      end
    end
    context "--id" do
      before do
        @delete.options = @delete.options.merge("id" => true)
        stub_get("/1/lists/show.json").
          with(:query => {:owner_screen_name => "sferik", :list_id => "8863586"}).
          to_return(:body => fixture("list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      end
      it "should request the correct resource" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete the list \"presidents\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("yes")
        @delete.list("8863586")
        a_get("/1/lists/show.json").
          with(:query => {:owner_screen_name => "sferik", :list_id => "8863586"}).
          should have_been_made
        a_get("/1/account/verify_credentials.json").
          should have_been_made
        a_delete("/1/lists/destroy.json").
          with(:query => {:owner_screen_name => "sferik", :list_id => "8863586"}).
          should have_been_made
      end
    end
  end

  describe "#status" do
    before do
      @delete.options = @delete.options.merge("profile" => fixture_path + "/.trc")
      stub_get("/1/statuses/show/26755176471724032.json").
        with(:query => {:include_my_retweet => "false", :trim_user => "true"}).
        to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"})
      stub_delete("/1/statuses/destroy/26755176471724032.json").
        with(:query => {:trim_user => "true"}).
        to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end
    it "should request the correct resource" do
      $stdout.should_receive(:print).with("Are you sure you want to permanently delete @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\"? [y/N] ")
      $stdin.should_receive(:gets).and_return("yes")
      @delete.status("26755176471724032")
      a_get("/1/statuses/show/26755176471724032.json").
        with(:query => {:include_my_retweet => "false", :trim_user => "true"}).
        should have_been_made
      a_delete("/1/statuses/destroy/26755176471724032.json").
        with(:query => {:trim_user => "true"}).
        should have_been_made
    end
    context "yes" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("yes")
        @delete.status("26755176471724032")
        $stdout.string.chomp.should == "@testcli deleted the status: \"The problem with your code is that it's doing exactly what you told it to do.\""
      end
    end
    context "no" do
      it "should have the correct output" do
        $stdout.should_receive(:print).with("Are you sure you want to permanently delete @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\"? [y/N] ")
        $stdin.should_receive(:gets).and_return("no")
        @delete.status("26755176471724032")
        $stdout.string.chomp.should be_empty
      end
    end
    context "--force" do
      before do
        @delete.options = @delete.options.merge("force" => true)
      end
      it "should request the correct resource" do
        @delete.status("26755176471724032")
        a_delete("/1/statuses/destroy/26755176471724032.json").
          with(:query => {:trim_user => "true"}).
          should have_been_made
      end
      it "should have the correct output" do
        @delete.status("26755176471724032")
        $stdout.string.chomp.should == "@testcli deleted the status: \"The problem with your code is that it's doing exactly what you told it to do.\""
      end
    end
  end

end


text:
.cork-board {
    background-color: white;
}


text:
namespace chromeos {

namespace {

const char kInvalidResponseErrorName[] = "";  // No error name.
const char kInvalidResponseErrorMessage[] = "Invalid response.";

void OnBooleanMethodWithErrorCallback(
    const ShillClientHelper::BooleanCallback& callback,
    const ShillClientHelper::ErrorCallback& error_callback,
    dbus::Response* response) {
  if (!response) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  dbus::MessageReader reader(response);
  bool result;
  if (!reader.PopBool(&result)) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  callback.Run(result);
}

void OnStringMethodWithErrorCallback(
    const ShillClientHelper::StringCallback& callback,
    const ShillClientHelper::ErrorCallback& error_callback,
    dbus::Response* response) {
  if (!response) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  dbus::MessageReader reader(response);
  std::string result;
  if (!reader.PopString(&result)) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  callback.Run(result);
}

// Handles responses for methods without results.
void OnVoidMethod(const VoidDBusMethodCallback& callback,
                  dbus::Response* response) {
  if (!response) {
    callback.Run(DBUS_METHOD_CALL_FAILURE);
    return;
  }
  callback.Run(DBUS_METHOD_CALL_SUCCESS);
}

// Handles responses for methods with ObjectPath results.
void OnObjectPathMethod(
    const ObjectPathDBusMethodCallback& callback,
    dbus::Response* response) {
  if (!response) {
    callback.Run(DBUS_METHOD_CALL_FAILURE, dbus::ObjectPath());
    return;
  }
  dbus::MessageReader reader(response);
  dbus::ObjectPath result;
  if (!reader.PopObjectPath(&result)) {
    callback.Run(DBUS_METHOD_CALL_FAILURE, dbus::ObjectPath());
    return;
  }
  callback.Run(DBUS_METHOD_CALL_SUCCESS, result);
}

// Handles responses for methods with ObjectPath results and no status.
void OnObjectPathMethodWithoutStatus(
    const ObjectPathCallback& callback,
    const ShillClientHelper::ErrorCallback& error_callback,
    dbus::Response* response) {
  if (!response) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  dbus::MessageReader reader(response);
  dbus::ObjectPath result;
  if (!reader.PopObjectPath(&result)) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  callback.Run(result);
}

// Handles responses for methods with DictionaryValue results.
void OnDictionaryValueMethod(
    const ShillClientHelper::DictionaryValueCallback& callback,
    dbus::Response* response) {
  if (!response) {
    base::DictionaryValue result;
    callback.Run(DBUS_METHOD_CALL_FAILURE, result);
    return;
  }
  dbus::MessageReader reader(response);
  scoped_ptr<base::Value> value(dbus::PopDataAsValue(&reader));
  base::DictionaryValue* result = NULL;
  if (!value.get() || !value->GetAsDictionary(&result)) {
    base::DictionaryValue result;
    callback.Run(DBUS_METHOD_CALL_FAILURE, result);
    return;
  }
  callback.Run(DBUS_METHOD_CALL_SUCCESS, *result);
}

// Handles responses for methods without results.
void OnVoidMethodWithErrorCallback(
    const base::Closure& callback,
    dbus::Response* response) {
  callback.Run();
}

// Handles responses for methods with DictionaryValue results.
// Used by CallDictionaryValueMethodWithErrorCallback().
void OnDictionaryValueMethodWithErrorCallback(
    const ShillClientHelper::DictionaryValueCallbackWithoutStatus& callback,
    const ShillClientHelper::ErrorCallback& error_callback,
    dbus::Response* response) {
  dbus::MessageReader reader(response);
  scoped_ptr<base::Value> value(dbus::PopDataAsValue(&reader));
  base::DictionaryValue* result = NULL;
  if (!value.get() || !value->GetAsDictionary(&result)) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  callback.Run(*result);
}

// Handles responses for methods with ListValue results.
void OnListValueMethodWithErrorCallback(
    const ShillClientHelper::ListValueCallback& callback,
    const ShillClientHelper::ErrorCallback& error_callback,
    dbus::Response* response) {
  dbus::MessageReader reader(response);
  scoped_ptr<base::Value> value(dbus::PopDataAsValue(&reader));
  base::ListValue* result = NULL;
  if (!value.get() || !value->GetAsList(&result)) {
    error_callback.Run(kInvalidResponseErrorName, kInvalidResponseErrorMessage);
    return;
  }
  callback.Run(*result);
}

// Handles running appropriate error callbacks.
void OnError(const ShillClientHelper::ErrorCallback& error_callback,
             dbus::ErrorResponse* response) {
  std::string error_name;
  std::string error_message;
  if (response) {
    // Error message may contain the error message as string.
    dbus::MessageReader reader(response);
    error_name = response->GetErrorName();
    reader.PopString(&error_message);
  }
  error_callback.Run(error_name, error_message);
}

}  // namespace

ShillClientHelper::ShillClientHelper(dbus::Bus* bus,
                                     dbus::ObjectProxy* proxy)
    : blocking_method_caller_(new BlockingMethodCaller(bus, proxy)),
      proxy_(proxy),
      weak_ptr_factory_(this) {
}

ShillClientHelper::~ShillClientHelper() {
  LOG_IF(ERROR, observer_list_.size() != 0u)
      << "ShillClientHelper destroyed with active observers: "
      << observer_list_.size();
}

void ShillClientHelper::AddPropertyChangedObserver(
    ShillPropertyChangedObserver* observer) {
  // Excecute all the pending MonitorPropertyChanged calls.
  for (size_t i = 0; i < interfaces_to_be_monitored_.size(); ++i) {
    MonitorPropertyChangedInternal(interfaces_to_be_monitored_[i]);
  }
  interfaces_to_be_monitored_.clear();

  observer_list_.AddObserver(observer);
}

void ShillClientHelper::RemovePropertyChangedObserver(
    ShillPropertyChangedObserver* observer) {
  observer_list_.RemoveObserver(observer);
}

void ShillClientHelper::MonitorPropertyChanged(
    const std::string& interface_name) {
  if (observer_list_.size() > 0) {
    // Effectively monitor the PropertyChanged now.
    MonitorPropertyChangedInternal(interface_name);
  } else {
    // Delay the ConnectToSignal until an observer is added.
    interfaces_to_be_monitored_.push_back(interface_name);
  }
}

void ShillClientHelper::MonitorPropertyChangedInternal(
    const std::string& interface_name) {
  // We are not using dbus::PropertySet to monitor PropertyChanged signal
  // because the interface is not "org.freedesktop.DBus.Properties".
  proxy_->ConnectToSignal(interface_name,
                          flimflam::kMonitorPropertyChanged,
                          base::Bind(&ShillClientHelper::OnPropertyChanged,
                                     weak_ptr_factory_.GetWeakPtr()),
                          base::Bind(&ShillClientHelper::OnSignalConnected,
                                     weak_ptr_factory_.GetWeakPtr()));
}

void ShillClientHelper::CallVoidMethod(
    dbus::MethodCall* method_call,
    const VoidDBusMethodCallback& callback) {
  proxy_->CallMethod(method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                     base::Bind(&OnVoidMethod,
                                callback));
}

void ShillClientHelper::CallObjectPathMethod(
    dbus::MethodCall* method_call,
    const ObjectPathDBusMethodCallback& callback) {
  proxy_->CallMethod(method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                     base::Bind(&OnObjectPathMethod,
                                callback));
}

void ShillClientHelper::CallObjectPathMethodWithErrorCallback(
    dbus::MethodCall* method_call,
    const ObjectPathCallback& callback,
    const ErrorCallback& error_callback) {
  proxy_->CallMethodWithErrorCallback(
      method_call,
      dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&OnObjectPathMethodWithoutStatus,
                 callback,
                 error_callback),
      base::Bind(&OnError,
                 error_callback));
}

void ShillClientHelper::CallDictionaryValueMethod(
    dbus::MethodCall* method_call,
    const DictionaryValueCallback& callback) {
  proxy_->CallMethod(method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                     base::Bind(&OnDictionaryValueMethod,
                                callback));
}

void ShillClientHelper::CallVoidMethodWithErrorCallback(
    dbus::MethodCall* method_call,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  proxy_->CallMethodWithErrorCallback(
      method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&OnVoidMethodWithErrorCallback,
                 callback),
      base::Bind(&OnError,
                 error_callback));
}

void ShillClientHelper::CallBooleanMethodWithErrorCallback(
    dbus::MethodCall* method_call,
    const BooleanCallback& callback,
    const ErrorCallback& error_callback) {
  proxy_->CallMethodWithErrorCallback(
      method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&OnBooleanMethodWithErrorCallback,
                 callback,
                 error_callback),
      base::Bind(&OnError,
                 error_callback));
}

void ShillClientHelper::CallStringMethodWithErrorCallback(
    dbus::MethodCall* method_call,
    const StringCallback& callback,
    const ErrorCallback& error_callback) {
  proxy_->CallMethodWithErrorCallback(
      method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&OnStringMethodWithErrorCallback,
                 callback,
                 error_callback),
      base::Bind(&OnError,
                 error_callback));
}

void ShillClientHelper::CallDictionaryValueMethodWithErrorCallback(
    dbus::MethodCall* method_call,
    const DictionaryValueCallbackWithoutStatus& callback,
    const ErrorCallback& error_callback) {
  proxy_->CallMethodWithErrorCallback(
      method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(
          &OnDictionaryValueMethodWithErrorCallback,
          callback,
          error_callback),
      base::Bind(&OnError,
                 error_callback));
}

void ShillClientHelper::CallListValueMethodWithErrorCallback(
    dbus::MethodCall* method_call,
    const ListValueCallback& callback,
    const ErrorCallback& error_callback) {
  proxy_->CallMethodWithErrorCallback(
      method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(
          &OnListValueMethodWithErrorCallback,
          callback,
          error_callback),
      base::Bind(&OnError,
                 error_callback));
}

bool ShillClientHelper::CallVoidMethodAndBlock(
    dbus::MethodCall* method_call) {
  scoped_ptr<dbus::Response> response(
      blocking_method_caller_->CallMethodAndBlock(method_call));
  if (!response.get())
    return false;
  return true;
}

base::DictionaryValue* ShillClientHelper::CallDictionaryValueMethodAndBlock(
    dbus::MethodCall* method_call) {
  scoped_ptr<dbus::Response> response(
      blocking_method_caller_->CallMethodAndBlock(method_call));
  if (!response.get())
    return NULL;

  dbus::MessageReader reader(response.get());
  base::Value* value = dbus::PopDataAsValue(&reader);
  base::DictionaryValue* result = NULL;
  if (!value || !value->GetAsDictionary(&result)) {
    delete value;
    return NULL;
  }
  return result;
}

// static
void ShillClientHelper::AppendValueDataAsVariant(dbus::MessageWriter* writer,
                                                 const base::Value& value) {
  // Support basic types and string-to-string dictionary.
  switch (value.GetType()) {
    case base::Value::TYPE_DICTIONARY: {
      const base::DictionaryValue* dictionary = NULL;
      value.GetAsDictionary(&dictionary);
      dbus::MessageWriter variant_writer(NULL);
      writer->OpenVariant("a{ss}", &variant_writer);
      dbus::MessageWriter array_writer(NULL);
      variant_writer.OpenArray("{ss}", &array_writer);
      for (base::DictionaryValue::Iterator it(*dictionary);
           it.HasNext();
           it.Advance()) {
        dbus::MessageWriter entry_writer(NULL);
        array_writer.OpenDictEntry(&entry_writer);
        entry_writer.AppendString(it.key());
        const base::Value& value = it.value();
        std::string value_string;
        DLOG_IF(ERROR, value.GetType() != base::Value::TYPE_STRING)
            << "Unexpected type " << value.GetType();
        value.GetAsString(&value_string);
        entry_writer.AppendString(value_string);
        array_writer.CloseContainer(&entry_writer);
      }
      variant_writer.CloseContainer(&array_writer);
      writer->CloseContainer(&variant_writer);
      break;
    }
    case base::Value::TYPE_BOOLEAN:
    case base::Value::TYPE_INTEGER:
    case base::Value::TYPE_DOUBLE:
    case base::Value::TYPE_STRING:
      dbus::AppendBasicTypeValueDataAsVariant(writer, value);
      break;
    default:
      DLOG(ERROR) << "Unexpected type " << value.GetType();
  }

}

void ShillClientHelper::OnSignalConnected(const std::string& interface,
                                          const std::string& signal,
                                          bool success) {
  LOG_IF(ERROR, !success) << "Connect to " << interface << " " << signal
                          << " failed.";
}

void ShillClientHelper::OnPropertyChanged(dbus::Signal* signal) {
  if (!observer_list_.might_have_observers())
    return;

  dbus::MessageReader reader(signal);
  std::string name;
  if (!reader.PopString(&name))
    return;
  scoped_ptr<base::Value> value(dbus::PopDataAsValue(&reader));
  if (!value.get())
    return;

  FOR_EACH_OBSERVER(ShillPropertyChangedObserver, observer_list_,
                    OnPropertyChanged(name, *value));
}

}  // namespace chromeos


text:
<?php

// snippet-start:[ec2.php.modify_vpc_endpoint.complete]
// snippet-start:[ec2.php.modify_vpc_endpoint.import]

require 'vendor/autoload.php';

use Aws\Ec2\Ec2Client;
// snippet-end:[ec2.php.modify_vpc_endpoint.import]
/**
 * Modify VPC Endpoint
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

// snippet-start:[ec2.php.modify_vpc_endpoint.main]
$ec2Client = new Aws\Ec2\Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);

$result = $ec2Client->modifyVpcEndpoint(array(
    // VpcEndpointId is required
    'VpcEndpointId' => 'string',
    'ResetPolicy' => true,
    'PolicyDocument' => 'string'
));

var_dump($result);

// snippet-end:[ec2.php.modify_vpc_endpoint.main]
// snippet-end:[ec2.php.modify_vpc_endpoint.complete]
// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[ModifyVpcEndpoint.php demonstrates how to modify attributes of a specified VPC endpoint.]
// snippet-keyword:[PHP]
// snippet-sourcesyntax:[php]
// snippet-keyword:[AWS SDK for PHP v3]
// snippet-keyword:[Code Sample]
// snippet-keyword:[Amazon EC2]
// snippet-service:[ec2]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[2018-09-20]
// snippet-sourceauthor:[jschwarzwalder (AWS)]