text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<!-- 参数管理手工映射SQL语句 -->
<sqlMap namespace="Param">
	<typeAlias alias="dto" type="org.g4studio.core.metatype.impl.BaseDto"/>

	<!-- 参数管理-查询参数列表 -->
	<select id="queryParamsForManage" parameterClass="map" resultClass="dto">
		SELECT   paramid, paramkey, paramvalue, remark
		    FROM eaparam a
		   WHERE 1 = 1
		<dynamic>
			<isNotEmpty prepend="AND" property="paramid">
									a.paramid = #paramid#
			</isNotEmpty>
			<isNotEmpty prepend="AND" property="paramkey">
									a.paramkey = #paramkey#
			</isNotEmpty>
			<isNotEmpty prepend="AND" property="queryParam">
				                    a.paramkey like '%$queryParam$%' or a.paramvalue like '%$queryParam$%'
			</isNotEmpty>
		</dynamic>
		ORDER BY paramid DESC
	</select>

	<select id="queryParamsForManageForPageCount" parameterClass="map" resultClass="java.lang.Integer">
		SELECT count(*) as count
		  FROM eaparam a WHERE 1 = 1
		<dynamic>
			<isNotEmpty prepend="AND" property="paramid">
									a.paramid = #paramid#
			</isNotEmpty>
			<isNotEmpty prepend="AND" property="exceptioncode">
									a.paramkey = #paramkey#
			</isNotEmpty>
			<isNotEmpty prepend="AND" property="queryParam">
				                     a.paramkey like '%$queryParam$%' or a.paramvalue like '%$queryParam$%'
			</isNotEmpty>
		</dynamic>
	</select>

	<!-- 插入一条参数表记录 -->
	<insert id="saveParamItem" parameterClass="dto">
		INSERT INTO eaparam (
		   paramid, paramkey, paramvalue,
		   remark)
		VALUES (#paramid#, #paramkey#, #paramvalue#, #remark#)
	</insert>

	<!-- 删除参数表  -->
	<delete id="deletParamItem" parameterClass="map" >
		DELETE FROM eaparam
		      WHERE paramid = #paramid#
	</delete>

	<!-- 根据主键更新参数表 -->
	<update id="updateParamItem" parameterClass="dto">
         UPDATE eaparam
		<dynamic prepend="SET">
			<isNotNull prepend="," property="paramkey">
	         paramkey = #paramkey#
			</isNotNull>
			<isNotNull prepend="," property="paramvalue">
	         paramvalue = #paramvalue#
			</isNotNull>
			<isNotNull prepend="," property="remark">
	         remark = #remark#
			</isNotNull>
		</dynamic>
	        WHERE paramid = #paramid#
	</update>
	<!-- 根据Key查询参数值 -->
	<select id="queryParamvalueByParamkey" parameterClass="java.lang.String" resultClass="java.lang.String">
		SELECT paramvalue from eaparam where paramkey = #paramkey#
	</select>
</sqlMap>


text:
layout: post
title: 'Standord Machine Learning Class: Week4 Assignment'
date: 2015-11-01 12:00
comments: true
tags: [machine-learning, Coursera, Stanford]
categories: [post-machine-learning]
---

## ex3.m

> implement one-vs-all logistic regression and neural networks to recognize hand-written digits.

- Plot Data (in ex3data1.mat)

![ex3_plotting_data.png](http://imgur.com/huVH9AS.png)

- Training One-vs-All Logistic Regression

hypothesis function: 1./(1+e.^(-1*(X*theta)))

K = 10 (0 to 9)

Iteration: 50

<script src="https://gist.github.com/joyhuang9473/0ca0a82a0b2616759a7e.js"></script>

- Predict for One-Vs-All

<script src="https://gist.github.com/joyhuang9473/8a964d894e25dc3aa1c4.js"></script>

## ex3_nn.m

>  implement a neural network to recognize handwritten digits using the same training set as before.

> provided with a set of network parameters (Θ(1),Θ(2)) already trained (in ex3weights.mat)

- Feedforward Propagation and Prediction

Loading Saved Neural Network Parameters in ex3weights.mat

<script src="https://gist.github.com/joyhuang9473/bc9786e6cb0ed377dc1f.js"></script>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Actinoids\Modlr\RestOdm\Metadata\Driver;

/**
 * Interface for locating metadata mapping files for generating EntityMetadata classes.
 *
 * @author Jacob Bare <jacob.bare@gmail.com>
 */
interface FileLocatorInterface
{
    /**
     * Finds the file location for a metadata file (for loading an EntityMetadata class instance), based on entity type.
     *
     * @param   string  $type
     * @param   string  $extension
     *
     * @return  string|null
     */
    public function findFileForType($type, $extension);

    /**
     * Finds the file location for a metadata mixin file.
     *
     * @param   string  $mixinName
     * @param   string  $extension
     *
     * @return  string|null
     */
    public function findFileForMixin($mixinName, $extension);

    /**
     * Finds all possible metadata files.
     *
     * @param   string  $extension
     * @return  array
     */
    public function findAllTypes($extension);
}


text:
<!DOCTYPE html>

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

<link rel="shortcut icon" type="image/x-icon" href="../../../../../../favicon.ico" />
<title>PlusOneButton.DefaultOnPlusOneClickListener | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">

<link href="../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

          API level:

            <select id="apiLevelSelector">

            </select>

Android APIs

  com.google.android.gms

  com.google.android.gms.ads

  com.google.android.gms.ads.doubleclick

  com.google.android.gms.ads.identifier

  com.google.android.gms.ads.mediation

  com.google.android.gms.ads.mediation.admob

  com.google.android.gms.ads.mediation.customevent

  com.google.android.gms.ads.search

  com.google.android.gms.appstate

  com.google.android.gms.auth

  com.google.android.gms.common

  com.google.android.gms.common.annotation

  com.google.android.gms.common.api

  com.google.android.gms.common.data

  com.google.android.gms.common.images

  com.google.android.gms.drive

  com.google.android.gms.drive.metadata

  com.google.android.gms.drive.query

  com.google.android.gms.drive.widget

  com.google.android.gms.games

  com.google.android.gms.games.achievement

  com.google.android.gms.games.leaderboard

  com.google.android.gms.games.multiplayer

  com.google.android.gms.games.multiplayer.realtime

  com.google.android.gms.games.multiplayer.turnbased

  com.google.android.gms.gcm

  com.google.android.gms.location

  com.google.android.gms.maps

  com.google.android.gms.maps.model

  com.google.android.gms.panorama

  com.google.android.gms.plus

  com.google.android.gms.plus.model.moments

  com.google.android.gms.plus.model.people

  com.google.android.gms.wallet

Interfaces

PlusClient.OnAccessRevokedListener

PlusClient.OnMomentsLoadedListener

PlusClient.OnPeopleLoadedListener

PlusClient.OrderBy

PlusOneButton.OnPlusOneClickListener

Classes

PlusClient

PlusClient.Builder

PlusOneButton

PlusOneButton.DefaultOnPlusOneClickListener

PlusOneButtonWithPopup

PlusOneDummyView

PlusShare

PlusShare.Builder

      fullscreen
      Use Tree NavigationUse Panel Navigation

Summary:

  Ctors

  | Methods

  | Inherited Methods

| [Expand All]

    protected

    class

PlusOneButton.DefaultOnPlusOneClickListener

    extends Object

      implements

        View.OnClickListener

        PlusOneButton.OnPlusOneClickListener

        java.lang.Object

               ↳

        com.google.android.gms.plus.PlusOneButton.DefaultOnPlusOneClickListener

Class Overview

This is an View.OnClickListener that will proxy clicks to an
 attached PlusOneButton.OnPlusOneClickListener, or default to attempt to start
 the intent using an Activity context.

 Important: The implementation of ERROR(/OnClickListener#onClick(android.view.View))
 used by DefaultOnPlusOneClickListener relies on the tag of this class'
 PlusOneButtonView remaining unused.

Summary

Public Constructors

        <nobr>

            </nobr>

        <nobr>
        PlusOneButton.DefaultOnPlusOneClickListener(PlusOneButton.OnPlusOneClickListener proxy)</nobr>

Public Methods

        <nobr>

            void</nobr>

        <nobr>
        onClick(View view)</nobr>

        <nobr>

            void</nobr>

        <nobr>
        onPlusOneClick(Intent intent)</nobr>

Called when the +1 button is clicked.

  [Expand]

Inherited Methods

From class

  java.lang.Object

        <nobr>

            Object</nobr>

        <nobr>
        clone()</nobr>

        <nobr>

            boolean</nobr>

        <nobr>
        equals(Object arg0)</nobr>

        <nobr>

            void</nobr>

        <nobr>
        finalize()</nobr>

        <nobr>

            final

            Class<?></nobr>

        <nobr>
        getClass()</nobr>

        <nobr>

            int</nobr>

        <nobr>
        hashCode()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        notify()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        notifyAll()</nobr>

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long arg0, int arg1)</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long arg0)</nobr>

From interface

  android.view.View.OnClickListener

        <nobr>
            abstract

            void</nobr>

        <nobr>
        onClick(View arg0)</nobr>

From interface

  com.google.android.gms.plus.PlusOneButton.OnPlusOneClickListener

        <nobr>
            abstract

            void</nobr>

        <nobr>
        onPlusOneClick(Intent intent)</nobr>

Called when the +1 button is clicked.

Public Constructors

        public

      PlusOneButton.DefaultOnPlusOneClickListener
      (PlusOneButton.OnPlusOneClickListener proxy)

Public Methods

        public

        void

      onClick
      (View view)

        public

        void

      onPlusOneClick
      (Intent intent)

Called when the +1 button is clicked.  Start the intent passed to this method
 to display the +1 confirmation dialog Activity with
 startActivityForResult(Intent, int).

Parameters

          intent
          The intent to display the +1 confirmation dialog.

  Except as noted, this content is licensed under Apache 2.0.
  For details and restrictions, see the
  Content License.

    Android  r —

    About Android  |
    Legal  |
    Support


text:
package com.mojang.mojam.network.packet;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.mojang.mojam.gui.menu.LevelSelectMenu;
import com.mojang.mojam.network.Packet;
import com.mojang.mojam.network.PacketListener;

public class VerifyLevelPacket extends Packet {

	private byte[] md5;
	private String name;
	private String fileSeperator;

	public VerifyLevelPacket() {
		fileSeperator=LevelSelectMenu.fileSeperator;
	}

	public VerifyLevelPacket(String lvl) {
		fileSeperator=LevelSelectMenu.fileSeperator;
		File level = new File(lvl);
		name=level.getName();
		boolean temp=false;
		if(!level.exists()){
			try {
				level.createNewFile();
				temp=true;
			} catch (IOException e) {

			}
		}
		byte[] bytes;
		try {
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(level));
			bytes=new byte[in.available()];
			in.read(bytes);
			in.close();
			MessageDigest digester = MessageDigest.getInstance("MD5");
			md5=digester.digest(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(temp){
			level.delete();
		}
	}
	@Override
	public void read(DataInputStream dis) throws IOException {
		byte[] name = new byte[dis.readInt()];
		dis.readFully(name);
		this.name = new String(name);
		md5 = new byte[dis.readInt()];
		dis.readFully(md5);

	}

	@Override
	public void write(DataOutputStream dos) throws IOException {
		byte[] name = this.name.getBytes();
		dos.writeInt(name.length);
		dos.write(name);
		dos.writeInt(md5.length);
		dos.write(md5);

	}

	public String getLevel(){
		String path=LevelSelectMenu.levelDirectory;
		File level = new File(path+fileSeperator+name);
		return level.getPath();
	}

	public boolean verify(String lvl) {
		File level = new File(lvl);
		name=level.getName();
		if(!level.exists()){
			return false;
		}
		byte[] bytes;
		byte[] localMd5 = null;
		try {
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(level));
			bytes=new byte[in.available()];
			in.read(bytes);
			in.close();
			MessageDigest digester = MessageDigest.getInstance("MD5");
			localMd5 =digester.digest(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return MessageDigest.isEqual(localMd5, md5);
	}

	@Override
	public void handle(PacketListener packetListener) {
		packetListener.handle(this);

	}

}


text:
require 'spec_helper'

describe CurriculumVitae do
  it 'has a version number' do
    expect(CurriculumVitae::VERSION).not_to be nil
  end

  context '.build' do
    let(:blokk) { -> { infinite 'joy' } }

    it 'passes block to `Builder.build`' do
      expect(CurriculumVitae::Builder).to receive(:build) do |_, &block|
        expect(blokk).to be(block)
      end

      subject.build(&blokk)
    end
  end
end


text:
export enum NoteRepetition {
    None,
    Tremolo
}


text:
package pl.kornakiewicz.basetodo.model.mongo;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import pl.kornakiewicz.basetodo.model.User;

import java.net.UnknownHostException;

import static org.junit.Assert.*;

/**
 * Created by krnk on 09/03/5.
 */
public class MongoUsersTests {

    String host;
    MongoClient mongoClient;
    MongoDatabase db;
    MongoTodoService service;

    @Before
    public void init() throws UnknownHostException {
        host = "localhost";
        mongoClient = new MongoClient("localhost");
        db = mongoClient.getDatabase("todos-test");
        service = new MongoTodoService(db);
    }

    @After
    public void clean() {
        mongoClient.dropDatabase("todos-test");
    }

    @Test
    public void addUserTest() {
        assertTrue(service.addUser(new User("test", "test")));
    }

    @Test
    public void addUserTest2() {
        service.addUser(new User("test", "test"));
        assertFalse(service.addUser(new User("test", "test")));
    }

    @Test
    public void addUserTest3() {
        service.addUser(new User("test", "test"));
        assertEquals(service.findUser("test").getUsername(), "test");
    }

    @Test
    public void findUserTest() {
        service.addUser(new User("test", "test"));
        assertNotNull(service.findUser("test"));
    }

    @Test
    public void findUserTest2() {
        assertNull(service.findUser("test"));
    }

    @Test
    public void authenticateTest1() {
        assertFalse(service.authenticate(new User("test", "test")));
    }

    @Test
    public void authenticateTest2() {
        service.addUser(new User("test", "test"));
        assertTrue(service.authenticate(new User("test", "test")));
    }

    @Test
    public void authenticateTest3() {
        service.addUser(new User("test", "nope"));
        assertFalse(service.authenticate(new User("test", "test")));
    }
}


text:
"""
This file contains the outline of an implementation to load environment modules
(http://modules.sourceforge.net/).

This is a community contributed feature and the core Galaxy team does utilize
it, hence support for it will be minimal. The Galaxy team eagerly welcomes
community contribution and maintenance however.
"""
from os import environ, pathsep
from os.path import exists, isdir, join
from StringIO import StringIO
from subprocess import Popen, PIPE

from ..resolvers import DependencyResolver, INDETERMINATE_DEPENDENCY, Dependency

import logging
log = logging.getLogger( __name__ )

DEFAULT_MODULECMD_PATH = "modulecmd"  # Just check path
DEFAULT_MODULE_PATH = '/usr/share/modules/modulefiles'
DEFAULT_INDICATOR = '(default)'
DEFAULT_MODULE_PREFETCH = "true"
UNKNOWN_FIND_BY_MESSAGE = "ModuleDependencyResolver does not know how to find modules by [%s], find_by should be one of %s"

class ModuleDependencyResolver(DependencyResolver):
    resolver_type = "modules"

    def __init__(self, dependency_manager, **kwds):
        self.versionless = _string_as_bool(kwds.get('versionless', 'false'))
        find_by = kwds.get('find_by', 'avail')
        prefetch = _string_as_bool(kwds.get('prefetch', DEFAULT_MODULE_PREFETCH))
        self.modulecmd = kwds.get('modulecmd', DEFAULT_MODULECMD_PATH)
        if find_by == 'directory':
            modulepath = kwds.get('modulepath', self.__default_modulespath())
            self.module_checker = DirectoryModuleChecker(self, modulepath, prefetch)
        elif find_by == 'avail':
            self.module_checker = AvailModuleChecker(self, prefetch)
        else:
            raise Exception(UNKNOWN_FIND_BY_MESSAGE % (find_by, ["avail", "directory"]))

    def __default_modulespath(self):
        if 'MODULEPATH' in environ:
            module_path = environ['MODULEPATH']
        elif 'MODULESHOME' in environ:
            module_path = join(environ['MODULESHOME'], 'modulefiles')
        else:
            module_path = DEFAULT_MODULE_PATH
        return module_path

    def resolve( self, name, version, type, **kwds ):
        if type != "package":
            return INDETERMINATE_DEPENDENCY

        if self.__has_module(name, version):
            return ModuleDependency(self, name, version)
        elif self.versionless and self.__has_module(name, None):
            return ModuleDependency(self, name, None)

        return INDETERMINATE_DEPENDENCY

    def __has_module(self, name, version):
        return self.module_checker.has_module(name, version)

class DirectoryModuleChecker(object):

    def __init__(self, module_dependency_resolver, modulepath, prefetch):
        self.module_dependency_resolver = module_dependency_resolver
        self.directories = modulepath.split(pathsep)
        if prefetch:
            log.warn("Created module dependency resolver with prefetch enabled, but directory module checker does not support this.")
            pass

    def has_module(self, module, version):
        has_module = False
        for directory in self.directories:
            module_directory = join(directory, module)
            has_module_directory = isdir( module_directory )
            if not version:
                has_module = has_module_directory or exists(module_directory)  # could be a bare modulefile
            else:
                modulefile = join(  module_directory, version )
                has_modulefile = exists( modulefile )
                has_module = has_module_directory and has_modulefile
            if has_module:
                break
        return has_module

class AvailModuleChecker(object):

    def __init__(self, module_dependency_resolver, prefetch):
        self.module_dependency_resolver = module_dependency_resolver
        if prefetch:
            prefetched_modules = []
            for module in self.__modules():
                prefetched_modules.append(module)
        else:
            prefetched_modules = None
        self.prefetched_modules = prefetched_modules

    def has_module(self, module, version):
        module_generator = self.prefetched_modules
        if module_generator is None:
            module_generator = self.__modules()

        for module_name, module_version in module_generator:
            names_match = module == module_name
            module_match = names_match and (version == None or module_version == version)
            if module_match:
                return True
        return False

    def __modules(self):
        raw_output = self.__module_avail_output()
        for line in StringIO(raw_output):
            line = line and line.strip()
            if not line or line.startswith("-"):
                continue

            line_modules = line.split()
            for module in line_modules:
                if module.endswith(DEFAULT_INDICATOR):
                    module = module[0:-len(DEFAULT_INDICATOR)].strip()
                module_parts = module.split('/')
                module_version = None
                if len(module_parts) == 2:
                    module_version = module_parts[1]
                module_name = module_parts[0]
                yield module_name, module_version

    def __module_avail_output(self):
        avail_command = [self.module_dependency_resolver.modulecmd, 'sh', 'avail']
        return Popen(avail_command, stderr=PIPE).communicate()[1]

class ModuleDependency(Dependency):

    def __init__(self, module_dependency_resolver, module_name, module_version=None):
        self.module_dependency_resolver = module_dependency_resolver
        self.module_name = module_name
        self.module_version = module_version

    def shell_commands(self, requirement):
        module_to_load = self.module_name
        if self.module_version:
            module_to_load = '%s/%s' % (self.module_name, self.module_version)
        command = 'eval `%s sh load %s`' % (self.module_dependency_resolver.modulecmd, module_to_load)
        return command

def _string_as_bool( value ):
    return str( value ).lower() == "true"

__all__ = [ModuleDependencyResolver]


text:
+++
title = "digest"
description = ""
weight = 10
+++

{{% processordetails digest %}}


text:
"""Test the workbench views."""

import functools
import json

import pytest
from web_fragments.fragment import Fragment
from webob import Response
from xblock.core import Scope, String, XBlock
from xblock.exceptions import DisallowedFileError
from xblock.runtime import NoSuchHandlerError

from django.test.client import Client
from django.urls import reverse

from workbench import scenarios
from workbench.runtime import ID_MANAGER

pytestmark = pytest.mark.django_db

def temp_scenario(temp_class, scenario_name='test_scenario'):
    """Create a temporary scenario that uses `temp_class`."""
    def _decorator(func):
        @functools.wraps(func)
        @XBlock.register_temp_plugin(temp_class)
        def _inner(*args, **kwargs):
            # Create a scenario, just one tag for our mocked class.
            scenarios.add_xml_scenario(
                scenario_name, f"Temporary scenario {temp_class.__name__}",
                "<%s/>" % temp_class.__name__
            )
            try:
                return func(*args, **kwargs)
            finally:
                scenarios.remove_scenario(scenario_name)
        return _inner
    return _decorator

class MultiViewXBlock(XBlock):
    """A bare-bone XBlock with two views."""
    def student_view(self, context=None):  # pylint: disable=W0613
        """A view, with the default name."""
        return Fragment("This is student view!")

    def another_view(self, context=None):  # pylint: disable=W0613
        """A secondary view for this block."""
        return Fragment("This is another view!")

def test_unknown_scenario():
    client = Client()

    response = client.get(reverse('scenario', args=('unknown_scenario', 'unknown_view')))
    assert response.status_code == 404

@temp_scenario(MultiViewXBlock, "multiview")
def test_multiple_views():
    client = Client()

    # The default view is student_view
    response = client.get("/view/multiview/")
    assert "This is student view!" in response.content.decode('utf-8')

    # We can ask for student_view directly
    response = client.get("/view/multiview/student_view/")
    assert "This is student view!" in response.content.decode('utf-8')

    # We can also ask for another view.
    response = client.get("/view/multiview/another_view/")
    assert "This is another view!" in response.content.decode('utf-8')

class XBlockWithHandlerAndStudentState(XBlock):
    """A bare-bone XBlock with one view and one json handler."""
    the_data = String(default="def", scope=Scope.user_state)

    def student_view(self, context=None):  # pylint: disable=W0613
        """Provide the default view."""
        body = "The data: %r." % self.the_data
        body += ":::%s:::" % self.runtime.handler_url(self, "update_the_data")
        return Fragment(body)

    @XBlock.json_handler
    def update_the_data(self, _data, suffix=''):  # pylint: disable=unused-argument
        """Mock handler that updates the student state."""
        self.the_data = self.the_data + "x"
        return {'the_data': self.the_data}

@temp_scenario(XBlockWithHandlerAndStudentState, 'testit')
def test_xblock_with_handler():
    # Tests an XBlock that provides a handler, and has some simple
    # student state
    client = Client()

    # Initially, the data is the default.
    response = client.get("/view/testit/")
    response_content = response.content.decode('utf-8')

    expected = "The data: %r." % "def"
    assert expected in response_content

    parsed = response_content.split(':::')
    assert len(parsed) == 3
    handler_url = parsed[1]

    # Now change the data.
    response = client.post(handler_url, "{}", "text/json")
    the_data = json.loads(response.content.decode('utf-8'))['the_data']
    assert the_data == "defx"

    # Change it again.
    response = client.post(handler_url, "{}", "text/json")
    the_data = json.loads(response.content.decode('utf-8'))['the_data']
    assert the_data == "defxx"

@temp_scenario(XBlock)
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick the most-recent usage ID just made in the temp_scenario setup...
    usage_id = ID_MANAGER.last_created_usage_id()

    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = reverse('handler', kwargs={
        'usage_id': usage_id,
        'handler_slug': 'does_not_exist',
        'suffix': ''
    }) + '?student=student_doesntexist'

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with pytest.raises(NoSuchHandlerError):
        client.post(handler_url, '{}', 'text/json')

@temp_scenario(XBlock)
def test_xblock_invalid_handler_url():
    # Test that providing an invalid handler url will give a 404
    # when we try to hit a handler on it
    client = Client()

    handler_url = "/handler/obviously/a/fake/handler"
    result = client.post(handler_url, '{}', 'text/json')
    assert result.status_code == 404

class XBlockWithHandlers(XBlock):
    """A XBlock with one json handler."""

    def student_view(self, context=None):               # pylint: disable=W0613
        """Returned content has handler urls."""
        all_args = [
            # Arguments for handler_url
            ("send_it_back",),
            ("send_it_back", "with_some_suffix"),
            ("send_it_back", "", "a=123"),
            ("send_it_back", "", "a=123&b=456&c=789"),
            ("send_it_back", "another_suffix", "a=123&b=456&c=789"),
            ("send_it_back_public",),
            ("send_it_back_public", "with_some_suffix"),
            ("send_it_back_public", "", "a=123"),
            ("send_it_back_public", "", "a=123&b=456&c=789"),
            ("send_it_back_public", "another_suffix", "a=123&b=456&c=789"),
        ]
        urls = []
        for args in all_args:
            thirdparty = (args[0] == "send_it_back_public")
            urls.append(self.runtime.handler_url(self, *args, thirdparty=thirdparty))
        encoded = json.dumps(urls)
        return Fragment(":::" + encoded + ":::")

    def try_bad_handler_urls(self, context=None):       # pylint: disable=W0613
        """Force some assertions for the wrong kinds of handlers."""
        # A completely non-existing function name.
        with pytest.raises(ValueError, match="function name"):
            self.runtime.handler_url(self, "this_doesnt_exist")

        # An existing function, but it isn't a handler.
        with pytest.raises(ValueError, match="handler name"):
            self.runtime.handler_url(self, "try_bad_handler_urls")

        return Fragment("Everything is Fine!")

    @XBlock.handler
    def send_it_back(self, request, suffix=''):
        """Just return the data we got."""
        assert self.scope_ids.user_id == "student_1"
        response_json = json.dumps({
            'suffix': suffix,
            'a': request.GET.get('a', "no-a"),
            'b': request.GET.get('b', "no-b"),
        })
        return Response(text=str(response_json), content_type='application/json')

    @XBlock.handler
    def send_it_back_public(self, request, suffix=''):
        """Just return the data we got."""
        assert self.scope_ids.user_id == "none"
        response_json = json.dumps({
            'suffix': suffix,
            'a': request.GET.get('a', "no-a"),
            'b': request.GET.get('b', "no-b"),
        })
        return Response(text=str(response_json), content_type='application/json')

@temp_scenario(XBlockWithHandlers, 'with-handlers')
def test_xblock_with_handlers():
    # Tests of handler urls.
    client = Client()

    # The view sends a list of URLs to try.
    response = client.get("/view/with-handlers/")
    parsed = response.content.decode('utf-8').split(':::')
    assert len(parsed) == 3
    urls = json.loads(parsed[1])

    # These have to correspond to the urls in XBlockWithHandlers.student_view above.
    expecteds = [
        {'suffix': '', 'a': 'no-a', 'b': 'no-b'},
        {'suffix': 'with_some_suffix', 'a': 'no-a', 'b': 'no-b'},
        {'suffix': '', 'a': '123', 'b': 'no-b'},
        {'suffix': '', 'a': '123', 'b': '456'},
        {'suffix': 'another_suffix', 'a': '123', 'b': '456'},
        {'suffix': '', 'a': 'no-a', 'b': 'no-b'},
        {'suffix': 'with_some_suffix', 'a': 'no-a', 'b': 'no-b'},
        {'suffix': '', 'a': '123', 'b': 'no-b'},
        {'suffix': '', 'a': '123', 'b': '456'},
        {'suffix': 'another_suffix', 'a': '123', 'b': '456'},
    ]

    for url, expected in zip(urls, expecteds):
        print(url)   # so we can see which one failed, if any.
        response = client.get(url)
        assert response.status_code == 200
        actual = json.loads(response.content.decode('utf-8'))
        assert actual == expected

@temp_scenario(XBlockWithHandlers, 'with-handlers')
def test_bad_handler_urls():
    client = Client()

    response = client.get("/view/with-handlers/try_bad_handler_urls/")
    assert response.status_code == 200
    assert "Everything is Fine!" in response.content.decode('utf-8')

class XBlockWithoutStudentView(XBlock):
    """
    Test WorkbechRuntime.render caught `NoSuchViewError` exception path
    """
    the_data = String(default="def", scope=Scope.user_state)

@temp_scenario(XBlockWithoutStudentView, 'xblockwithoutstudentview')
def test_xblock_no_student_view():
    # Try to get a response. Will try to render via WorkbenchRuntime.render;
    # since no view is provided in the XBlock, will return a Fragment that
    # indicates there is no view available.
    client = Client()
    response = client.get("/view/xblockwithoutstudentview/")
    assert 'No such view' in response.content.decode('utf-8')

def test_local_resources():
    client = Client()

    # The Equality block has local resources
    result = client.get('/resource/equality_demo/public/images/correct-icon.png')
    assert result.status_code == 200
    assert result['Content-Type'] == 'image/png'

    # The Equality block defends against malicious resource URIs
    # This test has two possible ways of passing
    # 1. We return a 404.
    # 2. We raise a DisallowedFileError.
    # The code currently uses path #1 (through an overly broad
    # try/except clause). This is the right behavior in prod,
    # but horrible for debugging. It is convenient to modify
    # dev versions of xblocks to give behavior #2, since it
    # provides meaningful errors. The code below is setup to
    # support both prod and dev configurations.
    try:
        result = client.get('/resource/equality_demo/core.py')
        assert result.status_code == 404
    except DisallowedFileError:
        pass

class XBlockWithContextTracking(XBlock):
    """
    Provide a test XBlock with context tracking
    """
    registered_contexts = []

    @classmethod
    def register_context(cls, context):
        """
        Register a class-level context
        """
        cls.registered_contexts.append(context)

    @classmethod
    def clear_contexts(cls):
        """
        Clear class-level contexts
        """
        cls.registered_contexts = []

    def student_view(self, context):
        """
        Render a student view with context
        """
        self.register_context(context)
        return Fragment()

@temp_scenario(XBlockWithContextTracking, 'context_tracking')
def test_activate_id():
    client = Client()
    assert XBlockWithContextTracking.registered_contexts == []  # precondition check
    client.get("/view/context_tracking/")
    assert XBlockWithContextTracking.registered_contexts == [{'activate_block_id': None}]

    client.get("/view/context_tracking/?activate_block_id=123")
    expected = [{'activate_block_id': None}, {'activate_block_id': '123'}]
    assert XBlockWithContextTracking.registered_contexts == expected

    XBlockWithContextTracking.clear_contexts()
    client.get("/view/context_tracking/?activate_block_id=456")
    assert XBlockWithContextTracking.registered_contexts == [{'activate_block_id': '456'}]

def test_user_list():
    client = Client()
    result = client.get("/userlist/")
    assert result.status_code == 200
    assert result.content.decode('utf-8') == "[]"


text:
/*
 * @author Valentin Simonov / http://va.lent.in/
 */

using TouchScript.Editor.Gestures.TransformGestures.Base;
using TouchScript.Gestures.TransformGestures;
using UnityEditor;
using UnityEngine;
using TouchScript.Editor.EditorUI;

namespace TouchScript.Editor.Gestures.TransformGestures
{
    [CustomEditor(typeof(PinnedTransformGesture), true)]
    internal class PinnedTransformGestureEditor : OnePointTransformGestureBaseEditor
    {

		public static readonly GUIContent TEXT_HELP = new GUIContent("This component recognizes a combination of rotation and scaling gestures on the GameObject if it was pinned to the world position.");

        protected override void OnEnable()
        {
			base.OnEnable();

            initCustomProjection();
        }

		protected override void drawBasic()
		{
			base.drawBasic();

            customProjection = drawProjection(customProjection);
		}

		protected override GUIContent getHelpText()
		{
			return TEXT_HELP;
		}

		protected override void drawOtherGUI()
		{
			var display = GUIElements.Header(TEXT_PROJECTION_HEADER, projectionProps);
			if (display)
			{
				EditorGUI.indentLevel++;
				customProjection = drawProjection(customProjection);
                EditorGUILayout.Space();
				EditorGUI.indentLevel--;
			}
		}

    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE617_Reachable_Assertion__fscanf_05.c
Label Definition File: CWE617_Reachable_Assertion.label.xml
Template File: sources-sink-05.tmpl.c
*/
/*
 * @description
 * CWE: 617 Reachable Assertion
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Number greater than ASSERT_VALUE
 * Sink:
 *    BadSink : Assert if n is less than or equal to ASSERT_VALUE
 * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse)
 *
 * */

#include "std_testcase.h"

#include <assert.h>

#define ASSERT_VALUE 5

/* The two variables below are not defined as "const", but are never
 * assigned any other value, so a tool should be able to identify that
 * reads of these will always return their initialized values.
 */
static int staticTrue = 1; /* true */
static int staticFalse = 0; /* false */

#ifndef OMITBAD

void CWE617_Reachable_Assertion__fscanf_05_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Read data from the console using fscanf() */
        fscanf(stdin, "%d", &data);
    }
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */
static void goodG2B1()
{
    int data;
    /* Initialize data */
    data = -1;
    if(staticFalse)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Use a value greater than the assert value */
        data = ASSERT_VALUE+1;
    }
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
    int data;
    /* Initialize data */
    data = -1;
    if(staticTrue)
    {
        /* FIX: Use a value greater than the assert value */
        data = ASSERT_VALUE+1;
    }
    /* POTENTIAL FLAW: this assertion could trigger if n <= ASSERT_VALUE */
    assert(data > ASSERT_VALUE);
}

void CWE617_Reachable_Assertion__fscanf_05_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE617_Reachable_Assertion__fscanf_05_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE617_Reachable_Assertion__fscanf_05_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using Malware.MDKServices;
using Malware.MDKUtilities;
using MDK.Views;
using Microsoft.VisualStudio.Shell;
using MDKOptionsControl = MDK.Views.Options.MDKOptionsControl;

namespace MDK.Services
{
    /// <summary>
    /// Options page for the MDK extension
    /// </summary>
    [CLSCompliant(false)]
    [ComVisible(true)]
    public class MDKOptions : UIElementDialogPage, INotifyPropertyChanged
    {
        string _gameBinPath;
        string _outputPath;
        bool _useManualGameBinPath;
        bool _useManualOutputPath;
        bool _notifyUpdates = true;
        bool _notifyPrereleaseUpdates;
        SpaceEngineers _spaceEngineers;
        bool _promoteMDK = true;
        bool _showBlueprintManagerOnDeploy = true;
        bool _trimTypes;
        string _lastSuppressedIdeVersionWarning;

        /// <summary>
        /// Creates an instance of <see cref="MDKOptions" />
        /// </summary>
        public MDKOptions()
        {
            _spaceEngineers = new SpaceEngineers();

            ((MDKOptionsControl)Child).Options = this;
            _gameBinPath = _spaceEngineers.GetInstallPath("Bin64");
            _outputPath = _spaceEngineers.GetDataPath("IngameScripts", "local");
        }

        /// <inheritdoc />
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Determines whether the extension is a prerelease version
        /// </summary>
        public bool IsPrerelease => MDKPackage.IsPrerelease;

        /// <summary>
        /// Gets the current package version
        /// </summary>
        public string Version =>  IsPrerelease? $"v{MDKPackage.Version}-pre" : $"v{MDKPackage.Version}";

        /// <summary>
        /// Determines whether <see cref="GameBinPath"/> should be used rather than the automatically retrieved one.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Use manual binary path")]
        [Description("If checked, use the manually specified binary path")]
        public bool UseManualGameBinPath
        {
            get => _useManualGameBinPath;
            set
            {
                if (_useManualGameBinPath == value)
                    return;
                _useManualGameBinPath = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// If <see cref="UseManualGameBinPath"/> is <c>true</c>, this value is used instead of the automatically retrieved path.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Space Engineers binary path")]
        [Description("A manual assignment of the path to the binary files of Space Engineers. Does not affect existing projects.")]
        public string GameBinPath
        {
            get => _gameBinPath;
            set
            {
                if (_gameBinPath == value)
                    return;
                _gameBinPath = value;
                if (string.IsNullOrWhiteSpace(_gameBinPath))
                    _gameBinPath = _spaceEngineers.GetInstallPath("Bin64");
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Determines whether <see cref="OutputPath"/> should be used rather than the automatically retrieved path.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Use manual output path")]
        [Description("If checked, use the manually specified output path")]
        public bool UseManualOutputPath
        {
            get => _useManualOutputPath;
            set
            {
                if (_useManualOutputPath == value)
                    return;
                _useManualOutputPath = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// If <see cref="UseManualOutputPath"/> is <c>true</c>, this value is used rather than the automatically retreived path.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Script Output Path")]
        [Description("A manual assignment of the path to the default output path for the final scripts. Does not affect existing projects.")]
        public string OutputPath
        {
            get => _outputPath;
            set
            {
                if (_outputPath == value)
                    return;
                _outputPath = value;
                if (string.IsNullOrWhiteSpace(_outputPath))
                    _outputPath = _spaceEngineers.GetDataPath("IngameScripts", "local");
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Whether script projects should default to generating minified scripts.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Trim Types")]
        [Description("Determines whether script projects should default to removing unused type definitions. Does not affect existing projects.")]
        public bool TrimTypes
        {
            get => _trimTypes;
            set
            {
                if (_trimTypes == value)
                    return;
                _trimTypes = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Whether script projects should default to generating minified scripts.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Promote MDK on thumbnail")]
        [Description("Whether to use a variant of the game's thumbnail which promotes MDK or the default game one.")]
        public bool PromoteMDK
        {
            get => _promoteMDK;
            set
            {
                if (_promoteMDK == value)
                    return;
                _promoteMDK = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Whether script projects should default to generating minified scripts.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Show script manager on deploy")]
        [Description("Whether the script manager is shown when a deployment is complete.")]
        public bool ShowBlueprintManagerOnDeploy
        {
            get => _showBlueprintManagerOnDeploy;
            set
            {
                if (_showBlueprintManagerOnDeploy == value)
                    return;
                _showBlueprintManagerOnDeploy = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// The visual studio version warning that should be suppressed.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("The last suppressed ide version warning")]
        [Description("Gets the last suppressed ide version warning, if the currently required warning is less than or equal to this, the warning will be shown.")]
        public string LastSuppressedIdeVersionWarning
        {
            get => _lastSuppressedIdeVersionWarning;
            set
            {
                if (_lastSuppressedIdeVersionWarning == value)
                    return;
                _lastSuppressedIdeVersionWarning = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Whether script projects should default to generating minified scripts.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Notify me about updates")]
        [Description("Checks for new releases on the GitHub repository, and shows a Visual Studio notification if a new version is detected.")]
        public bool NotifyUpdates
        {
            get => _notifyUpdates;
            set
            {
                if (_notifyUpdates == value)
                    return;
                _notifyUpdates = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Whether script projects should default to generating minified scripts.
        /// </summary>
        [Category("MDK/SE")]
        [DisplayName("Include prerelease versions")]
        [Description("Include prerelease versions when checking for new releases on the GitHub repository.")]
        public bool NotifyPrereleaseUpdates
        {
            get => _notifyPrereleaseUpdates;
            set
            {
                if (_notifyPrereleaseUpdates == value)
                    return;
                _notifyPrereleaseUpdates = value;
                OnPropertyChanged();
            }
        }

        /// <inheritdoc />
        protected sealed override UIElement Child { get; } = new MDKOptionsControl();

        /// <summary>
        /// Called when a trackable property changes.
        /// </summary>
        /// <param name="propertyName">The name of the changed property, or <c>null</c> to signify a global change.</param>
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// Returns the actual game bin path which should be used, taking all settings into account.
        /// </summary>
        /// <returns></returns>
        public string GetActualGameBinPath()
        {
            return UseManualGameBinPath ? GameBinPath : _spaceEngineers.GetInstallPath("Bin64");
        }

        /// <summary>
        /// Returns the actual output path which should be used, taking all settings into account.
        /// </summary>
        /// <returns></returns>
        public string GetActualOutputPath()
        {
            return UseManualOutputPath ? OutputPath : _spaceEngineers.GetDataPath("IngameScripts", "local");
        }
    }
}


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

<title>Uses of Package io.parallec.core.actor.message.type</title>
<meta name="date" content="2016-09-29">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
io.parallec.core.actor.message.type

Packages that use io.parallec.core.actor.message.type

Package
Description

io.parallec.core.actor.message.type

Actor message types.

Classes in io.parallec.core.actor.message.type used by io.parallec.core.actor.message.type

Class and Description

ExecutionManagerMsgType

The Enum ExecutionManagerMsgType.

OperationWorkerMsgType

The Enum OperationWorkerMsgType.

RequestWorkerMsgType

The Enum RequestWorkerMsgType.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.smartdevicelink.proxy.rpc;

import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCRequest;

import java.util.Hashtable;
import java.util.List;

/**
 * Updates the list of next maneuvers, which can be requested by the user pressing the softbutton "Turns" on the
 * Navigation base screen. Three softbuttons are predefined by the system: Up, Down, Close
 *
 *
Function Group: Navigation

 *
 *
HMILevel needs to be FULL, LIMITED or BACKGROUND

 *
 *
 * @since SmartDeviceLink 2.0
 * @see ShowConstantTbt
 */
public class UpdateTurnList extends RPCRequest{
    public static final String KEY_TURN_LIST = "turnList";
    public static final String KEY_SOFT_BUTTONS = "softButtons";

    /**
     * Constructs a new UpdateTurnList object
     */
    public UpdateTurnList() {
        super(FunctionID.UPDATE_TURN_LIST.toString());
    }

    /**
    *

    * Constructs a new UpdateTurnList object indicated by the Hashtable
    * parameter
    *

    *
    * @param hash
    *            The Hashtable to use
    */
    public UpdateTurnList(Hashtable<String, Object> hash) {
        super(hash);
    }

    /**
     * Sets a list of turns to be shown to the user
     *
     * @param turnList
     *            a List<Turn> value representing a list of turns to be shown to the user
     *

     *            Notes: Minsize=1; Maxsize=100

     */
    public void setTurnList(List<Turn> turnList){
        setParameters(KEY_TURN_LIST, turnList);
    }

    /**
     * Gets a list of turns to be shown to the user
     *
     * @return List<Turn> -a List value representing a list of turns
     */
    @SuppressWarnings("unchecked")
    public List<Turn> getTurnList(){
        return (List<Turn>) getObject(Turn.class, KEY_TURN_LIST);
    }

    /**
     * Gets the SoftButton List object
     *
     * @return List<SoftButton> -a List<SoftButton> representing the List object
     * @since SmartDeviceLink 2.0
     */
    @SuppressWarnings("unchecked")
    public List<SoftButton> getSoftButtons(){
        return (List<SoftButton>) getObject(SoftButton.class, KEY_SOFT_BUTTONS);
    }

    /**
     * Sets the SoftButtons
     *
     * @param softButtons
     *            a List<SoftButton> value
     *

     *            Notes:

     *

     *
If omitted on supported displays, the alert will not have any SoftButton

     *
ArrayMin: 0

     *
ArrayMax: 4

     *

     * @since SmartDeviceLink 2.0
     */

    public void setSoftButtons(List<SoftButton> softButtons){
        setParameters(KEY_SOFT_BUTTONS, softButtons);
    }

}


text:
package lang4.validator.core.wrapper;

import lang4.validator.core.Assertor;
import lang4.validator.core.Reason;

/**
 * 对数组中每个元素的某个字段进行断言
 *
 * @author xiezhenzong
 *
 */
public class Every extends BaseWrapper {

    private Object[] objArrayPool;

    public Every(Object[] objPool) {
        checkNullParameter(objPool, "EveryField require not null ObjPool parameter");
        this.objArrayPool = objPool;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> boolean doAssert(Assertor<T> assertor, Reason reason) {
        checkNullParameter(assertor, "decorator require not null assertor");
        if (objArrayPool.length == 0) {
            return true;
        }
        for (Object o : objArrayPool) {
            T t = (T) o;
            if (!assertor.doAssert(t)) {
                reason.append("Every assertor find illegal object, see detial: ");
                assertor.describe(t, reason);
                return false;
            }
        }
        return true;
    }

}


text:
LRJSML5 ;ALB/GTS - Lab Vista Hospital Location Pre-Patch Utilities;02/22/2010 14:51:41
 ;;5.2;LAB SERVICE;**425**;Sep 27, 1994;Build 30
 ;
 ;
INIT ;* init variables and list array
 ;Called from Protocol: LRJ SYS MAP HL SCHED AUDIT RPT DISP
 ;
 ; This API will show the HLCMS Audit Rpt Task schedule
 ;
 NEW LRFROM,LRTO
 SET (LRFROM,LRTO)=""
 DO GETDATE^LRJSML8(.LRFROM,.LRTO)
 D KILL
 IF (+LRFROM=0)!(+LRTO=0) DO
 .SET LRFROM=$P($G(^TMP("LRJ SYS USER MANAGER - DATES",$JOB)),"^")
 .SET LRTO=$P($G(^TMP("LRJ SYS USER MANAGER - DATES",$JOB)),"^",2)
 SET ^TMP("LRJ SYS USER MANAGER - DATES",$JOB)=LRFROM_"^"_LRTO
 D CREATRPT
 D HDR
 D REFRESH
 QUIT
 ;
REFRESH ;* refresh display
 D MSG^LRJSML
 SET VALMBCK="R"
 SET VALMBG=1
 QUIT
 ;
CREATRPT ;Create array of Hospital Location changes between selected dates
 N LRSCHED
 D OPTSTAT^XUTMOPT("LRJ SYS MAP HL TASKMAN RPT",.LRSCHED)
 D BLDREC(.LRSCHED) ;Create outarray
 Q
 ;
BLDREC(LRSCHED) ;Build Listman Output for background task
 ; INPUT:
 ;    LRSCHED : Schedule information about option
 ;              format -
 ;              task number^scheduled time^reschedule freq^special queuing flag
 ;
 NEW X,PCE,LROPTDAT
 DO KILL^VALM10()
 SET VALMCNT=0
 SET X=" Hospital Location Audit task schedule"
 DO ADD^LRJSMLU(.VALMCNT,X)
 DO CNTRL^VALM10(VALMCNT,2,$LENGTH(X)-1,IOUON,IOUOFF_IOINORM)
 D ADD^LRJSMLU(.VALMCNT," ")
 SET X="                    OPTION: LRJ SYS MAP HL TASKMAN RPT"
 D ADD^LRJSMLU(.VALMCNT,X)
 IF +$G(LRSCHED(1))=0 DO
 .SET X="                   TASK ID: Not Scheduled"
 .DO ADD^LRJSMLU(.VALMCNT,X)
 .SET X="QUEUED TO RUN AT WHAT TIME: Not Scheduled"
 .DO ADD^LRJSMLU(.VALMCNT,X)
 .SET X="    RESCHEDULING FREQUENCY: Not Scheduled"
 .DO ADD^LRJSMLU(.VALMCNT,X)
 ;
 IF +$G(LRSCHED(1))'=0 DO
 .SET PCE=0
 .FOR PCE=1:1:3 SET LROPTDAT=$P(LRSCHED(1),"^",PCE)  DO
 ..SET:PCE=1 X="                   TASK ID: "_$S(LROPTDAT'="":LROPTDAT,1:"Not Scheduled")
 ..IF PCE=2 DO
 ...NEW LROUTDT,Y
 ...SET Y=LROPTDAT
 ...DO DD^%DT
 ...SET LROUTDT=Y
 ...SET X="QUEUED TO RUN AT WHAT TIME: "_$S(LROUTDT'="":LROUTDT,1:"Not Scheduled")
 ..SET:PCE=3 X="    RESCHEDULING FREQUENCY: "_$S(LROPTDAT'="":LROPTDAT,1:"Not Scheduled")
 ..DO ADD^LRJSMLU(.VALMCNT,X)
 D ADD^LRJSMLU(.VALMCNT," ")
 D ADD^LRJSMLU(.VALMCNT," ")
 D ADD^LRJSMLU(.VALMCNT," ")
 D ADD^LRJSMLU(.VALMCNT," ")
 SET LROPTDAT=""
 SET LROPTDAT=$$GET^XPAR("SYS","LRJ HL LAST END DATE",1,"Q")
 SET X="Hospital Location Audit Automated Reporting begin Date: "_$S(LROPTDAT'="":$$FMTE^XLFDT(LROPTDAT),1:"Not indicated")
 DO ADD^LRJSMLU(.VALMCNT,X)
 QUIT
KILL ; -- kill off display data array
 KILL ^TMP("LRJ SYS MAP HL INIT MGR",$JOB)
 QUIT
 ;
HDR ; -- header code
 SET VALMHDR(1)="           LAB Hospital Location Change Audit Task Option Schedule"
 SET VALMHDR(2)="                         Version: "_$$VERNUM^LRJSMLU()_"     Build: "_$$BLDNUM^LRJSMLU()
 Q


text:
//#include "geode_includes.hpp"
#include "StructSet.hpp"
#include "SelectResultsIterator.hpp"
#include "ExceptionTypes.hpp"
#include "impl/SafeConvert.hpp"

using namespace System;

namespace Apache
{
  namespace Geode
  {
    namespace Client
    {

      generic<class TResult>
      bool StructSet<TResult>::IsModifiable::get( )
      {
        try
        {
          return m_nativeptr->get()->isModifiable( );
        }
        finally
        {
          GC::KeepAlive(m_nativeptr);
        }
      }

      generic<class TResult>
      System::Int32 StructSet<TResult>::Size::get( )
      {
        try
        {
          return m_nativeptr->get()->size( );
        }
        finally
        {
          GC::KeepAlive(m_nativeptr);
        }
      }

      generic<class TResult>
      TResult StructSet<TResult>::default::get( size_t index )
      {
        try
        {
          return Serializable::GetManagedValueGeneric<TResult>((m_nativeptr->get()->operator[](static_cast<System::Int32>(index))));
        }
        finally
        {
          GC::KeepAlive(m_nativeptr);
        }
      }

      generic<class TResult>
      SelectResultsIterator<TResult>^ StructSet<TResult>::GetIterator( )
      {
        try
        {
          return SelectResultsIterator<TResult>::Create(std::make_unique<apache::geode::client::SelectResultsIterator>(m_nativeptr->get()->getIterator()));
        }
        finally
        {
          GC::KeepAlive(m_nativeptr);
        }
      }

      generic<class TResult>
      System::Collections::Generic::IEnumerator<TResult>^ StructSet<TResult>::GetEnumerator( )
      {
        return GetIterator( );
      }

      generic<class TResult>
      System::Collections::IEnumerator^ StructSet<TResult>::GetIEnumerator( )
      {
        return GetIterator( );
      }

      generic<class TResult>
      size_t StructSet<TResult>::GetFieldIndex( String^ fieldName )
      {
        ManagedString mg_fieldName( fieldName );

        _GF_MG_EXCEPTION_TRY2/* due to auto replace */

          try
          {
            return m_nativeptr->get()->getFieldIndex( mg_fieldName.CharPtr );
          }
          finally
          {
            GC::KeepAlive(m_nativeptr);
          }

        _GF_MG_EXCEPTION_CATCH_ALL2/* due to auto replace */
      }

      generic<class TResult>
      String^ StructSet<TResult>::GetFieldName(size_t index)
      {
        try
        {
          return ManagedString::Get(m_nativeptr->get()->getFieldName(static_cast<System::Int32> (index)).c_str());
        }
        finally
        {
          GC::KeepAlive(m_nativeptr);
        }
      }
    }  // namespace Client
  }  // namespace Geode
}  // namespace Apache


text:
'use strict'

let app = require('koa')()
let router = require('koa-router')()
let cors = require('kcors')
let serve = require('koa-static')
let uuid = require('node-uuid')
let bodyParser = require('koa-bodyparser')
let server = require('http').Server(app.callback()),
  io = require('socket.io')(server)

// email DB stuff

const PouchDB = require('pouchdb')
PouchDB.plugin(require('pouchdb-find'))
PouchDB.plugin(require('pouchdb-upsert'))

require('pouchdb/extras/websql')

const emailDB = new PouchDB('./dbs/emails.db', {adapter: 'websql'})

emailDB.allDocs()
.then(function (result) {
  if (result.rows.length == 0) {
    emailDB.bulkDocs(getInitialMessages()).then(function (result) {
      getInitialMessages()
    }).catch(function (err) {
      console.log(err);
    })
  }
}).catch(function (err) {
  console.log(err);
})

let pageSize = 50

let sockets = []

app.use(cors())
app.use(bodyParser())

// use it in production
// app.use(serve('public'))

router.get('/api/emails', function *() {
  this.body = yield getInfo()
})

router.get('/api/emails/page/:number', function *() {
  let page = this.params.number
  let results = yield emailDB.allDocs({
    startkey: 'fractalplatform@gmail.com',
    descending: false,
    skip: (page - 1) * pageSize,
    limit: pageSize,
    include_docs: true,
  })
  this.body = results.rows.map(r => r.doc)
})

router.get('/api/emails/email/:uid', function *() {
  let results = yield emailDB.allDocs({
    startkey: 'fractalplatform@gmail.com/' + this.params.uid,
    descending: false,
    limit: 1,
    include_docs: true,
  })
  this.body = (results.rows[0]) ? results.rows[0].doc : 'notFound'
})

router.get('/api/emails/email/:uid/read', function *() {
  try {
    console.log(this.params.uid)
    let email = yield getEmail(this.params.uid)
    let res = yield emailDB.upsert(email._id, function(doc) {
      doc.state = 'read'
      return doc
    })
    console.log(res)
    if (sockets[0]) {
      sockets[0].emit('data', {key: 'info', value: yield getInfo()})
    }
    this.body = 'updated'
  } catch(e) {
    this.body = 'notFound'
  }
})

router.post('/api/emails/new', function *() {
  // TODO: use pouchDB
  // let newMessage = this.request.body
  // newMessage.uid = uuid.v4()
  // data.messages.push(newMessage)
  // this.body = newMessage
})

app
  .use(router.routes())
  .use(router.allowedMethods())

io.on('connection', function(socket) {
  console.log('Client connected')

  sockets.push(socket)
  socket.on('disconnect', function() {
    sockets.slice(sockets.indexOf(socket), 1)
  })
})

server.listen(process.env.PORT || 4000, process.env.IP || 'localhost', function() {
  console.log('Server listening...')
})

// data stuff
function getEmail(uid) {
  return emailDB.allDocs()
  .then(function(res) {
    try {
      let emailId = res.rows.filter(r => r.id.split('/')[2] === uid)[0].id
      return emailDB.get(emailId)
    } catch(e) {
      return Promise.reject('notFound')
    }
  })
}

function getInfo() {
  return emailDB.createIndex({index: {fields: ['state']}})
  .then(function() {
    return Promise.all([
      emailDB.find({selector: {state: {$eq: 'read'}}}),
      emailDB.find({selector: {state: {$eq: 'unread'}}})
    ]).then(function(res) {
      let numMessages = res[0].docs.length + res[1].docs.length
      return Promise.resolve({
        read: res[0].docs.length,
        unread: res[1].docs.length,
        pages: Math.floor(numMessages / pageSize) + 1,
      })
    })
  })
}

function generateId(ownerName, title) {
  return ownerName + '/' + (new Date()).toJSON() + '/' + uuid.v4()
}

function getInitialMessages() {

  let messages = [
    {
      title: 'Hello Fractal',
      sender: 'bryanlarson@google.com',
      content: 'My name is Bryan, I want to use your library. It is a very nice way to building apps!! so I am very excited about it!!',
      state: 'unread',
    },
    {
      title: 'Publish in my platform',
      sender: 'theblogger@gmail.com',
      content: 'I want to publish your library in my blog. I have some questions about, can we talk about Fractal via videocall?',
      state: 'unread',
    },
    {
      sender: 'fractalenthusiast@gmail.com',
      title: 'JS functional UIs',
      content: 'This is awesome!! It is simple and fast, thanks for that!!',
      state: 'unread',
    },
    {
      title: 'Give us consultory',
      sender: 'iamacto@startup.com',
      content: 'My name is Thomas, I am CTO of a web development enterprise. Can we talk about?',
      state: 'unread',
    },
  ]

  // generated messages
  for (let i = 0; i < 500; i++) {
    messages[i + 4] = {
      title: 'title ' + i,
      sender: 'bot' + i +'@bots.com',
      content: 'My name is Robot' + i + ', I am CTO of a Robot development enterprise. Can we talk about your library?',
      state: 'unread',
    }
  }

  for (let i = 0; i < messages.length; i++) {
    messages[i]._id = generateId('fractalplatform@gmail.com', messages[i].title.toLowerCase())
    sleep(2)
  }

  return messages
}

// helper method
function sleep(ms) {
  var start = new Date().getTime(), expire = start + ms;
  while (new Date().getTime() < expire) { }
  return;
}


text:
<?php

namespace Gecko\LegemdaryBundle\Entity;

use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;

class DiamondBidRequest extends Diamond
{
	protected $diamondBids;

	/**
	 * Constructor.
	 */
	public function __construct()
	{
		parent::__construct();

		$this->diamondBids = new ArrayCollection();
	}

	public function setDiamondBids(Collection $diamondBids)
	{
		$this->diamondBids = $diamondBids;

		return $this;
	}

	public function getDiamondBids()
	{
		return $this->diamondBids;
	}

	public function clearDiamondBids()
	{
		$this->diamondBids->clear();

		return $this;
	}

	public function countDiamondBids()
	{
		return $this->diamondBids->count();
	}

	public function addDiamondBid(DiamondBid $diamondBid)
	{
		if ($this->hasDiamondBid($diamondBid)) {
			return $this;
		}

		$diamondBid->setDiamondBidRequest($this);
		$this->diamondBids->add($diamondBid);

		return $this;
	}

	public function removeDiamondBid(DiamondBid $diamondBid)
	{
		if ($this->hasDiamondBid($diamondBid)) {
			$diamondBid->setDiamondBidRequest(null);
			$this->diamondBids->removeElement($diamondBid);
		}

		return $this;
	}

	public function hasDiamondBid(DiamondBid $diamondBid)
	{
		return $this->diamondBids->contains($diamondBid);
	}

	public function getDiamondBidByVendor($vendor)
	{
		foreach ($this->getDiamondBids() as $diamondBid)
		{
			if($diamondBid->getVendor()->getId() == $vendor->getId())
			{
				return $diamondBid;
			}
		}

		return null;
	}

	public function hasDiamondBidByVendor($vendor)
	{
		return ($this->getDiamondBidByVendor($vendor))?true:false;
	}

	public function getOldestBid()
	{
		$oldestBid = null;
		foreach($this->diamondBids as $diamondBid)
		{
			if(!$oldestBid)
			{
				$oldestBid = $diamondBid;
			}else {
				if($diamondBid->getCreatedAt() < $oldestBid->getCreatedAt())
				{
					$oldestBid = $diamondBid;
				}
			}
		}

		return $oldestBid;
	}

	public function getTimeLeft()
	{
		if($oldestBid = $this->getOldestBid())
		{
			$timeLeft = clone $oldestBid->getCreatedAt();
			return $timeLeft->modify('+ 2 days');
		}

		return 0;
	}

	public function isBidTimeout()
	{
		if($timeLeft = $this->getTimeLeft())
		{
			$now = new \DateTime('now');

			return ($now->getTimestamp() > $timeLeft->getTimestamp());
		}

		return false;
	}
}


text:
package com.linkedin.pinot.core.common;

public interface BlockDocIdIterator {
  /**
   * returns the currentDocId the iterator is currently pointing to, -1 if
   * next/advance is not yet called, EOF if the iteration has exhausted
   *
   * @return
   */
  int currentDocId();

  /**
   * advances to next document in the set and returns the nextDocId, EOF if
   * there are no more docs
   *
   * @return
   */
  int next();

  /**
   * Moves to first entry beyond current docId whose docId is equal or greater
   * than targetDocId
   * @param targetDocId
   * @return docId that is beyond current docId or EOF if no documents exists that is >= targetDocId
   */
  int advance(int targetDocId);

}


text:
package com.workplacesystems.queuj.process;

/**
 *
 * @author dave
 */
public interface ProcessRunner
{
    void doStart();

    void stop();

    boolean isSleeping();

    void doNotify();

    void doInterrupt();
}


text:
package com.example.user.movieproject.sync;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by USER on 10/3/2015.
 */
public class MovieSyncService extends Service {
    private static final Object syncAdapterLock = new Object();
    private static MovieSyncAdapter sSyncAdapter = null;

    @Override
    public void onCreate() {
        synchronized (syncAdapterLock){
            if (sSyncAdapter == null){
                sSyncAdapter = new MovieSyncAdapter(getApplicationContext(), true);
            }
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return sSyncAdapter.getSyncAdapterBinder();
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _reactAriaModal = require('react-aria-modal');

var _reactAriaModal2 = _interopRequireDefault(_reactAriaModal);

var _reactCssModules = require('react-css-modules');

var _reactCssModules2 = _interopRequireDefault(_reactCssModules);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactFocusTrap = require('react-focus-trap');

var _reactFocusTrap2 = _interopRequireDefault(_reactFocusTrap);

var _modal = require('./modal.css');

var _modal2 = _interopRequireDefault(_modal);

var _Button = require('../Button');

var _Button2 = _interopRequireDefault(_Button);

var _Icon = require('../Icon');

var _Icon2 = _interopRequireDefault(_Icon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Modal = function (_React$Component) {
  (0, _inherits3.default)(Modal, _React$Component);

  function Modal(props) {
    (0, _classCallCheck3.default)(this, Modal);

    var _this = (0, _possibleConstructorReturn3.default)(this, (Modal.__proto__ || (0, _getPrototypeOf2.default)(Modal)).call(this, props));

    _this.handleEnter = function () {
      _this.setState({
        entered: true
      });
    };

    _this.handleActive = function () {
      _this.setState({
        active: true
      });
    };

    _this.handleExit = function () {
      _this.setState({
        entered: false
      }, function () {
        setTimeout(function () {
          _this.setState({
            active: false
          });
        }, 300);
      });
    };

    var state = {
      active: false,
      entered: false
    };

    _this.state = state;
    return _this;
  }

  (0, _createClass3.default)(Modal, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          rootElementId = _props.rootElementId,
          title = _props.title,
          focusElementId = _props.focusElementId,
          underlayClickExits = _props.underlayClickExits,
          alert = _props.alert,
          buttonChild = _props.buttonChild,
          isCard = _props.isCard,
          buttonClass = _props.buttonClass,
          buttonProps = _props.buttonProps,
          closeModal = _props.closeModal,
          openModal = _props.openModal,
          mounted = _props.mounted;

      var extras = {
        focusDialog: !focusElementId
      };

      var underlayClass = _modal2.default['modal-underlay'];
      var dialogContentClass = 'modal modal-animated';
      var closeIconClass = 'modal-close-icon';

      if (mounted || this.state.entered) {
        dialogContentClass += ' has-entered';
        underlayClass += ' ' + _modal2.default['has-entered'];
      }

      if (isCard) {
        closeIconClass += ' has-card';
        dialogContentClass += ' modal-card';
      }

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          _Button2.default,
          (0, _extends3.default)({
            type: 'primary',
            className: buttonClass,
            onClick: openModal ? openModal : this.handleActive
          }, buttonProps),
          buttonChild
        ),
        _react2.default.createElement(
          _reactAriaModal2.default,
          (0, _extends3.default)({}, extras, {
            titleText: title,
            underlayClickExits: underlayClickExits,
            mounted: mounted ? mounted : this.state.active,
            onEnter: openModal ? openModal : this.handleEnter,
            onExit: closeModal ? closeModal : this.handleExit,
            applicationNode: document.getElementById(rootElementId),
            underlayClass: underlayClass,
            underlayColor: false,
            initialFocus: '#close-modal',
            alert: alert,
            focusTrapPaused: true
          }),
          _react2.default.createElement(
            _reactFocusTrap2.default,
            null,
            _react2.default.createElement(
              'div',
              { styleName: dialogContentClass },
              _react2.default.createElement(
                'button',
                {
                  id: 'close-modal',
                  'aria-label': 'Close Dialog Box',
                  onClick: closeModal ? closeModal : this.handleExit,
                  styleName: closeIconClass
                },
                _react2.default.createElement(_Icon2.default, { name: 'close' })
              ),
              children
            )
          )
        )
      );
    }
  }]);
  return Modal;
}(_react2.default.Component);

exports.default = (0, _reactCssModules2.default)(Modal, _modal2.default, { allowMultiple: true });


text:
package org.butterfaces.component.showcase.text;

import org.butterfaces.component.showcase.AbstractInputShowcase;
import org.butterfaces.component.showcase.example.AbstractCodeExample;
import org.butterfaces.component.showcase.example.JavaCodeExample;
import org.butterfaces.component.showcase.example.XhtmlCodeExample;
import org.butterfaces.component.showcase.text.example.TextAutoTrimWebXmlExample;
import org.butterfaces.component.showcase.type.StyleClass;
import org.butterfaces.model.tree.EnumTreeBoxWrapper;
import org.butterfaces.util.StringUtils;
import org.butterfaces.component.showcase.example.AbstractCodeExample;
import org.butterfaces.component.showcase.example.JavaCodeExample;
import org.butterfaces.component.showcase.example.XhtmlCodeExample;
import org.butterfaces.component.showcase.text.example.TextAutoTrimWebXmlExample;
import org.butterfaces.component.showcase.type.StyleClass;
import org.butterfaces.util.StringUtils;

import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Named
@ViewScoped
@SuppressWarnings("serial")
public class TextShowcase extends AbstractInputShowcase implements Serializable {

    private FacetType selectedFacetType = FacetType.NONE;
    private String placeholder = DEFAULT_TEXT_PLACEHOLDER;
    private String type;
    private String pattern;
    private String min;
    private String max;
    private boolean autoFocus;
    private boolean useConverter;

    @Override
    protected Object initValue() {
        return null;
    }

    @Override
    public String getReadableValue() {
        if (this.getValue() != null) {
            return this.getValue().toString();
        }

        return "";
    }

    @Override
    public void buildCodeExamples(final List<AbstractCodeExample> codeExamples) {
        final XhtmlCodeExample xhtmlCodeExample = this.createXhtmlCodeExample();

        codeExamples.add(xhtmlCodeExample);
        codeExamples.add(createMyBeanCodeExample());
        if (useConverter) {
            codeExamples.add(createUrlConverterCodeExample());
            codeExamples.add(createUrlBookmarkCodeExample());
        }

        generateDemoCSS(codeExamples);
        codeExamples.add(new TextAutoTrimWebXmlExample());
    }

    private XhtmlCodeExample createXhtmlCodeExample() {
        final XhtmlCodeExample xhtmlCodeExample = new XhtmlCodeExample(false);

        xhtmlCodeExample.appendInnerContent("        <b:text id=\"input\"");
        xhtmlCodeExample.appendInnerContent("                label=\"" + this.getLabel() + "\"");
        xhtmlCodeExample.appendInnerContent("                hideLabel=\"" + isHideLabel() + "\"");
        xhtmlCodeExample.appendInnerContent("                value=\"#{myBean.value}\"");
        xhtmlCodeExample.appendInnerContent("                placeholder=\"" + this.getPlaceholder() + "\"");
        xhtmlCodeExample.appendInnerContent("                type=\"" + this.getType() + "\"");
        xhtmlCodeExample.appendInnerContent("                pattern=\"" + this.getPattern() + "\"");
        xhtmlCodeExample.appendInnerContent("                min=\"" + this.getMin() + "\"");
        xhtmlCodeExample.appendInnerContent("                max=\"" + this.getMax() + "\"");
        if (this.getStyleClass() == StyleClass.BIG_LABEL) {
            xhtmlCodeExample.appendInnerContent("                styleClass=\"" + this.getSelectedStyleClass() + "\"");
        }
        xhtmlCodeExample.appendInnerContent("                readonly=\"" + this.isReadonly() + "\"");
        xhtmlCodeExample.appendInnerContent("                required=\"" + this.isRequired() + "\"");
        xhtmlCodeExample.appendInnerContent("                disabled=\"" + this.isDisabled() + "\"");
        xhtmlCodeExample.appendInnerContent("                autoFocus=\"" + this.isAutoFocus() + "\"");
        xhtmlCodeExample.appendInnerContent("                rendered=\"" + this.isRendered() + "\">");

        this.addAjaxTag(xhtmlCodeExample, "keyup");

        if (this.isValidation()) {
            xhtmlCodeExample.appendInnerContent("            <f:validateLength minimum=\"2\" maximum=\"10\"/>");
        }

        if (StringUtils.isNotEmpty(getTooltip())) {
            xhtmlCodeExample.appendInnerContent("            ");
            xhtmlCodeExample.appendInnerContent("                " + getTooltip());
            xhtmlCodeExample.appendInnerContent("            ");
        }

        if (useConverter) {
            xhtmlCodeExample.appendInnerContent("            <f:converter converterId=\"urlConverter\" />");
        }

        if (selectedFacetType == FacetType.INPUT_GROUP_ADDON) {
            xhtmlCodeExample.appendInnerContent("            <f:facet name=\"input-group-addon-left\">");
            xhtmlCodeExample.appendInnerContent("                Left input-group-addon");
            xhtmlCodeExample.appendInnerContent("            </f:facet>");
            xhtmlCodeExample.appendInnerContent("            <f:facet name=\"input-group-addon-right\">");
            xhtmlCodeExample.appendInnerContent("                Right input-group-addon");
            xhtmlCodeExample.appendInnerContent("            </f:facet>");
        } else if (selectedFacetType == FacetType.INPUT_GROUP_BTN) {
            xhtmlCodeExample.appendInnerContent("            <f:facet name=\"input-group-btn-left\">");
            xhtmlCodeExample.appendInnerContent("                <button type=\"button\" class=\"btn btn-outline-secondary\">");
            xhtmlCodeExample.appendInnerContent("                     Go!");
            xhtmlCodeExample.appendInnerContent("                 </button>");
            xhtmlCodeExample.appendInnerContent("            </f:facet>");
            xhtmlCodeExample.appendInnerContent("            <f:facet name=\"input-group-btn-right\">");
            xhtmlCodeExample.appendInnerContent("                <button type=\"button\" class=\"btn btn-outline-secondary\"");
            xhtmlCodeExample.appendInnerContent("                        dropdown-toggle\"");
            xhtmlCodeExample.appendInnerContent("                        data-toggle=\"dropdown\"");
            xhtmlCodeExample.appendInnerContent("                        aria-expanded=\"false\">");
            xhtmlCodeExample.appendInnerContent("                     Action ");
            xhtmlCodeExample.appendInnerContent("                 </button>");
            xhtmlCodeExample.appendInnerContent("
");
            xhtmlCodeExample.appendInnerContent("
Action
");
            xhtmlCodeExample.appendInnerContent("
Another action
");
            xhtmlCodeExample.appendInnerContent("
Something else here
");
            xhtmlCodeExample.appendInnerContent("

");
            xhtmlCodeExample.appendInnerContent("
Separated link
");
            xhtmlCodeExample.appendInnerContent("
");
            xhtmlCodeExample.appendInnerContent("            </f:facet>");
        }

        xhtmlCodeExample.appendInnerContent("        ", false);

        this.addOutputExample(xhtmlCodeExample);

        return xhtmlCodeExample;
    }

    private JavaCodeExample createMyBeanCodeExample() {
        final JavaCodeExample myBean = new JavaCodeExample("MyBean.java", "myBean", "text.demo", "MyBean", true);

        if (useConverter) {
            myBean.appendInnerContent("   private URLBookmark value;\n");
            myBean.appendInnerContent("   public URLBookmark getValue() {");
            myBean.appendInnerContent("       return value;");
            myBean.appendInnerContent("   }");
            myBean.appendInnerContent("   public void setValue(URLBookmark value) {");
            myBean.appendInnerContent("       this.value = value;");
            myBean.appendInnerContent("   }");
        } else {
            myBean.appendInnerContent("   private String value;\n");
            myBean.appendInnerContent("   public String getValue() {");
            myBean.appendInnerContent("       return value;");
            myBean.appendInnerContent("   }");
            myBean.appendInnerContent("   public void setValue(String value) {");
            myBean.appendInnerContent("       this.value = value;");
            myBean.appendInnerContent("   }");
        }

        return myBean;
    }

    private JavaCodeExample createUrlBookmarkCodeExample() {
        final JavaCodeExample myBean = new JavaCodeExample("URLBookmark.java", "uRLBookmark", "text.demo", "URLBookmark", false);

        myBean.appendInnerContent("   private String fullURL;\n");
        myBean.appendInnerContent("   public URLBookmark(String fullURL) {");
        myBean.appendInnerContent("       this.fullURL = fullURL;");
        myBean.appendInnerContent("   }");
        myBean.appendInnerContent("   public String getFullURL() {");
        myBean.appendInnerContent("       return fullURL;");
        myBean.appendInnerContent("   }");
        myBean.appendInnerContent("   public void setFullURL(String fullURL) {");
        myBean.appendInnerContent("       this.fullURL = fullURL;");
        myBean.appendInnerContent("   }");
        myBean.appendInnerContent("   public String toString(){");
        myBean.appendInnerContent("       return fullURL;");
        myBean.appendInnerContent("   }");

        return myBean;
    }

    private JavaCodeExample createUrlConverterCodeExample() {
        final JavaCodeExample myBean = new JavaCodeExample("UrlConverter.java", "urlConverter", "text.demo", "UrlConverter", false, "@FacesConverter(\"urlConverter\")");

        myBean.addImport("org.apache.commons.validator.routines.UrlValidator");
        myBean.addImport("\njavax.faces.application.FacesMessage");
        myBean.addImport("javax.faces.component.UIComponent");
        myBean.addImport("javax.faces.context.FacesContext");
        myBean.addImport("javax.faces.convert.Converter");
        myBean.addImport("javax.faces.convert.ConverterException");
        myBean.addImport("javax.faces.convert.FacesConverter");

        myBean.addInterfaces("Converter");

        myBean.appendInnerContent("   public static final String HTTP = \"http://\";\n");
        myBean.appendInnerContent("   @Override");
        myBean.appendInnerContent("   public Object getAsObject(final FacesContext context,");
        myBean.appendInnerContent("                             final UIComponent component,");
        myBean.appendInnerContent("                             final String value) {");
        myBean.appendInnerContent("      final StringBuilder url = new StringBuilder();\n");
        myBean.appendInnerContent("      this.appendHttpIfNecessary(value, url);\n");
        myBean.appendInnerContent("      //use Apache common URL validator to validate URL");
        myBean.appendInnerContent("      if(!new UrlValidator().isValid(url.toString())){");
        myBean.appendInnerContent("          final FacesMessage msg = new FacesMessage(\"URL Conversion error.\", \"Invalid URL format.\");");
        myBean.appendInnerContent("          msg.setSeverity(FacesMessage.SEVERITY_ERROR);");
        myBean.appendInnerContent("          throw new ConverterException(msg);");
        myBean.appendInnerContent("      }\n");
        myBean.appendInnerContent("      return new URLBookmark(url.toString());");
        myBean.appendInnerContent("   }\n");
        myBean.appendInnerContent("   @Override");
        myBean.appendInnerContent("   public String getAsString(final FacesContext context,");
        myBean.appendInnerContent("                             final UIComponent component,");
        myBean.appendInnerContent("                             final Object value) {");
        myBean.appendInnerContent("      return value.toString();");
        myBean.appendInnerContent("   }\n");
        myBean.appendInnerContent("   private void appendHttpIfNecessary(final String value,");
        myBean.appendInnerContent("                                      final StringBuilder url) {");
        myBean.appendInnerContent("      if(!value.startsWith(HTTP, 0)){");
        myBean.appendInnerContent("          url.append(HTTP);");
        myBean.appendInnerContent("      }");
        myBean.appendInnerContent("      url.append(value);");
        myBean.appendInnerContent("   }");

        return myBean;
    }

    public void someListenerAction(AjaxBehaviorEvent event) {

    }

    public List<EnumTreeBoxWrapper> getAvailableFacetTypes() {
        final List<EnumTreeBoxWrapper> items = new ArrayList<>();

        for (final FacetType type : FacetType.values()) {
            items.add(new EnumTreeBoxWrapper(type, type.label));
        }
        return items;
    }

    public String getPlaceholder() {
        return this.placeholder;
    }

    public void setPlaceholder(final String placeholder) {
        this.placeholder = placeholder;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public boolean isAutoFocus() {
        return autoFocus;
    }

    public void setAutoFocus(boolean autoFocus) {
        this.autoFocus = autoFocus;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getMin() {
        return min;
    }

    public void setMin(String min) {
        this.min = min;
    }

    public String getMax() {
        return max;
    }

    public void setMax(String max) {
        this.max = max;
    }

    public FacetType getSelectedFacetType() {
        return selectedFacetType;
    }

    public void setSelectedFacetType(FacetType selectedFacetType) {
        this.selectedFacetType = selectedFacetType;
        if (this.selectedFacetType != FacetType.NONE) {
            this.useConverter = false;
        }
    }

    public boolean isUseConverter() {
        return useConverter;
    }

    public void setUseConverter(boolean useConverter) {
        this.useConverter = useConverter;
        this.selectedFacetType = FacetType.NONE;
    }
}


text:
#ifndef	PARSER_HPP
#define	PARSER_HPP

/****************************************************************************
*
* Created:  7/20/98
*
*****************************************************************************
*
* File Name:		Parser.hpp
* Module:
* Contributors:		Lee Page
* Description:		This class is an object factory that accepts a command-line string
					in.  Then it creates a an array of objects, one per command.
					This array can then be fetched and executed.
* Version Control:
*
* $Revision$
* $NoKeywords: $
* $Log$
* Revision 1.1.1.1  2004-04-29 10:20:14  bap
* Imported upstream version 0.0.4.
*
*****************************************************************************/

/*** INCLUDES ***/
#include "cmdlist.hpp"
#include "creatrad.hpp"
#include "scsilist.hpp"
#include "intlist.hpp"
/*** CONSTANTS ***/
/*** TYPES ***/
/*** STATIC DATA ***/
/*** MACROS ***/
/*** PROTOTYPES ***/
/*** FUNCTIONS ***/
class Parser
	{
	public:
		Parser(
			char	*command_Line,
			bool	*quiet_Mode_Ptr		// A pointer to the quiet mode boolean
			);
		virtual	~Parser();

		Command_List	&get_Command_List();

	private:
/*		static const unsigned long	RAID_0_DEFAULT_STRIPE_SIZE;
		static const unsigned long	RAID_1_DEFAULT_STRIPE_SIZE;
		static const unsigned long	RAID_5_DEFAULT_STRIPE_SIZE;
*/		static const unsigned long	BLOCK_SIZE;
		// a structure used in the retrieving of a constant associated with a string.
		struct str_to_Const_Struct
			{
			char	*str;		// this is the string that is associated with the
								// constant
			int		constant;
			};
		char		*Extract_Command( char *this_Commands_Text, char *buffer );
		char		*Extract_Word( char *str, char *word );
      char     *TranslateNext (char *str, int *retVal);
		char		*Skip_White( char *str );
		char		*Skip_Non_White( char *str );
		char		*Skip_Non_Word( char *str );
		char		*Skip_Word( char *str );
		static void	To_Lower( char *str );
		static int	StrICmp(
						const char *str1,
						const char *str2
 						);
		void	Reset_Params_to_Defaults();
		void	Error_in_Parsing(
					char	*error_Str,
					char	*this_Command_Line
					);
		int	Str_to_Constant(
				char				*str_to_Match,	// this is the string the user supplies
				str_to_Const_Struct *str_to_Const 	// this is an array in which we have
													// to match the string the user supplies
				);
		Int_List	*Get_Int_List(
							char	*int_Str,				// pointer to a list of comma
															// delimited constants
							char	**end_Ptr,				// this will be set to point
															// to the end of the parsed list
							char	*this_Commands_Text,	// this is the whole command,
															// used to create a context-based
															// error string when the command fails
							bool	*done					// set true when an error is
															// detected
							);
		char *			Get_Address(
							char    *address_Str,			// pointer to an address
							SCSI_Address * component
						);
		SCSI_Addr_List	*Get_Address_List(
							char	*address_Str,			// pointer to a list of comma
															// delimited constants
							char	**end_Ptr,				// this will be set to point
															// to the end of the parsed list
							char	*this_Commands_Text,	// this is the whole command,
															// used to create a context-based
															// error string when the command fails
							bool	*done					// set true when an error is
															// detected
							);

		Command_List	*cmd_List;
		bool			*quiet_Mode;
		// the "..._Specified" bool is intended to aid in parameter checking to make
		// sure that mandatory parameters are used, else the command invocation fails.
		struct Parameters
			{
			bool					hba_Num_Specified;
			int						hba_Num;

			bool					hba_Bus_Specified;
			int						hba_Bus;

			bool					unix_Style_Hba_Num_Specified;
			char					*unix_Style_Hba_Num;

			bool					raid_Type_Specified;
			Create_Raid::Raid_Type	raid_Type;

			bool					stripe_Size_Specified;
			unsigned long		    stripe_Size;

			bool					task_Rate_Specified;
			int						task_Rate;

			// this is 1024 x 1024
			bool					logical_Drive_Capacity_in_Megs_Specified;
			unsigned long			logical_Drive_Capacity_in_Megs;

			Int_List				*logical_Drive_Number;
			} params;
	};

#endif
/*** END OF FILE ***/


text:
namespace Google.Cloud.DataCatalog.V1.Snippets
{
    // [START datacatalog_v1_generated_DataCatalog_DeleteTagTemplate_async_flattened_resourceNames]
    using Google.Cloud.DataCatalog.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDataCatalogClientSnippets
    {
        /// <summary>Snippet for DeleteTagTemplateAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task DeleteTagTemplateResourceNamesAsync()
        {
            // Create client
            DataCatalogClient dataCatalogClient = await DataCatalogClient.CreateAsync();
            // Initialize request argument(s)
            TagTemplateName name = TagTemplateName.FromProjectLocationTagTemplate("[PROJECT]", "[LOCATION]", "[TAG_TEMPLATE]");
            bool force = false;
            // Make the request
            await dataCatalogClient.DeleteTagTemplateAsync(name, force);
        }
    }
    // [END datacatalog_v1_generated_DataCatalog_DeleteTagTemplate_async_flattened_resourceNames]
}


text:
@class MISSING_TYPE;

@interface _TtC12SourceEditorP33_16A4144E11761DD62349E8D325DE8ECB36PlaceholderVisualizationColorManager : _TtCs12_SwiftObject
{
    MISSING_TYPE *inactiveBackgroundColorCacher;
    MISSING_TYPE *activeBackgroundColorCacher;
    MISSING_TYPE *altTokenBackgroundColorCacher;
}

- (void)systemColorsDidChangeNotification;

@end


text:
#if defined(LINUX)

#include <sys/types.h>
#include <string.h>

/*
 * Copy src to string dst of size siz.  At most siz-1 characters
 * will be copied.  Always NUL terminates (unless siz == 0).
 * Returns strlen(src); if retval >= siz, truncation occurred.
 */
size_t strlcpy(char *dst, const char *src, size_t siz) {
	register char *d = dst;
	register const char *s = src;
	register size_t n = siz;

	/* Copy as many bytes as will fit */
	if (n != 0 && --n != 0) {
		do {
			if ((*d++ = *s++) == 0)
				break;
		} while (--n != 0);
	}

	/* Not enough room in dst, add NUL and traverse rest of src */
	if (n == 0) {
		if (siz != 0)
			*d = '\0';		/* NUL-terminate dst */
		while (*s++)
			;
	}

	return(s - src - 1);	/* count does not include NUL */
}

#else
typedef int _translation_declaration;
#endif // LINUX


text:
extern int mvsmr_init_fpga(void);

extern int fpga_pgm_fn(int assert_pgm, int flush, int cookie);
extern int fpga_init_fn(int cookie);
extern int fpga_clk_fn(int assert_clk, int flush, int cookie);
extern int fpga_wr_fn(int assert_write, int flush, int cookie);
extern int fpga_done_fn(int cookie);
extern int fpga_pre_config_fn(int cookie);


text:
package cn.bishiti.base.test.DesignPattern.abstractFactory;

public class SmsSender implements Sender{

	@Override
	public void send() {
		// TODO Auto-generated method stub
		System.out.println("sms send.");
	}

}


text:
<!--
Copyright (C) 2015 The Android Open Source Project

   Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24.0dp"
        android:height="24.0dp"
        android:viewportWidth="48.0"
        android:viewportHeight="48.0">
    <path
        android:fillColor="#ffffffff"
        android:pathData="M12 38c0 2.21 1.79 4 4 4h16c2.21 0 4,-1.79 4,-4V14H12v24zM38 8h-7l-2,-2H19l-2 2h-7v4h28V8z"/>
</vector>


text:
import unittest

from flask import Flask
from flask.ext.twisted import Twisted

class TestTwisted(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_app_run(self):
        app = Flask(__name__)
        twisted = Twisted()
        self.assertNotEqual(twisted.run, app.run)
        twisted.init_app(app)
        self.assertEqual(twisted.run, app.run)

        app = Flask(__name__)
        twisted = Twisted(app)
        self.assertEqual(twisted.run, app.run)

    def test_run_trigger(self):
        app = Flask(__name__)
        twisted = Twisted(app)

        @twisted.on('run')
        def on_run(_app):
            self.assertEqual(app, _app)

        self.assertTrue('run' in twisted.events and twisted.events['run'])

        app.run(host='127.0.0.1', port=5000, run_reactor=False)
        twisted.run(host='127.0.0.1', port=5001, run_reactor=False)
        twisted.run_simple(app=app, host='127.0.0.1', port=5002, run_reactor=False)

if __name__ == '__main__':
    unittest.main()