text:
/* Flash memory module for stm32f3 and stm32f4 */

#include <stdbool.h>
#include "common.h"
#include "flash.h"
#include "flash-f.h"
#include "flash-regs.h"
#include "hooks.h"
#include "registers.h"
#include "system.h"
#include "panic.h"

/*****************************************************************************/
/* Physical layer APIs */
#ifdef CHIP_VARIANT_STM32F76X
/*
 * 8 "erase" sectors : 32KB/32KB/32KB/32KB/128KB/256KB/256KB/256KB
 */
struct ec_flash_bank const flash_bank_array[] = {
	{
		.count = 4,
		.size_exp = __fls(SIZE_32KB),
		.write_size_exp = __fls(CONFIG_FLASH_WRITE_SIZE),
		.erase_size_exp = __fls(SIZE_32KB),
		.protect_size_exp = __fls(SIZE_32KB),
	},
	{
		.count = 1,
		.size_exp = __fls(SIZE_128KB),
		.write_size_exp = __fls(CONFIG_FLASH_WRITE_SIZE),
		.erase_size_exp = __fls(SIZE_128KB),
		.protect_size_exp = __fls(SIZE_128KB),
	},
	{
		.count = (CONFIG_FLASH_SIZE_BYTES - SIZE_256KB) / SIZE_256KB,
		.write_size_exp = __fls(CONFIG_FLASH_WRITE_SIZE),
		.size_exp = __fls(SIZE_256KB),
		.erase_size_exp = __fls(SIZE_256KB),
		.protect_size_exp = __fls(SIZE_256KB),
	},
};
#elif defined(CHIP_FAMILY_STM32F4)
/*
 * STM32F412xE has 512 KB flash
 *   8 "erase" sectors (512 KB) : 16KB/16KB/16KB/16KB/64KB/128KB/128KB/128KB
 *
 * STM32F412xG has 1 MB flash
 *   12 "erase" sectors (1024 KB) :
 *           16KB/16KB/16KB/16KB/64KB/128KB/128KB/128KB/128KB/128KB/128KB/128KB
 *
 * https://www.st.com/resource/en/datasheet/stm32f412cg.pdf
 */
struct ec_flash_bank const flash_bank_array[] = {
	{
		.count = 4,
		.size_exp = __fls(SIZE_16KB),
		.write_size_exp = __fls(CONFIG_FLASH_WRITE_SIZE),
		.erase_size_exp = __fls(SIZE_16KB),
		.protect_size_exp = __fls(SIZE_16KB),
	},
	{
		.count = 1,
		.size_exp = __fls(SIZE_64KB),
		.write_size_exp = __fls(CONFIG_FLASH_WRITE_SIZE),
		.erase_size_exp = __fls(SIZE_64KB),
		.protect_size_exp = __fls(SIZE_64KB),
	},
	{
		.count = (CONFIG_FLASH_SIZE_BYTES - SIZE_128KB) / SIZE_128KB,
		.write_size_exp = __fls(CONFIG_FLASH_WRITE_SIZE),
		.size_exp = __fls(SIZE_128KB),
		.erase_size_exp = __fls(SIZE_128KB),
		.protect_size_exp = __fls(SIZE_128KB),
	},
};
#endif

/* Flag indicating whether we have locked down entire flash */
static int entire_flash_locked;

#define FLASH_SYSJUMP_TAG 0x5750 /* "WP" - Write Protect */
#define FLASH_HOOK_VERSION 1

/* The previous write protect state before sys jump */
struct flash_wp_state {
	int entire_flash_locked;
};

/*****************************************************************************/
/* Physical layer APIs */

int crec_flash_physical_get_protect(int block)
{
	return (entire_flash_locked ||
#if defined(CHIP_FAMILY_STM32F3)
		!(STM32_FLASH_WRPR & BIT(block))
#elif defined(CHIP_FAMILY_STM32F4)
		!(STM32_OPTB_WP & STM32_OPTB_nWRP(block))
#endif
	);
}

uint32_t crec_flash_physical_get_protect_flags(void)
{
	uint32_t flags = 0;

	/* Read all-protected state from our shadow copy */
	if (entire_flash_locked)
		flags |= EC_FLASH_PROTECT_ALL_NOW;

#if defined(CONFIG_FLASH_READOUT_PROTECTION_AS_PSTATE)
	if (is_flash_rdp_enabled())
		flags |= EC_FLASH_PROTECT_RO_AT_BOOT;
#endif

	return flags;
}

int crec_flash_physical_protect_now(int all)
{
	if (all) {
		disable_flash_control_register();
		entire_flash_locked = 1;

		return EC_SUCCESS;
	}

	disable_flash_option_bytes();

	return EC_SUCCESS;
}

uint32_t crec_flash_physical_get_valid_flags(void)
{
	return EC_FLASH_PROTECT_RO_AT_BOOT | EC_FLASH_PROTECT_RO_NOW |
	       EC_FLASH_PROTECT_ALL_NOW;
}

uint32_t crec_flash_physical_get_writable_flags(uint32_t cur_flags)
{
	uint32_t ret = 0;

	/* If RO protection isn't enabled, its at-boot state can be changed. */
	if (!(cur_flags & EC_FLASH_PROTECT_RO_NOW))
		ret |= EC_FLASH_PROTECT_RO_AT_BOOT;

	/*
	 * If entire flash isn't protected at this boot, it can be enabled if
	 * the WP GPIO is asserted.
	 */
	if (!(cur_flags & EC_FLASH_PROTECT_ALL_NOW) &&
	    (cur_flags & EC_FLASH_PROTECT_GPIO_ASSERTED))
		ret |= EC_FLASH_PROTECT_ALL_NOW;

	return ret;
}

int crec_flash_physical_restore_state(void)
{
	uint32_t reset_flags = system_get_reset_flags();
	int version, size;
	const struct flash_wp_state *prev;

	/*
	 * If we have already jumped between images, an earlier image could
	 * have applied write protection. Nothing additional needs to be done.
	 */
	if (reset_flags & EC_RESET_FLAG_SYSJUMP) {
		prev = (const struct flash_wp_state *)system_get_jump_tag(
			FLASH_SYSJUMP_TAG, &version, &size);
		if (prev && version == FLASH_HOOK_VERSION &&
		    size == sizeof(*prev))
			entire_flash_locked = prev->entire_flash_locked;
		return 1;
	}

	return 0;
}

/*****************************************************************************/
/* Hooks */

static void flash_preserve_state(void)
{
	struct flash_wp_state state;

	state.entire_flash_locked = entire_flash_locked;

	system_add_jump_tag(FLASH_SYSJUMP_TAG, FLASH_HOOK_VERSION,
			    sizeof(state), &state);
}
DECLARE_HOOK(HOOK_SYSJUMP, flash_preserve_state, HOOK_PRIO_DEFAULT);


text:
package cn.cloudself.controller;

import cn.cloudself.bean.EntitysWithVersion;
import cn.cloudself.model.*;
import cn.cloudself.service.IAppService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author HerbLuo
 * @version 1.0.0.d
 */
@Api(description = "应用级的Api,如App版本信息")
@RestController
@RequestMapping("/app/native")
public class ApplicationNativeController {

    private final IAppService appService;

    @Autowired
    public ApplicationNativeController(IAppService appService) {
        this.appService = appService;
    }

    @ApiOperation(value = "获取app信息", notes = "获取app信息,包括版本信息,组件版本信息")
    @RequestMapping(value = "/info/", method = RequestMethod.GET)
    public AppEntity version() throws Exception {
        return appService.getAppInfo();
    }

    @ApiOperation(value = "获取app的十个入口")
    @RequestMapping(value = "/entrance/", method = RequestMethod.GET)
    public EntitysWithVersion<AppEntranceEntity> getEntrance() throws Exception {
        return appService.getEntraceBar();
    }

    @ApiOperation(value = "获取热门信息")
    @RequestMapping(value = "/hotbar/", method = RequestMethod.GET)
    public Iterable<AppHotbarEntity> getHotbar() throws Exception {
        return appService.getHotbar();
    }

    @ApiOperation(value = "获取抢购信息")
    @RequestMapping(value = "/rushbuy/page/{page}/apagesize/{aPageSize}/", method = RequestMethod.GET)
    public AppBlockEntity<?, AppRushbuyContentEntity> getRushbuy(
            @ApiParam(value = "页码,从0开始计",
                    defaultValue = "0", allowableValues = "range[0, infinity]", required = true)
            @PathVariable("page") Integer page,

            @ApiParam(value = "单页大小;-1代表获取全部数据,此时page失效\"",
                    defaultValue = "2", allowableValues = "range[-1, infinity]", required = true)
            @PathVariable("aPageSize") Integer aPageSize
    ) throws Exception {

        return appService.getRushbuy(page, aPageSize);
    }

    @ApiOperation(value = "获取极有家")
    @RequestMapping(value = "/jiyoujia/page/{page}/apagesize/{aPageSize}/", method = RequestMethod.GET)
    public AppBlockEntity<AppJiyoujiaHeadEntity, AppJiyoujiaContentEntity> getJiyoujia(
            @ApiParam(value = "页码,从0开始计",
                    defaultValue = "0", allowableValues = "range[0, infinity]", required = true)
            @PathVariable("page") Integer page,

            @ApiParam(value = "单页大小;-1代表获取全部数据,此时page失效",
                    defaultValue = "2", allowableValues = "range[-1, infinity]", required = true)
            @PathVariable("aPageSize") Integer aPageSize) throws Exception {

        return appService.getJiyoujia(page, aPageSize);
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace app_list {
class AppListViewDelegate;
class AppListModel;
class AppListModelObserverBridge;
}

@class AppListPagerView;
@class AppsGridController;
@class SigninViewController;

// Controller for the top-level view of the app list UI. It creates and hosts an
// AppsGridController (displaying an AppListModel), pager control to navigate
// between pages in the grid, and search entry box with a pop up menu.
APP_LIST_EXPORT
@interface AppListViewController : NSViewController<AppsPaginationModelObserver,
                                                    AppsSearchBoxDelegate,
                                                    AppsSearchResultsDelegate> {
 @private
  base::scoped_nsobject<AppsGridController> appsGridController_;
  base::scoped_nsobject<AppListPagerView> pagerControl_;
  base::scoped_nsobject<AppsSearchBoxController> appsSearchBoxController_;
  base::scoped_nsobject<AppsSearchResultsController>
      appsSearchResultsController_;
  base::scoped_nsobject<SigninViewController> signinViewController_;

  // Subview for drawing the background. Hidden when the signin view is visible.
  base::scoped_nsobject<NSView> backgroundView_;

  // Subview of |backgroundView_| that slides out when search results are shown.
  base::scoped_nsobject<NSView> contentsView_;

  // Progress indicator that is visible while the delegate is NULL.
  base::scoped_nsobject<NSProgressIndicator> loadingIndicator_;

  scoped_ptr<app_list::AppListViewDelegate> delegate_;
  scoped_ptr<app_list::AppListModelObserverBridge>
      app_list_model_observer_bridge_;
  BOOL showingSearchResults_;
}

@property(readonly, nonatomic) AppsSearchBoxController*
    searchBoxController;

- (app_list::AppListViewDelegate*)delegate;
- (void)setDelegate:(scoped_ptr<app_list::AppListViewDelegate>)newDelegate;
- (void)onProfilesChanged;

@end

@interface AppListViewController (TestingAPI)

@property(nonatomic, readonly) BOOL showingSearchResults;

- (AppsGridController*)appsGridController;
- (NSSegmentedControl*)pagerControl;
- (NSView*)backgroundView;

@end

#endif  // UI_APP_LIST_COCOA_APP_LIST_VIEW_CONTROLLER_H_


text:
package cmdclient

import (
	gomock "github.com/golang/mock/gomock"

	v1 "kubevirt.io/client-go/api/v1"
	v10 "kubevirt.io/kubevirt/pkg/handler-launcher-com/cmd/v1"
	api "kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/api"
	stats "kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/stats"
)

// Mock of LauncherClient interface
type MockLauncherClient struct {
	ctrl     *gomock.Controller
	recorder *_MockLauncherClientRecorder
}

// Recorder for MockLauncherClient (not exported)
type _MockLauncherClientRecorder struct {
	mock *MockLauncherClient
}

func NewMockLauncherClient(ctrl *gomock.Controller) *MockLauncherClient {
	mock := &MockLauncherClient{ctrl: ctrl}
	mock.recorder = &_MockLauncherClientRecorder{mock}
	return mock
}

func (_m *MockLauncherClient) EXPECT() *_MockLauncherClientRecorder {
	return _m.recorder
}

func (_m *MockLauncherClient) SyncVirtualMachine(vmi *v1.VirtualMachineInstance, options *v10.VirtualMachineOptions) error {
	ret := _m.ctrl.Call(_m, "SyncVirtualMachine", vmi, options)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) SyncVirtualMachine(arg0, arg1 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "SyncVirtualMachine", arg0, arg1)
}

func (_m *MockLauncherClient) PauseVirtualMachine(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "PauseVirtualMachine", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) PauseVirtualMachine(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "PauseVirtualMachine", arg0)
}

func (_m *MockLauncherClient) UnpauseVirtualMachine(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "UnpauseVirtualMachine", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) UnpauseVirtualMachine(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "UnpauseVirtualMachine", arg0)
}

func (_m *MockLauncherClient) SyncMigrationTarget(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "SyncMigrationTarget", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) SyncMigrationTarget(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "SyncMigrationTarget", arg0)
}

func (_m *MockLauncherClient) SignalTargetPodCleanup(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "SignalTargetPodCleanup", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) SignalTargetPodCleanup(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "SignalTargetPodCleanup", arg0)
}

func (_m *MockLauncherClient) ShutdownVirtualMachine(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "ShutdownVirtualMachine", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) ShutdownVirtualMachine(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "ShutdownVirtualMachine", arg0)
}

func (_m *MockLauncherClient) KillVirtualMachine(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "KillVirtualMachine", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) KillVirtualMachine(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "KillVirtualMachine", arg0)
}

func (_m *MockLauncherClient) MigrateVirtualMachine(vmi *v1.VirtualMachineInstance, options *MigrationOptions) error {
	ret := _m.ctrl.Call(_m, "MigrateVirtualMachine", vmi, options)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) MigrateVirtualMachine(arg0, arg1 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "MigrateVirtualMachine", arg0, arg1)
}

func (_m *MockLauncherClient) CancelVirtualMachineMigration(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "CancelVirtualMachineMigration", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) CancelVirtualMachineMigration(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "CancelVirtualMachineMigration", arg0)
}

func (_m *MockLauncherClient) FinalizeVirtualMachineMigration(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "FinalizeVirtualMachineMigration", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) FinalizeVirtualMachineMigration(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "FinalizeVirtualMachineMigration", arg0)
}

func (_m *MockLauncherClient) DeleteDomain(vmi *v1.VirtualMachineInstance) error {
	ret := _m.ctrl.Call(_m, "DeleteDomain", vmi)
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) DeleteDomain(arg0 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "DeleteDomain", arg0)
}

func (_m *MockLauncherClient) GetDomain() (*api.Domain, bool, error) {
	ret := _m.ctrl.Call(_m, "GetDomain")
	ret0, _ := ret[0].(*api.Domain)
	ret1, _ := ret[1].(bool)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}

func (_mr *_MockLauncherClientRecorder) GetDomain() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "GetDomain")
}

func (_m *MockLauncherClient) GetDomainStats() (*stats.DomainStats, bool, error) {
	ret := _m.ctrl.Call(_m, "GetDomainStats")
	ret0, _ := ret[0].(*stats.DomainStats)
	ret1, _ := ret[1].(bool)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}

func (_mr *_MockLauncherClientRecorder) GetDomainStats() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "GetDomainStats")
}

func (_m *MockLauncherClient) GetGuestInfo() (*v1.VirtualMachineInstanceGuestAgentInfo, error) {
	ret := _m.ctrl.Call(_m, "GetGuestInfo")
	ret0, _ := ret[0].(*v1.VirtualMachineInstanceGuestAgentInfo)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

func (_mr *_MockLauncherClientRecorder) GetGuestInfo() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "GetGuestInfo")
}

func (_m *MockLauncherClient) GetUsers() (v1.VirtualMachineInstanceGuestOSUserList, error) {
	ret := _m.ctrl.Call(_m, "GetUsers")
	ret0, _ := ret[0].(v1.VirtualMachineInstanceGuestOSUserList)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

func (_mr *_MockLauncherClientRecorder) GetUsers() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "GetUsers")
}

func (_m *MockLauncherClient) GetFilesystems() (v1.VirtualMachineInstanceFileSystemList, error) {
	ret := _m.ctrl.Call(_m, "GetFilesystems")
	ret0, _ := ret[0].(v1.VirtualMachineInstanceFileSystemList)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

func (_mr *_MockLauncherClientRecorder) GetFilesystems() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "GetFilesystems")
}

func (_m *MockLauncherClient) Exec(_param0 string, _param1 string, _param2 []string, _param3 int32) (int, string, error) {
	ret := _m.ctrl.Call(_m, "Exec", _param0, _param1, _param2, _param3)
	ret0, _ := ret[0].(int)
	ret1, _ := ret[1].(string)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}

func (_mr *_MockLauncherClientRecorder) Exec(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Exec", arg0, arg1, arg2, arg3)
}

func (_m *MockLauncherClient) Ping() error {
	ret := _m.ctrl.Call(_m, "Ping")
	ret0, _ := ret[0].(error)
	return ret0
}

func (_mr *_MockLauncherClientRecorder) Ping() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Ping")
}

func (_m *MockLauncherClient) Close() {
	_m.ctrl.Call(_m, "Close")
}

func (_mr *_MockLauncherClientRecorder) Close() *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Close")
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.llama.android.licenseview.example" >

    <application
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:allowBackup="true">
        <activity
            android:name="com.llama.android.licenseview.example.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>


text:
package org.artificer.common;

import org.apache.commons.lang.StringUtils;
import org.artificer.common.i18n.Messages;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.Artifact;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactEnum;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.DocumentArtifactType;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.ExtendedArtifactType;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.ExtendedDocument;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * A class representing all of the Artifact Types defined by S-RAMP.
 *
 * @author eric.wittmann@redhat.com
 */
public class ArtifactType implements Serializable {

    /**
     * Returns true if the given artifact type is valid.  It must be alphanumeric only.
     * @param artifactType the artifact type
     * @return true if valid
     */
    public static final boolean isValid(String artifactType) {
        for (int i = 0; i < artifactType.length(); i++) {
            char c = artifactType.charAt(i);
            if (!(Character.isLetter(c) || Character.isDigit(c))) {
                return false;
            }
        }
        return true;
    }

    public static final ArtifactType Document() {
        return new ArtifactType(ArtifactTypeEnum.Document, "application/octet-stream");
    }
    public static final ArtifactType Document(String mimeType) {
        return new ArtifactType(ArtifactTypeEnum.Document, mimeType);
    }
    public static final ArtifactType XmlDocument() {
        return new ArtifactType(ArtifactTypeEnum.XmlDocument, "application/xml");
    }
    public static final ArtifactType XsdDocument() {
        return new ArtifactType(ArtifactTypeEnum.XsdDocument, "application/xml");
    }
    public static final ArtifactType WsdlDocument() {
        return new ArtifactType(ArtifactTypeEnum.WsdlDocument, "application/xml");
    }
    public static final ArtifactType PolicyDocument() {
        return new ArtifactType(ArtifactTypeEnum.PolicyDocument, "application/xml");
    }
    public static final ArtifactType ExtendedArtifactType(String extendedType) {
        return ExtendedArtifactType(extendedType, false);
    }
    public static final ArtifactType ExtendedArtifactType(String extendedType, boolean derived) {
        ArtifactType at = new ArtifactType(ArtifactTypeEnum.ExtendedArtifactType, null);
        at.setExtendedType(extendedType);
        at.setExtendedDerivedType(derived);
        return at;
    }
    public static final ArtifactType ExtendedDocument(String extendedType) {
        ArtifactType at = new ArtifactType(ArtifactTypeEnum.ExtendedDocument, null);
        at.setExtendedType(extendedType);
        return at;
    }

    private ArtifactTypeEnum artifactType;
    private String mimeType;
    /** for a Extended Type, the type should be stored here */
    private String extendedType;
    private boolean extendedDerivedType;

    /**
     * Constructor.
     * @param artifactType
     * @param mimeType
     */
    private ArtifactType(ArtifactTypeEnum artifactType, String mimeType) {
        setArtifactType(artifactType);
        // TODO: This needs re-thought.  The mimeType should only be non-null when artifactType.isDocument().  But
        // if you let null happen, you'll eventually get NPEs within RESTEasy.
        if (mimeType == null) {
            if (artifactType == ArtifactTypeEnum.Document || artifactType == ArtifactTypeEnum.ExtendedDocument) {
                mimeType = "application/octet-stream";
            } else {
                mimeType = "application/xml";
            }
        }
        setMimeType(mimeType);
    }

    /**
     * Called to unwrap the S-RAMP artifact from its wrapper.
     * @param artifactWrapper the S-RAMP artifact wrapper
     * @return the specific artifact based on type
     */
    public BaseArtifactType unwrap(Artifact artifactWrapper) {
        try {
            Method method = Artifact.class.getMethod("get" + getArtifactType().getType());
            BaseArtifactType artifact = (BaseArtifactType) method.invoke(artifactWrapper);
            artifact.setArtifactType(this.getArtifactType().getApiType());
            return artifact;
        } catch (Exception e) {
            throw new RuntimeException(Messages.i18n.format("ARTIFACT_UNWRAP_ERROR", getArtifactType().getType()), e);
        }
    }

    /**
     * Figures out the artifact type (enum) from the given S-RAMP artifact type string.
     * @param artifactType
     */
    public static ArtifactType valueOf(String artifactType) {
        return valueOf(artifactType, false);
    }

    public static ArtifactType valueOf(String artifactType, boolean isDocument) {
        if (StringUtils.isEmpty(artifactType)) {
            return null;
        } else if (ArtifactTypeEnum.hasEnum(artifactType)) {
            ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.valueOf(artifactType);
            return new ArtifactType(artifactTypeEnum, null);
        } else {
            ArtifactTypeEnum artifactTypeEnum;
            if (isDocument) {
                artifactTypeEnum = ArtifactTypeEnum.ExtendedDocument;
            } else {
                artifactTypeEnum = ArtifactTypeEnum.ExtendedArtifactType;
            }
            ArtifactType rval = new ArtifactType(artifactTypeEnum, null);
            rval.setExtendedType(artifactType);
            rval.setMimeType("application/octet-stream");
            return rval;
        }
    }

    /**
     * Determines the ArtifactType from the model and type. If the model is "ext"
     * (extended) then the artifactType can be either ExtendedArtifactType or
     * ExtendedDocument. All extended artifacts that have contend inherit from
     * ExtendedDocument.
     *
     * @param model - the model, for example core, xsd, wsdl, ext, etc.
     * @param type - the type, for example XmlDocument, WsdlDocument
     * @param isDocument - this flag is taken into account ONLY when the model is 'ext',
     * in this case the 'type' can be ExtendedDocument,
     * ExtendedArtifactType, or a user defined value (for example 'SwitchYardApplication').
     * The flag 'isDocument' is required only if the type is user defined so it can
     * distinguish between an artifact with (true) or without (false) content.
     * If this is not known at the time of calling a value of null can be given which will
     * default the ArtifactType of ExtendedArtifactType.
     *
     * @return ArtifactType
     */
    public static ArtifactType valueOf(String model, String type, Boolean isDocument) {
        ArtifactType artifactType = null;
        if ("ext".equals(model)) {
        	ArtifactTypeEnum artifactTypeEnum = null;
            if  ( type.equals(ArtifactTypeEnum.ExtendedDocument.getType()) ||
            		( !type.equals(ArtifactTypeEnum.ExtendedArtifactType.getType()) && isDocument!=null && isDocument ) ) {
            	artifactTypeEnum = ArtifactTypeEnum.ExtendedDocument;
            } else {
        		artifactTypeEnum = ArtifactTypeEnum.ExtendedArtifactType;
            }
            artifactType = new ArtifactType(artifactTypeEnum, null);
            artifactType.setExtendedType(type);
        } else {
            ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.valueOf(type);
            artifactType = new ArtifactType(artifactTypeEnum, null);
        }
        return artifactType;
    }

    /**
     * Figures out the type from the artifact instance.
     * @param artifact
     */
    public static ArtifactType valueOf(BaseArtifactType artifact) {
        BaseArtifactEnum apiType = artifact.getArtifactType();
        // First, figure it out by the ArtifactType enum on the object
        if (apiType != null) {
            ArtifactType artifactType = valueOf(apiType);
            if (DocumentArtifactType.class.isAssignableFrom(artifact.getClass())) {
                artifactType.setMimeType(((DocumentArtifactType)artifact).getContentType());
            }
            if (artifactType.isExtendedType()) {
                if ((artifact.getOtherAttributes().keySet().contains(ArtificerConstants.SRAMP_CONTENT_TYPE_QNAME))) {
                    String contentTypeStr = artifact.getOtherAttributes().get(ArtificerConstants.SRAMP_CONTENT_TYPE_QNAME);
                    artifactType.setMimeType(contentTypeStr);
                }
                String extendedDerived = artifact.getOtherAttributes().get(ArtificerConstants.SRAMP_DERIVED_QNAME);
                artifactType.setExtendedDerivedType("true".equals(extendedDerived));
            }
            if (artifactType.getArtifactType() == ArtifactTypeEnum.ExtendedArtifactType) {
                String extendedType = ((ExtendedArtifactType) artifact).getExtendedType();
                artifactType.setExtendedType(extendedType);
            } else if (artifactType.getArtifactType() == ArtifactTypeEnum.ExtendedDocument) {
                String extendedType = ((ExtendedDocument) artifact).getExtendedType();
                artifactType.setExtendedType(extendedType);
            }
            return artifactType;
        }
        // If that didn't work, then iterate through and test against all possible artifact types.
        ArtifactTypeEnum[] values = ArtifactTypeEnum.values();
        for (ArtifactTypeEnum artifactTypeEnum : values) {
            if (artifactTypeEnum.getTypeClass().equals(artifact.getClass())) {
                ArtifactType artifactType = new ArtifactType(artifactTypeEnum, null);
                if (artifactTypeEnum == ArtifactTypeEnum.ExtendedArtifactType || artifactTypeEnum == ArtifactTypeEnum.ExtendedDocument) {
                    if ((artifact.getOtherAttributes().keySet().contains(ArtificerConstants.SRAMP_CONTENT_TYPE_QNAME))) {
                        String contentTypeStr = artifact.getOtherAttributes().get(ArtificerConstants.SRAMP_CONTENT_TYPE_QNAME);
                        artifactType.setMimeType(contentTypeStr);
                    }
                    String extendedType = (artifact instanceof ExtendedArtifactType) ? ((ExtendedArtifactType) artifact)
                            .getExtendedType() : ((ExtendedDocument) artifact).getExtendedType();
                    String extendedDerived = artifact.getOtherAttributes().get(ArtificerConstants.SRAMP_DERIVED_QNAME);
                    artifactType.setExtendedType(extendedType);
                    artifactType.setExtendedDerivedType("true".equals(extendedDerived));
                }
                return artifactType;
            }
        }
        throw new RuntimeException(Messages.i18n.format("ARTIFACT_TYPE_FROM_CLASS_ERROR", artifact.getClass()));
    }

    /**
     * Instantiates an S-RAMP artifact of the correct type, and populates the artifactType and the
     * contentType.
     * @param artifactType
     */
    public BaseArtifactType newArtifactInstance() {
        try {
            BaseArtifactType baseArtifactType = getArtifactType().getTypeClass().newInstance();
            baseArtifactType.setArtifactType(getArtifactType().getApiType());
            if (DocumentArtifactType.class.isAssignableFrom(baseArtifactType.getClass())) {
                ((DocumentArtifactType) baseArtifactType).setContentType(getMimeType());
            }
            if (getArtifactType() == ArtifactTypeEnum.ExtendedArtifactType) {
                baseArtifactType.getOtherAttributes().put(ArtificerConstants.SRAMP_CONTENT_TYPE_QNAME, getMimeType());
                ((ExtendedArtifactType) baseArtifactType).setExtendedType(getExtendedType());
            }
            if (getArtifactType() == ArtifactTypeEnum.ExtendedDocument) {
                baseArtifactType.getOtherAttributes().put(ArtificerConstants.SRAMP_CONTENT_TYPE_QNAME, getMimeType());
                ((ExtendedDocument) baseArtifactType).setExtendedType(getExtendedType());
            }
            return baseArtifactType;
        } catch (Exception e) {
            throw new RuntimeException(Messages.i18n.format("ARTIFACT_INSTANTIATION_ERROR", getArtifactType().getTypeClass()), e);
        }
    }

    /**
     * Figures out the type from the s-ramp API type.
     * @param apiType
     */
    public static ArtifactType valueOf(BaseArtifactEnum apiType) {
        ArtifactTypeEnum[] values = ArtifactTypeEnum.values();
        for (ArtifactTypeEnum artifactType : values) {
            if (artifactType.getApiType() == apiType) {
                return new ArtifactType(artifactType, null);
            }
        }
        throw new RuntimeException(Messages.i18n.format("ARTIFACT_TYPE_FROM_APITYPE_ERROR", apiType.value()));
    }

    /**
     * @return the artifactType
     */
    public ArtifactTypeEnum getArtifactType() {
        return artifactType;
    }

    /**
     * @return true if the type is a {@link ExtendedArtifactType}.
     */
    public boolean isExtendedType() {
        return getArtifactType() == ArtifactTypeEnum.ExtendedArtifactType || getArtifactType() == ArtifactTypeEnum.ExtendedDocument;
    }

    /**
     * @return true if the artifact is a document artifact
     */
    public boolean isDocument() {
        if (isDerived()) {
            return false;
        } else {
            return getArtifactType().isDocument();
        }
    }

    /**
     * @return true if the artifact is derived
     */
    public boolean isDerived() {
        return getArtifactType().isDerived() || isExtendedDerivedType();
    }

    /**
     * @param artifactType the artifactType to set
     */
    public void setArtifactType(ArtifactTypeEnum artifactType) {
        this.artifactType = artifactType;
    }

    /**
     * @return the artifact model
     */
    public String getModel() {
        return getArtifactType().getModel();
    }

    /**
     * @return the artifact type
     */
    public String getType() {
        if (getArtifactType() == ArtifactTypeEnum.ExtendedArtifactType || getArtifactType() == ArtifactTypeEnum.ExtendedDocument) {
            return getExtendedType();
        } else {
            return getArtifactType().getType();
        }
    }

    /**
     * @return the artifact type label
     */
    public String getLabel() {
        return getArtifactType().getLabel();
    }

    /**
     * @return the mimeType
     */
    public String getMimeType() {
        return mimeType;
    }

    /**
     * @param mimeType the mimeType to set
     */
    public void setMimeType(String mimeType) {
        this.mimeType = mimeType;
    }

    /**
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("/s-ramp/%1$s/%2$s (%3$s)", getArtifactType().getModel(), getArtifactType()
                .getType(), getMimeType());
    }

    /**
     * Sets the extended type.
     * @param extendedType
     */
    public void setExtendedType(String extendedType) {
        if (extendedType != null && !isValid(extendedType)) {
            throw new RuntimeException(Messages.i18n.format("ArtifactType.InvalidExtendedType", extendedType));
        }
        this.extendedType = extendedType;
    }

    /**
     * Gets the extended artifact type.
     */
    public String getExtendedType() {
        return extendedType;
    }

    private static class ModelMime {
        public ModelMime(String extendedModel, String mimeType) {
            this.extendedModel = extendedModel;
            this.mimeType = mimeType;
        }
        public String extendedModel;
        public String mimeType;
    }

    /**
     * What kind of artifact is inside that wrapper?
     * @param artifactWrapper
     */
    public static ArtifactType valueOf(Artifact artifactWrapper, String hint) {
        ArtifactType type = null;
        // We were given a hint - try using that first.
        if (hint != null) {
            String methodName = "get" + hint;
            try {
                Method method = artifactWrapper.getClass().getMethod(methodName);
                Object o = method.invoke(artifactWrapper);
                if (o != null && BaseArtifactType.class.isAssignableFrom(o.getClass())) {
                    Class<? extends BaseArtifactType> artyClass = ((BaseArtifactType) o).getClass();
                    return valueOf(artyClass);
                }
            } catch (Exception e) {
                // eat it
            }
        }

        // Didn't find it based on the hint - try them all!
        if (type == null) {
            Method[] methods = artifactWrapper.getClass().getMethods();
            try {
                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        Object o = method.invoke(artifactWrapper);
                        if (o != null && BaseArtifactType.class.isAssignableFrom(o.getClass())) {
                            Class<? extends BaseArtifactType> artyClass = ((BaseArtifactType) o).getClass();
                            return valueOf(artyClass);
                        }
                    }
                }
            } catch (Exception e) {
                // eat it
            }
        }
        return type;
    }

    /**
     * Figures out the artifact type from the class.
     * @param artyClass
     */
    private static ArtifactType valueOf(Class<? extends BaseArtifactType> artyClass) {
        ArtifactType rval = null;
        for (ArtifactTypeEnum e : ArtifactTypeEnum.values()) {
            if (e.getTypeClass().equals(artyClass)) {
                rval = new ArtifactType(e, null);
            }
        }
        return rval;
    }

    /**
     * @return the extendedDerivedType
     */
    protected boolean isExtendedDerivedType() {
        return extendedDerivedType;
    }

    /**
     * @param extendedDerivedType the extendedDerivedType to set
     */
    public void setExtendedDerivedType(boolean extendedDerivedType) {
        this.extendedDerivedType = extendedDerivedType;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((artifactType == null) ? 0 : artifactType.hashCode());
        result = prime * result + ((extendedType == null) ? 0 : extendedType.hashCode());
        return result;
    }
    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ArtifactType other = (ArtifactType) obj;
        if (artifactType != other.artifactType)
            return false;
        if (extendedType == null) {
            if (other.extendedType != null)
                return false;
        } else if (!extendedType.equals(other.extendedType))
            return false;
        return true;
    }
}


text:
/***************************************************************************//**
 * \file ISC_out_jpeg.c
 * \brief Module for encoding images as JPEG files.
 *
 * ISC_out_jpeg.c contains the functions for saving processed images
 * in the JPEG format.
*******************************************************************************/

#include "ISC_out_jpeg.h"
#include "ISC_util_assert.h"
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>

#include "ISC_util_imagecontext.h"

/**
 * \brief Creates an ISC_out_jpeg module.
 *
 * This function creates a new ISC_out_jpeg module.  Give it the image
 * context of the image expected to come in, and give it the file pointer to
 * dump the file to.  It will return an ISC_out_jpeg state structure.
 *
 * \param context The intended context of the image to feed into the module.
 * \param fp The file pointer.  Make this stdout to send it over the serial port.
 * \return ISC_out_jpeg state structure.
 */
__attribute__((gnu_inline)) inline ISC_out_jpeg *ISC_out_jpeg_start( ISC_util_imagecontext context, FILE *fp )
{
    ISC_out_jpeg *temp = (ISC_out_jpeg *)malloc( sizeof( ISC_out_jpeg ) );
    if ( !temp )
        ISC_util_assert_message( "Ran out of memory creating the JPEG compression schema." );

	temp->theContext = context;
	temp->filePointer = fp;

    temp->compressInfo.err = jpeg_std_error( &temp->jpegError );
    jpeg_create_compress( &temp->compressInfo );

    temp->compressInfo.image_width = temp->theContext.frame.width;
    temp->compressInfo.image_height = temp->theContext.frame.height;
    temp->compressInfo.input_components = 3;
    temp->compressInfo.in_color_space = JCS_RGB;

    jpeg_set_defaults( &temp->compressInfo );
    jpeg_set_quality( &temp->compressInfo, 85, 1 /*true*/ );

    jpeg_stdio_dest(&temp->compressInfo, temp->filePointer);

    jpeg_start_compress(&temp->compressInfo, TRUE);

	temp->rowsLeft = temp->theContext.frame.height;
	temp->finished = false;

    return temp;
}

/**
 * \brief Feed a row into an ISC_out_jpeg module.
 *
 * This module feeds a row into the ISC_out_jpeg module, which gives the JPEG
 * module the newest information.
 *
 * \param ijc The module's state structure.
 * \param row A pointer to a row of pixels.
 * \return Nothing.
 */
__attribute__((gnu_inline)) inline void ISC_out_jpeg_feed( ISC_out_jpeg *ijc, uint8_t *row )
{
    JSAMPROW jpegRow[1];

	if ( ijc->rowsLeft > 0 )
	{
    	jpegRow[0] = row;
    	jpeg_write_scanlines(&ijc->compressInfo, jpegRow, 1);
		free(row);
		ijc->rowsLeft--;

		if ( ijc->rowsLeft == 0 )
			ijc->finished = true;
	}
}

/**
 * \brief End an ISC_out_jpeg module.
 *
 * This function clears up the state structure for an ISC_out_jpeg module.
 *
 * \param ijc The module's state structure.
 * \return Nothing.
 */
__attribute__((gnu_inline)) inline void ISC_out_jpeg_end( ISC_out_jpeg *ijc )
{
    jpeg_finish_compress(&ijc->compressInfo);
    jpeg_destroy_compress(&ijc->compressInfo);
    free(ijc);
}

/**
 * \brief Check to see if a JPEG module is running.
 *
 * This function checks to see if the JPEG module still needs to do work.
 *
 * \param ijc The module's state structure.
 * \return Whether or not the ISC_out_jpeg module still needs to do work.
 */
__attribute__((gnu_inline)) inline bool ISC_out_jpeg_running( ISC_out_jpeg *ijc )
{
	return !ijc->finished;
}


text:
comments: false
date: 2014-04-26T21:58:34Z
tags:
- github
- gist
- geojson
- jq
- ebird
title: Scripted Github GeoJSON Gists
url: /blog/2014/04/26/scripted-github-geojson-gists/
---

Below is a Github [Gist](https://gist.github.com/nhoag/9995803) with a map comprised of [GeoJSON](http://geojson.org/) data, along with the bash command that was used to create it.

Github automatically generates maps for GeoJSON files in Gists and repositories. This is well documented at the following article: https://help.github.com/articles/mapping-geojson-files-on-github

The map below pulls data from [eBird API](https://confluence.cornell.edu/display/CLOISAPI/eBird+API+1.1), transforms the data structure into GeoJSON format using [jq](http://stedolan.github.io/jq/), and then POSTs to a Github Gist.

<script src="https://gist.github.com/nhoag/9995803.js"></script>


text:
There is an excellent open source library called `u8g2` that can be found on Github here:

[https://github.com/olikraus/u8g2](https://github.com/olikraus/u8g2)

The purpose of the library is to provide a display independent driver layer for monochrome displays including LCD and OLED.
The library "knows" how to driver the underlying displays as well as providing drawing primitives including text, fonts, lines and
other geometrical shapes.

A version of the library is available in cleanly compiling C and compiles without incident on the ESP32-IDF framework.

However, since the library is agnostic of MCU environments and will work on a variety of boards, there has to be a mapping from
the functions expected by the library to the underlying MCU board hardware.  This includes driving GPIOs, I2C, SPI and more.

The code in this folder provides a mapping from U8g2 to the ESP32 ESP-IDF.  This should be included in your build of U8g2 applications.

To use with the ESP32, we must invoke the `u8g2_esp32_hal_init()` function before invoking any of the normal U8g2 functons.  What
this call does is tell the ESP32 what pins we wish to map.  Here is an example of SPI use:

```
u8g2_esp32_hal_t u8g2_esp32_hal = U8G2_ESP32_HAL_DEFAULT;
u8g2_esp32_hal.clk   = PIN_CLK;
u8g2_esp32_hal.mosi  = PIN_MOSI;
u8g2_esp32_hal.cs    = PIN_CS;
u8g2_esp32_hal.dc    = PIN_DC;
u8g2_esp32_hal.reset = PIN_RESET;
u8g2_esp32_hal_init(u8g2_esp32_hal);
```

and here is an example of I2C use:

```
u8g2_esp32_hal_t u8g2_esp32_hal = U8G2_ESP32_HAL_DEFAULT;
u8g2_esp32_hal.sda = PIN_SDA;
u8g2_esp32_hal.scl = PIN_SCL;
u8g2_esp32_hal_init(u8g2_esp32_hal);
```

Note: For I2C, after calling the display specific setup, invoke:

```
u8x8_SetI2CAddress(&u8g2.u8x8,<address>);
```

Note that `<address>` is the I2C address already shifted left to include the read/write flag.  For example, if you are using an SSD1305, instead of supplying the address `0x3C` which would be `0011 1100` supply `0x78` which would be `0111 1000`.

The function takes as input a `u8g2_esp32_hal` structure instance which has the logical pins that U8g2 needs mapped to the
physical pins on the ESP32 that we wish to use.  If we don't use a specific pin for our specific display, set the value to
be `U8G2_ESP32_HAL_UNDEFINED` which is the default initialization value.

Remember, ESP32 pins are not hard-coded to functions and as such, all the GPIO pins on the ESP32 are open for use.  Following
this initialization, we can use U8g2 as normal and described in the U8g2 documentation.

## Compiling U8G2
To use the actual U8g2 library in your ESP32 project, perform the following steps:

1. Create a directory called `components` in your main project directory.
2. Change into the `components` directory.
3. Run `git clone https://github.com/olikraus/u8g2.git` to bring in a the latest copy of u8g2 library.
4. Change into the `u8g2` directory.
5. Create a file called `component.mk`
6. Enter the following in the `component.mk` file:
```
COMPONENT_SRCDIRS:=csrc
COMPONENT_ADD_INCLUDEDIRS:=csrc
```

## Development
While in principal, there should be nothing specific needed beyond this addition to make U8g2 work on the ESP32, only a small
number of boards have been tested.


text:
/* eslint-disable no-param-reassign, no-underscore-dangle */

import { tokTypes as tt } from 'acorn'

export default function parseFromInput () {
  return function ha (node) {
    this.next()
    // For the `导入 「./xxx」;`, it should be handled by parseImport.
    node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
    this.expect(tt._import)
    node.specifiers = this.parseImportSpecifiers()
    this.semicolon()
    return this.finishNode(node, 'ImportDeclaration')
  }
}


text:
package uk.org.binky.channel;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TransactionTest {
	@Test
	public void testMate() {
		Integer value = 5;
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> wtransaction = new Transaction<Integer>(channel, value);
		Transaction<Integer> rtransaction = new Transaction<Integer>(channel);
		assertEquals(wtransaction.result(), null);
		assertEquals(rtransaction.result(), null);
		Result<Integer> result = wtransaction.mate(rtransaction);
		assertTrue(wtransaction.put);
		assertFalse(rtransaction.put);
		assertEquals(wtransaction.result(), result);
		assertEquals(rtransaction.result(), result);
	}

	@Test
	public void testMateReverse() {
		Integer value = 5;
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> wtransaction = new Transaction<Integer>(channel, value);
		Transaction<Integer> rtransaction = new Transaction<Integer>(channel);
		assertEquals(wtransaction.result(), null);
		assertEquals(rtransaction.result(), null);
		Result<Integer> result = rtransaction.mate(wtransaction);
		assertTrue(wtransaction.put);
		assertFalse(rtransaction.put);
		assertEquals(wtransaction.result(), result);
		assertEquals(rtransaction.result(), result);
	}

	@Test(expected = IllegalArgumentException.class)
	public void testLikeTransaction() {
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> atransaction = new Transaction<Integer>(channel);
		Transaction<Integer> btransaction = new Transaction<Integer>(channel);
		atransaction.mate(btransaction);
	}

	@Test
	public void testSolo() {
		Integer value = 5;
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> wtransaction = new Transaction<Integer>(channel, value);
		Result<Integer> result = wtransaction.solo();
		assertEquals(result.reader, null);
		assertEquals(result.writer, wtransaction);
		assertEquals(result.value, value);

		Transaction<Integer> rtransaction = new Transaction<Integer>(channel);
		result = rtransaction.solo(value);
		assertEquals(result.reader, rtransaction);
		assertEquals(result.writer, null);
		assertEquals(result.value, value);
	}

	@Test(expected = IllegalArgumentException.class)
	public void testPutPut() {
		Integer value = 5;
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> wtransaction = new Transaction<Integer>(channel, value);
		wtransaction.solo(value);
	}

	@Test(expected = IllegalArgumentException.class)
	public void testGetGet() {
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> wtransaction = new Transaction<Integer>(channel);
		wtransaction.solo();
	}

	@Test
	public void testClose() {
		Channel<Integer> channel = new Channel<Integer>();
		Transaction<Integer> rtransaction = new Transaction<Integer>(channel);
		Result<Integer> result = rtransaction.close();
		assertTrue(result.isClosed());
	}
}


text:
@echo off

for /f "usebackq tokens=*" %%i in (`vswhere -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do (
  set InstallDir=%%i
)

if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" (
  "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" %*
)
@echo on
if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" (
  set msBuildExe="%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe"
)

call .nuget\NuGet.exe update /self
call .nuget\NuGet.exe restore
call %msBuildExe% WinFormsUI.Docking.sln /t:build /p:Configuration=Release /p:OutputPath=..\bin\net35-client\
@IF %ERRORLEVEL% NEQ 0 PAUSE


text:
package io.github.draggonfantasy.muselang.interpreter;

import io.github.draggonfantasy.muselang.core.*;

import javax.sound.midi.*;
import java.util.List;

public class MuseInterpreter
{
    private static final int CHANNEL = 10;
    private static final int RESOLUTION = 60;

    public Sequence toMidiSequence(Music music) throws InvalidMidiDataException, MuseRuntimeException
    {
        Sequence seq = new Sequence(Sequence.PPQ, RESOLUTION);
        Track track = seq.createTrack();

        List<MusicUnit> musicUnits = music.getUnits();
        long tick = 0;
        for (MusicUnit unit : musicUnits)
        {
            tick = addUnitToTrack(music, track, tick, unit);
        }

        return seq;
    }

    private long addUnitToTrack(Music music, Track track, long tick, MusicUnit unit) throws InvalidMidiDataException, MuseRuntimeException
    {
        if (unit instanceof ScoreNote)
        {
            tick = addNoteToTrack(track, tick, (ScoreNote) unit);
        } else if (unit instanceof PhraseCall)
        {
            PhraseCall  phraseCall = (PhraseCall) unit;
            PhraseProto phrase = music.getPhrase(phraseCall.getPhraseName());
            if(phrase == null)
            {
                throw new MuseRuntimeException("No prototype found for phrase " + phraseCall.getPhraseName());
            }
            for(MusicUnit phraseUnit : phrase.getNotes())
            {
                tick = addUnitToTrack(music, track, tick, phraseUnit);
            }
        } else if(unit instanceof Repeat)
        {
            Repeat repeat = (Repeat) unit;
            for(int i = 0; i < repeat.getTimes(); ++i)
            {
                for(MusicUnit repeatUnit : repeat.getUnits())
                {
                    tick = addUnitToTrack(music, track, tick, repeatUnit);
                }
            }
        } else if(unit instanceof Chord)
        {
            Chord chord = (Chord) unit;
            long nextTick = tick;
            for(ScoreNote chordUnit : chord.getUnits())
            {
                long t = addNoteToTrack(track, tick, chordUnit);
                if(nextTick < t) nextTick = t;
            }
            tick = nextTick;
        } else if(unit instanceof Pause)
        {
            tick += RESOLUTION / (((Pause)unit).getDuration() / 4f);
        }
        return tick;
    }

    private long addNoteToTrack(Track track, long tick, ScoreNote note) throws InvalidMidiDataException
    {
        ShortMessage midiMessageOn  = new ShortMessage(ShortMessage.NOTE_ON,  CHANNEL, note.getNote().noteId(), note.getVelocity());
        ShortMessage midiMessageOff = new ShortMessage(ShortMessage.NOTE_OFF, CHANNEL, note.getNote().noteId(), note.getVelocity());
        track.add(new MidiEvent(midiMessageOn, tick));

        tick += RESOLUTION / (note.getDuration() / 4f); // Resolution is how many ticks is done per quarter note
        // So if the note's duration is quarter, we need to increase tick in value of resolution
        // If note's duration is eighth, we need to increase tick in value of resolution/2 and so on
        track.add(new MidiEvent(midiMessageOff, tick));
        return tick;
    }
}


text:
<!DOCTYPE IllegalNameChar [
<!ELEMENT IllegalNameChar ANY>
]>
<!-- IllegalNameChar #0xFDD0 -->
<IllegalNameChar/>


text:
package com.leonardobishop.quests.quests.tasktypes.types;

import com.leonardobishop.quests.Quests;
import com.leonardobishop.quests.api.QuestsAPI;
import com.leonardobishop.quests.player.QPlayer;
import com.leonardobishop.quests.player.questprogressfile.QuestProgress;
import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile;
import com.leonardobishop.quests.player.questprogressfile.TaskProgress;
import com.leonardobishop.quests.quests.Quest;
import com.leonardobishop.quests.quests.Task;
import com.leonardobishop.quests.quests.tasktypes.ConfigValue;
import com.leonardobishop.quests.quests.tasktypes.TaskType;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.ItemStack;

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

public final class InventoryTaskType extends TaskType {

    private List<ConfigValue> creatorConfigValues = new ArrayList<>();

    public InventoryTaskType() {
        super("inventory", "LMBishop", "Obtain a set of items.");
        this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of item to retrieve."));
        this.creatorConfigValues.add(new ConfigValue("item", true, "Name or ID of item."));
        this.creatorConfigValues.add(new ConfigValue("remove-items-when-complete", false, "Take the items away from the player on completion (true/false, " +
                "default = false)."));
        this.creatorConfigValues.add(new ConfigValue("update-progress", false, "Update the displayed progress (if this causes lag then disable it)."));
    }

    @Override
    public List<ConfigValue> getCreatorConfigValues() {
        return creatorConfigValues;
    }

    @SuppressWarnings("deprecation")
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onItemPickup(PlayerPickupItemEvent event) {
        Bukkit.getScheduler().runTaskLater(Quests.get(), () -> this.checkInventory(event.getPlayer()), 1L);
    }

    @EventHandler(priority = EventPriority.MONITOR/*, ignoreCancelled = true*/)
    public void onInventoryClick(InventoryClickEvent event) {
        Bukkit.getScheduler().runTaskLater(Quests.get(), () -> checkInventory((Player) event.getWhoClicked()), 1L); //Still some work to do as it doesn't really work
    }

    @SuppressWarnings("deprecation")
    private void checkInventory(Player player) {
        QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId(), true);
        if (qPlayer == null) {
            return;
        }

        QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile();

        for (Quest quest : super.getRegisteredQuests()) {
            if (questProgressFile.hasStartedQuest(quest)) {
                QuestProgress questProgress = questProgressFile.getQuestProgress(quest);

                for (Task task : quest.getTasksOfType(super.getType())) {
                    TaskProgress taskProgress = questProgress.getTaskProgress(task.getId());

                    if (taskProgress.isCompleted()) {
                        continue;
                    }

                    Material material;
                    int amount = (int) task.getConfigValue("amount");
                    Object configBlock = task.getConfigValue("item");
                    Object configData = task.getConfigValue("data");
                    Object remove = task.getConfigValue("remove-items-when-complete");

                    material = Material.getMaterial(String.valueOf(configBlock));

                    if (material == null) {
                        continue;
                    }
                    ItemStack is;
                    if (configData != null) {
                        is = new ItemStack(material, 1, ((Integer) configData).shortValue());
                    } else {
                        is = new ItemStack(material, 1);
                    }

                    if (task.getConfigValue("update-progress") != null && (Boolean) task.getConfigValue("update-progress")) {
                        taskProgress.setProgress(getAmount(player, is, amount));
                    }

                    if (player.getInventory().containsAtLeast(is, amount)) {
                        is.setAmount(amount);
                        taskProgress.setCompleted(true);

                        if (remove != null && ((Boolean) remove)) {
                            player.getInventory().removeItem(is);
                        }
                    }
                }
            }
        }
    }

    private int getAmount(Player player, ItemStack is, int max) {
        if (is == null) {
            return 0;
        }
        int amount = 0;
        for (int i = 0; i < 36; i++) {
            ItemStack slot = player.getInventory().getItem(i);
            if (slot == null || !slot.isSimilar(is))
                continue;
            amount += slot.getAmount();
        }
        return Math.min(amount, max);
    }

}


text:
import os

from twisted.internet import defer
from twisted.python import log
from twisted.protocols import basic

from buildbot import pbutil
from buildbot.util.maildir import MaildirService
from buildbot.util import netstrings
from buildbot.process.properties import Properties
from buildbot.schedulers import base
from buildbot.status.buildset import BuildSetStatus

class TryBase(base.BaseScheduler):

    def filterBuilderList(self, builderNames):
        """
        Make sure that C{builderNames} is a subset of the configured
        C{self.builderNames}, returning an empty list if not.  If
        C{builderNames} is empty, use C{self.builderNames}.

        @returns: list of builder names to build on
        """

        # self.builderNames is the configured list of builders
        # available for try.  If the user supplies a list of builders,
        # it must be restricted to the configured list.  If not, build
        # on all of the configured builders.
        if builderNames:
            for b in builderNames:
                if not b in self.builderNames:
                    log.msg("%s got with builder %s" % (self, b))
                    log.msg(" but that wasn't in our list: %s"
                            % (self.builderNames,))
                    return []
        else:
            builderNames = self.builderNames
        return builderNames

class BadJobfile(Exception):
    pass

class JobdirService(MaildirService):
    # NOTE: tightly coupled with Try_Jobdir, below

    def messageReceived(self, filename):
        f = self.moveToCurDir(filename)
        return self.parent.handleJobFile(filename, f)

class Try_Jobdir(TryBase):

    compare_attrs = TryBase.compare_attrs + ( 'jobdir', )

    def __init__(self, name, builderNames, jobdir,
                 properties={}):
        TryBase.__init__(self, name=name, builderNames=builderNames, properties=properties)
        self.jobdir = jobdir
        self.watcher = JobdirService()
        self.watcher.setServiceParent(self)

    def startService(self):
        # set the watcher's basedir now that we have a master
        self.watcher.setBasedir(os.path.join(self.master.basedir, self.jobdir))
        TryBase.startService(self)

    def parseJob(self, f):
        # jobfiles are serialized build requests. Each is a list of
        # serialized netstrings, in the following order:
        #  "2", the format version number ("1" does not have project/repo)
        #  buildsetID, arbitrary string, used to find the buildSet later
        #  branch name, "" for default-branch
        #  base revision, "" for HEAD
        #  patchlevel, usually "1"
        #  patch
        #  builderNames...
        p = netstrings.NetstringParser()
        try:
            p.feed(f.read())
        except basic.NetstringParseError:
            raise BadJobfile("unable to parse netstrings")
        if not p.strings:
            raise BadJobfile("could not find any complete netstrings")
        ver = p.strings.pop(0)

        if ver == "1":
            buildsetID, branch, baserev, patchlevel, diff = p.strings[:5]
            builderNames = p.strings[5:]
            if branch == "":
                branch = None
            if baserev == "":
                baserev = None
            patchlevel = int(patchlevel)
            repository=''
            project=''
            who=''
        elif ver == "2": # introduced the repository and project property
            buildsetID, branch, baserev, patchlevel, diff, repository, project = p.strings[:7]
            builderNames = p.strings[7:]
            if branch == "":
                branch = None
            if baserev == "":
                baserev = None
            patchlevel = int(patchlevel)
            who=''
        elif ver == "3": # introduced who property
            buildsetID, branch, baserev, patchlevel, diff, repository, project, who = p.strings[:8]
            builderNames = p.strings[8:]
            if branch == "":
                branch = None
            if baserev == "":
                baserev = None
            patchlevel = int(patchlevel)
        else:
            raise BadJobfile("unknown version '%s'" % ver)
        return dict(
                builderNames=builderNames,
                branch=branch,
                baserev=baserev,
                patch_body=diff,
                patch_level=patchlevel,
                repository=repository,
                project=project,
                who=who,
                jobid=buildsetID)

    def handleJobFile(self, filename, f):
        try:
            parsed_job = self.parseJob(f)
            builderNames = parsed_job['builderNames']
        except BadJobfile:
            log.msg("%s reports a bad jobfile in %s" % (self, filename))
            log.err()
            return defer.succeed(None)

        # Validate/fixup the builder names.
        builderNames = self.filterBuilderList(builderNames)
        if not builderNames:
            log.msg("incoming Try job did not specify any allowed builder names")
            return defer.succeed(None)

        d = self.master.db.sourcestamps.addSourceStamp(
                branch=parsed_job['branch'],
                revision=parsed_job['baserev'],
                patch_body=parsed_job['patch_body'],
                patch_level=parsed_job['patch_level'],
                patch_subdir='', # TODO: can't set this remotely - #1769
                project=parsed_job['project'],
                repository=parsed_job['repository'])
        def create_buildset(ssid):
            reason = "'try' job"
            if parsed_job['who']:
                reason += " by user %s" % parsed_job['who']
            return self.addBuildsetForSourceStamp(ssid=ssid,
                    reason=reason, external_idstring=parsed_job['jobid'],
                    builderNames=builderNames)
        d.addCallback(create_buildset)
        return d

class Try_Userpass_Perspective(pbutil.NewCredPerspective):
    def __init__(self, scheduler, username):
        self.scheduler = scheduler
        self.username = username

    @defer.deferredGenerator
    def perspective_try(self, branch, revision, patch, repository, project,
                        builderNames, who='', properties={} ):
        db = self.scheduler.master.db
        log.msg("user %s requesting build on builders %s" % (self.username,
                                                             builderNames))

        # build the intersection of the request and our configured list
        builderNames = self.scheduler.filterBuilderList(builderNames)
        if not builderNames:
            return

        wfd = defer.waitForDeferred(
                db.sourcestamps.addSourceStamp(branch=branch, revision=revision,
                    repository=repository, project=project, patch_level=patch[0],
                    patch_body=patch[1], patch_subdir=''))
                    # note: no way to specify patch subdir - #1769
        yield wfd
        ssid = wfd.getResult()

        reason = "'try' job"
        if who:
            reason += " by user %s" % who

        requested_props = Properties()
        requested_props.update(properties, "try build")
        wfd = defer.waitForDeferred(
                self.scheduler.addBuildsetForSourceStamp(ssid=ssid,
                        reason=reason, properties=requested_props,
                        builderNames=builderNames))
        yield wfd
        (bsid,brids) = wfd.getResult()

        # return a remotely-usable BuildSetStatus object
        wfd = defer.waitForDeferred(
                db.buildsets.getBuildset(bsid))
        yield wfd
        bsdict = wfd.getResult()

        bss = BuildSetStatus(bsdict, self.scheduler.master.status)
        from buildbot.status.client import makeRemote
        r = makeRemote(bss)
        yield r # return value

    def perspective_getAvailableBuilderNames(self):
        # Return a list of builder names that are configured
        # for the try service
        # This is mostly intended for integrating try services
        # into other applications
        return self.scheduler.listBuilderNames()

class Try_Userpass(TryBase):
    compare_attrs = ( 'name', 'builderNames', 'port', 'userpass', 'properties' )

    def __init__(self, name, builderNames, port, userpass,
                 properties={}):
        TryBase.__init__(self, name=name, builderNames=builderNames, properties=properties)
        self.port = port
        self.userpass = userpass

    def startService(self):
        TryBase.startService(self)

        # register each user/passwd with the pbmanager
        def factory(mind, username):
            return Try_Userpass_Perspective(self, username)
        self.registrations = []
        for user, passwd in self.userpass:
            self.registrations.append(
                    self.master.pbmanager.register(self.port, user, passwd, factory))

    def stopService(self):
        d = defer.maybeDeferred(TryBase.stopService, self)
        def unreg(_):
            return defer.gatherResults(
                [ reg.unregister() for reg in self.registrations ])
        d.addCallback(unreg)
        return d


text:
using Senparc.Weixin.Entities;

namespace Senparc.Weixin.Work.Entities
{
    /// <summary>
    /// openid转换成userid接口返回的Json结果
    /// </summary>
    public class ConvertToUserIdResult : WorkJsonResult
    {
        /// <summary>
        /// 该openid在企业号中对应的成员userid
        /// </summary>
        public string userid { get; set; }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN
__attribute__ ((deprecated))
@interface CardinalSessionConfig : CardinalSessionConfiguration

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<title>Form validation

					 - Plugins

				 - Documentation

 - Web Experience Toolkit
</title>
		<meta content="width=device-width, initial-scale=1" name="viewport" />

		<meta name="description" content="Provides generic validation and error message handling for Web forms." />

<link href="../../../assets/favicon.ico" rel="icon" type="image/x-icon" />
<link rel="stylesheet" href="../../../css/wet-boew.css" />

<link rel="stylesheet" href="../../../css/theme.css" />

<link rel="stylesheet" href="../../../css/noscript.css" />

		Skip to main content

		Skip to "About this site"

Language selection

Français

English (current)

Search and menus

Search and menus

	<object type="image/svg+xml" tabindex="-1" data="../../../assets/logo.svg"></object>
	Web Experience Toolkit, Collaborative open source project led by the Government of Canada

Search

					<form action="https://google.ca/search" method="get" role="search" class="form-inline">

		Search website
		<input id="wb-srch-q" class="form-control" name="q" type="search" value="" size="27" maxlength="150" />
		<input type="hidden" name="q" value="site:wet-boew.github.io OR site:github.com/wet-boew/" />

	<button type="submit" id="wb-srch-sub" class="btn btn-default">Search</button>

</form>

Topics menu

WET project

Implement WET

Contribute to WET

You are here:

				Home

						Documentation

						Plugins

Form validation

Form validation

Looking for WET v3.1?

As of September 23, 2014, version 3.1 of the Web Experience Toolkit is no longer supported. The source code and documentation have been moved to the wet-boew-legacy repository.

	Questions or comments?

Purpose

This component provides generic validation and error message handling for Web forms.

Use when

Web forms

Working example

English example

French example

How to implement

Add class="wb-frmvld" to a div element surrounding the form element

<div class="wb-frmvld">
	<form action="#" method="get" id="validation-example">
	...
	</form>

Optional: Wrap each form field name with <span class="field-name">...</span>. This specifies the prefix to use for the error message summary.

<label for="fname1">
	<span class="field-name">First Name</span> <strong>(required)</strong>
</label>

Add required="required" to each mandatory form field

<input id="fname1" name="fname1" type="text" required="required" />

Optional: For input fields, add one of the configuration options for specialized validation.

Configuration options

				Option
				Description
				How to configure
				Values

				hdLvl
				Heading level for error summary.
				Add "hdLvl": "headingLevel" to the data-wb-frmvld attribute or window[ "wb-frmvld" ] where headingLevel is the heading level. Use the following JavaScript code instead to configure all instances of the plugin: window[ "wb-frmvld" ] = {"hdLvl": "headingLevel"};.

h2 (default):

Heading level 2

h3:

Heading level 3

h4:

Heading level 4

h5:

Heading level 5

h6:

Heading level 6

				ignore
				Selector identifying the fields to ignore.
				Add "ignore": "selector" to the data-wb-frmvld attribute or window[ "wb-frmvld" ] where selector is a valid jQuery selector. Use the following JavaScript code instead to configure all instances of the plugin: window[ "wb-frmvld" ] = {"ignore": ".ignore"};.

:hidden (default):

All hidden fields

.ignore:

All fields with the ignore class

Empty string ("")

None of the fields

Specialized validation

Add specialized validation to an input field by applying the following options.

					Option
					Validation type

					data-rule-alphanumeric="true"
					Alphanumeric

					type="date"
					Date

					type="date" data-rule-dateISO="true"
					Date (ISO)

					type="number"
					Digits only

					data-rule-lettersonly="true"
					Letters only

					data-rule-letterswithbasicpunc="true"
					Letters and basic punctuation only (allowed punctuation: [.])

					data-rule-maxlength="x"
					Maximum length of x

					max="x"
					Maximum number x

					data-rule-minlength="x"
					Minimum length of x

					min="x"
					Minimum number x

					type="email"
					Email

					data-rule-rangelength="[x,y]"
					Range length x to y

					type="tel" data-rule-phoneUS="true"
					Telephone number (US)

					type="time"
					Time

					type="url"
					URL (IPv4)

					type="url" data-rule-ipv6="true"
					URL (IPv6)

See jQuery Validation Plugin - Documentation for more details.

Events

Document the public events that can be used by implementers or developers.

				Event
				Trigger
				What it does

				wb-init.wb-frmvld
				Triggered manually (e.g., $( ".wb-frmvld" ).trigger( "wb-init.wb-frmvld" );).
				Used to manually initialize the form validation. Note: The Form validation plugin will be initialized automatically unless the form elements are added after the page has already loaded.

				wb-ready.wb-frmvld (v4.0.5+)
				Triggered automatically after form validation initializes.
				Used to identify the element where form validation has initialized (target of the event)

$( document ).on( "wb-ready.wb-frmvld", ".wb-frmvld", function( event ) {
});

$( ".wb-frmvld" ).on( "wb-ready.wb-frmvld", function( event ) {
});

				wb-ready.wb (v4.0.5+)
				Triggered automatically when WET has finished loading and executing.
				Used to identify when all WET plugins and polyfills have finished loading and executing.

$( document ).on( "wb-ready.wb", function( event ) {
});

See jQuery Validation Plugin - Documentation for details about events specific to jQuery Validation.

Source code

Form validation source code on GitHub

Date modified:

<time property="dateModified">2014-10-28</time>

About this site

Contact us

Questions or comments?

About

About the Web Experience Toolkit

About the Web Standards

News

Recent project activity

Project statistics

Stay connected

Twitter


text:
/* global ConversationPanel: true, PayloadPanel: true*/
/* eslint no-unused-vars: "off" */

// Other JS files required to be loaded first: apis.js, conversation.js, payload.js
(function() {
  // Initialize all modules
  ConversationPanel.init();
  /*PayloadPanel.init(); */
})();


text:
'use strict';

angular
  .module('sugerpocket')
  .config([
    '$stateProvider',
    '$urlRouterProvider',
    '$locationProvider',
    function ($stateProvider, $urlRouterProvider, $locationProvider) {
    //配置一级路由
      $stateProvider
        .state('home', {
          url: '/home',
          templateUrl: 'includes/home'
        })
        .state('blog', {
          url: '/blog',
          templateUrl: 'includes/blog'
        })
        .state('assignment', {
          url: '/assignment',
          templateUrl: 'includes/assignment'
        });

      $urlRouterProvider.otherwise('blog');
      $locationProvider.html5Mode(true);
    }]);


text:
<?php

/**
 * Copy-paste this file to your config/autoload folder
 */
return [
    'webino_canonical_redirect' => [
        'enabled' => true,
        'www'     => false,   // bool = enabled|Site URI with www
        'slash'   => false,   // bool = enabled|Site URI with trailing slash
    ],
];


text:
require "helper"

describe Google::Cloud::Pubsub::Subscription, :delay, :mock_pubsub do
  let(:topic_name) { "topic-name-goes-here" }
  let(:sub_name) { "subscription-name-goes-here" }
  let(:sub_json) { subscription_json topic_name, sub_name }
  let(:sub_hash) { JSON.parse sub_json }
  let(:sub_grpc) { Google::Pubsub::V1::Subscription.decode_json(sub_json) }
  let(:subscription) { Google::Cloud::Pubsub::Subscription.from_grpc sub_grpc, pubsub.service }
  let(:rec_msg1_grpc) { Google::Pubsub::V1::ReceivedMessage.decode_json rec_message_json("rec_message1-msg-goes-here") }
  let(:rec_msg2_grpc) { Google::Pubsub::V1::ReceivedMessage.decode_json rec_message_json("rec_message2-msg-goes-here") }
  let(:rec_msg3_grpc) { Google::Pubsub::V1::ReceivedMessage.decode_json rec_message_json("rec_message3-msg-goes-here") }
  let(:rec_message1) { Google::Cloud::Pubsub::ReceivedMessage.from_grpc rec_msg1_grpc, subscription }
  let(:rec_message2) { Google::Cloud::Pubsub::ReceivedMessage.from_grpc rec_msg2_grpc, subscription }
  let(:rec_message3) { Google::Cloud::Pubsub::ReceivedMessage.from_grpc rec_msg3_grpc, subscription }

  it "can delay an ack id" do
    ack_id = rec_message1.ack_id
    new_deadline = 42
    mad_res = Google::Protobuf::Empty.new
    mock = Minitest::Mock.new
    mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), [ack_id], new_deadline]
    subscription.service.mocked_subscriber = mock

    subscription.delay new_deadline, ack_id

    mock.verify
  end

  it "can delay many ack ids" do
    ack_ids = [rec_message1.ack_id, rec_message3.ack_id, rec_message3.ack_id]
    new_deadline = 42
    mad_res = Google::Protobuf::Empty.new
    mock = Minitest::Mock.new
    mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), ack_ids, new_deadline]
    subscription.service.mocked_subscriber = mock

    subscription.delay new_deadline, *ack_ids

    mock.verify
  end

  it "can delay many ack ids in an array" do
    ack_ids = [rec_message1.ack_id, rec_message3.ack_id, rec_message3.ack_id]
    new_deadline = 42
    mad_res = Google::Protobuf::Empty.new
    mock = Minitest::Mock.new
    mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), ack_ids, new_deadline]
    subscription.service.mocked_subscriber = mock

    subscription.delay new_deadline, ack_ids

    mock.verify
  end

  it "can delay a message" do
    new_deadline = 42
    mad_res = Google::Protobuf::Empty.new
    mock = Minitest::Mock.new
    mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), [rec_message1.ack_id], new_deadline]
    subscription.service.mocked_subscriber = mock

    subscription.delay new_deadline, rec_message1

    mock.verify
  end

  it "can delay many messages" do
    rec_messages = [rec_message1, rec_message3, rec_message3]
    new_deadline = 42
    mad_res = Google::Protobuf::Empty.new
    mock = Minitest::Mock.new
    mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), rec_messages.map(&:ack_id), new_deadline]
    subscription.service.mocked_subscriber = mock

    subscription.delay new_deadline, *rec_messages

    mock.verify
  end

  it "can delay many messages in an array" do
    rec_messages = [rec_message1, rec_message3, rec_message3]
    new_deadline = 42
    mad_res = Google::Protobuf::Empty.new
    mock = Minitest::Mock.new
    mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), rec_messages.map(&:ack_id), new_deadline]
    subscription.service.mocked_subscriber = mock

    subscription.delay new_deadline, rec_messages

    mock.verify
  end

  describe "lazy subscription object of a subscription that does exist" do
    let :subscription do
      Google::Cloud::Pubsub::Subscription.new_lazy sub_name,
                                            pubsub.service
    end

    it "can delay an ack id" do
      ack_id = rec_message1.ack_id
      new_deadline = 42
      mad_res = Google::Protobuf::Empty.new
      mock = Minitest::Mock.new
      mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), [ack_id], new_deadline]
      subscription.service.mocked_subscriber = mock

      subscription.delay new_deadline, ack_id

      mock.verify
    end

    it "can delay many ack ids" do
      ack_ids = [rec_message1.ack_id, rec_message3.ack_id, rec_message3.ack_id]
      new_deadline = 42
      mad_res = Google::Protobuf::Empty.new
      mock = Minitest::Mock.new
      mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), ack_ids, new_deadline]
      subscription.service.mocked_subscriber = mock

      subscription.delay new_deadline, *ack_ids

      mock.verify
    end

    it "can delay many ack ids in an array" do
      ack_ids = [rec_message1.ack_id, rec_message3.ack_id, rec_message3.ack_id]
      new_deadline = 42
      mad_res = Google::Protobuf::Empty.new
      mock = Minitest::Mock.new
      mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), ack_ids, new_deadline]
      subscription.service.mocked_subscriber = mock

      subscription.delay new_deadline, ack_ids

      mock.verify
    end

    it "can delay a message" do
      new_deadline = 42
      mad_res = Google::Protobuf::Empty.new
      mock = Minitest::Mock.new
      mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), [rec_message1.ack_id], new_deadline]
      subscription.service.mocked_subscriber = mock

      subscription.delay new_deadline, rec_message1

      mock.verify
    end

    it "can delay many messages" do
      rec_messages = [rec_message1, rec_message3, rec_message3]
      new_deadline = 42
      mad_res = Google::Protobuf::Empty.new
      mock = Minitest::Mock.new
      mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), rec_messages.map(&:ack_id), new_deadline]
      subscription.service.mocked_subscriber = mock

      subscription.delay new_deadline, *rec_messages

      mock.verify
    end

    it "can delay many messages in an array" do
      rec_messages = [rec_message1, rec_message3, rec_message3]
      new_deadline = 42
      mad_res = Google::Protobuf::Empty.new
      mock = Minitest::Mock.new
      mock.expect :modify_ack_deadline, mad_res, [subscription_path(sub_name), rec_messages.map(&:ack_id), new_deadline]
      subscription.service.mocked_subscriber = mock

      subscription.delay new_deadline, rec_messages

      mock.verify
    end
  end

  describe "lazy subscription object of a subscription that does not exist" do
    let :subscription do
      Google::Cloud::Pubsub::Subscription.new_lazy sub_name,
                                            pubsub.service
    end

    it "raises NotFoundError when delaying an ack id" do
      ack_id = rec_message1.ack_id
      new_deadline = 42

      stub = Object.new
      def stub.modify_ack_deadline *args
        gax_error = Google::Gax::GaxError.new "not found"
        gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found")
        raise gax_error
      end
      subscription.service.mocked_subscriber = stub

      expect do
        subscription.delay new_deadline, ack_id
      end.must_raise Google::Cloud::NotFoundError
    end

    it "raises NotFoundError when delaying many ack ids" do
      ack_ids = [rec_message1.ack_id, rec_message3.ack_id, rec_message3.ack_id]
      new_deadline = 42

      stub = Object.new
      def stub.modify_ack_deadline *args
        gax_error = Google::Gax::GaxError.new "not found"
        gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found")
        raise gax_error
      end
      subscription.service.mocked_subscriber = stub

      expect do
        subscription.delay new_deadline, *ack_ids
      end.must_raise Google::Cloud::NotFoundError
    end

    it "raises NotFoundError when delaying many ack ids in an array" do
      ack_ids = [rec_message1.ack_id, rec_message3.ack_id, rec_message3.ack_id]
      new_deadline = 42

      stub = Object.new
      def stub.modify_ack_deadline *args
        gax_error = Google::Gax::GaxError.new "not found"
        gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found")
        raise gax_error
      end
      subscription.service.mocked_subscriber = stub

      expect do
        subscription.delay new_deadline, ack_ids
      end.must_raise Google::Cloud::NotFoundError
    end

    it "raises NotFoundError when delaying a message" do
      new_deadline = 42

      stub = Object.new
      def stub.modify_ack_deadline *args
        gax_error = Google::Gax::GaxError.new "not found"
        gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found")
        raise gax_error
      end
      subscription.service.mocked_subscriber = stub

      expect do
        subscription.delay new_deadline, rec_message1
      end.must_raise Google::Cloud::NotFoundError
    end

    it "raises NotFoundError when delaying many messages" do
      rec_messages = [rec_message1, rec_message3, rec_message3]
      new_deadline = 42

      stub = Object.new
      def stub.modify_ack_deadline *args
        gax_error = Google::Gax::GaxError.new "not found"
        gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found")
        raise gax_error
      end
      subscription.service.mocked_subscriber = stub

      expect do
        subscription.delay new_deadline, *rec_messages
      end.must_raise Google::Cloud::NotFoundError
    end

    it "raises NotFoundError when delaying many messages in an array" do
      rec_messages = [rec_message1, rec_message3, rec_message3]
      new_deadline = 42

      stub = Object.new
      def stub.modify_ack_deadline *args
        gax_error = Google::Gax::GaxError.new "not found"
        gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(5, "not found")
        raise gax_error
      end
      subscription.service.mocked_subscriber = stub

      expect do
        subscription.delay new_deadline, rec_messages
      end.must_raise Google::Cloud::NotFoundError
    end
  end
end


text:
REM @echo off
@echo Getting last Clousot version

set CLOUSOTROOT=..\..\Clousot

echo Getting the last version of Clousot from %CLOUSOTROOT%\bin\Debug
copy /y %CLOUSOTROOT%\bin\Debug\clousot.exe
copy /y %CLOUSOTROOT%\bin\Debug\CodeFixes.dll
copy /y %CLOUSOTROOT%\bin\Debug\"Abstract Domains.dll"
copy /y %CLOUSOTROOT%\bin\Debug\Analyzers.dll
copy /y %CLOUSOTROOT%\bin\Debug\CodeAnalysis.dll
copy /y %CLOUSOTROOT%\bin\Debug\ClousotMain.dll
copy /y %CLOUSOTROOT%\bin\Debug\DataStructures.dll
copy /y %CLOUSOTROOT%\bin\Debug\Graphs.dll
copy /y %CLOUSOTROOT%\bin\Debug\System.Compiler.dll
copy /y %CLOUSOTROOT%\bin\Debug\System.Compiler.Runtime.dll
copy /y %CLOUSOTROOT%\bin\Debug\CCI1CodeProvider.dll
copy /y %CLOUSOTROOT%\bin\Debug\Foxtrot.Extractor.dll
copy /y %CLOUSOTROOT%\bin\Debug\Microsoft.Contracts.Deserializer.dll
copy /y %CLOUSOTROOT%\bin\Debug\Microsoft.contracts.dll


text:
#region  Microsoft Public License
/* This code is part of Xipton.Razor v3.0
 * (c) Jaap Lamfers, 2013 - jaap.lamfers@xipton.net
 * Licensed under the Microsoft Public License (MS-PL) http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
 */
#endregion

using System.Configuration;
using System.Xml;
using System.Xml.Linq;

namespace Xipton.Razor.Config {
    /// <summary>
    /// General purpose configuration section. The whole section's inner xml is loaded without any validation.
    /// </summary>
    public class XmlConfigurationSection : ConfigurationSection
    {
        private bool _firstUnrecognizedElementHandled;

        public XElement InnerXml { get; private set; }

        protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader) {
            if (!_firstUnrecognizedElementHandled){
                _firstUnrecognizedElementHandled = true;
                InnerXml = (XElement) XNode.ReadFrom(reader);
            }
            else{
                throw new ConfigurationErrorsException("The XmlConfigurationSection must contain at most one child element (holding as many grand childs as you like).");
            }
            return true;
        }
    }
}


text:
module Gitlab
  module Diff
    class PositionTracer
      attr_accessor :repository
      attr_accessor :old_diff_refs
      attr_accessor :new_diff_refs
      attr_accessor :paths

      def initialize(repository:, old_diff_refs:, new_diff_refs:, paths: nil)
        @repository = repository
        @old_diff_refs = old_diff_refs
        @new_diff_refs = new_diff_refs
        @paths = paths
      end

      def trace(old_position)
        return unless old_diff_refs.complete? && new_diff_refs.complete?
        return unless old_position.diff_refs == old_diff_refs

        # Suppose we have an MR with source branch `feature` and target branch `master`.
        # When the MR was created, the head of `master` was commit A, and the
        # head of `feature` was commit B, resulting in the original diff A->B.
        # Since creation, `master` was updated to C.
        # Now `feature` is being updated to D, and the newly generated MR diff is C->D.
        # It is possible that C and D are direct decendants of A and B respectively,
        # but this isn't necessarily the case as rebases and merges come into play.
        #
        # Suppose we have a diff note on the original diff A->B. Now that the MR
        # is updated, we need to find out what line in C->D corresponds to the
        # line the note was originally created on, so that we can update the diff note's
        # records and continue to display it in the right place in the diffs.
        # If we cannot find this line in the new diff, this means the diff note is now
        # outdated, and we will display that fact to the user.
        #
        # In the new diff, the file the diff note was originally created on may
        # have been renamed, deleted or even created, if the file existed in A and B,
        # but was removed in C, and restored in D.
        #
        # Every diff note stores a Position object that defines a specific location,
        # identified by paths and line numbers, within a specific diff, identified
        # by start, head and base commit ids.
        #
        # For diff notes for diff A->B, the position looks like this:
        # Position
        #   base_sha - ID of commit A
        #   head_sha - ID of commit B
        #   old_path - path as of A (nil if file was newly created)
        #   new_path - path as of B (nil if file was deleted)
        #   old_line - line number as of A (nil if file was newly created)
        #   new_line - line number as of B (nil if file was deleted)
        #
        # We can easily update `base_sha` and `head_sha` to hold the IDs of commits C and D,
        # but need to find the paths and line numbers as of C and D.
        #
        # If the file was unchanged or newly created in A->B, the path as of D can be found
        # by generating diff B->D ("head to head"), finding the diff file with
        # `diff_file.old_path == position.new_path`, and taking `diff_file.new_path`.
        # The path as of C can be found by taking diff C->D, finding the diff file
        # with that same `new_path` and taking `diff_file.old_path`.
        # The line number as of D can be found by using the LineMapper on diff B->D
        # and providing the line number as of B.
        # The line number as of C can be found by using the LineMapper on diff C->D
        # and providing the line number as of D.
        #
        # If the file was deleted in A->B, the path as of C can be found
        # by generating diff A->C ("base to base"), finding the diff file with
        # `diff_file.old_path == position.old_path`, and taking `diff_file.new_path`.
        # The path as of D can be found by taking diff C->D, finding the diff file
        # with that same `old_path` and taking `diff_file.new_path`.
        # The line number as of C can be found by using the LineMapper on diff A->C
        # and providing the line number as of A.
        # The line number as of D can be found by using the LineMapper on diff C->D
        # and providing the line number as of C.

        results = nil
        results ||= trace_added_line(old_position)   if old_position.added?   || old_position.unchanged?
        results ||= trace_removed_line(old_position) if old_position.removed? || old_position.unchanged?

        return unless results

        file_diff, old_line, new_line = results

        new_position = Position.new(
          old_path: file_diff.old_path,
          new_path: file_diff.new_path,
          head_sha: new_diff_refs.head_sha,
          start_sha: new_diff_refs.start_sha,
          base_sha: new_diff_refs.base_sha,
          old_line: old_line,
          new_line: new_line
        )

        # If a position is found, but is not actually contained in the diff, for example
        # because it was an unchanged line in the context of a change that was undone,
        # we cannot return this as a successful trace.
        return unless new_position.diff_line(repository)

        new_position
      end

      private

      def trace_added_line(old_position)
        file_path = old_position.new_path

        return unless diff_head_to_head

        file_head_to_head = diff_head_to_head.find { |diff_file| diff_file.old_path == file_path }

        file_path = file_head_to_head.new_path if file_head_to_head

        new_line = LineMapper.new(file_head_to_head).old_to_new(old_position.new_line)

        return unless new_line

        file_diff = new_diffs.find { |diff_file| diff_file.new_path == file_path }
        return unless file_diff

        old_line = LineMapper.new(file_diff).new_to_old(new_line)

        [file_diff, old_line, new_line]
      end

      def trace_removed_line(old_position)
        file_path = old_position.old_path

        return unless diff_base_to_base

        file_base_to_base = diff_base_to_base.find { |diff_file| diff_file.old_path == file_path }

        file_path = file_base_to_base.old_path if file_base_to_base

        old_line = LineMapper.new(file_base_to_base).old_to_new(old_position.old_line)

        return unless old_line

        file_diff = new_diffs.find { |diff_file| diff_file.old_path == file_path }
        return unless file_diff

        new_line = LineMapper.new(file_diff).old_to_new(old_line)

        [file_diff, old_line, new_line]
      end

      def diff_base_to_base
        @diff_base_to_base ||= diff_files(old_diff_refs.base_sha || old_diff_refs.start_sha, new_diff_refs.base_sha || new_diff_refs.start_sha)
      end

      def diff_head_to_head
        @diff_head_to_head ||= diff_files(old_diff_refs.head_sha, new_diff_refs.head_sha)
      end

      def new_diffs
        @new_diffs ||= diff_files(new_diff_refs.start_sha, new_diff_refs.head_sha, use_base: true)
      end

      def diff_files(start_sha, head_sha, use_base: false)
        base_sha = self.repository.merge_base(start_sha, head_sha) || start_sha

        diffs = self.repository.raw_repository.diff(
          use_base ? base_sha : start_sha,
          head_sha,
          {},
          *paths
        )

        diffs.decorate! do |diff|
          Gitlab::Diff::File.new(diff, repository: self.repository)
        end
      end
    end
  end
end


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

<title>Calibrate</title>
<meta name="date" content="2017-01-07">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

lejos.robotics

Interface Calibrate

<map id="G" name="G">
<area shape="rect" id="node1_0" href="./Calibrate.html" title="lejos.robotics.Calibrate" alt="" coords="141,11,259,109"/>
<area shape="rect" id="node1" href="./Calibrate.html" title="<TABLE>" alt="" coords="131,5,269,115"/>
<area shape="rect" id="node2_1" href="./filter/AbstractCalibrationFilter.html" title="lejos.robotics.filter.AbstractCalibrationFilter" alt="" coords="16,169,384,573"/>
<area shape="rect" id="node2" href="./filter/AbstractCalibrationFilter.html" title="<TABLE>" alt="" coords="5,163,395,578"/>
</map>

All Known Implementing Classes:

AbstractCalibrationFilter, LinearCalibrationFilter

public interface Calibrate

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
startCalibration()

Starts calibration.

void
stopCalibration()

Ends calibration sequence.

Method Detail

startCalibration

void startCalibration()

Starts calibration.
 Must call stopCalibration() when done.

stopCalibration

void stopCalibration()

Ends calibration sequence.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
+++
categories = ["a", "b", "c"]
date = "2016-06-15T00:09:30-04:00"
description = ""
title = "Hi, I'm Eric!"
+++

# Eric Carlisle

Profession: Hired Geek

ericcarlisle.com

eric@ericcarlisle.com

@eric_carlisle

github.com/ecarlisle

slideshare.net/eric_carlisle


text:
#import <Cocoa/Cocoa.h>

/// A custom document view that has flipped geometry.
@interface JNWCollectionViewDocumentView : NSView

@end


text:
typedef NS_ENUM(NSUInteger, ZFModalTransitonDirection) {
    ZFModalTransitonDirectionBottom,
    ZFModalTransitonDirectionLeft,
    ZFModalTransitonDirectionRight,
};

@interface ZFDetectScrollViewEndGestureRecognizer : UIPanGestureRecognizer
@property (nonatomic, weak) UIScrollView *scrollview;
@end

@interface ZFModalTransitionAnimator : UIPercentDrivenInteractiveTransition <UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, assign, getter=isDragable) BOOL dragable;
@property BOOL bounces;
@property ZFModalTransitonDirection direction;
@property CGFloat behindViewScale;
@property CGFloat behindViewAlpha;
@property CGFloat transitionDuration;
@property (nonatomic, strong) UIViewController *modalController;

- (id)initWithModalViewController:(UIViewController *)modalViewController;
- (void)setContentScrollView:(UIScrollView *)scrollView;

@end