answer
stringlengths 15
1.25M
|
|---|
package ie.cit.caf.repository;
import ie.cit.caf.domain.Role;
import java.util.List;
public interface RoleRepository {
public Role get (int id);
public void save (Role role);
public void remove (Role role);
public List<Role> findAll();
public Role checkIfExist(int id);
}
|
<?php
use Hubzero\Content\Migration\Base;
// No direct access
defined('_HZEXEC_') or die();
/**
* Migration script to add access column to products table
**/
class <API key> extends Base
{
public function up()
{
if ($this->db->tableExists('#<API key>') && !$this->db->tableHasField('#<API key>', 'access'))
{
$query = "ALTER TABLE `#<API key>` ADD `access` tinyint(3) NOT NULL DEFAULT '0'";
$this->db->setQuery($query);
$this->db->query();
}
}
/**
* Down
**/
public function down()
{
if ($this->db->tableExists('#<API key>') && $this->db->tableHasField('#<API key>', 'access'))
{
$query = "ALTER TABLE `#<API key>` DROP COLUMN `access`";
$this->db->setQuery($query);
$this->db->query();
}
}
}
|
require 'test_helper'
module SessionTest
module CookiesTest
class ConfiTest < ActiveSupport::TestCase
def test_cookie_key
UserSession.cookie_key = "my_cookie_key"
assert_equal "my_cookie_key", UserSession.cookie_key
UserSession.cookie_key "user_credentials"
assert_equal "user_credentials", UserSession.cookie_key
end
def <API key>
assert_equal "user_credentials", UserSession.cookie_key
assert_equal "<API key>", <API key>.cookie_key
end
def test_remember_me
UserSession.remember_me = true
assert_equal true, UserSession.remember_me
session = UserSession.new
assert_equal true, session.remember_me
UserSession.remember_me false
assert_equal false, UserSession.remember_me
session = UserSession.new
assert_equal false, session.remember_me
end
def <API key>
UserSession.remember_me_for = 3.years
assert_equal 3.years, UserSession.remember_me_for
session = UserSession.new
session.remember_me = true
assert_equal 3.years, session.remember_me_for
UserSession.remember_me_for 3.months
assert_equal 3.months, UserSession.remember_me_for
session = UserSession.new
session.remember_me = true
assert_equal 3.months, session.remember_me_for
end
def test_secure
UserSession.secure = true
assert_equal true, UserSession.secure
session = UserSession.new
assert_equal true, session.secure
UserSession.secure false
assert_equal false, UserSession.secure
session = UserSession.new
assert_equal false, session.secure
end
def test_httponly
UserSession.httponly = true
assert_equal true, UserSession.httponly
session = UserSession.new
assert_equal true, session.httponly
UserSession.httponly false
assert_equal false, UserSession.httponly
session = UserSession.new
assert_equal false, session.httponly
end
def test_sign_cookie
UserSession.sign_cookie = true
assert_equal true, UserSession.sign_cookie
session = UserSession.new
assert_equal true, session.sign_cookie
UserSession.sign_cookie false
assert_equal false, UserSession.sign_cookie
session = UserSession.new
assert_equal false, session.sign_cookie
end
end
class InstanceMethodsTest < ActiveSupport::TestCase
def test_credentials
session = UserSession.new
session.credentials = {:remember_me => true}
assert_equal true, session.remember_me
end
def test_remember_me
session = UserSession.new
assert_equal false, session.remember_me
assert !session.remember_me?
session.remember_me = false
assert_equal false, session.remember_me
assert !session.remember_me?
session.remember_me = true
assert_equal true, session.remember_me
assert session.remember_me?
session.remember_me = nil
assert_nil session.remember_me
assert !session.remember_me?
session.remember_me = "1"
assert_equal "1", session.remember_me
assert session.remember_me?
session.remember_me = "true"
assert_equal "true", session.remember_me
assert session.remember_me?
end
def <API key>
session = UserSession.new
assert_nil session.remember_me_until
session.remember_me = true
assert 3.months.from_now <= session.remember_me_until
end
def <API key>
ben = users(:ben)
assert !UserSession.find
set_cookie_for(ben)
assert session = UserSession.find
assert_equal ben, session.record
end
def <API key>
ben = users(:ben)
session = UserSession.new(ben)
session.remember_me = true
assert session.save
assert !session.remember_me_expired?
session = UserSession.new(ben)
session.remember_me = false
assert session.save
assert !session.remember_me_expired?
end
def <API key>
ben = users(:ben)
session = UserSession.new(ben)
assert session.save
assert_equal "#{ben.persistence_token}::#{ben.id}", controller.cookies["user_credentials"]
end
def <API key>
ben = users(:ben)
assert_nil controller.cookies["user_credentials"]
payload = "#{ben.persistence_token}::#{ben.id}"
session = UserSession.new(ben)
session.sign_cookie = true
assert session.save
assert_equal payload, controller.cookies.signed["user_credentials"]
assert_equal "#{payload}--#{Digest::SHA1.hexdigest payload}", controller.cookies.signed.parent_jar["user_credentials"]
end
def <API key>
ben = users(:ben)
session = UserSession.new(ben)
session.remember_me = true
assert session.save
assert_equal "#{ben.persistence_token}::#{ben.id}::#{session.remember_me_until.iso8601}", controller.cookies["user_credentials"]
end
def <API key>
ben = users(:ben)
set_cookie_for(ben)
session = UserSession.find
assert controller.cookies["user_credentials"]
assert session.destroy
assert !controller.cookies["user_credentials"]
end
end
end
end
|
export * from './src/dom/Hover';
|
<?php
namespace Symfony\Component\DependencyInjection\Compiler;
/**
* Interface that must be implemented by passes that are run as part of an
* RepeatedPass.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface <API key> extends <API key>
{
function setRepeatedPass(RepeatedPass $repeatedPass);
}
|
package com.aspose.email.examples.exchangeews;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.aspose.email.EWSClient;
import com.aspose.email.<API key>;
import com.aspose.email.<API key>;
import com.aspose.email.<API key>;
import com.aspose.email.IEWSClient;
import com.aspose.email.MailQuery;
import com.aspose.email.MailQueryBuilder;
public class <API key> {
public static void main(String[] args) {
//Note: You will need a valid Exchange server account for testing these samples
<API key>();
<API key>();
<API key>();
<API key>();
<API key>();
<API key>();
<API key>();
<API key>();
<API key>();
}
public static void <API key>() {
// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.getEWSClient("https://outlook.office365.com/exchangeews/exchange.asmx", "testUser", "pwd", "domain");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
// Query building by means of <API key> class
<API key> builder = new <API key>();
// Subject contains "Newsletter"
builder.getSubject().contains("Newsletter");
// Emails that arrived today
try {
builder.getInternalDate().on(sdf.parse("10/05/2016 10:00:00"));
} catch (ParseException e) {
e.printStackTrace();
}
// Build the query
MailQuery query = builder.getQuery();
// Get list of messages
<API key> messages = client.listMessages(client.getMailboxInfo().getInboxUri(), query, false);
System.out.println("Imap: " + messages.size() + " message(s) found.");
}
public static void <API key>() {
// Emails that arrived today
MailQueryBuilder builder = new MailQueryBuilder();
builder.getInternalDate().on(new Date());
}
public static void <API key>() {
MailQueryBuilder builder = new MailQueryBuilder();
builder.getInternalDate().beforeOrEqual(new Date());
builder.getInternalDate().since(new Date(new Date().getTime() + TimeUnit.DAYS.toDays(1)));
}
public static void <API key>() {
MailQueryBuilder builder = new MailQueryBuilder();
// Get emails from specific sender
builder.getFrom().contains("saqib.razzaq@127.0.0.1");
}
public static void <API key>() {
MailQueryBuilder builder = new MailQueryBuilder();
// Get emails from specific domain
builder.getFrom().contains("SpecificHost.com");
}
public static void <API key>() {
MailQueryBuilder builder = new MailQueryBuilder();
// Get emails sent to specific recipient
builder.getTo().contains("recipient");
}
public static void <API key>() {
MailQueryBuilder builder = new MailQueryBuilder();
// Emails from specific host
builder.getFrom().contains("SpecificHost.com");
// AND all emails that arrived before today
builder.getInternalDate().before(new Date());
// AND all emails that arrived since 7 days ago
builder.getInternalDate().since(new Date(new Date().getTime() + TimeUnit.DAYS.toDays(-7)));
}
public static void <API key>() {
MailQueryBuilder builder = new MailQueryBuilder();
// Specify OR condition
builder.or(builder.getSubject().contains("test"), builder.getFrom().contains("noreply@host.com"));
}
public static void <API key>() {
//IgnoreCase is True
MailQueryBuilder builder1 = new MailQueryBuilder();
builder1.getFrom().contains("tesT", true);
MailQuery query1 = builder1.getQuery();
}
public static void <API key>(){
//ExStart: <API key>
<API key> builder1 = new <API key>();
builder1.getItemSize().greater(80000);
//ExEnd: <API key>
}
public static void <API key>()
{
IEWSClient client = EWSClient.getEWSClient("exchange server uri", "username", "password");
//ExStart: <API key>
int itemsPerPage = 5;
String subj = UUID.randomUUID().toString() + " - " + "Query 1";
MailQueryBuilder queryBuilder = new MailQueryBuilder();
queryBuilder.getSubject().contains(subj);
MailQuery query = queryBuilder.getQuery();
List<<API key>> pages = new ArrayList<<API key>>();
<API key> pageInfo = client.listMessagesByPage(client.getMailboxInfo().getInboxUri(),
query, itemsPerPage);
pages.add(pageInfo);
int count = pageInfo.getItems().size();
System.out.println("Total Count: " + count);
while (!pageInfo.getLastPage())
{
pageInfo = client.listMessagesByPage(client.getMailboxInfo().getInboxUri(),
query, itemsPerPage, pageInfo.getPageOffset() + 1);
pages.add(pageInfo);
count += pageInfo.getItems().size();
}
System.out.println("Total Count: " + count);
//ExEnd: <API key>
}
}
|
<?php
/**
* Template Name: Vertical One Page
*
* Template for displaying a page without sidebar even if a sidebar widget is published
*
* @package understrap
*/
get_header();
$container = get_theme_mod( '<API key>' );
?>
<?php
/*
* Exclude the posts page from being shown in this layout.
* Order pages by their order number.
*/
$exclude = array();
// exclude blog page.
array_push( $exclude, get_option( 'page_for_posts' ) );
// exclude WooCommerce pages.
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
array_push( $exclude, get_option( '<API key>' ) );
$args = array(
'post_type' => 'page',
'post__not_in' => $exclude,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$qry = new WP_Query( $args );
?>
<div class="wrapper" id="<API key>">
<div class="<?php echo esc_html( $container ); ?>" id="content">
<div class="col-md-12 content-area" id="primary">
<main class="site-main" id="main" role="main">
<?php if ( have_posts() ) : while ( $qry->have_posts() ) : $qry->the_post() ?>
<div class="page">
<?php get_template_part( 'loop-templates/content', 'verticalpage' ); ?>
</div>
<?php wp_reset_postdata(); // reset custom query. ?>
<?php
endwhile;
endif;
?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- Container end -->
</div><!-- Wrapper end -->
<?php get_footer(); ?>
|
import id_feature as idf
class BasicFeatures(idf.IDFeatures):
def __init__(self, dataset):
idf.IDFeatures.__init__(self, dataset)
# def <API key>(self,next_word,tag,idx):
# feat = "next_word:%s::%s"%(next_word,tag)
# nr_feat = self.add_feature(feat)
# idx.append(nr_feat)
# return idx
# def <API key>(self,prev_word,tag,idx):
# feat = "prev_word:%s::%s"%(prev_word,tag)
# nr_feat = self.add_feature(feat)
# idx.append(nr_feat)
# return idx
def add_node_feature(self, seq, pos, y, idx):
x = seq.x[pos]
word = self.dataset.int_to_word[x]
if self.dataset.word_counts[x] > 5:
y_name = self.dataset.int_to_pos[y]
word = self.dataset.int_to_word[x]
feat = "id:%s::%s" % (word, y_name)
nr_feat = self.add_feature(feat)
idx.append(nr_feat)
else:
# Check for upercase
if not unicode.islower(word):
feat = "upercased::%s" % y
nr_feat = self.add_feature(feat)
idx.append(nr_feat)
# Check for number
if not unicode.isalpha(word):
feat = "number::%s" % y
nr_feat = self.add_feature(feat)
idx.append(nr_feat)
# Check for number
if unicode.find(word, "-") != -1:
feat = "hyphen::%s" % y
nr_feat = self.add_feature(feat)
idx.append(nr_feat)
# Suffixes
max_suffix = 4
for i in xrange(max_suffix):
if len(word) > i+1:
suffix = word[-(i+1):]
feat = "suffix:%s::%s" % (suffix, y)
nr_feat = self.add_feature(feat)
idx.append(nr_feat)
# Prefixes
max_prefix = 4
for i in xrange(max_prefix):
if len(word) > i+1:
prefix = word[:i+1]
feat = "prefix:%s::%s" % (prefix, y)
nr_feat = self.add_feature(feat)
idx.append(nr_feat)
return idx
|
<?php
/**
* @namespace
*/
namespace Zend\CodeGenerator\Php\Docblock\Tag;
class ParamTag extends \Zend\CodeGenerator\Php\PhpDocblockTag
{
/**
* @var string
*/
protected $_datatype = null;
/**
* @var string
*/
protected $_paramName = null;
/**
* @var string
*/
protected $_description = null;
/**
* fromReflection()
*
* @param \Zend\Reflection\<API key> $reflectionTagParam
* @return \Zend\CodeGenerator\Php\Docblock\Tag\ParamTag
*/
public static function fromReflection(\Zend\Reflection\<API key> $reflectionTagParam)
{
$paramTag = new \self();
$paramTag->setName('param');
$paramTag->setDatatype($reflectionTagParam->getType()); // @todo rename
$paramTag->setParamName($reflectionTagParam->getVariableName());
$paramTag->setDescription($reflectionTagParam->getDescription());
return $paramTag;
}
/**
* setDatatype()
*
* @param string $datatype
* @return \Zend\CodeGenerator\Php\Docblock\Tag\ParamTag
*/
public function setDatatype($datatype)
{
$this->_datatype = $datatype;
return $this;
}
/**
* getDatatype
*
* @return string
*/
public function getDatatype()
{
return $this->_datatype;
}
/**
* setParamName()
*
* @param string $paramName
* @return \Zend\CodeGenerator\Php\Docblock\Tag\ParamTag
*/
public function setParamName($paramName)
{
$this->_paramName = $paramName;
return $this;
}
/**
* getParamName()
*
* @return string
*/
public function getParamName()
{
return $this->_paramName;
}
/**
* generate()
*
* @return string
*/
public function generate()
{
$output = '@param '
. (($this->_datatype != null) ? $this->_datatype : 'unknown')
. (($this->_paramName != null) ? ' $' . $this->_paramName : '')
. (($this->_description != null) ? ' ' . $this->_description : '');
return $output;
}
}
|
import com.github.theholywaffle.lolchatapi.ChatServer;
import com.github.theholywaffle.lolchatapi.FriendRequestPolicy;
import com.github.theholywaffle.lolchatapi.LolChat;
import com.github.theholywaffle.lolchatapi.listeners.ChatListener;
import com.github.theholywaffle.lolchatapi.listeners.FriendListener;
import com.github.theholywaffle.lolchatapi.riotapi.RateLimit;
import com.github.theholywaffle.lolchatapi.riotapi.RiotApiKey;
import com.github.theholywaffle.lolchatapi.wrapper.Friend;
public class ListenerExample {
public static void main(String[] args) {
new ListenerExample();
}
public ListenerExample() {
final LolChat api = new LolChat(ChatServer.EUW,
FriendRequestPolicy.ACCEPT_ALL, new RiotApiKey("RIOT-API-KEY",
RateLimit.DEFAULT));
/** First add or set all listeners BEFORE logging in! */
// Example 1: Adding FriendListeners - listens to changes in your
// friendlist
api.addFriendListener(new FriendListener() {
public void onFriendAvailable(Friend friend) {
System.out.println(friend.getName() + " is available!");
}
public void onFriendAway(Friend friend) {
System.out.println(friend.getName() + " is away!");
}
public void onFriendBusy(Friend friend) {
System.out.println(friend.getName() + " is busy!");
}
public void onFriendJoin(Friend friend) {
System.out.println(friend.getName() + " joined!");
}
public void onFriendLeave(Friend friend) {
System.out.println(friend.getName() + " left!");
}
public void <API key>(Friend friend) {
System.out.println(friend.getName()
+ " status changed! New GameStatus: "
+ friend.getStatus().getGameStatus());
}
public void onNewFriend(Friend friend) {
System.out.println("New friend: " + friend.getUserId());
}
public void onRemoveFriend(String userId, String name) {
System.out.println("Friend removed: " + userId + " " + name);
}
});
// Example 2: Adding ChatListener - listens to chat messages from
// any of your friends.
api.addChatListener(new ChatListener() {
public void onMessage(Friend friend, String message) {
System.out.println("[All]>" + friend.getName() + ": " + message);
}
});
// Example 3: Adding ChatListener to 1 Friend only - this only
// listens to messages from this friend only
api.getFriendByName("Dyrus").setChatListener(new ChatListener() {
public void onMessage(Friend friend, String message) {
// Dyrus sent us a message
System.out.println("Dyrus: " + message);
}
});
if (api.login("myusername", "mypassword")) {
System.out.println("Loaded!");
}
}
}
|
http://netcat.sourceforge.net/
Netcat is a featured networking utility which reads and writes data across network connections, using the TCP/IP protocol.
It is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts.
At the same time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection
you would need and has several interesting built-in capabilities
TCP
nc -v -z -w2 192.168.0.1 1-10000
Connection to 192.168.0.1 22 port [tcp/ssh] succeeded!
Connection to 192.168.0.1 80 port [tcp/http] succeeded!
Connection to 192.168.0.1 111 port [tcp/sunrpc] succeeded!
Connection to 192.168.0.1 3306 port [tcp/mysql] succeeded!
Connection to 192.168.0.1 8001 port [tcp/vcom-tunnel] succeeded!
Connection to 192.168.0.1 8002 port [tcp/teradataordbms] succeeded!
Connection to 192.168.0.1 8003 port [tcp/mcreport] succeeded!
Connection to 192.168.0.1 8200 port [tcp/trivnet1] succeeded!
UDP
nc -u -z -w2 192.168.0.1 1-10000
Connection to 192.168.0.1 111 port [udp/sunrpc] succeeded!
Connection to 192.168.0.1 600 port [udp/ipcserver] succeeded!
Connection to 192.168.0.1 631 port [udp/ipp] succeeded!
Connection to 192.168.0.1 989 port [udp/ftps-data] succeeded!
nc -nvv 192.168.0.1 80
|
const hyperquest = require('hyperzip')(require('hyperdirect'))
, bl = require('bl')
const maxConcurrent = 25
var queue = []
, inFlight = 0
function go () {
if (inFlight > maxConcurrent || !queue.length)
return
var req = queue.shift()
inFlight++
hyperquest(req.url, req.options).pipe(bl(function () {
inFlight
process.nextTick(go)
req.callback.apply(this, arguments)
}))
process.nextTick(go)
}
function fetch (url, options, callback) {
if (typeof options == 'function') {
callback = options
options = {}
}
queue.push({
url : url
, options : options
, callback : callback
})
go()
}
module.exports = fetch
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-gy",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
# encoding: utf-8
shared_examples_for 'an installation from mesosphere' do |opt|
if(opt[:with_zookeeper])
context 'with zookeeper' do
it 'installs zookeeper, zookeeperd, zookeeper-bin' do
['zookeeper', 'zookeeperd', 'zookeeper-bin'].each do |zk|
expect(package(zk)).to be_installed
end
end
describe service('zookeeper') do
it { should be_running }
end
end
end
it 'installs mesos package' do
expect(package('mesos')).to be_installed
end
end
|
// grunt-ts creates this file to help TypeScript find the compilation root of your project. If you wish to get to stop creating it, specify a `rootDir` setting in the Gruntfile ts `options`. See https://github.com/TypeStrong/grunt-ts#rootdir for details. Note that `rootDir` goes under `options`, and is case-sensitive. This message was revised in grunt-ts v6. Note that `rootDir` requires TypeScript 1.5 or higher.
|
// Camera Path 3
// Available on the Unity Asset Store
// For support contact email@jasperstocker.com
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using UnityEngine;
public class CameraPathColours
{
public static Color RED = new Color(0.6f, 0, 0);
public static Color GREEN = new Color(0, 0.5f, 0);
public static Color DARKGREEN = new Color(0, 0.2f, 0);
public static Color BLUE = new Color(0, 0, 0.6f);
public static Color GREY = new Color(0.6f, 0.6f, 0.6f);
public static Color DARKGREY = new Color(0.2f, 0.2f, 0.2f);
public static Color CYAN = new Color(0, 0.3f, 0.8f);
public static Color PURPLE = new Color(0.5f, 0.1f, 0.5f);
public static Color MAGENTA = new Color(0.8f, 0.1f, 0.8f);
}
|
/** \file
* \brief Board specific information header for the Atmel EVK527.
* \copydetails <API key>
*
* \note This file should not be included directly. It is automatically included as needed by the Board driver
* dispatch header located in LUFA/Drivers/Board/Board.h.
*/
/** \ingroup Group_BoardInfo
* \defgroup <API key> EVK527
* \brief Board specific information header for the Atmel EVK527.
*
* Board specific information header for the Atmel EVK527.
*
* @{
*/
#ifndef __BOARD_EVK527_H__
#define __BOARD_EVK527_H__
/* Includes: */
#include "../../../../Common/Common.h"
#include "../../Buttons.h"
#include "../../Dataflash.h"
#include "../../Joystick.h"
#include "../../LEDs.h"
/* Enable C linkage for C++ Compilers: */
#if defined(__cplusplus)
extern "C" {
#endif
/* Preprocessor Checks: */
#if !defined(<API key>)
#error Do not include this file directly. Include LUFA/Drivers/Board/Board.h instead.
#endif
/* Public Interface - May be used in end-application: */
/* Macros: */
/** Indicates the board has hardware Buttons mounted. */
#define BOARD_HAS_BUTTONS
/** Indicates the board has a hardware Dataflash mounted. */
#define BOARD_HAS_DATAFLASH
/** Indicates the board has a hardware Joystick mounted. */
#define BOARD_HAS_JOYSTICK
/** Indicates the board has hardware LEDs mounted. */
#define BOARD_HAS_LEDS
/* Disable C linkage for C++ Compilers: */
#if defined(__cplusplus)
}
#endif
#endif
|
layout: leetcode
date: 2016-07-11
title: Symmetric Tree
tags: [Tree, Depth First Search, Breadth First Search]
* Contents
{:toc #toc_of_keans_blog}
## Question
> Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
>
>For example, this binary tree `[1,2,2,3,4,4,3]` is symmetric:
>
> 1
> / \
> 2 2
> / \ / \
> 3 4 4 3
>
>
> But the following `[1,2,2,null,3,null,3]` is not:
>
> 1
> / \
> 2 2
> \ \
> 3 3
>
> **Note:**
>
> Bonus points if you could solve it both recursively and iteratively.
***
## Solution
**Result:** Accepted **Time:** 4 ms
Here should be some explanations.
c
bool _is_symmetric(struct TreeNode * r1,struct TreeNode * r2)
{
if(r1 == r2 && r1 == NULL)
return true;
if(!r1 || !r2)
return false;
if(r1->val != r2->val)
return false;
return _is_symmetric(r1->left,r2->right) && _is_symmetric(r1->right,r2->left);
}
bool isSymmetric(struct TreeNode* root) {
if(root == NULL) return true;
return _is_symmetric(root->left,root->right);
}
**Complexity Analytics**
- Time Complexity: $$O(n)$$
- Space Complexity: $$O(1)$$
|
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.fluent.models.<API key>;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Response for the <API key> API service call. */
@Fluent
public final class <API key> {
@JsonIgnore private final ClientLogger logger = new ClientLogger(<API key>.class);
/*
* List of available endpoint services in a region.
*/
@JsonProperty(value = "value")
private List<<API key>> value;
/*
* The URL to get the next set of results.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/**
* Get the value property: List of available endpoint services in a region.
*
* @return the value value.
*/
public List<<API key>> value() {
return this.value;
}
/**
* Set the value property: List of available endpoint services in a region.
*
* @param value the value value to set.
* @return the <API key> object itself.
*/
public <API key> withValue(List<<API key>> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: The URL to get the next set of results.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: The URL to get the next set of results.
*
* @param nextLink the nextLink value to set.
* @return the <API key> object itself.
*/
public <API key> withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws <API key> thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0) on Thu Sep 29 14:31:08 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.owasp.appsensor.rpc.thrift.generated.Attack (appsensor-parent 2.3.0 API)</title>
<meta name="date" content="2016-09-29">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.owasp.appsensor.rpc.thrift.generated.Attack (appsensor-parent 2.3.0 API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="header">
<h2 title="Uses of Class org.owasp.appsensor.rpc.thrift.generated.Attack" class="title">Uses of Class<br>org.owasp.appsensor.rpc.thrift.generated.Attack</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.owasp.appsensor.rpc.thrift">org.owasp.appsensor.rpc.thrift</a></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.owasp.appsensor.rpc.thrift.generated">org.owasp.appsensor.rpc.thrift.generated</a></td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.owasp.appsensor.rpc.thrift">
</a>
<h3>Uses of <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/package-summary.html">org.owasp.appsensor.rpc.thrift</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/package-summary.html">org.owasp.appsensor.rpc.thrift</a> with parameters of type <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApiHandler.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/AppSensorApiHandler.html#addAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-">addAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>)</code></td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.owasp.appsensor.rpc.thrift.generated">
</a>
<h3>Uses of <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/package-summary.html">org.owasp.appsensor.rpc.thrift.generated</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/package-summary.html">org.owasp.appsensor.rpc.thrift.generated</a> declared as <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.addAttack_args.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.addAttack_args.html#attack">attack</a></span></code></td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/package-summary.html">org.owasp.appsensor.rpc.thrift.generated</a> that return <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#deepCopy--">deepCopy</a></span>()</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.addAttack_args.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.addAttack_args.html#getAttack--">getAttack</a></span>()</code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#<API key>.owasp.appsensor.rpc.thrift.generated.DetectionPoint-">setDetectionPoint</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/DetectionPoint.html" title="class in org.owasp.appsensor.rpc.thrift.generated">DetectionPoint</a> detectionPoint)</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#<API key>.owasp.appsensor.rpc.thrift.generated.DetectionSystem-">setDetectionSystem</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/DetectionSystem.html" title="class in org.owasp.appsensor.rpc.thrift.generated">DetectionSystem</a> detectionSystem)</code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#setId-int-">setId</a></span>(int id)</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#setResource-org.owasp.appsensor.rpc.thrift.generated.Resource-">setResource</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Resource.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Resource</a> resource)</code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#setUser-org.owasp.appsensor.rpc.thrift.generated.User-">setUser</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/User.html" title="class in org.owasp.appsensor.rpc.thrift.generated">User</a> user)</code></td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/package-summary.html">org.owasp.appsensor.rpc.thrift.generated</a> with parameters of type <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.Iface.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.Iface.html#addAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-">addAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>)</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.Client.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.Client.html#addAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-">addAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>)</code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.AsyncIface.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncIface.html#addAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-org.apache.thrift.async.AsyncMethodCallback-">addAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>,
org.apache.thrift.async.AsyncMethodCallback<<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.addAttack_call.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient.addAttack_call</a>> resultHandler)</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.AsyncClient.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.html#addAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-org.apache.thrift.async.AsyncMethodCallback-">addAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>,
org.apache.thrift.async.AsyncMethodCallback<<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.addAttack_call.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient.addAttack_call</a>> resultHandler)</code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#compareTo-org.owasp.appsensor.rpc.thrift.generated.Attack-">compareTo</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> other)</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><span class="typeNameLabel">Attack.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#equals-org.owasp.appsensor.rpc.thrift.generated.Attack-">equals</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> that)</code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.Client.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.Client.html#send_addAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-">send_addAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>)</code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.addAttack_args.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.addAttack_args</a></code></td>
<td class="colLast"><span class="typeNameLabel">AppSensorApi.addAttack_args.</span><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.addAttack_args.html#setAttack-org.owasp.appsensor.rpc.thrift.generated.Attack-">setAttack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack)</code></td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/package-summary.html">org.owasp.appsensor.rpc.thrift.generated</a> with parameters of type <a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.addAttack_args.html#addAttack_args-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-">addAttack_args</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>)</code></td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.addAttack_call.html#addAttack_call-org.owasp.appsensor.rpc.thrift.generated.Attack-java.lang.String-org.apache.thrift.async.<API key>.apache.thrift.async.TAsyncClient-org.apache.thrift.protocol.<API key>.apache.thrift.transport.<API key>-">addAttack_call</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> attack,
<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> <API key>,
org.apache.thrift.async.AsyncMethodCallback<<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.addAttack_call.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient.addAttack_call</a>> resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.<API key> transport)</code></td>
</tr>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html#Attack-org.owasp.appsensor.rpc.thrift.generated.Attack-">Attack</a></span>(<a href="../../../../../../../org/owasp/appsensor/rpc/thrift/generated/Attack.html" title="class in org.owasp.appsensor.rpc.thrift.generated">Attack</a> other)</code></td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
module FFI
# This module is the base to use native functions.
# A basic usage may be:
# @example
# module MyLib
# extend FFI::Library
# ffi_lib 'c'
# attach_function :puts, [ :string ], :int
# end
# MyLib.puts 'Hello, World using libc!'
module Library
# @param libnames [Array] names of libraries to load
# @return [Array<FFICompat::DynamicLibrary>]
# @raise if a library cannot be opened
# Load native libraries.
def ffi_lib(libnames)
@ffi_libs ||= []
libnames = [libnames] unless libnames.is_a?(Array)
libnames.each do |libname|
lib = FFICompat::DynamicLibrary.new(libname)
if lib.exist? || (libnames[0] == :c)
@ffi_libs << lib
end
end
if @ffi_libs.empty?
raise "library not found: #{libnames}"
end
@ffi_libs
end
@@callbacks = {}
# Add a callback
# @param name [Symbol] to map to
# @param arguments_type [Array<Symbol,FFI::Struct,FFI::Struct::ReturnAsInstance>] of the parameter types
# @param result_type [Symbol,FFI::Struct,FFI::Struct::ReturnAsInstance] of the return type
# @return [Array] representing the callback
# @example
# # has Integer as paramater and returns boolean
# callback(:SomeLibCallback,[:int],:bool)
# # SomeFoo is a FFI::Struct
# # SomeFoo resolves to :pointer as parameter and returns Integer
# callback(:SomeFooCallback,[SomeFoo],:int)
# # No parameters, returns an instance of SomeOtherFoo wrapped to the resulting pointer
# callback(:<API key>,[],SomeOtherFoo.by_ref)
# TODO: implement structs as types
def callback(name, arguments_type, result_type)
@@callbacks[name] = [arguments_type,result_type]
end
# @return [Hash] of the callbacks
def self.callbacks
@@callbacks
end
@@typedefs = {}
# Adds a typedef
# @param type_name [Symbol,FFI::Struct] to alias against
# @param alias_name [Symbol] to map to
# @return the resolved type class
def typedef(type_name, alias_name)
@@typedefs[alias_name] = type_name
FFI::TYPES[alias_name] = FFI.find_type(type_name)
end
# @return [Hash] of the typedefs
def self.typedefs
@@typedefs
end
@@enums = {}
# Add a enum map
# @param name [Symbol] to map the enum to
# @param arr [Array<Symbol>,Array<Mixed>] of the enum members
# @example
# enum(:Foo,[:bar,:quux,:moof])
# enum(:Foo,[3,:moof,4,:quux])
# @return self
def enum(enum_name, arr)
idx = 0
values = {}
pos = 0
loop do
name = arr[pos]
value = arr[pos+1]
if value.is_a?(Integer)
idx = value
pos += 2
else
pos += 1
end
values[name] = idx
idx += 1
break if pos >= arr.size
end
@@enums[enum_name] = values
typedef(:int, enum_name)
self
end
# @return [Hash] of the added enums
def self.enums
@@enums
end
# @example attach function without an explicit name
# module Foo
# extend FFI::Library
# ffi_lib FFI::Library::LIBC
# attach_function :malloc, [:size_t], :pointer
# # has Integer as paramater and returns boolean
# attach_function(:foo,[:int],:bool)
# # SomeFoo is a FFI::Struct
# # SomeFoo resolves to :pointer as parameter and returns Integer
# attach_function(:bar,[SomeFoo],:int)
# # No parameters, returns an instance of SomeOtherFoo wrapped to the resulting pointer
# attach_function(:moof,[],SomeOtherFoo.by_ref)
# end
# # now callable via Foo.malloc
# Attach C function +func+ to this module.
# @param function_name [#to_s] name of C function to attach
# @param arguments_type [Array<Symbol,FFI::Struct,FFI::Struct::ReturnAsInstance>] an array of types of the parameters
# @param result_type [Symbol,FFI::Struct,FFI::Struct::ReturnAsInstance] type of return value
# @return [FFI::Function]
def attach_function(function_name, arguments_type, result_type)
lib = @ffi_libs.find do |l|
l.send(:get_symbol,function_name)
end
f = Function.new(result_type, arguments_type,[lib,function_name])
f.attach(self,function_name)
f
end
end
end
|
// <auto-generated>
// This code was generated from a template.
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
namespace NorthwindDb
{
using System;
using System.Collections.Generic;
public partial class <API key>
{
public string CategoryName { get; set; }
public string ProductName { get; set; }
public Nullable<decimal> ProductSales { get; set; }
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_21) on Mon Feb 03 10:44:04 PST 2014 -->
<TITLE>
MVException
</TITLE>
<META NAME="keywords" CONTENT="com.rocketsoftware.mvapi.exceptions.MVException class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="MVException";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV CLASS
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/rocketsoftware/mvapi/exceptions/MVException.html" target="_top"><B>FRAMES</B></A>
<A HREF="MVException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
com.rocketsoftware.mvapi.exceptions</FONT>
<BR>
Class MVException</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.lang.Throwable
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.lang.Exception
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.sql.SQLException
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>com.rocketsoftware.mvapi.exceptions.MVException</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>MVException</B><DT>extends java.sql.SQLException</DL>
</PRE>
<P>
Exception handling for MV API
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../serialized-form.html#com.rocketsoftware.mvapi.exceptions.MVException">Serialized Form</A></DL>
<HR>
<P>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#MVException(java.lang.Exception)">MVException</A></B>(java.lang.Exception e)</CODE>
<BR>
MVException constructor from an exception</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#MVException(java.lang.Exception, java.lang.String, int)">MVException</A></B>(java.lang.Exception e,
java.lang.String errorMessage,
int errorCode)</CODE>
<BR>
MVException constructor from an exception</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#MVException(java.lang.String)">MVException</A></B>(java.lang.String errorMessage)</CODE>
<BR>
MVException constructor with an error string</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#MVException(java.lang.String, int)">MVException</A></B>(java.lang.String errorMessage,
int errorCode)</CODE>
<BR>
MVException constructor with an error string and error code</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#getErrorCode()">getErrorCode</A></B>()</CODE>
<BR>
get the error code</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#getErrorMessage()">getErrorMessage</A></B>()</CODE>
<BR>
get the error message</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.Exception</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/rocketsoftware/mvapi/exceptions/MVException.html#getException()">getException</A></B>()</CODE>
<BR>
get the original exception if any</TD>
</TR>
</TABLE>
<A NAME="<API key>.sql.SQLException"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.sql.SQLException</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>getNextException, getSQLState, setNextException</CODE></TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Throwable"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Throwable</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString</CODE></TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="MVException(java.lang.Exception)"></A><H3>
MVException</H3>
<PRE>
public <B>MVException</B>(java.lang.Exception e)</PRE>
<DL>
<DD>MVException constructor from an exception
<P>
</DL>
<HR>
<A NAME="MVException(java.lang.Exception, java.lang.String, int)"></A><H3>
MVException</H3>
<PRE>
public <B>MVException</B>(java.lang.Exception e,
java.lang.String errorMessage,
int errorCode)</PRE>
<DL>
<DD>MVException constructor from an exception
<P>
</DL>
<HR>
<A NAME="MVException(java.lang.String)"></A><H3>
MVException</H3>
<PRE>
public <B>MVException</B>(java.lang.String errorMessage)</PRE>
<DL>
<DD>MVException constructor with an error string
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>errorMessage</CODE> - error description</DL>
</DL>
<HR>
<A NAME="MVException(java.lang.String, int)"></A><H3>
MVException</H3>
<PRE>
public <B>MVException</B>(java.lang.String errorMessage,
int errorCode)</PRE>
<DL>
<DD>MVException constructor with an error string and error code
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>errorMessage</CODE> - error message<DD><CODE>errorCode</CODE> - error code from MVErrors list</DL>
</DL>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getException()"></A><H3>
getException</H3>
<PRE>
public java.lang.Exception <B>getException</B>()</PRE>
<DL>
<DD>get the original exception if any
<P>
<DD><DL>
<DT><B>Returns:</B><DD>exception causing this exception to be raised</DL>
</DD>
</DL>
<HR>
<A NAME="getErrorMessage()"></A><H3>
getErrorMessage</H3>
<PRE>
public java.lang.String <B>getErrorMessage</B>()</PRE>
<DL>
<DD>get the error message
<P>
<DD><DL>
<DT><B>Returns:</B><DD>error message string</DL>
</DD>
</DL>
<HR>
<A NAME="getErrorCode()"></A><H3>
getErrorCode</H3>
<PRE>
public int <B>getErrorCode</B>()</PRE>
<DL>
<DD>get the error code
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>getErrorCode</CODE> in class <CODE>java.sql.SQLException</CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>error code</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV CLASS
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/rocketsoftware/mvapi/exceptions/MVException.html" target="_top"><B>FRAMES</B></A>
<A HREF="MVException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
/* node.cpp */
/* This file is part of: */
/* GODOT ENGINE */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* included in all copies or substantial portions of the Software. */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "node.h"
#include "print_string.h"
#include "message_queue.h"
#include "scene/scene_string_names.h"
#include "scene/resources/packed_scene.h"
#include "io/resource_loader.h"
#include "viewport.h"
#include "<API key>.h"
VARIANT_ENUM_CAST(Node::PauseMode);
void Node::_notification(int p_notification) {
switch(p_notification) {
case <API key>: {
if (get_script_instance()) {
Variant time=<API key>();
const Variant*ptr[1]={&time};
Variant::CallError err;
get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_process,ptr,1);
}
} break;
case <API key>: {
if (get_script_instance()) {
Variant time=<API key>();
const Variant*ptr[1]={&time};
Variant::CallError err;
get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_fixed_process,ptr,1);
}
} break;
case <API key>: {
if (data.pause_mode==PAUSE_MODE_INHERIT) {
if (data.parent)
data.pause_owner=data.parent->data.pause_owner;
else
data.pause_owner=NULL;
} else {
data.pause_owner=this;
}
if (data.input)
add_to_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
if (data.unhandled_input)
add_to_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
if (data.unhandled_key_input)
add_to_group("<API key>"+itos(get_viewport()->get_instance_ID()));
get_tree()->node_count++;
} break;
case <API key>: {
get_tree()->node_count
if (data.input)
remove_from_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
if (data.unhandled_input)
remove_from_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
if (data.unhandled_key_input)
remove_from_group("<API key>"+itos(get_viewport()->get_instance_ID()));
} break;
case NOTIFICATION_READY: {
if (get_script_instance()) {
Variant::CallError err;
get_script_instance()-><API key>(SceneStringNames::get_singleton()->_ready,NULL,0);
}
//emit_signal(SceneStringNames::get_singleton()->enter_tree);
} break;
case <API key>: {
data.in_constructor=false;
} break;
case <API key>: {
set_owner(NULL);
while ( data.owned.size() ) {
data.owned.front()->get()->set_owner(NULL);
}
if (data.parent) {
data.parent->remove_child(this);
}
// kill children as cleanly as possible
while( data.children.size() ) {
Node *child = data.children[0];
remove_child(child);
memdelete( child );
}
} break;
}
}
void Node::_propagate_ready() {
data.blocked++;
for (int i=0;i<data.children.size();i++) {
data.children[i]->_propagate_ready();
}
data.blocked
notification(NOTIFICATION_READY);
}
void Node::<API key>() {
// this needs to happen to all childs before any enter_tree
if (data.parent) {
data.tree=data.parent->data.tree;
data.depth=data.parent->data.depth+1;
} else {
data.depth=1;
}
data.viewport = cast_to<Viewport>();
if (!data.viewport)
data.viewport = data.parent->data.viewport;
data.inside_tree=true;
const StringName *K=NULL;
while ((K=data.grouped.next(K))) {
data.tree->add_to_group(*K,this);
}
notification(<API key>);
if (get_script_instance()) {
Variant::CallError err;
get_script_instance()-><API key>(SceneStringNames::get_singleton()->_enter_tree,NULL,0);
}
emit_signal(SceneStringNames::get_singleton()->enter_tree);
data.blocked++;
//block while adding children
for (int i=0;i<data.children.size();i++) {
if (!data.children[i]->is_inside_tree()) // could have been added in enter_tree
data.children[i]-><API key>();
}
data.blocked
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && data.filename!=String()) {
//used for live edit
data.tree-><API key>[data.filename].insert(this);
}
#endif
// enter groups
}
void Node::<API key>() {
//block while removing children
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && data.filename!=String()) {
//used for live edit
Map<String,Set<Node*> >::Element *E=data.tree-><API key>.find(data.filename);
if (E) {
E->get().erase(this);
if (E->get().size()==0) {
data.tree-><API key>.erase(E);
}
}
Map<Node*,Map<ObjectID,Node*> >::Element *F=data.tree-><API key>.find(this);
if (F) {
for (Map<ObjectID,Node*>::Element*G=F->get().front();G;G=G->next()) {
memdelete(G->get());
}
data.tree-><API key>.erase(F);
}
}
#endif
data.blocked++;
for (int i=data.children.size()-1;i>=0;i
data.children[i]-><API key>();
}
data.blocked
if (get_script_instance()) {
Variant::CallError err;
get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_tree,NULL,0);
}
emit_signal(SceneStringNames::get_singleton()->exit_tree);
notification(<API key>,true);
if (data.tree)
data.tree->node_removed(this);
// exit groups
const StringName *K=NULL;
while ((K=data.grouped.next(K))) {
data.tree->remove_from_group(*K,this);
}
data.viewport = NULL;
if (data.tree)
data.tree->tree_changed();
data.inside_tree=false;
data.tree=NULL;
data.depth=-1;
}
void Node::move_child(Node *p_child,int p_pos) {
ERR_FAIL_NULL(p_child);
ERR_EXPLAIN("Invalid new child position: "+itos(p_pos));
ERR_FAIL_INDEX( p_pos, data.children.size()+1 );
ERR_EXPLAIN("child is not a child of this node.");
ERR_FAIL_COND(p_child->data.parent!=this);
ERR_FAIL_COND(data.blocked>0);
data.children.remove( p_child->data.pos );
data.children.insert( p_pos, p_child );
if (data.tree) {
data.tree->tree_changed();
}
data.blocked++;
//new pos first
for (int i=0;i<data.children.size();i++) {
data.children[i]->data.pos=i;
}
// notification second
move_child_notify(p_child);
for (int i=0;i<data.children.size();i++) {
data.children[i]->notification( <API key> );
}
data.blocked
}
void Node::raise() {
if (!data.parent)
return;
data.parent->move_child(this,data.parent->data.children.size()-1);
}
void Node::add_child_notify(Node *p_child) {
// to be used when not wanted
}
/*
void Node::<API key>(Node *p_child) {
ERR_FAIL_NULL( p_child );
ERR_FAIL_COND( p_child->get_parent()!=this );
remove_child(p_child);
memdelete(p_child);
}
*/
void Node::remove_child_notify(Node *p_child) {
// to be used when not wanted
}
void Node::move_child_notify(Node *p_child) {
// to be used when not wanted
}
void Node::set_fixed_process(bool p_process) {
if (data.fixed_process==p_process)
return;
data.fixed_process=p_process;
if (data.fixed_process)
add_to_group("fixed_process",false);
else
remove_from_group("fixed_process");
data.fixed_process=p_process;
_change_notify("fixed_process");
}
void Node::set_pause_mode(PauseMode p_mode) {
if (data.pause_mode==p_mode)
return;
bool prev_inherits=data.pause_mode==PAUSE_MODE_INHERIT;
data.pause_mode=p_mode;
if (!is_inside_tree())
return; //pointless
if ((data.pause_mode==PAUSE_MODE_INHERIT) == prev_inherits)
return; ///nothing changed
Node *owner=NULL;
if (data.pause_mode==PAUSE_MODE_INHERIT) {
if (data.parent)
owner=data.parent->data.pause_owner;
} else {
owner=this;
}
<API key>(owner);
}
Node::PauseMode Node::get_pause_mode() const {
return data.pause_mode;
}
void Node::<API key>(Node*p_owner) {
if (data.pause_mode!=PAUSE_MODE_INHERIT)
return;
data.pause_owner=p_owner;
for(int i=0;i<data.children.size();i++) {
data.children[i]-><API key>(p_owner);
}
}
bool Node::can_process() const {
ERR_FAIL_COND_V( !is_inside_tree(), false );
if (get_tree()->is_paused()) {
if (data.pause_mode==PAUSE_MODE_STOP)
return false;
if (data.pause_mode==PAUSE_MODE_PROCESS)
return true;
if (data.pause_mode==PAUSE_MODE_INHERIT) {
if (!data.pause_owner)
return false; //clearly no pause owner by default
if (data.pause_owner->data.pause_mode==PAUSE_MODE_PROCESS)
return true;
if (data.pause_owner->data.pause_mode==PAUSE_MODE_STOP)
return false;
}
}
return true;
}
float Node::<API key>() const {
if (data.tree)
return data.tree-><API key>();
else
return 0;
}
void Node::set_process(bool p_idle_process) {
if (data.idle_process==p_idle_process)
return;
data.idle_process=p_idle_process;
if (data.idle_process)
add_to_group("idle_process",false);
else
remove_from_group("idle_process");
data.idle_process=p_idle_process;
_change_notify("idle_process");
}
float Node::<API key>() const {
if (data.tree)
return data.tree-><API key>();
else
return 0;
}
bool Node::is_fixed_processing() const {
return data.fixed_process;
}
bool Node::is_processing() const {
return data.idle_process;
}
void Node::set_process_input(bool p_enable) {
if (p_enable==data.input)
return;
data.input=p_enable;
if (!is_inside_tree())
return;
if (p_enable)
add_to_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
else
remove_from_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
}
bool Node::is_processing_input() const {
return data.input;
}
void Node::<API key>(bool p_enable) {
if (p_enable==data.unhandled_input)
return;
data.unhandled_input=p_enable;
if (!is_inside_tree())
return;
if (p_enable)
add_to_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
else
remove_from_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
}
bool Node::<API key>() const {
return data.unhandled_input;
}
void Node::<API key>(bool p_enable) {
if (p_enable==data.unhandled_key_input)
return;
data.unhandled_key_input=p_enable;
if (!is_inside_tree())
return;
if (p_enable)
add_to_group("<API key>"+itos(get_viewport()->get_instance_ID()));
else
remove_from_group("<API key>"+itos(get_viewport()->get_instance_ID()));
}
bool Node::<API key>() const {
return data.unhandled_key_input;
}
StringName Node::get_name() const {
return data.name;
}
void Node::_set_name_nocheck(const StringName& p_name) {
data.name=p_name;
}
void Node::set_name(const String& p_name) {
String name=p_name.replace(":","").replace("/","").replace("@","");
ERR_FAIL_COND(name=="");
data.name=name;
if (data.parent) {
data.parent-><API key>(this);
}
if (is_inside_tree()) {
emit_signal("renamed");
get_tree()->tree_changed();
}
}
static bool node_hrcr=false;
static SafeRefCount node_hrcr_count;
void Node::init_node_hrcr() {
node_hrcr_count.init(1);
}
void Node::<API key>(bool p_enabled) {
node_hrcr=p_enabled;
}
String Node::validate_child_name(const String& p_name) const {
//this approach to autoset node names is human readable but very slow
//it's turned on while running in the editor
String basename = p_name;
if (basename==String()) {
return String();
}
int val=1;
for(;;) {
String attempted = val > 1 ? (basename + " " +itos(val) ) : basename;
bool found=false;
for (int i=0;i<data.children.size();i++) {
//if (data.children[i]==p_child)
// continue;
if (data.children[i]->get_name() == attempted) {
found=true;
break;
}
}
if (found) {
val++;
continue;
}
return attempted;
break;
}
return basename;
}
void Node::<API key>(Node *p_child, bool <API key>) {
/* Make sure the name is unique */
if (node_hrcr || <API key>) {
//this approach to autoset node names is human readable but very slow
//it's turned on while running in the editor
String basename = p_child->data.name;
if (basename=="") {
basename = p_child->get_type();
}
int val=1;
for(;;) {
String attempted = val > 1 ? (basename + " " +itos(val) ) : basename;
bool found=false;
for (int i=0;i<data.children.size();i++) {
if (data.children[i]==p_child)
continue;
if (data.children[i]->get_name() == attempted) {
found=true;
break;
}
}
if (found) {
val++;
continue;
}
p_child->data.name=attempted;
break;
}
} else {
//this approach to autoset node names is fast but not as readable
//it's the default and reserves the '@' character for unique names.
bool unique=true;
if (p_child->data.name==StringName() || p_child->data.name.operator String()[0]=='@') {
//new unique name must be assigned
unique=false;
} else {
//check if exists
Node **childs=data.children.ptr();
int cc = data.children.size();
for(int i=0;i<cc;i++) {
if (childs[i]==p_child)
continue;
if (childs[i]->data.name==p_child->data.name) {
unique=false;
break;
}
}
}
if (!unique) {
node_hrcr_count.ref();
String name = "@"+String(p_child->get_name())+"@"+itos(node_hrcr_count.get());
p_child->data.name=name;
}
}
}
void Node::_add_child_nocheck(Node* p_child,const StringName& p_name) {
//add a child node quickly, without name validation
p_child->data.name=p_name;
p_child->data.pos=data.children.size();
data.children.push_back( p_child );
p_child->data.parent=this;
p_child->notification(<API key>);
if (data.tree) {
p_child->_set_tree(data.tree);
}
/* Notify */
//recognize childs created in this node constructor
p_child->data.parent_owned=data.in_constructor;
add_child_notify(p_child);
}
void Node::add_child(Node *p_child, bool <API key>) {
ERR_FAIL_NULL(p_child);
/* Fail if node has a parent */
if (p_child==this) {
ERR_EXPLAIN("Can't add child "+p_child->get_name()+" to itself.")
ERR_FAIL_COND( p_child==this ); // adding to itself!
}
ERR_EXPLAIN("Can't add child, already has a parent");
ERR_FAIL_COND( p_child->data.parent );
ERR_EXPLAIN("Can't add child while a notification is happening");
ERR_FAIL_COND( data.blocked > 0 );
/* Validate name */
<API key>(p_child,<API key>);
_add_child_nocheck(p_child,p_child->data.name);
}
void Node::<API key>() {
if (data.owner) {
bool found=false;
Node *parent = data.parent;
while(parent) {
if (parent==data.owner) {
found=true;
break;
}
parent=parent->data.parent;
}
if (!found) {
data.owner->data.owned.erase(data.OW);
data.owner=NULL;
}
}
for(int i=0;i<data.children.size();i++) {
data.children[i]-><API key>();
}
}
void Node::remove_child(Node *p_child) {
ERR_FAIL_NULL(p_child);
ERR_FAIL_COND( data.blocked > 0 );
int idx=-1;
for (int i=0;i<data.children.size();i++) {
if (data.children[i]==p_child) {
idx=i;
break;
}
}
ERR_FAIL_COND( idx==-1 );
//ERR_FAIL_COND( p_child->data.blocked > 0 );
//if (data.scene) { does not matter
p_child->_set_tree(NULL);
remove_child_notify(p_child);
p_child->notification(<API key>);
data.children.remove(idx);
for (int i=idx;i<data.children.size();i++) {
data.children[i]->data.pos=i;
}
p_child->data.parent=NULL;
p_child->data.pos=-1;
// validate owner
p_child-><API key>();
}
int Node::get_child_count() const {
return data.children.size();
}
Node *Node::get_child(int p_index) const {
ERR_FAIL_INDEX_V( p_index, data.children.size(), NULL );
return data.children[p_index];
}
Node *Node::_get_child_by_name(const StringName& p_name) const {
int cc=data.children.size();
Node* const* cd=data.children.ptr();
for(int i=0;i<cc;i++){
if (cd[i]->data.name==p_name)
return cd[i];
}
return NULL;
}
Node *Node::_get_node(const NodePath& p_path) const {
if (!data.inside_tree && p_path.is_absolute()) {
ERR_EXPLAIN("Can't use get_node() with absolute paths from outside the active scene tree.");
ERR_FAIL_V(NULL);
}
Node *current=NULL;
Node *root=NULL;
if (!p_path.is_absolute()) {
current=const_cast<Node*>(this); //start from this
} else {
root=const_cast<Node*>(this);;
while (root->data.parent)
root=root->data.parent; //start from root
}
for(int i=0;i<p_path.get_name_count();i++) {
StringName name = p_path.get_name(i);
Node *next = NULL;
if (name==SceneStringNames::get_singleton()->dot) {
next=current;
} else if (name==SceneStringNames::get_singleton()->doubledot) {
if (current==NULL || !current->data.parent)
return NULL;
next=current->data.parent;
} else if (current==NULL) {
if (name==root->get_name())
next=root;
} else {
next=NULL;
for(int j=0;j<current->data.children.size();j++) {
Node *child = current->data.children[j];
if ( child->data.name == name ) {
next = child;
break;
}
}
if (next == NULL) {
return NULL;
};
}
current=next;
}
return current;
}
Node *Node::get_node(const NodePath& p_path) const {
Node *node = _get_node(p_path);
if (!node) {
ERR_EXPLAIN("Node not found: "+p_path);
ERR_FAIL_COND_V(!node,NULL);
}
return node;
}
bool Node::has_node(const NodePath& p_path) const {
return _get_node(p_path)!=NULL;
}
Node* Node::find_node(const String& p_mask,bool p_recursive,bool p_owned) const {
Node * const*cptr = data.children.ptr();
int ccount = data.children.size();
for(int i=0;i<ccount;i++) {
if (p_owned && !cptr[i]->data.owner)
continue;
if (cptr[i]->data.name.operator String().match(p_mask))
return cptr[i];
if (!p_recursive)
continue;
Node* ret = cptr[i]->find_node(p_mask,true,p_owned);
if (ret)
return ret;
}
return NULL;
}
Node *Node::get_parent() const {
return data.parent;
}
bool Node::is_a_parent_of(const Node *p_node) const {
ERR_FAIL_NULL_V(p_node,false);
Node *p=p_node->data.parent;
while(p) {
if (p==this)
return true;
p=p->data.parent;
}
return false;
}
bool Node::is_greater_than(const Node *p_node) const {
ERR_FAIL_NULL_V(p_node,false);
ERR_FAIL_COND_V( !data.inside_tree, false );
ERR_FAIL_COND_V( !p_node->data.inside_tree, false );
ERR_FAIL_COND_V( data.depth<0, false);
ERR_FAIL_COND_V( p_node->data.depth<0, false);
#ifdef NO_ALLOCA
Vector<int> this_stack;
Vector<int> that_stack;
this_stack.resize(data.depth);
that_stack.resize(p_node->data.depth);
#else
int *this_stack=(int*)alloca(sizeof(int)*data.depth);
int *that_stack=(int*)alloca(sizeof(int)*p_node->data.depth);
#endif
const Node *n = this;
int idx=data.depth-1;
while(n) {
ERR_FAIL_INDEX_V(idx, data.depth,false);
this_stack[idx--]=n->data.pos;
n=n->data.parent;
}
ERR_FAIL_COND_V(idx!=-1,false);
n = p_node;
idx=p_node->data.depth-1;
while(n) {
ERR_FAIL_INDEX_V(idx, p_node->data.depth,false);
that_stack[idx--]=n->data.pos;
n=n->data.parent;
}
ERR_FAIL_COND_V(idx!=-1,false);
idx=0;
bool res;
while(true) {
// using -2 since out-of-tree or nonroot nodes have -1
int this_idx = (idx >= data.depth)? -2 : this_stack[idx];
int that_idx = (idx >= p_node->data.depth)? -2 : that_stack[idx];
if (this_idx > that_idx) {
res=true;
break;
} else if (this_idx < that_idx) {
res=false;
break;
} else if (this_idx == -2 ) {
res=false; // equal
break;
}
idx++;
}
return res;
}
void Node::get_owned_by(Node *p_by,List<Node*> *p_owned) {
if (data.owner==p_by)
p_owned->push_back(this);
for (int i=0;i<get_child_count();i++)
get_child(i)->get_owned_by(p_by,p_owned);
}
void Node::_set_owner_nocheck(Node* p_owner) {
ERR_FAIL_COND(data.owner);
data.owner=p_owner;
data.owner->data.owned.push_back( this );
data.OW = data.owner->data.owned.back();
}
void Node::set_owner(Node *p_owner) {
if (data.owner) {
data.owner->data.owned.erase( data.OW );
data.OW=NULL;
data.owner=NULL;
}
ERR_FAIL_COND(p_owner==this);
if (!p_owner)
return;
Node *check=this->get_parent();
bool owner_valid=false;
while(check) {
if (check==p_owner) {
owner_valid=true;
break;
}
check=check->data.parent;
}
ERR_FAIL_COND(!owner_valid);
_set_owner_nocheck(p_owner);
}
Node *Node::get_owner() const {
return data.owner;
}
NodePath Node::get_path_to(const Node *p_node) const {
ERR_FAIL_NULL_V(p_node,NodePath());
if (this==p_node)
return NodePath(".");
Set<const Node*> visited;
const Node *n=this;
while(n) {
visited.insert(n);
n=n->data.parent;
}
const Node *common_parent=p_node;
while(common_parent) {
if (visited.has(common_parent))
break;
common_parent=common_parent->data.parent;
}
ERR_FAIL_COND_V(!common_parent,NodePath()); //nodes not in the same tree
visited.clear();
Vector<StringName> path;
n=p_node;
while(n!=common_parent) {
path.push_back( n->get_name() );
n=n->data.parent;
}
n=this;
StringName up=String("..");
while(n!=common_parent) {
path.push_back( up );
n=n->data.parent;
}
path.invert();
return NodePath(path,false);
}
NodePath Node::get_path() const {
ERR_FAIL_COND_V(!is_inside_tree(),NodePath());
const Node *n = this;
Vector<StringName> path;
while(n) {
path.push_back(n->get_name());
n=n->data.parent;
}
path.invert();
return NodePath( path, true );
}
bool Node::is_in_group(const StringName& p_identifier) const {
return data.grouped.has(p_identifier);
}
void Node::add_to_group(const StringName& p_identifier,bool p_persistent) {
ERR_FAIL_COND(!p_identifier.operator String().length());
if (data.grouped.has(p_identifier))
return;
GroupData gd;
if (data.tree)
data.tree->add_to_group(p_identifier,this);
gd.persistent=p_persistent;
data.grouped[p_identifier]=gd;
}
void Node::remove_from_group(const StringName& p_identifier) {
ERR_FAIL_COND(!data.grouped.has(p_identifier) );
GroupData *g=data.grouped.getptr(p_identifier);
ERR_FAIL_COND(!g);
if (data.tree)
data.tree->remove_from_group(p_identifier,this);
data.grouped.erase(p_identifier);
}
Array Node::_get_groups() const {
Array groups;
List<GroupInfo> gi;
get_groups(&gi);
for (List<GroupInfo>::Element *E=gi.front();E;E=E->next()) {
groups.push_back(E->get().name);
}
return groups;
}
void Node::get_groups(List<GroupInfo> *p_groups) const {
const StringName *K=NULL;
while ((K=data.grouped.next(K))) {
GroupInfo gi;
gi.name=*K;
gi.persistent=data.grouped[*K].persistent;
p_groups->push_back(gi);
}
}
void Node::_print_tree(const Node *p_node) {
print_line(String(p_node->get_path_to(this)));
for (int i=0;i<data.children.size();i++)
data.children[i]->_print_tree(p_node);
}
void Node::print_tree() {
_print_tree(this);
}
void Node::<API key>(int p_notification) {
data.blocked++;
for (int i=data.children.size()-1;i>=0;i
data.children[i]-><API key>(p_notification);
}
notification(p_notification,true);
data.blocked
}
void Node::<API key>(int p_notification, bool p_reverse) {
ERR_FAIL_COND(!is_inside_tree());
data.blocked++;
if (!p_reverse)
MessageQueue::get_singleton()->push_notification(this,p_notification);
for (int i=0;i<data.children.size();i++) {
data.children[i]-><API key>(p_notification,p_reverse);
}
if (p_reverse)
MessageQueue::get_singleton()->push_notification(this,p_notification);
data.blocked
}
void Node::<API key>(int p_notification) {
data.blocked++;
notification(p_notification);
for (int i=0;i<data.children.size();i++) {
data.children[i]-><API key>(p_notification);
}
data.blocked
}
void Node::<API key>(Node *p_owner,Node* p_by_owner) {
if (get_owner()==p_owner)
set_owner(p_by_owner);
data.blocked++;
for (int i=0;i<data.children.size();i++)
data.children[i]-><API key>(p_owner,p_by_owner);
data.blocked
}
int Node::get_index() const {
return data.pos;
}
void Node::remove_and_skip() {
ERR_FAIL_COND(!data.parent);
Node *new_owner=get_owner();
List<Node*> children;
while(true) {
bool clear=true;
for (int i=0;i<data.children.size();i++) {
if (!data.children[i]->get_owner())
continue;
remove_child(data.children[i]);
data.children[i]-><API key>(this,NULL);
children.push_back(data.children[i]);
clear=false;
break;
}
if (clear)
break;
}
while(!children.empty()) {
Node *c=children.front()->get();
data.parent->add_child(c);
c-><API key>(NULL,new_owner);
children.pop_front();
}
data.parent->remove_child(this);
}
void Node::set_filename(const String& p_filename) {
data.filename=p_filename;
}
String Node::get_filename() const {
return data.filename;
}
void Node::<API key>(Node* p_node,bool p_editable) {
ERR_FAIL_NULL(p_node);
ERR_FAIL_COND(!is_a_parent_of(p_node));
NodePath p = get_path_to(p_node);
if (!p_editable)
data.editable_instances.erase(p);
else
data.editable_instances[p]=true;
}
bool Node::<API key>(Node *p_node) const {
if (!p_node)
return false; //easier, null is never editable :)
ERR_FAIL_COND_V(!is_a_parent_of(p_node),false);
NodePath p = get_path_to(p_node);
return data.editable_instances.has(p);
}
#if 0
void Node::<API key>() {
List<PropertyInfo> properties;
get_property_list(&properties);
data.instance_state.clear();
for( List<PropertyInfo>::Element *E=properties.front();E;E=E->next() ) {
PropertyInfo &pi=E->get();
if ((pi.usage&<API key>) || !(pi.usage&<API key>) || !(pi.usage&<API key>))
continue;
data.instance_state[pi.name]=get(pi.name);
}
List<GroupInfo> groups;
get_groups(&groups);
for(List<GroupInfo>::Element *E=groups.front();E;E=E->next()) {
if (!E->get().persistent)
continue;
data.instance_groups.push_back(E->get().name);
}
List<MethodInfo> signal_list;
get_signal_list(&signal_list);
for(List<MethodInfo>::Element *E=signal_list.front();E;E=E->next()) {
StringName name = E->get().name;
List<Connection> connections;
<API key>(name,&connections);
for(List<Connection>::Element *F=connections.front();F;F=F->next()) {
if (F->get().flags&CONNECT_PERSIST)
data.<API key>.push_back(F->get());
}
}
}
Dictionary Node::get_instance_state() const {
return data.instance_state;
}
#endif
void Node::<API key>(const Ref<SceneState>& p_state) {
data.instance_state=p_state;
}
Ref<SceneState> Node::<API key>() const{
return data.instance_state;
}
void Node::<API key>(const Ref<SceneState>& p_state) {
data.inherited_state=p_state;
}
Ref<SceneState> Node::<API key>() const{
return data.inherited_state;
}
void Node::<API key>(bool p_enable) {
data.use_placeholder=p_enable;
}
bool Node::<API key>() const{
return data.use_placeholder;
}
int Node::<API key>() const {
return data.pos;
}
Node *Node::duplicate(bool p_use_instancing) const {
Node *node=NULL;
bool instanced=false;
if (cast_to<InstancePlaceholder>()) {
const InstancePlaceholder *ip = cast_to<const InstancePlaceholder>();
InstancePlaceholder *nip = memnew( InstancePlaceholder );
nip->set_instance_path( ip->get_instance_path() );
node=nip;
} else if (p_use_instancing && get_filename()!=String()) {
Ref<PackedScene> res = ResourceLoader::load(get_filename());
ERR_FAIL_COND_V(res.is_null(),NULL);
node=res->instance();
ERR_FAIL_COND_V(!node,NULL);
instanced=true;
} else {
Object *obj = ObjectTypeDB::instance(get_type());
ERR_FAIL_COND_V(!obj,NULL);
node = obj->cast_to<Node>();
if (!node)
memdelete(obj);
ERR_FAIL_COND_V(!node,NULL);
}
if (get_filename()!="") { //an instance
node->set_filename(get_filename());
}
List<PropertyInfo> plist;
get_property_list(&plist);
for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
if (!(E->get().usage&<API key>))
continue;
String name = E->get().name;
node->set( name, get(name) );
}
node->set_name(get_name());
List<GroupInfo> gi;
get_groups(&gi);
for (List<GroupInfo>::Element *E=gi.front();E;E=E->next()) {
node->add_to_group(E->get().name, E->get().persistent);
}
_duplicate_signals(this, node);
for(int i=0;i<get_child_count();i++) {
if (get_child(i)->data.parent_owned)
continue;
if (instanced && get_child(i)->data.owner==this)
continue; //part of instance
Node *dup = get_child(i)->duplicate(p_use_instancing);
if (!dup) {
memdelete(node);
return NULL;
}
node->add_child(dup);
}
return node;
}
void Node::<API key>(Node* p_new_parent, const Map<Node*,Node*>& p_reown_map) const {
if (get_owner()!=get_parent()->get_owner())
return;
Node *node=NULL;
if (get_filename()!="") {
Ref<PackedScene> res = ResourceLoader::load(get_filename());
ERR_FAIL_COND(res.is_null());
node=res->instance();
ERR_FAIL_COND(!node);
} else {
Object *obj = ObjectTypeDB::instance(get_type());
if (!obj) {
print_line("could not duplicate: "+String(get_type()));
}
ERR_FAIL_COND(!obj);
node = obj->cast_to<Node>();
if (!node)
memdelete(obj);
}
List<PropertyInfo> plist;
get_property_list(&plist);
for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
if (!(E->get().usage&<API key>))
continue;
String name = E->get().name;
node->set( name, get(name) );
}
node->set_name(get_name());
p_new_parent->add_child(node);
Node *owner=get_owner();
if (p_reown_map.has(owner))
owner=p_reown_map[owner];
if (owner) {
NodePath p = get_path_to(owner);
if (owner!=this) {
Node *new_owner = node->get_node(p);
if (new_owner) {
node->set_owner(new_owner);
}
}
}
for(int i=0;i<get_child_count();i++) {
get_child(i)-><API key>(node,p_reown_map);
}
}
void Node::_duplicate_signals(const Node* p_original,Node* p_copy) const {
if (this!=p_original && get_owner()!=p_original)
return;
List<Connection> conns;
<API key>(&conns);
for (List<Connection>::Element *E=conns.front();E;E=E->next()) {
if (E->get().flags&CONNECT_PERSIST) {
//user connected
NodePath p = p_original->get_path_to(this);
Node *copy = p_copy->get_node(p);
Node *target = E->get().target->cast_to<Node>();
if (!target)
continue;
NodePath ptarget = p_original->get_path_to(target);
Node *copytarget = p_copy->get_node(ptarget);
if (copy && copytarget) {
copy->connect(E->get().signal,copytarget,E->get().method,E->get().binds,CONNECT_PERSIST);
}
}
}
for(int i=0;i<get_child_count();i++) {
get_child(i)->_duplicate_signals(p_original,p_copy);
}
}
Node *Node::duplicate_and_reown(const Map<Node*,Node*>& p_reown_map) const {
ERR_FAIL_COND_V(get_filename()!="",NULL);
Node *node=NULL;
Object *obj = ObjectTypeDB::instance(get_type());
if (!obj) {
print_line("could not duplicate: "+String(get_type()));
}
ERR_FAIL_COND_V(!obj,NULL);
node = obj->cast_to<Node>();
if (!node)
memdelete(obj);
ERR_FAIL_COND_V(!node,NULL);
node->set_name(get_name());
List<PropertyInfo> plist;
get_property_list(&plist);
for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
if (!(E->get().usage&<API key>))
continue;
String name = E->get().name;
node->set( name, get(name) );
}
for(int i=0;i<get_child_count();i++) {
get_child(i)-><API key>(node,p_reown_map);
}
_duplicate_signals(this,node);
return node;
}
static void find_owned_by(Node* p_by, Node* p_node, List<Node*> *p_owned) {
if (p_node->get_owner()==p_by)
p_owned->push_back(p_node);
for(int i=0;i<p_node->get_child_count();i++) {
find_owned_by(p_by,p_node->get_child(i),p_owned);
}
}
struct _NodeReplaceByPair {
String name;
Variant value;
};
void Node::replace_by(Node* p_node,bool p_keep_data) {
ERR_FAIL_NULL(p_node);
ERR_FAIL_COND(p_node->data.parent);
List<Node*> owned = data.owned;
List<Node*> owned_by_owner;
Node *owner = (data.owner==this)?p_node:data.owner;
List<_NodeReplaceByPair> replace_data;
if (p_keep_data) {
List<PropertyInfo> plist;
get_property_list(&plist);
for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next() ) {
_NodeReplaceByPair rd;
if (!(E->get().usage&<API key>))
continue;
rd.name=E->get().name;
rd.value=get(rd.name);
}
}
if (data.owner) {
for(int i=0;i<get_child_count();i++)
find_owned_by(data.owner,get_child(i),&owned_by_owner);
}
Node *parent = data.parent;
int pos_in_parent = data.pos;
if (data.parent) {
parent->remove_child(this);
parent->add_child(p_node);
parent->move_child(p_node,pos_in_parent);
}
while(get_child_count()) {
Node * child = get_child(0);
remove_child(child);
p_node->add_child(child);
}
p_node->set_owner(owner);
for(int i=0;i<owned.size();i++)
owned[i]->set_owner(p_node);
for(int i=0;i<owned_by_owner.size();i++)
owned_by_owner[i]->set_owner(owner);
p_node->set_filename(get_filename());
for (List<_NodeReplaceByPair>::Element *E=replace_data.front();E;E=E->next()) {
p_node->set(E->get().name,E->get().value);
}
}
Vector<Variant> Node::make_binds(VARIANT_ARG_DECLARE) {
Vector<Variant> ret;
if (p_arg1.get_type()==Variant::NIL)
return ret;
else
ret.push_back(p_arg1);
if (p_arg2.get_type()==Variant::NIL)
return ret;
else
ret.push_back(p_arg2);
if (p_arg3.get_type()==Variant::NIL)
return ret;
else
ret.push_back(p_arg3);
if (p_arg4.get_type()==Variant::NIL)
return ret;
else
ret.push_back(p_arg4);
if (p_arg5.get_type()==Variant::NIL)
return ret;
else
ret.push_back(p_arg5);
return ret;
}
bool Node::<API key>(const NodePath& p_path) const {
if (!has_node(p_path))
return false;
Node *node = get_node(p_path);
if (p_path.get_subname_count()) {
RES r;
for(int j=0;j<p_path.get_subname_count();j++) {
r = j==0 ? node->get(p_path.get_subname(j)) : r->get(p_path.get_subname(j));
if (r.is_null())
return false;
}
}
return true;
}
Array Node::<API key>(const NodePath& p_path) {
Node *node;
RES res;
node = <API key>(p_path,res);
Array result;
if (node)
result.push_back(node);
else
result.push_back(Variant());
if (res.is_valid())
result.push_back(res);
else
result.push_back(Variant());
return result;
}
Node *Node::<API key>(const NodePath& p_path,RES& r_res) const {
Node *node = get_node(p_path);
r_res = RES();
if (!node)
return NULL;
if (p_path.get_subname_count()) {
for(int j=0;j<p_path.get_subname_count();j++) {
r_res = j==0 ? node->get(p_path.get_subname(j)) : r_res->get(p_path.get_subname(j));
ERR_FAIL_COND_V( r_res.is_null(), node );
}
}
return node;
}
void Node::_set_tree(SceneTree *p_tree) {
SceneTree *tree_changed_a=NULL;
SceneTree *tree_changed_b=NULL;
// ERR_FAIL_COND(p_scene && data.parent && !data.parent->data.scene); //nobug if both are null
if (data.tree) {
<API key>();
tree_changed_a=data.tree;
}
data.tree=p_tree;
if (data.tree) {
<API key>();
_propagate_ready(); //<API key>(NOTIFICATION_READY);
tree_changed_b=data.tree;
}
if (tree_changed_a)
tree_changed_a->tree_changed();
if (tree_changed_b)
tree_changed_b->tree_changed();
}
static void _Node_debug_sn(Object *p_obj) {
Node *n = p_obj->cast_to<Node>();
if (!n)
return;
if (n->is_inside_tree())
return;
Node *p=n;
while(p->get_parent()) {
p=p->get_parent();
}
String path;
if (p==n)
path=n->get_name();
else
path=String(p->get_name())+"/"+p->get_path_to(n);
print_line(itos(p_obj->get_instance_ID())+"- Stray Node: "+path+" (Type: "+n->get_type()+")");
}
void Node::_print_stray_nodes() {
print_stray_nodes();
}
void Node::print_stray_nodes() {
#ifdef DEBUG_ENABLED
ObjectDB::debug_objects(_Node_debug_sn);
#endif
}
void Node::queue_delete() {
ERR_FAIL_COND( !is_inside_tree() );
get_tree()->queue_delete(this);
}
Array Node::_get_children() const {
Array arr;
int cc = get_child_count();
arr.resize(cc);
for(int i=0;i<cc;i++)
arr[i]=get_child(i);
return arr;
}
#ifdef TOOLS_ENABLED
void Node::set_import_path(const NodePath& p_import_path) {
data.import_path=p_import_path;
}
NodePath Node::get_import_path() const {
return data.import_path;
}
#endif
static void <API key>(const Node *p_base,const Node *p_node,List<String>*r_options) {
if (p_node!=p_base && !p_node->get_owner())
return;
String n = p_base->get_path_to(p_node);
r_options->push_back("\""+n+"\"");
for(int i=0;i<p_node->get_child_count();i++) {
<API key>(p_base,p_node->get_child(i),r_options);
}
}
void Node::<API key>(const StringName& p_function,int p_idx,List<String>*r_options) const {
String pf=p_function;
if ((pf=="has_node" || pf=="get_node") && p_idx==0) {
<API key>(this,this,r_options);
}
Object::<API key>(p_function,p_idx,r_options);
}
void Node::<API key>() {
<API key>();
for(int i=0;i<data.children.size();i++) {
data.children[i]-><API key>();
}
}
void Node::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_name","name"),&Node::set_name);
ObjectTypeDB::bind_method(_MD("get_name"),&Node::get_name);
ObjectTypeDB::bind_method(_MD("add_child","node:Node","legible_unique_name"),&Node::add_child,DEFVAL(false));
ObjectTypeDB::bind_method(_MD("remove_child","node:Node"),&Node::remove_child);
//ObjectTypeDB::bind_method(_MD("<API key>","node:Node"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("get_child_count"),&Node::get_child_count);
ObjectTypeDB::bind_method(_MD("get_children"),&Node::_get_children);
ObjectTypeDB::bind_method(_MD("get_child:Node","idx"),&Node::get_child);
ObjectTypeDB::bind_method(_MD("has_node","path"),&Node::has_node);
ObjectTypeDB::bind_method(_MD("get_node:Node","path"),&Node::get_node);
ObjectTypeDB::bind_method(_MD("get_parent:Parent"),&Node::get_parent);
ObjectTypeDB::bind_method(_MD("find_node:Node","mask","recursive","owned"),&Node::find_node,DEFVAL(true),DEFVAL(true));
ObjectTypeDB::bind_method(_MD("<API key>","path"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("<API key>","path"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("is_inside_tree"),&Node::is_inside_tree);
ObjectTypeDB::bind_method(_MD("is_a_parent_of","node:Node"),&Node::is_a_parent_of);
ObjectTypeDB::bind_method(_MD("is_greater_than","node:Node"),&Node::is_greater_than);
ObjectTypeDB::bind_method(_MD("get_path"),&Node::get_path);
ObjectTypeDB::bind_method(_MD("get_path_to","node:Node"),&Node::get_path_to);
ObjectTypeDB::bind_method(_MD("add_to_group","group","persistent"),&Node::add_to_group,DEFVAL(false));
ObjectTypeDB::bind_method(_MD("remove_from_group","group"),&Node::remove_from_group);
ObjectTypeDB::bind_method(_MD("is_in_group","group"),&Node::is_in_group);
ObjectTypeDB::bind_method(_MD("move_child","child_node:Node","to_pos"),&Node::move_child);
ObjectTypeDB::bind_method(_MD("get_groups"),&Node::_get_groups);
ObjectTypeDB::bind_method(_MD("raise"),&Node::raise);
ObjectTypeDB::bind_method(_MD("set_owner","owner:Node"),&Node::set_owner);
ObjectTypeDB::bind_method(_MD("get_owner:Node"),&Node::get_owner);
ObjectTypeDB::bind_method(_MD("remove_and_skip"),&Node::remove_and_skip);
ObjectTypeDB::bind_method(_MD("get_index"),&Node::get_index);
ObjectTypeDB::bind_method(_MD("print_tree"),&Node::print_tree);
ObjectTypeDB::bind_method(_MD("set_filename","filename"),&Node::set_filename);
ObjectTypeDB::bind_method(_MD("get_filename"),&Node::get_filename);
ObjectTypeDB::bind_method(_MD("<API key>","what"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("set_fixed_process","enable"),&Node::set_fixed_process);
ObjectTypeDB::bind_method(_MD("<API key>"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("is_fixed_processing"),&Node::is_fixed_processing);
ObjectTypeDB::bind_method(_MD("set_process","enable"),&Node::set_process);
ObjectTypeDB::bind_method(_MD("<API key>"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("is_processing"),&Node::is_processing);
ObjectTypeDB::bind_method(_MD("set_process_input","enable"),&Node::set_process_input);
ObjectTypeDB::bind_method(_MD("is_processing_input"),&Node::is_processing_input);
ObjectTypeDB::bind_method(_MD("<API key>","enable"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("<API key>"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("<API key>","enable"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("<API key>"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("set_pause_mode","mode"),&Node::set_pause_mode);
ObjectTypeDB::bind_method(_MD("get_pause_mode"),&Node::get_pause_mode);
ObjectTypeDB::bind_method(_MD("can_process"),&Node::can_process);
ObjectTypeDB::bind_method(_MD("print_stray_nodes"),&Node::_print_stray_nodes);
ObjectTypeDB::bind_method(_MD("<API key>"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("get_tree:SceneTree"),&Node::get_tree);
ObjectTypeDB::bind_method(_MD("duplicate:Node","use_instancing"),&Node::duplicate,DEFVAL(false));
ObjectTypeDB::bind_method(_MD("replace_by","node:Node","keep_data"),&Node::replace_by,DEFVAL(false));
ObjectTypeDB::bind_method(_MD("<API key>","load_placeholder"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("<API key>"),&Node::<API key>);
ObjectTypeDB::bind_method(_MD("get_viewport"),&Node::get_viewport);
ObjectTypeDB::bind_method(_MD("queue_free"),&Node::queue_delete);
#ifdef TOOLS_ENABLED
ObjectTypeDB::bind_method(_MD("_set_import_path","import_path"),&Node::set_import_path);
ObjectTypeDB::bind_method(_MD("_get_import_path"),&Node::get_import_path);
ADD_PROPERTYNZ( PropertyInfo(Variant::NODE_PATH,"_import_path",PROPERTY_HINT_NONE,"",<API key>),_SCS("_set_import_path"),_SCS("_get_import_path"));
#endif
BIND_CONSTANT( <API key> );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( <API key> );
//BIND_CONSTANT( <API key> );
BIND_CONSTANT( NOTIFICATION_READY );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( NOTIFICATION_PAUSED );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( <API key> );
BIND_CONSTANT( PAUSE_MODE_INHERIT );
BIND_CONSTANT( PAUSE_MODE_STOP );
BIND_CONSTANT( PAUSE_MODE_PROCESS );
ADD_SIGNAL( MethodInfo("renamed") );
ADD_SIGNAL( MethodInfo("enter_tree") );
ADD_SIGNAL( MethodInfo("exit_tree") );
// ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/process" ),_SCS("set_process"),_SCS("is_processing") );
// ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/fixed_process" ), _SCS("set_fixed_process"),_SCS("is_fixed_processing") );
//ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/input" ), _SCS("set_process_input"),_SCS("is_processing_input" ) );
//ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/unhandled_input" ), _SCS("<API key>"),_SCS("<API key>" ) );
ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "process/pause_mode",PROPERTY_HINT_ENUM,"Inherit,Stop,Process" ), _SCS("set_pause_mode"),_SCS("get_pause_mode" ) );
BIND_VMETHOD( MethodInfo("_process",PropertyInfo(Variant::REAL,"delta")) );
BIND_VMETHOD( MethodInfo("_fixed_process",PropertyInfo(Variant::REAL,"delta")) );
BIND_VMETHOD( MethodInfo("_enter_tree") );
BIND_VMETHOD( MethodInfo("_exit_tree") );
BIND_VMETHOD( MethodInfo("_ready") );
BIND_VMETHOD( MethodInfo("_input",PropertyInfo(Variant::INPUT_EVENT,"event")) );
BIND_VMETHOD( MethodInfo("_unhandled_input",PropertyInfo(Variant::INPUT_EVENT,"event")) );
BIND_VMETHOD( MethodInfo("<API key>",PropertyInfo(Variant::INPUT_EVENT,"key_event")) );
//ObjectTypeDB::bind_method(_MD("get_child",&Node::get_child,PH("index")));
//ObjectTypeDB::bind_method(_MD("get_node",&Node::get_node,PH("path")));
}
Node::Node() {
data.pos=-1;
data.depth=-1;
data.blocked=0;
data.parent=NULL;
data.tree=NULL;
data.fixed_process=false;
data.idle_process=false;
data.inside_tree=false;
data.owner=NULL;
data.OW=NULL;
data.input=false;
data.unhandled_input=false;
data.unhandled_key_input=false;
data.pause_mode=PAUSE_MODE_INHERIT;
data.pause_owner=NULL;
data.parent_owned=false;
data.in_constructor=true;
data.viewport=NULL;
data.use_placeholder=false;
}
Node::~Node() {
data.grouped.clear();
data.owned.clear();
data.children.clear();
ERR_FAIL_COND(data.parent);
ERR_FAIL_COND(data.children.size());
}
|
package com.laytonsmith.PureUtilities.VirtualFS;
import java.io.File;
import java.io.FileInputStream;
import java.io.<API key>;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
@FileSystemLayer.fslayer("file")
public class RealFileSystemLayer extends FileSystemLayer {
protected final File real;
public RealFileSystemLayer(VirtualFile path, VirtualFileSystem fileSystem, String symlink) throws IOException {
super(path, fileSystem);
if (symlink == null) {
real = new File(fileSystem.root, path.getPath());
if (!real.getCanonicalPath().startsWith(fileSystem.root.getCanonicalPath())) {
throw new PermissionException(path.getPath() + " extends above the root directory of this file system, and does not point to a valid file.");
}
} else {
File symlinkRoot = new File(fileSystem.symlinkFile, symlink);
real = new File(symlinkRoot, path.getPath());
//If the path extends above the symlink, disallow it
if (!real.getCanonicalPath().startsWith(symlinkRoot.getCanonicalPath())) {
//Unless of course, the path is still within the full real path, then
//eh, we'll allow it.
if (!real.getCanonicalPath().startsWith(fileSystem.root.getCanonicalPath())) {
throw new PermissionException(path.getPath() + " extends above the root directory of this file system, and does not point to a valid file.");
}
}
}
}
@Override
public InputStream getInputStream() throws <API key> {
return new FileInputStream(real);
}
@Override
public void writeByteArray(byte[] bytes) throws IOException {
FileUtils.<API key>(real, bytes);
}
@Override
public VirtualFile[] listFiles() throws IOException {
List<VirtualFile> virtuals = new ArrayList<VirtualFile>();
for (File sub : real.listFiles()) {
virtuals.add(normalize(sub));
}
return virtuals.toArray(new VirtualFile[virtuals.size()]);
}
private VirtualFile normalize(File real) throws IOException {
String path = real.getCanonicalPath().replaceFirst(Pattern.quote(fileSystem.root.getCanonicalPath()), "");
path = path.replace("\\", "/");
if (!path.startsWith("/")) {
path = "/" + path;
}
return new VirtualFile(path);
}
@Override
public void delete() throws IOException {
if (!real.delete()) {
throw new IOException("Could not delete the file");
}
}
@Override
public void deleteOnExit() {
real.deleteOnExit();
}
@Override
public boolean exists() {
return real.exists();
}
@Override
public boolean canRead() {
return real.canRead();
}
@Override
public boolean canWrite() {
return real.canWrite();
}
@Override
public boolean isDirectory() {
return real.isDirectory();
}
@Override
public boolean isFile() {
return real.isFile();
}
@Override
public void mkdirs() throws IOException {
if (!real.mkdirs()) {
throw new IOException("Directory structure could not be created");
}
}
@Override
public void createNewFile() throws IOException {
if (!real.createNewFile()) {
throw new IOException("File already exists!");
}
}
}
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImport;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddMissingImports
{
internal abstract class <API key> : <API key>
{
protected abstract ImmutableArray<string> <API key> { get; }
public async Task<bool> <API key>(Document document, TextSpan textSpan, Cancellation<API key>)
{
// Get the diagnostics that indicate a missing import.
var diagnostics = await GetDiagnosticsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (diagnostics.IsEmpty)
{
return false;
}
// Find fixes for the diagnostic where there is only a single fix.
var usableFixes = await <API key>(document, diagnostics, cancellationToken).ConfigureAwait(false);
return !usableFixes.IsEmpty;
}
public async Task<Project> <API key>(Document document, TextSpan textSpan, Cancellation<API key>)
{
// Get the diagnostics that indicate a missing import.
var diagnostics = await GetDiagnosticsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (diagnostics.IsEmpty)
{
return document.Project;
}
// Find fixes for the diagnostic where there is only a single fix.
var unambiguousFixes = await <API key>(document, diagnostics, cancellationToken).ConfigureAwait(false);
// We do not want to add project or framework references without the user's input, so filter those out.
var usableFixes = unambiguousFixes.WhereAsArray(fixData => DoesNotAddReference(fixData, document.Project.Id));
if (usableFixes.IsEmpty)
{
return document.Project;
}
// Apply those fixes to the document.
var newDocument = await ApplyFixesAsync(document, usableFixes, cancellationToken).ConfigureAwait(false);
return newDocument.Project;
}
private static bool DoesNotAddReference(AddImportFixData fixData, ProjectId currentProjectId)
{
return (fixData.<API key> is null || fixData.<API key> == currentProjectId)
&& (fixData.<API key> is null || fixData.<API key> == currentProjectId)
&& string.IsNullOrEmpty(fixData.<API key>);
}
private async Task<ImmutableArray<Diagnostic>> GetDiagnosticsAsync(Document document, TextSpan textSpan, Cancellation<API key>)
{
var semanticModel = await document.<API key>(cancellationToken).ConfigureAwait(false);
if (semanticModel is null)
{
return ImmutableArray<Diagnostic>.Empty;
}
return semanticModel.GetDiagnostics(textSpan, cancellationToken)
.Where(diagnostic => <API key>.Contains(diagnostic.Id))
.ToImmutableArray();
}
private static async Task<ImmutableArray<AddImportFixData>> <API key>(Document document, ImmutableArray<Diagnostic> diagnostics, Cancellation<API key>)
{
var solution = document.Project.Solution;
var symbolSearchService = solution.Workspace.Services.GetService<<API key>>();
// Since we are not currently considering NuGet packages, pass an empty array
var packageSources = ImmutableArray<PackageSource>.Empty;
var addImportService = document.GetLanguageService<<API key>>();
// We only need to receive 2 results back per diagnostic to determine that the fix is ambiguous.
var <API key> = diagnostics
.GroupBy(diagnostic => diagnostic.Location.SourceSpan)
.Select(<API key> => addImportService
.<API key>(document, <API key>.Key, <API key>.AsImmutable(),
<API key>: 2, symbolSearchService, <API key>: true, packageSources, cancellationToken));
using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var fixes);
foreach (var <API key> in <API key>)
{
var fixesForDiagnostics = await <API key>.ConfigureAwait(false);
foreach (var fixesForDiagnostic in fixesForDiagnostics)
{
// When there is more than one potential fix for a missing import diagnostic,
// which is possible when the same class name is present in multiple namespaces,
// we do not want to choose for the user and be wrong. We will not attempt to
// fix this diagnostic and instead leave it for the user to resolve since they
// will have more context for determining the proper fix.
if (fixesForDiagnostic.Fixes.Length == 1)
fixes.Add(fixesForDiagnostic.Fixes[0]);
}
}
return fixes.ToImmutable();
}
private static async Task<Document> ApplyFixesAsync(Document document, ImmutableArray<AddImportFixData> fixes, Cancellation<API key>)
{
if (fixes.IsEmpty)
{
return document;
}
var solution = document.Project.Solution;
var progressTracker = new ProgressTracker();
var textDiffingService = solution.Workspace.Services.GetService<<API key>>();
var <API key> = solution.Workspace.Services.GetService<<API key>>();
var addImportService = document.GetLanguageService<<API key>>();
// Do not limit the results since we plan to fix all the reported issues.
var codeActions = addImportService.<API key>(document, fixes, <API key>, maxResults: int.MaxValue);
var getChangesTasks = codeActions.Select(
action => <API key>(document, action, progressTracker, textDiffingService, cancellationToken));
// Using Sets allows us to accumulate only the distinct changes.
var allTextChanges = new HashSet<TextChange>();
// Some fixes require adding missing references.
var <API key> = new HashSet<ProjectReference>();
var <API key> = new HashSet<MetadataReference>();
foreach (var getChangesTask in getChangesTasks)
{
var (projectChanges, textChanges) = await getChangesTask.ConfigureAwait(false);
allTextChanges.UnionWith(textChanges);
<API key>.UnionWith(projectChanges.<API key>());
<API key>.UnionWith(projectChanges.<API key>());
}
// Apply changes to both the project and document.
var newProject = document.Project;
newProject = newProject.<API key>(<API key>);
newProject = newProject.<API key>(<API key>);
// Only consider insertion changes to reduce the chance of producing a
// badly merged final document. Alphabetize the new imports, this will not
// change the insertion point but will give a more correct result. The user
// may still need to use organize imports afterwards.
var orderedTextInserts = allTextChanges.Where(change => change.Span.IsEmpty)
.OrderBy(change => change.NewText);
// Capture each location where we are inserting imports as well as the total
// length of the text we are inserting so that we can format the span afterwards.
var insertSpans = allTextChanges
.GroupBy(change => change.Span)
.Select(changes => new TextSpan(changes.Key.Start, changes.Sum(change => change.NewText.Length)));
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = text.WithChanges(orderedTextInserts);
var newDocument = newProject.GetDocument(document.Id).WithText(newText);
// When imports are added to a code file that has no previous imports, extra
// newlines are generated between each import because the fix is expecting to
// separate the imports from the rest of the code file. We need to format the
// imports to remove these extra newlines.
return await <API key>(newDocument, insertSpans, cancellationToken).ConfigureAwait(false);
}
private static async Task<Document> <API key>(Document document, IEnumerable<TextSpan> insertSpans, Cancellation<API key>)
{
var languageFormatter = document.GetLanguageService<<API key>>();
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var newDocument = document;
// Since imports can be added at both the CompilationUnit and the Namespace level,
// format each span individually so that we can retain each newline that was intended
// to separate the import section from the other content.
foreach (var insertSpan in insertSpans)
{
newDocument = await <API key>(newDocument, insertSpan, languageFormatter, options, cancellationToken).ConfigureAwait(false);
}
return newDocument;
}
private static async Task<Document> <API key>(Document document, TextSpan insertSpan, <API key> languageFormatter, OptionSet optionSet, Cancellation<API key>)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var optionService = document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>();
var <API key> = optionSet.GetOption(FormattingOptions.<API key>);
var options = optionSet.<API key>(optionService, root.Language);
var textChanges = languageFormatter.Format(root, new[] { insertSpan }, <API key>, options, new[] { new <API key>(text) }, cancellationToken).GetTextChanges(cancellationToken);
// If there are no changes then, do less work.
if (textChanges.Count == 0)
{
return document;
}
// The last text change should include where the insert span ends
Debug.Assert(textChanges.Last().Span.IntersectsWith(insertSpan.End));
// If there are changes then, this was a case where there were no
// previous imports statements. We need to retain the final extra
// newline because that separates the imports section from the rest
// of the code.
textChanges.RemoveAt(textChanges.Count - 1);
var newText = text.WithChanges(textChanges);
return document.WithText(newText);
}
private static async Task<(ProjectChanges, IEnumerable<TextChange>)> <API key>(
Document document,
CodeAction codeAction,
ProgressTracker progressTracker,
<API key> textDiffingService,
Cancellation<API key>)
{
var newSolution = await codeAction.<API key>(
progressTracker, cancellation<API key>).ConfigureAwait(false);
var newDocument = newSolution.GetDocument(document.Id);
// Use Line differencing to reduce the possibility of changes that overwrite existing code.
var textChanges = await textDiffingService.GetTextChangesAsync(
document, newDocument, TextDifferenceTypes.Line, cancellationToken).ConfigureAwait(false);
var projectChanges = newDocument.Project.GetChanges(document.Project);
return (projectChanges, textChanges);
}
private sealed class <API key> : <API key>
{
private readonly SourceText _text;
public <API key>(SourceText text)
=> _text = text;
public override <API key> <API key>(in SyntaxToken previousToken, in SyntaxToken currentToken, in <API key> nextOperation)
{
// Since we know the general shape of these new import statements, we simply look for where
// tokens are not on the same line and force them to only be separated by a single newline.
_text.GetLineAndOffset(previousToken.Span.Start, out var previousLine, out _);
_text.GetLineAndOffset(currentToken.Span.Start, out var currentLine, out _);
if (previousLine != currentLine)
{
return <API key>.<API key>(1, <API key>.ForceLines);
}
return null;
}
}
}
}
|
/**
* @ngdoc service
* @name umbraco.services.umbRequestHelper
* @description A helper object used for sending requests to the server
**/
function umbRequestHelper($http, $q, <API key>, eventsService, formHelper, overlayService) {
return {
/**
* @ngdoc method
* @name umbraco.services.umbRequestHelper#<API key>
* @methodOf umbraco.services.umbRequestHelper
* @function
*
* @description
* This will convert a virtual path (i.e. ~/App_Plugins/Blah/Test.html ) to an absolute path
*
* @param {string} a virtual path, if this is already an absolute path it will just be returned, if this is a relative path an exception will be thrown
*/
<API key>: function(virtualPath) {
if (virtualPath.startsWith("/")) {
return virtualPath;
}
if (!virtualPath.startsWith("~/")) {
throw "The path " + virtualPath + " is not a virtual path";
}
if (!Umbraco.Sys.ServerVariables.application.applicationPath) {
throw "No applicationPath defined in Umbraco.ServerVariables.application.applicationPath";
}
return Umbraco.Sys.ServerVariables.application.applicationPath + virtualPath.trimStart("~/");
},
/**
* @ngdoc method
* @name umbraco.services.umbRequestHelper#<API key>
* @methodOf umbraco.services.umbRequestHelper
* @function
*
* @description
* This will turn an array of key/value pairs or a standard dictionary into a query string
*
* @param {Array} queryStrings An array of key/value pairs
*/
<API key>: function (queryStrings) {
if (Utilities.isArray(queryStrings)) {
return _.map(queryStrings, function (item) {
var key = null;
var val = null;
for (var k in item) {
key = k;
val = item[k];
break;
}
if (key === null || val === null) {
throw "The object in the array was not formatted as a key/value pair";
}
return encodeURIComponent(key) + "=" + encodeURIComponent(val);
}).join("&");
}
else if (Utilities.isObject(queryStrings)) {
//this allows for a normal object to be passed in (ie. a dictionary)
return decodeURIComponent($.param(queryStrings));
}
throw "The queryString parameter is not an array or object of key value pairs";
},
/**
* @ngdoc method
* @name umbraco.services.umbRequestHelper#getApiUrl
* @methodOf umbraco.services.umbRequestHelper
* @function
*
* @description
* This will return the webapi Url for the requested key based on the servervariables collection
*
* @param {string} apiName The webapi name that is found in the servervariables["umbracoUrls"] dictionary
* @param {string} actionName The webapi action name
* @param {object} queryStrings Can be either a string or an array containing key/value pairs
*/
getApiUrl: function (apiName, actionName, queryStrings) {
if (!Umbraco || !Umbraco.Sys || !Umbraco.Sys.ServerVariables || !Umbraco.Sys.ServerVariables["umbracoUrls"]) {
throw "No server variables defined!";
}
if (!Umbraco.Sys.ServerVariables["umbracoUrls"][apiName]) {
throw "No url found for api name " + apiName;
}
return Umbraco.Sys.ServerVariables["umbracoUrls"][apiName] + actionName +
(!queryStrings ? "" : "?" + (Utilities.isString(queryStrings) ? queryStrings : this.<API key>(queryStrings)));
},
/**
* @ngdoc function
* @name umbraco.services.umbRequestHelper#resourcePromise
* @methodOf umbraco.services.umbRequestHelper
* @function
*
* @description
* This returns a promise with an underlying http call, it is a helper method to reduce
* the amount of duplicate code needed to query http resources and automatically handle any
* Http errors. See /docs/source/<API key>.md
*
* @param {object} opts A mixed object which can either be a string representing the error message to be
* returned OR an object containing either:
* { success: successCallback, errorMsg: errorMessage }
* OR
* { success: successCallback, error: errorCallback }
* In both of the above, the successCallback must accept these parameters: data, status, headers, config
* If using the errorCallback it must accept these parameters: data, status, headers, config
* The success callback must return the data which will be resolved by the deferred object.
* The error callback must return an object containing: {errorMsg: errorMessage, data: originalData, status: status }
*/
resourcePromise: function (httpPromise, opts) {
/** The default success callback used if one is not supplied in the opts */
function defaultSuccess(data, status, headers, config) {
//when it's successful, just return the data
return data;
}
/** The default error callback used if one is not supplied in the opts */
function defaultError(data, status, headers, config) {
var err = {
//NOTE: the default error message here should never be used based on the above docs!
errorMsg: (Utilities.isString(opts) ? opts : 'An error occurred!'),
data: data,
status: status
};
// if "opts" is a promise, we set "err.errorMsg" to be that promise
if (typeof(opts) == "object" && typeof(opts.then) == "function") {
err.errorMsg = opts;
}
return err;
}
//create the callbacs based on whats been passed in.
var callbacks = {
success: (!opts || !opts.success) ? defaultSuccess : opts.success,
error: (!opts || !opts.error ? defaultError : opts.error)
};
return httpPromise.then(function (response) {
//invoke the callback
var result = callbacks.success.apply(this, [response.data, response.status, response.headers, response.config]);
formHelper.showNotifications(response.data);
//when it's successful, just return the data
return $q.resolve(result);
}, function (response) {
if (!response) {
return; //sometimes oddly this happens, nothing we can do
}
if (!response.status) {
//this is a JS/angular error
return $q.reject(response);
}
//invoke the callback
var result = callbacks.error.apply(this, [response.data, response.status, response.headers, response.config]);
//when there's a 500 (unhandled) error show a YSOD overlay if debugging is enabled.
if (response.status >= 500 && response.status < 600) {
//show a ysod dialog
if (Umbraco.Sys.ServerVariables["isDebuggingEnabled"] === true) {
const error = { errorMsg: 'An error occured', data: response.data };
// TODO: All YSOD handling should be done with an interceptor
overlayService.ysod(error);
}
else {
//show a simple error notification
<API key>.error("Server error", "Contact administrator, see log for full details.<br/><i>" + result.errorMsg + "</i>");
}
}
else {
formHelper.showNotifications(result.data);
}
//return an error object including the error message for UI
return $q.reject({
errorMsg: result.errorMsg,
data: result.data,
status: result.status
});
});
},
/**
* @ngdoc method
* @name umbraco.resources.contentResource#postSaveContent
* @methodOf umbraco.resources.contentResource
*
* @description
* Used for saving content/media/members specifically
*
* @param {Object} args arguments object
* @returns {Promise} http promise object.
*/
postSaveContent: function (args) {
if (!args.restApiUrl) {
throw "args.restApiUrl is a required argument";
}
if (!args.content) {
throw "args.content is a required argument";
}
if (!args.action) {
throw "args.action is a required argument";
}
if (!args.files) {
throw "args.files is a required argument";
}
if (!args.dataFormatter) {
throw "args.dataFormatter is a required argument";
}
if (args.showNotifications === null || args.showNotifications === undefined) {
args.showNotifications = true;
}
//save the active tab id so we can set it when the data is returned.
var activeTab = _.find(args.content.tabs, function (item) {
return item.active;
});
var activeTabIndex = (activeTab === undefined ? 0 : _.indexOf(args.content.tabs, activeTab));
//save the data
return this.<API key>(
args.restApiUrl,
{ key: "contentItem", value: args.dataFormatter(args.content, args.action) },
//data transform callback:
function (data, formData) {
//now add all of the assigned files
for (var f in args.files) {
//each item has a property alias and the file object, we'll ensure that the alias is suffixed to the key
// so we know which property it belongs to on the server side
var file = args.files[f];
var fileKey = "file_" + file.alias + "_" + (file.culture ? file.culture : "") + "_" + (file.segment ? file.segment : "");
if (Utilities.isArray(file.metaData) && file.metaData.length > 0) {
fileKey += ("_" + file.metaData.join("_"));
}
formData.append(fileKey, file.file);
}
}).then(function (response) {
//success callback
//reset the tabs and set the active one
if (response.data.tabs && response.data.tabs.length > 0) {
response.data.tabs.forEach(item => item.active = false);
response.data.tabs[activeTabIndex].active = true;
}
if (args.showNotifications) {
formHelper.showNotifications(response.data);
}
// TODO: Do we need to pass the result through umbDataFormatter.<API key>? Right now things work so not sure but we should check
//the data returned is the up-to-date data so the UI will refresh
return $q.resolve(response.data);
}, function (response) {
if (!response.status) {
//this is a JS/angular error
return $q.reject(response);
}
//when there's a 500 (unhandled) error show a YSOD overlay if debugging is enabled.
if (response.status >= 500 && response.status < 600) {
//This is a bit of a hack to check if the error is due to a file being uploaded that is too large,
// we have to just check for the existence of a string value but currently that is the best way to
// do this since it's very hacky/difficult to catch this on the server
if (typeof response.data !== "undefined" && typeof response.data.indexOf === "function" && response.data.indexOf("Maximum request length exceeded") >= 0) {
<API key>.error("Server error", "The uploaded file was too large, check with your site administrator to adjust the maximum size allowed");
}
else if (Umbraco.Sys.ServerVariables["isDebuggingEnabled"] === true) {
//show a ysod dialog
const error = { errorMsg: 'An error occured', data: response.data };
// TODO: All YSOD handling should be done with an interceptor
overlayService.ysod(error);
}
else {
//show a simple error notification
<API key>.error("Server error", "Contact administrator, see log for full details.<br/><i>" + response.data.ExceptionMessage + "</i>");
}
}
else if (args.showNotifications) {
formHelper.showNotifications(response.data);
}
//return an error object including the error message for UI
return $q.reject({
errorMsg: 'An error occurred',
data: response.data,
status: response.status
});
});
},
/** Posts a multi-part mime request to the server */
<API key>: function (url, jsonData, transformCallback) {
//validate input, jsonData can be an array of key/value pairs or just one key/value pair.
if (!jsonData) { throw "jsonData cannot be null"; }
if (Utilities.isArray(jsonData)) {
jsonData.forEach(item => {
if (!item.key || !item.value) { throw "jsonData array item must have both a key and a value property"; }
});
}
else if (!jsonData.key || !jsonData.value) { throw "jsonData object must have both a key and a value property"; }
return $http({
method: 'POST',
url: url,
//IMPORTANT!!! You might think this should be set to 'multipart/form-data' but this is not true because when we are sending up files
// the request needs to include a 'boundary' parameter which identifies the boundary name between parts in this multi-part request
// and setting the Content-type manually will not set this boundary parameter. For whatever reason, setting the Content-type to 'undefined'
// will force the request to automatically populate the headers properly including the boundary parameter.
headers: { 'Content-Type': undefined },
transformRequest: function(data) {
var formData = new FormData();
//add the json data
if (Utilities.isArray(data)) {
data.forEach(item => {
formData.append(item.key, !Utilities.isString(item.value) ? Utilities.toJson(item.value) : item.value);
});
}
else {
formData.append(data.key, !Utilities.isString(data.value) ? Utilities.toJson(data.value) : data.value);
}
//call the callback
if (transformCallback) {
transformCallback.apply(this, [data, formData]);
}
return formData;
},
data: jsonData
}).then(function(response) {
return $q.resolve(response);
}, function(response) {
return $q.reject(response);
});
},
/**
* @ngdoc method
* @name umbraco.resources.contentResource#downloadFile
* @methodOf umbraco.resources.contentResource
*
* @description
* Downloads a file to the client using AJAX/XHR
*
* @param {string} httpPath the path (url) to the resource being downloaded
* @returns {Promise} http promise object.
*/
downloadFile : function (httpPath) {
// Use an arraybuffer
return $http.get(httpPath, { responseType: 'arraybuffer' })
.then(function (response) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get the headers
var headers = response.headers();
// Get the filename from the x-filename header or default to "download.bin"
var filename = headers['x-filename'] || 'download.bin';
filename = decodeURIComponent(filename);
// Determine the content type from the header or default to "application/octet-stream"
var contentType = headers['content-type'] || octetStreamMime;
try {
// Try using msSaveBlob if supported
var blob = new Blob([response.data], { type: contentType });
if (navigator.msSaveBlob)
navigator.msSaveBlob(blob, filename);
else {
// Try using other saveBlob implementations, if available
var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
if (saveBlob === undefined) throw "Not supported";
saveBlob(blob, filename);
}
success = true;
} catch (ex) {
console.log("saveBlob method failed with the following exception:");
console.log(ex);
}
if (!success) {
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (urlCreator) {
// Try to use a download link
var link = document.createElement('a');
if ('download' in link) {
// Try to simulate a click
try {
// Prepare a blob URL
var blob = new Blob([response.data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute('href', url);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
success = true;
} catch (ex) {
console.log("Download link method with simulated click failed with the following exception:");
console.log(ex);
}
}
if (!success) {
// Fallback to window.location method
try {
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
var blob = new Blob([response.data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
window.location = url;
success = true;
} catch (ex) {
console.log("Download link method with window.location failed with the following exception:");
console.log(ex);
}
}
}
}
if (!success) {
// Fallback to window.open method
window.open(httpPath, '_blank', '');
}
return $q.resolve();
}, function (response) {
return $q.reject({
errorMsg: "An error occurred downloading the file",
data: response.data,
status: response.status
});
});
}
};
}
angular.module('umbraco.services').factory('umbRequestHelper', umbRequestHelper);
|
/**
* This class will simulate LocalStorage on IE 7 and return the native version on modern browsers.
* Storage is done using userData on IE 7 and a special serialization format. The format is designed
* to be as small as possible by making sure that the keys and values doesn't need to be encoded. This
* makes it possible to store for example HTML data.
*
* Storage format for userData:
* <base 32 key length>,<key string>,<base 32 value length>,<value>,...
*
* For example this data key1=value1,key2=value2 would be:
* 4,key1,6,value1,4,key2,6,value2
*
* @class tinymce.util.LocalStorage
* @static
* @version 4.0
* @example
* tinymce.util.LocalStorage.setItem('key', 'value');
* var value = tinymce.util.LocalStorage.getItem('key');
*/
define(
'tinymce.core.util.LocalStorage',
[
'global!document',
'global!window'
],
function (document, window) {
var LocalStorage, storageElm, items, keys, userDataKey, hasOldIEDataSupport;
// Check for native support
try {
if (window.localStorage) {
return window.localStorage;
}
} catch (ex) {
// Ignore
}
userDataKey = "tinymce";
storageElm = document.documentElement;
hasOldIEDataSupport = !!storageElm.addBehavior;
if (hasOldIEDataSupport) {
storageElm.addBehavior('#default#userData');
}
/**
* Gets the keys names and updates LocalStorage.length property. Since IE7 doesn't have any getters/setters.
*/
var updateKeys = function () {
keys = [];
for (var key in items) {
keys.push(key);
}
LocalStorage.length = keys.length;
};
/**
* Loads the userData string and parses it into the items structure.
*/
var load = function () {
var key, data, value, pos = 0;
items = {};
// localStorage can be disabled on WebKit/Gecko so make a dummy storage
if (!hasOldIEDataSupport) {
return;
}
var next = function (end) {
var value, nextPos;
nextPos = end !== undefined ? pos + end : data.indexOf(',', pos);
if (nextPos === -1 || nextPos > data.length) {
return null;
}
value = data.substring(pos, nextPos);
pos = nextPos + 1;
return value;
};
storageElm.load(userDataKey);
data = storageElm.getAttribute(userDataKey) || '';
do {
var offset = next();
if (offset === null) {
break;
}
key = next(parseInt(offset, 32) || 0);
if (key !== null) {
offset = next();
if (offset === null) {
break;
}
value = next(parseInt(offset, 32) || 0);
if (key) {
items[key] = value;
}
}
} while (key !== null);
updateKeys();
};
/**
* Saves the items structure into a the userData format.
*/
var save = function () {
var value, data = '';
// localStorage can be disabled on WebKit/Gecko so make a dummy storage
if (!hasOldIEDataSupport) {
return;
}
for (var key in items) {
value = items[key];
data += (data ? ',' : '') + key.length.toString(32) + ',' + key + ',' + value.length.toString(32) + ',' + value;
}
storageElm.setAttribute(userDataKey, data);
try {
storageElm.save(userDataKey);
} catch (ex) {
// Ignore disk full
}
updateKeys();
};
LocalStorage = {
/**
* Length of the number of items in storage.
*
* @property length
* @type Number
* @return {Number} Number of items in storage.
*/
//length:0,
/**
* Returns the key name by index.
*
* @method key
* @param {Number} index Index of key to return.
* @return {String} Key value or null if it wasn't found.
*/
key: function (index) {
return keys[index];
},
/**
* Returns the value if the specified key or null if it wasn't found.
*
* @method getItem
* @param {String} key Key of item to retrieve.
* @return {String} Value of the specified item or null if it wasn't found.
*/
getItem: function (key) {
return key in items ? items[key] : null;
},
/**
* Sets the value of the specified item by it's key.
*
* @method setItem
* @param {String} key Key of the item to set.
* @param {String} value Value of the item to set.
*/
setItem: function (key, value) {
items[key] = "" + value;
save();
},
/**
* Removes the specified item by key.
*
* @method removeItem
* @param {String} key Key of item to remove.
*/
removeItem: function (key) {
delete items[key];
save();
},
/**
* Removes all items.
*
* @method clear
*/
clear: function () {
items = {};
save();
}
};
load();
return LocalStorage;
}
);
|
namespace ODataValidator.Rule
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Xml.Linq;
using System.Xml.XPath;
using Newtonsoft.Json.Linq;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
<summary>
Class of extension rule for Entry.Core.4106
</summary>
[Export(typeof(ExtensionRule))]
public class EntryCore4106 : ExtensionRule
{
<summary>
Gets Category property
</summary>
public override string Category
{
get
{
return "core";
}
}
<summary>
Gets rule name
</summary>
public override string Name
{
get
{
return "Entry.Core.4106";
}
}
<summary>
Gets rule description
</summary>
public override string Description
{
get
{
return "For expanded navigation property, if at most one entity can be related, the value is the representation of the related entity.";
}
}
<summary>
Gets rule specification in OData document
</summary>
public override string <API key>
{
get
{
return "8.3";
}
}
<summary>
Gets the version.
</summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V3_V4;
}
}
<summary>
Gets location of help information of the rule
</summary>
public override string HelpLink
{
get
{
return null;
}
}
<summary>
Gets the error message for validation failure
</summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
<summary>
Gets the requirement level.
</summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
<summary>
Gets the payload type to which the rule applies.
</summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Entry;
}
}
<summary>
Gets the payload format to which the rule applies.
</summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.JsonLight;
}
}
<summary>
Gets the RequireMetadata property to which the rule applies.
</summary>
public override bool? RequireMetadata
{
get
{
return null;
}
}
<summary>
Gets the IsOfflineContext property to which the rule applies.
</summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
<summary>
Verifies the extension rule.
</summary>
<param name="context">The Interop service context</param>
<param name="info">out parameter to return violation information when rule does not pass</param>
<returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out <API key> info)
{
if (context == null)
{
throw new <API key>("context");
}
bool? passed = null;
info = null;
JObject entry;
context.ResponsePayload.TryToJObject(out entry);
XElement metadata = XElement.Parse(context.MetadataDocument);
// Use the XPath query language to access the metadata document and get the node which will be used.
|
#pragma once
#include <memory>
#include <vector>
#include "tatum/tags/TimingTags.hpp"
#include "tatum/TimingGraph.hpp"
#include "tatum/TimingConstraints.hpp"
#include "tatum/graph_visitors/<API key>.hpp"
#include "tatum/graph_visitors/HoldAnalysisOps.hpp"
#include "tatum/util/tatum_assert.hpp"
namespace tatum {
/** \class HoldAnalysis
*
* The 'HoldAnalysis' class defines the operations needed by a timing analyzer
* to perform a hold (min/shortest path) analysis.
*
* \see SetupAnalysis
* \see TimingAnalyzer
* \see <API key>
*/
class HoldAnalysis : public detail::<API key><detail::HoldAnalysisOps> {
public:
HoldAnalysis(size_t num_tags, size_t num_slacks)
: detail::<API key><detail::HoldAnalysisOps>(num_tags, num_slacks) {}
TimingTags::tag_range hold_tags(const NodeId node) const { return ops_.get_tags(node); }
TimingTags::tag_range hold_tags(const NodeId node, TagType type) const { return ops_.get_tags(node, type); }
#ifdef <API key>
TimingTags::tag_range hold_edge_slacks(const EdgeId edge) const { return ops_.get_edge_slacks(edge); }
#endif
TimingTags::tag_range hold_node_slacks(const NodeId node) const { return ops_.get_node_slacks(node); }
};
} //namepsace
|
layout: post
date: 2010-06-07
time: "10:00:00"
author: "Greg Wilson"
title: The Big Picture (version 2)
category: ["Content"]
<p>Thanks to everyone who gave us feedback on <a href="{{site.baseurl}}/blog/2010/06/concept-map.html">the first version of a concept map</a> for Software Carpentry. The second version is shown below, along with a list of terms that <em>ought</em> to be on it, but aren't. Where would you place them, and how would they connect to each other and to the concepts that are already linked?</p>
<p><img src="{{site.filesurl}}/2010/06/<API key>.png" /></p>
|
<?php return unserialize('a:3:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:9:"pk_son_id";s:4:"type";s:7:"integer";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}i:1;O:23:"Doctrine\\ORM\\Mapping\\Id":0:{}i:2;O:35:"Doctrine\\ORM\\Mapping\\GeneratedValue":1:{s:8:"strategy";s:8:"IDENTITY";}}');
|
package couchdb
import (
"context"
"encoding/json"
"github.com/flimzy/kivik"
"github.com/flimzy/kivik/driver"
)
type session struct {
Data json.RawMessage
Info authInfo `json:"info"`
UserCtx userContext `json:"userCtx"`
}
type authInfo struct {
<API key> string `json:"authenticated"`
AuthenticationDB string `json:"authentiation_db"`
<API key> []string `json:"<API key>`
}
type userContext struct {
Name string `json:"name"`
Roles []string `json:"roles"`
}
func (s *session) UnmarshalJSON(data []byte) error {
type alias session
var a alias
if err := json.Unmarshal(data, &a); err != nil {
return err
}
*s = session(a)
s.Data = data
return nil
}
func (c *client) Session(ctx context.Context) (*driver.Session, error) {
s := &session{}
_, err := c.DoJSON(ctx, kivik.MethodGet, "/_session", nil, s)
return &driver.Session{
RawResponse: s.Data,
Name: s.UserCtx.Name,
Roles: s.UserCtx.Roles,
<API key>: s.Info.<API key>,
AuthenticationDB: s.Info.AuthenticationDB,
<API key>: s.Info.<API key>,
}, err
}
|
require 'spec_helper'
describe ROM::Setup do
it 'is configurable' do
setup = ROM::Setup.new({})
setup.configure do |config|
config.sql.infer_relations = false
end
expect(setup.config.sql.infer_relations).to be(false)
expect(setup.config[:sql][:infer_relations]).to be(false)
expect(setup.config).to respond_to(:sql)
expect(setup.config).to respond_to(:other=)
setup.config.freeze
expect(setup.config.other).to be(nil)
expect(setup.config.key?(:other)).to be(false)
expect(setup.config.key?(:sql)).to be(true)
end
it 'is configurable via settings hash' do
setup = ROM.setup(:memory, 'something', infer_schema: false)
setup.finalize
expect(setup.config.gateways.default.infer_schema).to be(false)
setup = ROM.setup(:memory, infer_schema: false)
setup.finalize
expect(setup.config.gateways.default.infer_schema).to be(false)
setup = ROM.setup(default: [:memory, infer_schema: false])
setup.finalize
expect(setup.config.gateways.default.infer_schema).to be(false)
end
describe '#finalize' do
context 'with gateway that supports schema inferring' do
it 'builds relation from inferred schema' do
setup = ROM.setup(:memory)
repo = setup.default
dataset = double('dataset')
allow(repo).to receive(:schema).and_return([:users])
allow(repo).to receive(:dataset).with(:users).and_return(dataset)
rom = setup.finalize
expect(rom.relations.users.dataset).to be(dataset)
end
it 'skips inferring a relation when there is a defined one already' do
setup = ROM.setup(:memory)
repo = setup.default
dataset = double('dataset')
allow(repo).to receive(:schema).and_return([:test_users])
allow(repo).to receive(:dataset).with(:test_users).and_return(dataset)
class Test::Users < ROM::Relation[:memory]; end
expect { setup.finalize }.not_to raise_error
rom = setup.env
expect(rom.relations.test_users).to be_instance_of(Test::Users)
end
it 'skips inferring when it is turned off for the adapter' do
setup = ROM.setup(:memory)
setup.configure do |config| config.gateways.default.infer_relations = false end
repo = setup.default
expect(repo).not_to receive(:schema)
setup.finalize
end
it 'infers configured relations' do
setup = ROM.setup(:memory)
setup.configure do |config|
config.gateways.default.<API key> = [:test_tasks]
end
repo = setup.default
dataset = double('dataset')
allow(repo).to receive(:schema).and_return([:test_tasks, :test_users])
expect(repo).to receive(:dataset).with(:test_tasks).and_return(dataset)
expect(repo).to_not receive(:dataset).with(:test_users)
rom = setup.finalize
expect(rom.relations.elements.key?(:test_users)).to be(false)
expect(rom.relations[:test_tasks]).to be_kind_of(ROM::Memory::Relation)
expect(rom.relations[:test_tasks].dataset).to be(dataset)
end
it 'skip inferring blacklisted relations' do
setup = ROM.setup(:memory)
setup.configure do |config|
config.gateways.default.<API key> = [:test_users]
end
repo = setup.default
dataset = double('dataset')
allow(repo).to receive(:schema).and_return([:test_tasks, :test_users])
expect(repo).to receive(:dataset).with(:test_tasks).and_return(dataset)
expect(repo).to_not receive(:dataset).with(:test_users)
rom = setup.finalize
expect(rom.relations.elements.key?(:test_users)).to be(false)
expect(rom.relations[:test_tasks]).to be_kind_of(ROM::Memory::Relation)
expect(rom.relations[:test_tasks].dataset).to be(dataset)
end
it 'can register multiple relations with same dataset' do
setup = ROM.setup(:memory)
Class.new(ROM::Relation[:memory]) do
dataset :fruits
register_as :apples
def apple?
true
end
end
Class.new(ROM::Relation[:memory]) do
dataset :fruits
register_as :oranges
def orange?
true
end
end
rom = setup.finalize
expect(rom.relations.apples).to be_apple
expect(rom.relations.oranges).to be_orange
expect(rom.relations.apples).to_not eq(rom.relations.oranges)
end
it "raises an error when registering relations with the same `register_as`" do
setup = ROM.setup(:memory)
Class.new(ROM::Relation[:memory]) do
dataset :guests
register_as :users
end
Class.new(ROM::Relation[:memory]) do
dataset :admins
register_as :users
end
expect { setup.finalize }.to raise_error(
ROM::<API key>, /register_as :users/
)
end
it 'resets boot to nil' do
setup = ROM.setup(:memory)
allow(setup).to receive(:container).and_raise(StandardError)
expect { ROM.finalize }.to raise_error(StandardError)
expect(ROM.boot).to be(nil)
end
end
context 'empty setup' do
let(:setup) { ROM::Setup.new({}) }
let(:env) { setup.finalize }
it 'builds empty gateways' do
expect(env.gateways).to eql({})
end
it 'builds empty relations' do
expect(env.relations).to eql(ROM::RelationRegistry.new)
end
it 'builds empty mappers' do
expect(env.mappers).to eql(ROM::Registry.new)
end
it 'builds empty commands' do
expect(env.commands).to eql(ROM::Registry.new)
end
end
end
describe '#method_missing' do
it 'returns a gateway if it is defined' do
repo = double('repo')
setup = ROM::Setup.new(repo: repo)
expect(setup.repo).to be(repo)
end
it 'raises error if repo is not defined' do
setup = ROM::Setup.new({})
expect { setup.not_here }.to raise_error(NoMethodError, /not_here/)
end
end
describe '
it 'returns a gateway if it is defined' do
repo = double('repo')
setup = ROM::Setup.new(repo: repo)
expect(setup[:repo]).to be(repo)
end
it 'raises error if repo is not defined' do
setup = ROM::Setup.new({})
expect { setup[:not_here] }.to raise_error(KeyError, /not_here/)
end
end
describe 'defining components when adapter was not registered' do
it 'raises error when trying to define a relation' do
expect {
Class.new(ROM::Relation[:not_here])
}.to raise_error(ROM::<API key>, /not_here/)
end
it 'raises error when trying to define a command' do
expect {
Class.new(ROM::Commands::Create[:not_here])
}.to raise_error(ROM::<API key>, /not_here/)
end
end
end
|
using System;
using System.Globalization;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace LiveCharts.Uwp.Components.MultiBinding
{
<summary>
An <see cref="IValueConverter"/> abstract implementation to be used with the <see cref="<API key>"/>.
</summary>
public abstract class <API key> : DependencyObject, IValueConverter
{
<summary>
Modifies the source data before passing it to the target for display in the UI.
</summary>
<returns>The value to be passed to the target dependency property.</returns>
<param name="values">The source data being passed to the target.</param>
<param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param>
<param name="parameter">An optional parameter to be used in the converter logic.</param>
<param name="culture">The culture of the conversion.</param>
public abstract object Convert(object[] values, Type targetType, object parameter, CultureInfo culture);
<summary>
Modifies the target data before passing it to the source object. This method is called only in <see cref="F:System.Windows.Data.BindingMode.TwoWay"/> bindings.
</summary>
<returns>The value to be passed to the source object.</returns>
<param name="value">The target data being passed to the source.</param>
<param name="targetType">The <see cref="T:System.Type"/> of data expected by the source object.</param>
<param name="parameter">An optional parameter to be used in the converter logic.</param>
<param name="culture">The culture of the conversion.</param>
public abstract object[] ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
{
var cultureInfo = !string.IsNullOrEmpty(language) ? new CultureInfo(language) : null;
return Convert((object[])value, targetType, parameter, cultureInfo);
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
{
var cultureInfo = !string.IsNullOrEmpty(language) ? new CultureInfo(language) : null;
return ConvertBack(value, targetType, parameter, cultureInfo);
}
}
}
|
var prettyURLs = require('../middleware/pretty-urls'),
cors = require('../middleware/api/cors'),
auth = require('../auth');
/**
* Auth Middleware Packages
*
* IMPORTANT
* - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost
* - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains
*/
/**
* Authentication for public endpoints
*/
module.exports.authenticatePublic = [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
// This is a labs-enabled middleware
auth.authorize.requires<API key>,
cors,
prettyURLs
];
/**
* Authentication for private endpoints
*/
module.exports.authenticatePrivate = [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
auth.authorize.<API key>,
cors,
prettyURLs
];
/**
* Authentication for client endpoints
*/
module.exports.authenticateClient = function authenticateClient(client) {
return [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
auth.authorize.<API key>(client),
cors,
prettyURLs
];
};
|
<?php
namespace XeroPHP\Models\PayrollAU\PayItem;
use XeroPHP\Remote;
class DeductionType extends Remote\Object {
/**
* Name of the deduction type (max length = 50)
*
* @property string Name
*/
/**
* See Accounts
*
* @property string AccountCode
*/
/**
* Indicates that this is a pre-tax deduction that will reduce the amount of tax you withhold from an
* employee.
*
* @property float ReducesTax
*/
/**
* Xero identifier
*
* @property string DeductionTypeID
*/
/**
* Get the resource uri of the class (Contacts) etc
*
* @return string
*/
public static function getResourceURI(){
return 'DeductionTypes';
}
/**
* Get the root node name. Just the unqualified classname
*
* @return string
*/
public static function getRootNodeName(){
return 'DeductionType';
}
/**
* Get the guid property
*
* @return string
*/
public static function getGUIDProperty(){
return 'DeductionTypeID';
}
/**
* Get the stem of the API (core.xro) etc
*
* @return string|null
*/
public static function getAPIStem(){
return Remote\URL::API_PAYROLL;
}
/**
* Get the supported methods
*/
public static function getSupportedMethods() {
return array(
);
}
/**
*
* Get the properties of the object. Indexed by constants
* [0] - Mandatory
* [1] - Type
* [2] - PHP type
* [3] - Is an Array
* [4] - Saves directly
*
* @return array
*/
public static function getProperties() {
return array(
'Name' => array (true, self::<API key>, null, false, false),
'AccountCode' => array (true, self::<API key>, null, false, false),
'ReducesTax' => array (true, self::PROPERTY_TYPE_FLOAT, null, false, false),
'ReducesSuper' => array (true, self::<API key>, null, false, false),
'DeductionTypeID' => array (false, self::<API key>, null, false, false)
);
}
public static function isPageable(){
return false;
}
/**
* @return string
*/
public function getName() {
return $this->_data['Name'];
}
/**
* @param string $value
* @return DeductionType
*/
public function setName($value) {
$this->propertyUpdated('Name', $value);
$this->_data['Name'] = $value;
return $this;
}
/**
* @return string
*/
public function getAccountCode() {
return $this->_data['AccountCode'];
}
/**
* @param string $value
* @return DeductionType
*/
public function setAccountCode($value) {
$this->propertyUpdated('AccountCode', $value);
$this->_data['AccountCode'] = $value;
return $this;
}
/**
* @return float
*/
public function getReducesTax() {
return $this->_data['ReducesTax'];
}
/**
* @param float $value
* @return DeductionType
*/
public function setReducesTax($value) {
$this->propertyUpdated('ReducesTax', $value);
$this->_data['ReducesTax'] = $value;
return $this;
}
/**
* @return string
*/
public function getReducesSuper() {
return $this->_data['ReducesSuper'];
}
/**
* @param string $value
* @return DeductionType
*/
public function setReducesSuper($value) {
$this->propertyUpdated('ReducesSuper', $value);
$this->_data['ReducesSuper'] = $value;
return $this;
}
/**
* @return string
*/
public function getDeductionTypeID() {
return $this->_data['DeductionTypeID'];
}
/**
* @param string $value
* @return DeductionType
*/
public function setDeductionTypeID($value) {
$this->propertyUpdated('DeductionTypeID', $value);
$this->_data['DeductionTypeID'] = $value;
return $this;
}
}
|
<?php
class <API key>
{
/** Constants */
/** Regular Expressions */
// Fraction
const <API key> = '(-?)(\d+)\s+(\d+\/\d+)';
/**
* Control characters array
*
* @var string[]
*/
private static $_controlCharacters = array();
/**
* SYLK Characters array
*
* $var array
*/
private static $_SYLKCharacters = array();
/**
* Decimal separator
*
* @var string
*/
private static $_decimalSeparator;
/**
* Thousands separator
*
* @var string
*/
private static $_thousandsSeparator;
/**
* Is mbstring extension avalable?
*
* @var boolean
*/
private static $_isMbstringEnabled;
/**
* Is iconv extension avalable?
*
* @var boolean
*/
private static $_isIconvEnabled;
/**
* Build control characters array
*/
private static function <API key>() {
for ($i = 0; $i <= 31; ++$i) {
if ($i != 9 && $i != 10 && $i != 13) {
$find = '_x' . sprintf('%04s' , strtoupper(dechex($i))) . '_';
$replace = chr($i);
self::$_controlCharacters[$find] = $replace;
}
}
}
/**
* Build SYLK characters array
*/
private static function <API key>()
{
self::$_SYLKCharacters = array(
"\x1B 0" => chr(0),
"\x1B 1" => chr(1),
"\x1B 2" => chr(2),
"\x1B 3" => chr(3),
"\x1B 4" => chr(4),
"\x1B 5" => chr(5),
"\x1B 6" => chr(6),
"\x1B 7" => chr(7),
"\x1B 8" => chr(8),
"\x1B 9" => chr(9),
"\x1B :" => chr(10),
"\x1B ;" => chr(11),
"\x1B <" => chr(12),
"\x1B :" => chr(13),
"\x1B >" => chr(14),
"\x1B ?" => chr(15),
"\x1B!0" => chr(16),
"\x1B!1" => chr(17),
"\x1B!2" => chr(18),
"\x1B!3" => chr(19),
"\x1B!4" => chr(20),
"\x1B!5" => chr(21),
"\x1B!6" => chr(22),
"\x1B!7" => chr(23),
"\x1B!8" => chr(24),
"\x1B!9" => chr(25),
"\x1B!:" => chr(26),
"\x1B!;" => chr(27),
"\x1B!<" => chr(28),
"\x1B!=" => chr(29),
"\x1B!>" => chr(30),
"\x1B!?" => chr(31),
"\x1B'?" => chr(127),
"\x1B(0" => '€', // 128 in CP1252
"\x1B(2" => '‚', // 130 in CP1252
"\x1B(3" => 'ƒ', // 131 in CP1252
"\x1B(4" => '„', // 132 in CP1252
"\x1B(5" => '…', // 133 in CP1252
"\x1B(6" => '†', // 134 in CP1252
"\x1B(7" => '‡', // 135 in CP1252
"\x1B(8" => 'ˆ', // 136 in CP1252
"\x1B(9" => '‰', // 137 in CP1252
"\x1B(:" => 'Š', // 138 in CP1252
"\x1B(;" => '‹', // 139 in CP1252
"\x1BNj" => 'Œ', // 140 in CP1252
"\x1B(>" => 'Ž', // 142 in CP1252
"\x1B)1" => '‘', // 145 in CP1252
"\x1B)2" => '’', // 146 in CP1252
"\x1B)3" => '“', // 147 in CP1252
"\x1B)4" => '”', // 148 in CP1252
"\x1B)5" => '•', // 149 in CP1252
"\x1B)6" => '–', // 150 in CP1252
"\x1B)7" => '—', // 151 in CP1252
"\x1B)8" => '˜', // 152 in CP1252
"\x1B)9" => '™', // 153 in CP1252
"\x1B):" => 'š', // 154 in CP1252
"\x1B);" => '›', // 155 in CP1252
"\x1BNz" => 'œ', // 156 in CP1252
"\x1B)>" => 'ž', // 158 in CP1252
"\x1B)?" => 'Ÿ', // 159 in CP1252
"\x1B*0" => ' ', // 160 in CP1252
"\x1BN!" => '¡', // 161 in CP1252
"\x1BN\"" => '¢', // 162 in CP1252
"\x1BN
"\x1BN(" => '¤', // 164 in CP1252
"\x1BN%" => '¥', // 165 in CP1252
"\x1B*6" => '¦', // 166 in CP1252
"\x1BN'" => '§', // 167 in CP1252
"\x1BNH " => '¨', // 168 in CP1252
"\x1BNS" => '©', // 169 in CP1252
"\x1BNc" => 'ª', // 170 in CP1252
"\x1BN+" => '«', // 171 in CP1252
"\x1B*<" => '¬', // 172 in CP1252
"\x1B*=" => '', // 173 in CP1252
"\x1BNR" => '®', // 174 in CP1252
"\x1B*?" => '¯', // 175 in CP1252
"\x1BN0" => '°', // 176 in CP1252
"\x1BN1" => '±', // 177 in CP1252
"\x1BN2" => '²', // 178 in CP1252
"\x1BN3" => '³', // 179 in CP1252
"\x1BNB " => '´', // 180 in CP1252
"\x1BN5" => 'µ', // 181 in CP1252
"\x1BN6" => '¶', // 182 in CP1252
"\x1BN7" => '·', // 183 in CP1252
"\x1B+8" => '¸', // 184 in CP1252
"\x1BNQ" => '¹', // 185 in CP1252
"\x1BNk" => 'º', // 186 in CP1252
"\x1BN;" => '»', // 187 in CP1252
"\x1BN<" => '¼', // 188 in CP1252
"\x1BN=" => '½', // 189 in CP1252
"\x1BN>" => '¾', // 190 in CP1252
"\x1BN?" => '¿', // 191 in CP1252
"\x1BNAA" => 'À', // 192 in CP1252
"\x1BNBA" => 'Á', // 193 in CP1252
"\x1BNCA" => 'Â', // 194 in CP1252
"\x1BNDA" => 'Ã', // 195 in CP1252
"\x1BNHA" => 'Ä', // 196 in CP1252
"\x1BNJA" => 'Å', // 197 in CP1252
"\x1BNa" => 'Æ', // 198 in CP1252
"\x1BNKC" => 'Ç', // 199 in CP1252
"\x1BNAE" => 'È', // 200 in CP1252
"\x1BNBE" => 'É', // 201 in CP1252
"\x1BNCE" => 'Ê', // 202 in CP1252
"\x1BNHE" => 'Ë', // 203 in CP1252
"\x1BNAI" => 'Ì', // 204 in CP1252
"\x1BNBI" => 'Í', // 205 in CP1252
"\x1BNCI" => 'Î', // 206 in CP1252
"\x1BNHI" => 'Ï', // 207 in CP1252
"\x1BNb" => 'Ð', // 208 in CP1252
"\x1BNDN" => 'Ñ', // 209 in CP1252
"\x1BNAO" => 'Ò', // 210 in CP1252
"\x1BNBO" => 'Ó', // 211 in CP1252
"\x1BNCO" => 'Ô', // 212 in CP1252
"\x1BNDO" => 'Õ', // 213 in CP1252
"\x1BNHO" => 'Ö', // 214 in CP1252
"\x1B-7" => '×', // 215 in CP1252
"\x1BNi" => 'Ø', // 216 in CP1252
"\x1BNAU" => 'Ù', // 217 in CP1252
"\x1BNBU" => 'Ú', // 218 in CP1252
"\x1BNCU" => 'Û', // 219 in CP1252
"\x1BNHU" => 'Ü', // 220 in CP1252
"\x1B-=" => 'Ý', // 221 in CP1252
"\x1BNl" => 'Þ', // 222 in CP1252
"\x1BN{" => 'ß', // 223 in CP1252
"\x1BNAa" => 'à', // 224 in CP1252
"\x1BNBa" => 'á', // 225 in CP1252
"\x1BNCa" => 'â', // 226 in CP1252
"\x1BNDa" => 'ã', // 227 in CP1252
"\x1BNHa" => 'ä', // 228 in CP1252
"\x1BNJa" => 'å', // 229 in CP1252
"\x1BNq" => 'æ', // 230 in CP1252
"\x1BNKc" => 'ç', // 231 in CP1252
"\x1BNAe" => 'è', // 232 in CP1252
"\x1BNBe" => 'é', // 233 in CP1252
"\x1BNCe" => 'ê', // 234 in CP1252
"\x1BNHe" => 'ë', // 235 in CP1252
"\x1BNAi" => 'ì', // 236 in CP1252
"\x1BNBi" => 'í', // 237 in CP1252
"\x1BNCi" => 'î', // 238 in CP1252
"\x1BNHi" => 'ï', // 239 in CP1252
"\x1BNs" => 'ð', // 240 in CP1252
"\x1BNDn" => 'ñ', // 241 in CP1252
"\x1BNAo" => 'ò', // 242 in CP1252
"\x1BNBo" => 'ó', // 243 in CP1252
"\x1BNCo" => 'ô', // 244 in CP1252
"\x1BNDo" => 'õ', // 245 in CP1252
"\x1BNHo" => 'ö', // 246 in CP1252
"\x1B/7" => '÷', // 247 in CP1252
"\x1BNy" => 'ø', // 248 in CP1252
"\x1BNAu" => 'ù', // 249 in CP1252
"\x1BNBu" => 'ú', // 250 in CP1252
"\x1BNCu" => 'û', // 251 in CP1252
"\x1BNHu" => 'ü', // 252 in CP1252
"\x1B/=" => 'ý', // 253 in CP1252
"\x1BN|" => 'þ', // 254 in CP1252
"\x1BNHy" => 'ÿ', // 255 in CP1252
);
}
/**
* Get whether mbstring extension is available
*
* @return boolean
*/
public static function <API key>()
{
if (isset(self::$_isMbstringEnabled)) {
return self::$_isMbstringEnabled;
}
self::$_isMbstringEnabled = function_exists('mb_convert_encoding') ?
true : false;
return self::$_isMbstringEnabled;
}
/**
* Get whether iconv extension is available
*
* @return boolean
*/
public static function getIsIconvEnabled()
{
if (isset(self::$_isIconvEnabled)) {
return self::$_isIconvEnabled;
}
// Fail if iconv doesn't exist
if (!function_exists('iconv')) {
self::$_isIconvEnabled = false;
return false;
}
// Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false,
if (!@iconv('UTF-8', 'UTF-16LE', 'x')) {
self::$_isIconvEnabled = false;
return false;
}
// Sometimes iconv_substr('A', 0, 1, 'UTF-8') just returns false in PHP 5.2.0
if (!@iconv('UTF-8', 'UTF-16LE', 'x')) {
self::$_isIconvEnabled = false;
return false;
}
// CUSTOM: IBM AIX iconv() does not work
if ( defined('PHP_OS') && @stristr(PHP_OS, 'AIX')
&& defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0)
&& defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0) )
{
self::$_isIconvEnabled = false;
return false;
}
// If we reach here no problems were detected with iconv
self::$_isIconvEnabled = true;
return true;
}
public static function <API key>($value = '') {
if(empty(self::$_controlCharacters)) {
self::<API key>();
}
return str_replace( array_keys(self::$_controlCharacters), array_values(self::$_controlCharacters), $value );
}
public static function <API key>($value = '') {
if(empty(self::$_controlCharacters)) {
self::<API key>();
}
return str_replace( array_values(self::$_controlCharacters), array_keys(self::$_controlCharacters), $value );
}
/**
* Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters.
*
* @param string $value
* @return string
*/
public static function SanitizeUTF8($value)
{
if (self::getIsIconvEnabled()) {
$value = @iconv('UTF-8', 'UTF-8', $value);
return $value;
}
if (self::<API key>()) {
$value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
return $value;
}
// else, no conversion
return $value;
}
/**
* Check if a string contains UTF8 data
*
* @param string $value
* @return boolean
*/
public static function IsUTF8($value = '') {
return utf8_encode(utf8_decode($value)) === $value;
}
/**
* Formats a numeric value as a string for output in various output writers forcing
* point as decimal separator in case locale is other than English.
*
* @param mixed $value
* @return string
*/
public static function FormatNumber($value) {
if (is_float($value)) {
return str_replace(',', '.', $value);
}
return (string) $value;
}
/**
* Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length)
* Writes the string using uncompressed notation, no rich text, no Asian phonetics
* If mbstring extension is not available, ASCII is assumed, and compressed notation is used
* although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3
*
* @param string $value UTF-8 encoded string
* @return string
*/
public static function <API key>($value)
{
// character count
$ln = self::CountCharacters($value, 'UTF-8');
// option flags
$opt = (self::getIsIconvEnabled() || self::<API key>()) ?
0x0001 : 0x0000;
// characters
$chars = self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8');
$data = pack('CC', $ln, $opt) . $chars;
return $data;
}
/**
* Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length)
* Writes the string using uncompressed notation, no rich text, no Asian phonetics
* If mbstring extension is not available, ASCII is assumed, and compressed notation is used
* although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3
*
* @param string $value UTF-8 encoded string
* @return string
*/
public static function <API key>($value)
{
// character count
$ln = self::CountCharacters($value, 'UTF-8');
// option flags
$opt = (self::getIsIconvEnabled() || self::<API key>()) ?
0x0001 : 0x0000;
// characters
$chars = self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8');
$data = pack('vC', $ln, $opt) . $chars;
return $data;
}
/**
* Convert string from one encoding to another. First try iconv, then mbstring, or no convertion
*
* @param string $value
* @param string $to Encoding to convert to, e.g. 'UTF-8'
* @param string $from Encoding to convert from, e.g. 'UTF-16LE'
* @return string
*/
public static function ConvertEncoding($value, $to, $from)
{
if (self::getIsIconvEnabled()) {
$value = iconv($from, $to, $value);
return $value;
}
if (self::<API key>()) {
$value = mb_convert_encoding($value, $to, $from);
return $value;
}
if($from == 'UTF-16LE'){
return self::utf16_decode($value, false);
}else if($from == 'UTF-16BE'){
return self::utf16_decode($value);
}
// else, no conversion
return $value;
}
public static function utf16_decode( $str, $bom_be=true ) {
if( strlen($str) < 2 ) return $str;
$c0 = ord($str{0});
$c1 = ord($str{1});
if( $c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); }
elseif( $c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; }
$len = strlen($str);
$newstr = '';
for($i=0;$i<$len;$i+=2) {
if( $bom_be ) { $val = ord($str{$i}) << 4; $val += ord($str{$i+1}); }
else { $val = ord($str{$i+1}) << 4; $val += ord($str{$i}); }
$newstr .= ($val == 0x228) ? "\n" : chr($val);
}
return $newstr;
}
/**
* Get character count. First try mbstring, then iconv, finally strlen
*
* @param string $value
* @param string $enc Encoding
* @return int Character count
*/
public static function CountCharacters($value, $enc = 'UTF-8')
{
if (self::getIsIconvEnabled()) {
$count = iconv_strlen($value, $enc);
return $count;
}
if (self::<API key>()) {
$count = mb_strlen($value, $enc);
return $count;
}
// else strlen
$count = strlen($value);
return $count;
}
/**
* Get a substring of a UTF-8 encoded string
*
* @param string $pValue UTF-8 encoded string
* @param int $start Start offset
* @param int $length Maximum number of characters in substring
* @return string
*/
public static function Substring($pValue = '', $pStart = 0, $pLength = 0)
{
if (self::getIsIconvEnabled()) {
$string = iconv_substr($pValue, $pStart, $pLength, 'UTF-8');
return $string;
}
if (self::<API key>()) {
$string = mb_substr($pValue, $pStart, $pLength, 'UTF-8');
return $string;
}
// else substr
$string = substr($pValue, $pStart, $pLength);
return $string;
}
/**
* Identify whether a string contains a fractional numeric value,
* and convert it to a numeric if it is
*
* @param string &$operand string value to test
* @return boolean
*/
public static function <API key>(&$operand) {
if (preg_match('/^'.self::<API key>.'$/i', $operand, $match)) {
$sign = ($match[1] == '-') ? '-' : '+';
$fractionFormula = '='.$sign.$match[2].$sign.$match[3];
$operand = <API key>::getInstance()-><API key>($fractionFormula);
return true;
}
return false;
} // function <API key>()
/**
* Get the decimal separator. If it has not yet been set explicitly, try to obtain number
* formatting information from locale.
*
* @return string
*/
public static function getDecimalSeparator()
{
if (!isset(self::$_decimalSeparator)) {
$localeconv = localeconv();
self::$_decimalSeparator = $localeconv['decimal_point'] != ''
? $localeconv['decimal_point'] : $localeconv['mon_decimal_point'];
if (self::$_decimalSeparator == '')
{
// Default to .
self::$_decimalSeparator = '.';
}
}
return self::$_decimalSeparator;
}
/**
* Set the decimal separator. Only used by <API key>::toFormattedString()
* to format output by <API key> and PHPExcel_Writer_PDF
*
* @param string $pValue Character for decimal separator
*/
public static function setDecimalSeparator($pValue = '.')
{
self::$_decimalSeparator = $pValue;
}
/**
* Get the thousands separator. If it has not yet been set explicitly, try to obtain number
* formatting information from locale.
*
* @return string
*/
public static function <API key>()
{
if (!isset(self::$_thousandsSeparator)) {
$localeconv = localeconv();
self::$_thousandsSeparator = $localeconv['thousands_sep'] != ''
? $localeconv['thousands_sep'] : $localeconv['mon_thousands_sep'];
}
return self::$_thousandsSeparator;
}
/**
* Set the thousands separator. Only used by <API key>::toFormattedString()
* to format output by <API key> and PHPExcel_Writer_PDF
*
* @param string $pValue Character for thousands separator
*/
public static function <API key>($pValue = ',')
{
self::$_thousandsSeparator = $pValue;
}
/**
* Convert SYLK encoded string to UTF-8
*
* @param string $pValue
* @return string UTF-8 encoded string
*/
public static function SYLKtoUTF8($pValue = '')
{
// If there is no escape character in the string there is nothing to do
if (strpos($pValue, '') === false) {
return $pValue;
}
if(empty(self::$_SYLKCharacters)) {
self::<API key>();
}
foreach (self::$_SYLKCharacters as $k => $v) {
$pValue = str_replace($k, $v, $pValue);
}
return $pValue;
}
}
|
Sequel.migration do
change do
create_table :reg_p200 do
column :id, :Bignum, primary_key: true
column :id_pai, :Bignum, index: true, null: false
column :per_ref, String, size: 6
column :vl_tot_cont_apu, BigDecimal, size: [18, 2]
column :vl_tot_aj_reduc, BigDecimal, size: [18, 2]
column :vl_tot_aj_acres, BigDecimal, size: [18, 2]
column :vl_tot_cont_dev, BigDecimal, size: [18, 2]
column :cod_rec, String, size: 6
column :cnpj_pai, String, size: 14, index: true
end
end
end
|
title:
date: 31/01/2020
**43**
**413314312015310434372111**
**
****
1. ****
2. ****
3. ****
****
JH201794
1. ****431711519101431312
42742930 JH101
1618
2. **** 43412 343436 437
4
3 7820053437
3. ****43435
(1) 435 434
(2) 435
(3) 437
(4)334 56 BJ 21NashvilleTNThomas Nelson19889697
`1. `
`2. `
`3. `
`4. `
`5. `
`6.
• ?
•
•
• `
|
using System;
using System.Collections.Generic;
using System.Linq;
using <API key>.Core.Config;
using <API key>.Core.Tracing;
namespace <API key>.Core
{
using Annotations;
public class <API key>
{
public static Lazy<Configuration> Configuration =
new Lazy<Configuration>(() => <API key>.UseConfig() ?? <API key>.UseAppSettings());
private static readonly Lazy<IDictionary<string, I<API key>>> Providers =
new Lazy<IDictionary<string, I<API key>>>(
() =>
{
var <API key> = new Dictionary<string, I<API key>>();
Initialize(<API key>);
return <API key>;
});
public <API key>()
{
TraceManager = new Lazy<ITraceManager>(() => new TraceManager()).Value;
}
public IDictionary<string, I<API key>> <API key>
{
get { return Providers.Value; }
}
public ITraceManager TraceManager { set; [UsedImplicitly] private get; }
public void AddProvider(I<API key> provider, bool replaceExisting = true)
{
<API key>(<API key>, provider, replaceExisting);
}
[Obsolete("Use RemoveProvider<T>(), this will be removed in a future version.")]
public void RemoveProvider(string providerName)
{
<API key>(providerName, <API key>);
}
public void RemoveProvider<T>()
{
var providerName = typeof(T).Name.ToLowerInvariant();
<API key>(providerName, <API key>);
}
private static void Initialize(IDictionary<string, I<API key>> <API key>)
{
<API key>.ThrowIfNull("<API key>);
var discoveredProviders = ReflectionHelpers.FindAllTypesOf<I<API key>>();
if (discoveredProviders == null)
{
return;
}
if (Configuration == null)
{
return;
}
if (Configuration.Value.Providers != null &&
Configuration.Value.Providers.Any())
{
<API key>(<API key>, discoveredProviders, Configuration.Value.Providers);
}
}
private static void <API key>(
IDictionary<string, I<API key>> <API key>,
IList<Type> discoveredProviders,
IEnumerable<Provider> providers)
{
<API key>.ThrowIfNull("<API key>);
discoveredProviders.ThrowIfNull("discoveredProviders");
providers.ThrowIfNull("appSettings");
foreach (var provider in providers)
{
var discoveredProvider = DiscoverProvider(discoveredProviders, provider);
<API key>(<API key>, discoveredProvider, false);
}
}
//private static void <API key>(
// IDictionary<string, I<API key>> <API key>,
// IList<Type> discoveredProviders,
// <API key> providerConfig)
// <API key>.ThrowIfNull("<API key>);
// discoveredProviders.ThrowIfNull("discoveredProviders");
// providerConfig.ThrowIfNull("providerConfig");
// providerConfig.Providers.ThrowIfNull("providerConfig.Providers");
// foreach (ProviderKey provider in providerConfig.Providers)
// var discoveredProvider = DiscoverProvider(discoveredProviders, provider);
// <API key>(<API key>, discoveredProvider, false);
public static I<API key> DiscoverProvider<T>(IList<Type> discoveredProviders,
string name,
Func<T> providerParamsFunc) where T : ProviderParams
{
discoveredProviders.ThrowIfNull("discoveredProviders");
var provider = discoveredProviders.SingleOrDefault(x => x.Name.ToLowerInvariant().StartsWith(name));
if (provider == null)
{
var errorMessage =
string.Format(
"Unable to find the provider [{0}]. Is there a provider dll available? Is there a typo in the provider name? Solution suggestions: Check to make sure the correct dll's are in the 'bin' directory and/or check the name to make sure there's no typo's in there. Example: If you're trying include the GitHub provider, make sure the name is 'github' (any case) and that the ExtraProviders dll exists in the 'bin' directory or make sure you've downloaded the package via NuGet -> install-package <API key>.ExtraProviders.",
name);
throw new <API key>(errorMessage);
}
I<API key> <API key> = null;
// Make sure we have a provider with the correct constructor parameters.
// How? If a person creates their own provider and doesn't offer a constructor
// that has a sigle ProviderParams, then we're stuffed. So we need to help them.
if (provider.GetConstructor(new[] { typeof(ProviderParams) }) != null)
{
var parameters = providerParamsFunc();
<API key> = Activator.CreateInstance(provider, parameters) as I<API key>;
}
if (<API key> == null)
{
// We didn't find a proper constructor for the provider class we wish to instantiate.
var errorMessage =
string.Format(
"The type {0} doesn't have the proper constructor. It requires a constructor that only accepts 1 argument of type ProviderParams. Eg. public MyProvider(ProviderParams providerParams){{ .. }}.",
provider.FullName);
throw new <API key>(errorMessage);
}
return <API key>;
}
private static I<API key> DiscoverProvider(IList<Type> discoveredProviders, Provider provider)
{
provider.ThrowIfNull("providerKey");
var name = provider.Name.ToLowerInvariant();
return DiscoverProvider(discoveredProviders, name, () => new ProviderParams
{
PublicApiKey = provider.Key,
SecretApiKey = provider.Secret,
Scopes = provider.Scopes.ScopesToCollection()
});
}
private static void <API key>(
IDictionary<string, I<API key>> <API key>,
I<API key> provider,
[UsedImplicitly] bool replaceExisting = true)
{
provider.ThrowIfNull("provider");
<API key>.ThrowIfNull("<API key>);
var key = provider.Name.ToLower();
if (<API key>.ContainsKey(key) && !replaceExisting)
{
throw new <API key>(
string.Format(
"The provider '{0}' already exists and cannot be overridden, either set `replaceExisting` to `true`, or remove the provider first.",
provider.Name));
}
<API key>[key] = provider;
}
private static void <API key>(string providerName, ICollection<KeyValuePair<string, I<API key>>> <API key>)
{
providerName.ThrowIfNull("providerName");
<API key>.ThrowIfNull("<API key>);
var providersToRemove =
<API key>.Where(x => providerName.StartsWith(x.Key.ToLowerInvariant()))
.ToList();
foreach (var providerPair in providersToRemove)
{
<API key>.Remove(providerPair);
}
}
}
public static class Extensions
{
public static void ThrowIfNull(this object thing, string parameter)
{
if (thing == null)
{
throw new <API key>(parameter);
}
}
public static ICollection<string> ScopesToCollection(this string scopes)
{
if (string.IsNullOrEmpty(scopes))
{
return null;
}
return scopes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
|
{{Waterloo}}
<html>
<div id ="mainContainer">
<div id ="contentContainer">
<h1>Medal Requirements</h1>
<p>
A list of medal requirements and checklists
</p>
</div>
</div>
</html>
{{Waterloo_Footer}}
|
// error_returnval.go
package main
import (
"errors"
"fmt"
"math"
)
func main() {
fmt.Print("First example with -1: ")
ret1, err1 := MySqrt(-1)
if err1 != nil {
fmt.Println("Error! Return values are: ", ret1, err1)
} else {
fmt.Println("It's ok! Return values are: ", ret1, err1)
}
fmt.Print("Second example with 5: ")
//you could also write it like this
if ret2, err2 := MySqrt(5); err2 != nil {
fmt.Println("Error! Return values are: ", ret2, err2)
} else {
fmt.Println("It's ok! Return values are: ", ret2, err2)
}
// named return variables:
fmt.Println(MySqrt2(5))
}
func MySqrt(f float64) (float64, error) {
//return an error as second parameter if invalid input
if f < 0 {
return float64(math.NaN()), errors.New("I won't be able to do a sqrt of negative number!")
}
//otherwise use default square root function
return math.Sqrt(f), nil
}
//name the return variables - by default it will have 'zero-ed' values i.e. numbers are 0, string is empty, etc.
func MySqrt2(f float64) (ret float64, err error) {
if f < 0 {
//then you can use those variables in code
ret = float64(math.NaN())
err = errors.New("I won't be able to do a sqrt of negative number!")
} else {
ret = math.Sqrt(f)
//err is not assigned, so it gets default value nil
}
//automatically return the named return variables ret and err
return
}
/* Output:
First example with -1: Error! Return values are: NaN I won't be able to do a sqrt of negative number!
Second example with 5: It's ok! Return values are: 2.23606797749979 <nil>
2.23606797749979 <nil>
*/
|
layout: post
author: "Greg Wilson"
title: "Our Store Is Open"
date: 2013-12-31
time: "18:30:00"
category: ["Community"]
<p>
Show your Software Carpentry pride with a shirt, sticker, button, or coffee mug
from our <a href="{{site.store_url}}">CafePress store</a>.
And Happy Hogmanay:
may 2014 be kind to you and yours.
</p>
<!--more
|
#!/usr/bin/env bash
cd "$( dirname "${BASH_SOURCE[0]}" )"
cp ../Assets/slua_src/slua.c luajit-2.1.0/src/
cd luajit-2.1.0
LIPO="xcrun -sdk iphoneos lipo"
STRIP="xcrun -sdk iphoneos strip"
IXCODE=`xcode-select -print-path`
ISDK=$IXCODE/Platforms/iPhoneOS.platform/Developer
ISDKVER=iPhoneOS8.4.sdk
ISDKP=$IXCODE/usr/bin/
if [ ! -e $ISDKP/ar ]; then
sudo cp $ISDK/usr/bin/ar $ISDKP
fi
if [ ! -e $ISDKP/ranlib ]; then
sudo cp $ISDK/usr/bin/ranlib $ISDKP
fi
if [ ! -e $ISDKP/strip ]; then
sudo cp $ISDK/usr/bin/strip $ISDKP
fi
make clean
ISDKF="-arch armv7 -isysroot $ISDK/SDKs/$ISDKVER"
make HOST_CC="gcc -m32 -std=c99" CROSS="$ISDKP" TARGET_FLAGS="$ISDKF" TARGET=armv7 TARGET_SYS=iOS LUAJIT_A=libsluav7.a
make clean
ISDKF="-arch armv7s -isysroot $ISDK/SDKs/$ISDKVER"
make HOST_CC="gcc -m32 -std=c99" CROSS="$ISDKP" TARGET_FLAGS="$ISDKF" TARGET=armv7s TARGET_SYS=iOS LUAJIT_A=libsluav7s.a
make clean
ISDKF="-arch arm64 -isysroot $ISDK/SDKs/$ISDKVER"
make HOST_CC="gcc -std=c99" CROSS="$ISDKP" TARGET_FLAGS="$ISDKF" TARGET=arm64 TARGET_SYS=iOS LUAJIT_A=libslua64.a
cd src
lipo libsluav7.a -create libsluav7s.a libslua64.a -output libslua.a
cp libslua.a ../../../Assets/Plugins/iOS/
cd ..
|
#ifndef <API key>
#define <API key> 1
#include <Core/Algorithms/Base/AlgorithmBase.h>
#include <Core/Algorithms/Legacy/Fields/share.h>
namespace SCIRun {
namespace Core {
namespace Algorithms {
namespace Fields {
class SCISHARE SetMeshNodesAlgo : public AlgorithmBase
{
public:
SetMeshNodesAlgo()
{}
bool run(FieldHandle input, Datatypes::DenseMatrixHandle matrix, FieldHandle& output) const;
static AlgorithmInputName MatrixNodes;
static AlgorithmOutputName OutputField;
virtual AlgorithmOutput run(const AlgorithmInput& input) const;
};
}}}}
#endif
|
#import <Foundation/Foundation.h>
#import "ASPObject.h"
#import "ASPTaskLink.h"
@protocol ASPTaskLinkResponse
@end
@interface ASPTaskLinkResponse : ASPObject
@property(nonatomic) ASPTaskLink* taskLink;
@property(nonatomic) NSString* code;
@property(nonatomic) NSString* status;
@end
|
using System;
using Internal.Runtime.Augments;
using Debug = System.Diagnostics.Debug;
namespace Internal.Runtime.TypeLoader
{
internal abstract class GenericDictionary
{
protected <API key>[] _cells;
protected IntPtr <API key>;
public GenericDictionary(<API key>[] cells)
{
Debug.Assert(cells != null);
_cells = cells;
}
public abstract IntPtr Allocate();
public unsafe void Finish(TypeBuilder typeBuilder)
{
Debug.Assert(_cells.Length == 0 || <API key> != IntPtr.Zero);
IntPtr* realCells = (IntPtr*)<API key>;
for (int i = 0; i < _cells.Length; i++)
{
realCells[i] = _cells[i].Create(typeBuilder);
}
}
}
internal class <API key> : GenericDictionary
{
public <API key>(<API key>[] cells)
: base(cells)
{ }
public override IntPtr Allocate()
{
Debug.Assert(<API key> == IntPtr.Zero);
if (_cells.Length > 0)
{
// Use checked typecast to int to ensure there aren't any overflows/truncations
<API key> = MemoryHelpers.AllocateMemory(checked((int)(_cells.Length * IntPtr.Size)));
}
return <API key>;
}
}
internal class <API key> : GenericDictionary
{
public <API key>(<API key>[] cells)
: base(cells)
{ }
public unsafe override IntPtr Allocate()
{
Debug.Assert(<API key> == IntPtr.Zero);
// Method dictionaries start with a header containing the hash code, which is not part of the native layout.
// The real first slot is located after the header.
// Use checked typecast to int to ensure there aren't any overflows/truncations
IntPtr <API key> = MemoryHelpers.AllocateMemory(checked((int)((_cells.Length + 1) * IntPtr.Size)));
// Put a magic hash code to indicate dynamically allocated method dictionary for
// debugging purposes.
*(int*)<API key> = 0xD1CC0DE; // DICCODE
<API key> = IntPtr.Add(<API key>, IntPtr.Size);
return <API key>;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using Dimebrain.TweetSharp.Fluent;
using System.Xml;
using System.Xml.Linq;
using SurfaceTwitter.Model;
using Dimebrain.TweetSharp.Fluent.Services;
using Dimebrain.TweetSharp;
using System;
using SurfaceTwitter.Util;
namespace SurfaceTwitter.Services
{
public class TwitterService : ITwitterService
{
private NetworkCredential _credentials;
private <TwitterConsumerkey> _info;
public bool IsAuthenticated { get; set; }
public TwitterService(NetworkCredential credential)
{
this._info = new <TwitterConsumerkey>();
this._info.ClientName = "SurfaceTwitterApp";
this._info.ClientVersion = "0.1";
this._info.ClientUrl = "http:
this._credentials = credential;
var <TwitterConsumerkey>.CreateRequest()
.AuthenticateAs(this._credentials.UserName, this._credentials.Password)
.Statuses().Replies().AsXml();
var response = twitter.Request();
<API key>(response);
this.IsAuthenticated = true;
}
public void SendTweet(string message)
{
var <TwitterConsumerkey>.CreateRequest(this._info)
.AuthenticateAs(this._credentials.UserName, this._credentials.Password)
.Statuses().Update(message)
.AsXml();
var response = twitter.Request();
this.<API key>(response);
}
public void SendTweet(string message, string picture)
{
var <TwitterConsumerkey>.CreateRequest(this._info)
.AuthenticateAs(this._credentials.UserName, this._credentials.Password)
.Photos().PostPhoto(picture, <API key>.TwitPic)
.Statuses().Update(message)
.AsXml();
var response = twitter.Request();
this.<API key>(response);
}
public IList<Tweet> GetTweets()
{
var <TwitterConsumerkey>.CreateRequest()
.AuthenticateAs(this._credentials.UserName, this._credentials.Password)
.Statuses().OnFriendsTimeline().AsXml();
var response = twitter.Request();
this.<API key>(response);
XDocument doc = XDocument.Parse(response);
List<Tweet> tweets = (from x in doc.Descendants("status")
let u = x.Element("user")
select new Tweet()
{
Id = int.Parse(x.Element("id").Value),
CreatedOn = x.Element("created_at").Value.ParseDateTime(),
Message = x.Element("text").Value,
User = new User()
{
Name = u.Element("name").Value,
PictureUrl = u.Element("profile_image_url").Value
}
}).ToList();
return tweets;
}
private void <API key>(string response)
{
XDocument doc = XDocument.Parse(response);
var error = (from x in doc.Descendants("error")
select x).SingleOrDefault();
if(error != null)
{
if (error.ToString().Contains("Could not authenticate you."))
throw new <API key>("Could not authenticate you with Twitter");
}
}
public void SendPicture(string picture)
{
var <TwitterConsumerkey>.CreateRequest(this._info)
.AuthenticateAs(this._credentials.UserName, this._credentials.Password)
.Photos().PostPhoto(picture, <API key>.TwitPic)
.Statuses().Update("")
.AsXml();
var response = twitter.Request();
this.<API key>(response);
}
}
}
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html>
<head>
<title>clear (Imlib2::Image)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre>/*
* Clear the contents of an image
*
* Examples:
* image.clear
*
*/
static VALUE image_clear(VALUE self) {
</pre>
</body>
</html>
|
'use strict';
describe('groupByFilter', function() {
var filter;
beforeEach(module('a8m.group-by'));
beforeEach(inject(function ($filter) {
filter = $filter('groupBy');
}));
it('should get array as collection, property(nested to) as identifier and ' +
'returns the composed aggregate object.', function() {
var players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
expect(filter(players, 'team')).toEqual( {
alpha: [players[0]],
beta: [players[1], players[3]],
gamma: [players[2], players[4]]
});
});
it('should support nested properties to', function() {
var orders = [
{ id:10, customer: { name: 'foo', id: 1 } },
{ id:11, customer: { name: 'bar', id: 2 } },
{ id:12, customer: { name: 'foo', id: 1 } },
{ id:13, customer: { name: 'bar', id: 2 } },
{ id:14, customer: { name: 'bar', id: 3 } },
2, null, true
];
expect(filter(orders, 'customer.name')).toEqual( {
foo: [orders[0], orders[2]],
bar: [orders[1], orders[3], orders[4]],
undefined: [2, null, true]
});
});
it('should get object as collection, property(nested to) as identifier and ' +
'returns the composed aggregate object.', function() {
var dataObject = {
0: { id: 1, data: {} },
1: { id: 1, data: {} },
2: { id: 2, data: {} },
3: { id: 2, data: {} }
};
expect(filter(dataObject, 'id')).toEqual({
1: [dataObject[0], dataObject[1]],
2: [dataObject[2], dataObject[3]]
});
});
it('should get !collection and return it as-is ', function() {
expect(filter('string')).toEqual('string');
expect(filter(1)).toEqual(1);
expect(filter(!1)).toBeFalsy();
expect(filter(null)).toBeNull();
});
});
|
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'spline',
type: 'spline'
},
title: {
text: 'Monthly Average Temperature'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Temperature'
},
labels: {
formatter: function() {
return this.value +'°'
}
}
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
series: [{
name: 'Tokyo',
marker: {
symbol: 'square'
},
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, {
y: 26.5,
marker: {
symbol: 'url(http:
}
}, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
marker: {
symbol: 'diamond'
},
data: [{
y: 3.9,
marker: {
symbol: 'url(http:
}
}, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
});
});
});
|
// ViewController.h
// Auth0Login
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.<API key>(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Plugin, Cordova } from './plugin';
/**
* @name LaunchReview
* @description
*
* This launches the native store app in order for the user to leave a review.
* On Android, the plugin opens the the app's storepage in the Play Store where the user can leave a review by pressing the stars to give a rating.
* On iOS, the plugin opens the app's storepage in the App Store and focuses the Review tab, where the user can leave a review by pressing "Write a review".
*
* @usage
* ```
* import { LaunchReview } from 'ionic-native';
*
* const appId: string = 'yourAppId';
* LaunchReview.launch(appId)
* .then(() => console.log('Successfully launched store app');
* ```
*/
export var LaunchReview = (function () {
function LaunchReview() {
}
/**
* Launch store app using given app ID
* @returns {Promise<void>}
*/
LaunchReview.launch = function (appId) { return; };
__decorate([
Cordova()
], LaunchReview, "launch", null);
LaunchReview = __decorate([
Plugin({
pluginName: 'LaunchReview',
plugin: '<API key>',
pluginRef: 'LaunchReview',
repo: 'https://github.com/dpa99c/<API key>',
platforms: ['Android', 'iOS']
})
], LaunchReview);
return LaunchReview;
}());
//# sourceMappingURL=launch-review.js.map
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_37) on Tue Apr 30 23:00:53 PDT 2013 -->
<TITLE>
project.android.imageprocessing.filter.effect
</TITLE>
<META NAME="date" CONTENT="2013-04-30">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="project.android.imageprocessing.filter.effect";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../project/android/imageprocessing/filter/colour/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../project/android/imageprocessing/filter/processing/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?project/android/imageprocessing/filter/effect/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
Package project.android.imageprocessing.filter.effect
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Creates a bulge distortion on the image
radius: The radius from the center to apply the distortion (in normalized coordinates from 0 - 1.0)
center: The center of the image (in normalized coordinates from 0 - 1.0) about which to distort
scale: The amount of distortion to apply, from -1.0 to 1.0</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Simulates the colorspace of a CGA monitor</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/CrosshatchFilter.html" title="class in project.android.imageprocessing.filter.effect">CrosshatchFilter</A></B></TD>
<TD>This converts an image into a black-and-white crosshatch pattern
crossHatchSpacing: The fractional width of the image to use as the spacing for the crosshatch.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/EmbossFilter.html" title="class in project.android.imageprocessing.filter.effect">EmbossFilter</A></B></TD>
<TD>Applies an embossing effect on the image
intensity: The strength of the embossing, from 0.0 to 4.0, with 1.0 as the normal level</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/GlassSphereFilter.html" title="class in project.android.imageprocessing.filter.effect">GlassSphereFilter</A></B></TD>
<TD>Same as the <API key>, only the image is not inverted and there's a little bit of frosting at the edges of the glass
center: The center about which to apply the distortion
radius: The radius of the distortion, ranging from 0.0 to 1.0
refractiveIndex: The index of refraction for the sphere</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/HalftoneFilter.html" title="class in project.android.imageprocessing.filter.effect">HalftoneFilter</A></B></TD>
<TD>Applies a halftone effect to an image, like news print
<API key>: How large the halftone dots are, as a fraction of the width and height of the image (0.0 - 1.0)
aspectRatio: the ratio of width and height for dots</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/KuwaharaFilter.html" title="class in project.android.imageprocessing.filter.effect">KuwaharaFilter</A></B></TD>
<TD>Kuwahara image abstraction, drawn from the work of Kyprianidis, et.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>A "faster" version of <A HREF="../../../../../project/android/imageprocessing/filter/effect/KuwaharaFilter.html" title="class in project.android.imageprocessing.filter.effect"><CODE>KuwaharaFilter</CODE></A> that has a fixed radius of 3.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/MosaicFilter.html" title="class in project.android.imageprocessing.filter.effect">MosaicFilter</A></B></TD>
<TD>This filter takes an input tileset, the tiles must ascend in luminance.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Creates a pinch distortion of the image
radius: The radius from the center to apply the distortion
center: The center of the image (in normalized coordinates from 0 - 1.0) about which to distort)
scale: The amount of distortion to apply, from -2.0 to 2.0</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/PixellateFilter.html" title="class in project.android.imageprocessing.filter.effect">PixellateFilter</A></B></TD>
<TD>Applies a pixellation effect on an image or video
<API key>: How large the pixels are, as a fraction of the width and height of the image (0.0 - 1.0)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Applies a pixellation effect on an image or video in a spiral
<API key>: How large the pixels are, as a fraction of the width and height of the image (0.0 - 1.0)
center: The point that the polar pixellization will begin at and spiral around.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/PolkaDotFilter.html" title="class in project.android.imageprocessing.filter.effect">PolkaDotFilter</A></B></TD>
<TD>Breaks an image up into colored dots within a regular grid
<API key>: How large the dots are, as a fraction of the width and height of the image (0.0 - 1.0)
dotScaling: What fraction of each grid space is taken up by a dot, from 0.0 to 1.0.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/PosterizeFilter.html" title="class in project.android.imageprocessing.filter.effect">PosterizeFilter</A></B></TD>
<TD>This reduces the color dynamic range into the number of steps specified, leading to a cartoon-like simple shading of the image.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/SketchFilter.html" title="class in project.android.imageprocessing.filter.effect">SketchFilter</A></B></TD>
<TD>Converts video to look like a sketch.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/SmoothToonFilter.html" title="class in project.android.imageprocessing.filter.effect">SmoothToonFilter</A></B></TD>
<TD>This uses a similar process as the GPUImageToonFilter, only it precedes the toon effect with a Gaussian blur to smooth out noise.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Simulates the refraction through a solid glass sphere
center: The center about which to apply the distortion
radius: The radius of the distortion, ranging from 0.0 to 1.0
refractiveIndex: The index of refraction for the sphere</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Creates a stretch distortion of the image
center: The center of the image (in normalized coordinates from 0 - 1.0) about which to distort</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/SwirlFilter.html" title="class in project.android.imageprocessing.filter.effect">SwirlFilter</A></B></TD>
<TD>Creates a swirl distortion on the image
radius: The radius from the center to apply the distortion
center: The center of the image (in normalized coordinates from 0 - 1.0) about which to twist
angle: The amount of twist to apply to the image</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/<API key>.html" title="class in project.android.imageprocessing.filter.effect"><API key></A></B></TD>
<TD>Same as the sketch filter, only the edges are thresholded instead of being grayscale</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/ToonFilter.html" title="class in project.android.imageprocessing.filter.effect">ToonFilter</A></B></TD>
<TD>This uses Sobel edge detection to place a black border around objects, and then it quantizes the colors present in the image to give a cartoon-like quality to the image.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../project/android/imageprocessing/filter/effect/VignetteFilter.html" title="class in project.android.imageprocessing.filter.effect">VignetteFilter</A></B></TD>
<TD>Performs a vignetting effect, fading out the image at the edges
colour: The colour outside
center: The starting location for the vignetting effect
start, end: The directional intensity of the vignetting</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../project/android/imageprocessing/filter/colour/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../project/android/imageprocessing/filter/processing/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?project/android/imageprocessing/filter/effect/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* English spoken in Great Britain
*/
FE.LANGUAGE['en_gb'] = {
translation: {
// Place holder
'Type something': 'Type something',
// Basic formatting
'Bold': 'Bold',
'Italic': 'Italic',
'Underline': 'Underline',
'Strikethrough': 'Strikethrough',
// Main buttons
'Insert': 'Insert',
'Delete': 'Delete',
'Cancel': 'Cancel',
'OK': 'OK',
'Back': 'Back',
'Remove': 'Remove',
'More': 'More',
'Update': 'Update',
'Style': 'Style',
// Font
'Font Family': 'Font Family',
'Font Size': 'Font Size',
// Colors
'Colors': 'Colours',
'Background': 'Background',
'Text': 'Text',
'HEX Color': 'HEX Colour',
// Paragraphs
'Paragraph Format': 'Paragraph Format',
'Normal': 'Normal',
'Code': 'Code',
'Heading 1': 'Heading 1',
'Heading 2': 'Heading 2',
'Heading 3': 'Heading 3',
'Heading 4': 'Heading 4',
// Style
'Paragraph Style': 'Paragraph Style',
'Inline Style': 'Inline Style',
// Alignment
'Align': 'Align',
'Align Left': 'Align Left',
'Align Center': 'Align Centre',
'Align Right': 'Alight Right',
'Align Justify': 'Align Justify',
'None': 'None',
// Lists
'Ordered List': 'Ordered List',
'Unordered List': 'Unordered List',
// Indent
'Decrease Indent': 'Decrease Indent',
'Increase Indent': 'Increase Indent',
// Links
'Insert Link': 'Insert Link',
'Open in new tab': 'Open in new tab',
'Open Link': 'Open Link',
'Edit Link': 'Edit Link',
'Unlink': 'Unlink',
'Choose Link': 'Choose Link',
// Images
'Insert Image': 'Insert Image',
'Upload Image': 'Upload Image',
'By URL': 'By URL',
'Browse': 'Browse',
'Drop image': 'Drop image',
'or click': 'or click',
'Manage Images': 'Manage Images',
'Loading': 'Loading',
'Deleting': 'Deleting',
'Tags': 'Tags',
'Are you sure? Image will be deleted.': 'Are you sure? Image will be deleted.',
'Replace': 'Replace',
'Uploading': 'Uploading',
'Loading image': 'Loading image',
'Display': 'Display',
'Inline': 'Inline',
'Break Text': 'Break Text',
'Alternative Text': 'Alternative Text',
'Change Size': 'Change Size',
'Width': 'Width',
'Height': 'Height',
'Something went wrong. Please try again.': 'Something went wrong. Please try again.',
'Image Caption': 'Image Caption',
'Advanced Edit': 'Advanced Edit',
// Video
'Insert Video': 'Insert Video',
'Embedded Code': 'Embedded Code',
'Paste in a video URL': 'Paste in a video URL',
'Drop video': 'Drop video',
'Your browser does not support HTML5 video.': 'Your browser does not support HTML5 video.',
'Upload Video': 'Upload Video',
// Tables
'Insert Table': 'Insert Table',
'Table Header': 'Table Header',
'Remove Table': 'Remove Table',
'Table Style': 'Table Style',
'Horizontal Align': 'Horizontal Align',
'Row': 'Row',
'Insert row above': 'Insert row above',
'Insert row below': 'Insert row below',
'Delete row': 'Delete row',
'Column': 'Column',
'Insert column before': 'Insert column before',
'Insert column after': 'Insert column after',
'Delete column': 'Delete column',
'Cell': 'Cell',
'Merge cells': 'Merge cells',
'Horizontal split': 'Horizontal split',
'Vertical split': 'Vertical split',
'Cell Background': 'Cell Background',
'Vertical Align': 'Vertical Align',
'Top': 'Top',
'Middle': 'Middle',
'Bottom': 'Bottom',
'Align Top': 'Align Top',
'Align Middle': 'Align Middle',
'Align Bottom': 'Align Bottom',
'Cell Style': 'Cell Style',
// Files
'Upload File': 'Upload File',
'Drop file': 'Drop file',
// Emoticons
'Emoticons': 'Emoticons',
// Line breaker
'Break': 'Break',
// Math
'Subscript': 'Subscript',
'Superscript': 'Superscript',
// Full screen
'Fullscreen': 'Fullscreen',
// Horizontal line
'Insert Horizontal Line': 'Insert Horizontal Line',
// Clear formatting
'Clear Formatting': 'Cell Formatting',
// Save
'Save': 'Save',
// Undo, redo
'Undo': 'Undo',
'Redo': 'Redo',
// Select all
'Select All': 'Select All',
// Code view
'Code View': 'Code View',
// Quote
'Quote': 'Quote',
'Increase': 'Increase',
'Decrease': 'Decrease',
// Quick Insert
'Quick Insert': 'Quick Insert',
// Spcial Characters
'Special Characters': 'Special Characters',
'Latin': 'Latin',
'Greek': 'Greek',
'Cyrillic': 'Cyrillic',
'Punctuation': 'Punctuation',
'Currency': 'Currency',
'Arrows': 'Arrows',
'Math': 'Math',
'Misc': 'Misc',
// Print.
'Print': 'Print',
// Spell Checker.
'Spell Checker': 'Spell Checker',
// Help
'Help': 'Help',
'Shortcuts': 'Shortcuts',
'Inline Editor': 'Inline Editor',
'Show the editor': 'Show the editor',
'Common actions': 'Common actions',
'Copy': 'Copy',
'Cut': 'Cut',
'Paste': 'Paste',
'Basic Formatting': 'Basic Formatting',
'Increase quote level': 'Increase quote level',
'Decrease quote level': 'Decrease quote level',
'Image / Video': 'Image / Video',
'Resize larger': 'Resize larger',
'Resize smaller': 'Resize smaller',
'Table': 'Table',
'Select table cell': 'Select table cell',
'Extend selection one cell': 'Extend selection one cell',
'Extend selection one row': 'Extend selection one row',
'Navigation': 'Navigation',
'Focus popup / toolbar': 'Focus popup / toolbar',
'Return focus to previous position': 'Return focus to previous position',
// Embed.ly
'Embed URL': 'Embed URL',
'Paste in a URL to embed': 'Paste in a URL to embed',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?',
'Keep': 'Keep',
'Clean': 'Clean',
'Word Paste Detected': 'Word Paste Detected',
// Character Counter
'Characters': 'Characters',
// More Buttons
'More Text': 'More Text',
'More Paragraph': 'More Paragraph',
'More Rich': 'More Rich',
'More Misc': 'More Misc'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=en_gb.js.map
|
@import "common-css";
/* i dunno just something to verify */
body {
font-size: 20px;
}
.App {
background-image: url(../img/a_hot_mess.gif);
}
@media
only screen and (-<API key>: 2),
only screen and ( <API key>: 2),
only screen and ( min-resolution: 192dpi),
only screen and ( min-resolution: 2dppx) {
.App {
background-image: url(../img/aww-yiss.gif);
}
}
|
import { Architectures } from "common/butlerd/messages";
interface PlatformData {
icon: string;
platform: string;
emoji: string;
}
interface PlatformDataMap {
windows: PlatformData;
linux: PlatformData;
osx: PlatformData;
[key: string]: PlatformData;
}
const data: PlatformDataMap = {
windows: { icon: "windows8", platform: "windows", emoji: "" },
linux: { icon: "tux", platform: "linux", emoji: "" },
osx: { icon: "apple", platform: "osx", emoji: "" },
};
export default data;
export type PlatformHolder = {
platforms: {
windows: Architectures;
linux: Architectures;
osx: Architectures;
};
type: "html" | any;
};
export function hasPlatforms(target: PlatformHolder): boolean {
for (const key of Object.keys(data)) {
if ((target.platforms as { [key: string]: Architectures })[key]) {
return true;
}
}
if (target.type === "html") {
return true;
}
return false;
}
|
require 'hdf5'
local pretty = require 'pl.pretty'
local path = require 'pl.path'
local totem = require 'totem'
local myTests = {}
local tester = totem.Tester()
local testUtils = hdf5._testUtils
local function writeAndReread(location, data)
local got
local typeIn = type(data)
if typeIn == 'userdata' then
typeIn = torch.typename(data) or typeIn
end
testUtils.withTmpDir(function(tmpDir)
local filename = path.join(tmpDir, "test.h5")
local writeFile = hdf5.open(filename, 'w')
tester:assertne(writeFile, nil, "hdf5.open returned nil")
writeFile:write(location, data)
writeFile:close()
local readFile = hdf5.open(filename, 'r')
tester:assertne(readFile, nil, "hdf5.open returned nil")
local data = readFile:read(location)
got = data:all()
readFile:close()
tester:assertne(got, nil, "hdf5.read returned nil")
local typeOut = torch.typename(got) or type(got)
tester:asserteq(typeIn, typeOut, "type read not the same as type written: was " .. typeIn .. "; is " .. typeOut)
end)
return got
end
local function deepAlmostEq(a, b, epsilon, msg)
local typeA = torch.typename(a) or type(a)
local typeB = torch.typename(b) or type(b)
if typeA ~= typeB then
return false, "type mismatch", a, b
end
if typeA == 'table' then
for k, v in pairs(a) do
if not b[k] then
return false, "mismatching table keys", a, b
end
end
for k, v in pairs(b) do
if not a[k] then
return false, "mismatching table keys", a, b
end
local result, msg, subA, subB = deepAlmostEq(a[k], v, epsilon, msg)
if not result then
return false, msg, subA, subB
end
end
end
if typeA:sub(-6, -1) == 'Tensor' then
local diff = a:add(-b):apply(function(x) return math.abs(x) end):sum()
if diff > epsilon then
return false, "tensor values differ by " .. diff .. " > " .. epsilon, a, b
end
end
return true
end
local function writeAndRereadTest(dataPath, testData)
local got = writeAndReread(dataPath, testData)
local result, msg, a, b = deepAlmostEq(got, testData, 1e-16)
tester:assert(result, "data read is not the same as data written: " .. tostring(msg) .. " in "
.. pretty.write(a) .. " (GOT)\n-- VS --\n"
.. pretty.write(b) .. " (EXPECTED)\n")
end
function myTests:testWriteTableRoot()
local testData = { data = torch.rand(4, 6) }
local dataPath = "/"
writeAndRereadTest(dataPath, testData)
end
function myTests:<API key>()
local testData = { data = torch.rand(4, 6) }
local dataPath = "/group"
writeAndRereadTest(dataPath, testData)
end
function myTests:testWriteTensorRoot()
local testData = torch.rand(4, 6)
local dataPath = "/data"
writeAndRereadTest(dataPath, testData)
end
function myTests:<API key>()
local testData = torch.rand(4, 6)
local dataPath = "/group/data"
writeAndRereadTest(dataPath, testData)
end
function myTests:<API key>()
local testData = { group = { data = torch.rand(4, 6) } }
local dataPath = "/"
writeAndRereadTest(dataPath, testData)
end
function myTests:<API key>()
local testData = { group2 = { data = torch.rand(4, 6) } }
local dataPath = "/group1"
writeAndRereadTest(dataPath, testData)
end
function myTests:<API key>()
local testData = { group4 = { group5 = { data = torch.rand(4, 6) } } }
local dataPath = "/group1/group2/group3"
writeAndRereadTest(dataPath, testData)
end
return tester:add(myTests):run()
|
package mpi.group;
import mpjdev.*;
import mpjbuf.*;
import mpi.*;
import java.util.Arrays;
public class Group_intersect {
public static void main(String args[]) throws Exception {
try {
Group_intersect a = new Group_intersect(args);
}
catch (Exception e) {
}
}
public Group_intersect() {
}
public Group_intersect(String[] args) throws Exception {
MPI.Init(args);
mpi.Group grp = MPI.COMM_WORLD.Group();
int me = grp.Rank();
int tasks = grp.Size();
if (tasks < 8) {
if (me == 0)
System.out.println("group->Group_intersect: MUST RUN with 8 tasks");
MPI.COMM_WORLD.Barrier();
MPI.Finalize();
return;
}
int[] incl1 = { 4, 0, 5, 6 };
int[] incl2 = { 6, 7, 4 };
mpi.Group grp1 = grp.Incl(incl1);
mpi.Group grp2 = grp.Incl(incl2);
if (grp1.Size() != 4) {
System.out.println("Error(1): ?|?|?|? ");
} else if (grp2.Size() != 3) {
System.out.println("Error(2): ?|?|?|? ");
}
mpi.Group grp3 = mpi.Group.Intersection(grp1, grp2);
if (grp3.Size() != 2) {
System.out.println("Error(3): ");
}
MPI.COMM_WORLD.Barrier();
if (me == 0)
System.out.println("Group_intersect TEST COMPLETED");
MPI.Finalize();
}
}
|
package net.glowstone.generator;
import net.glowstone.GlowWorld;
import net.glowstone.constants.GlowBiome;
import net.glowstone.generator.ground.*;
import net.glowstone.generator.ground.MesaGroundGenerator.MesaType;
import net.glowstone.generator.populators.OverworldPopulator;
import net.glowstone.generator.populators.StructurePopulator;
import net.glowstone.generator.populators.overworld.SnowPopulator;
import net.glowstone.util.noise.<API key>;
import net.glowstone.util.noise.<API key>;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.WorldType;
import org.bukkit.block.Biome;
import org.bukkit.util.noise.OctaveGenerator;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static org.bukkit.block.Biome.*;
public class OverworldGenerator extends GlowChunkGenerator {
// Still need to parse ServerConfig.Key.GENERATOR_SETTINGS string
// and set below fields from that.
private static final double COORDINATE_SCALE = 684.412D; // coordinateScale
private static final double HEIGHT_SCALE = 684.412D; // heightScale
private static final double <API key> = 200.0D; // depthNoiseScaleX
private static final double <API key> = 200.0D; // depthNoiseScaleZ
private static final double <API key> = 80.0D; // mainNoiseScaleX
private static final double <API key> = 160.0D; // mainNoiseScaleY
private static final double <API key> = 80.0D; // mainNoiseScaleZ
private static final double SURFACE_SCALE = 1 / 16.0D;
private static final double BASE_SIZE = 8.5D; // baseSize
private static final double STRETCH_Y = 12.0D; // stretchY
private static final double BIOME_HEIGHT_OFFSET = 0.0D; // biomeDepthOffset
private static final double BIOME_HEIGHT_WEIGHT = 1.0D; // biomeDepthWeight
private static final double BIOME_SCALE_OFFSET = 0.0D; // biomeScaleOffset
private static final double BIOME_SCALE_WEIGHT = 1.0D; // biomeScaleWeight
private static final double[][] ELEVATION_WEIGHT = new double[5][5];
private static final Map<Biome, GroundGenerator> GROUND_MAP = new HashMap<>();
private static final Map<Biome, BiomeHeight> HEIGHT_MAP = new HashMap<>();
static {
<API key>(new <API key>(), BEACHES, COLD_BEACH, DESERT, DESERT_HILLS, MUTATED_DESERT);
<API key>(new <API key>(), STONE_BEACH);
<API key>(new <API key>(), MUTATED_ICE_FLATS);
<API key>(new <API key>(), MUSHROOM_ISLAND, <API key>);
<API key>(new <API key>(), EXTREME_HILLS);
<API key>(new <API key>(), <API key>, <API key>);
<API key>(new <API key>(), MUTATED_SAVANNA, <API key>);
<API key>(new <API key>(), REDWOOD_TAIGA, REDWOOD_TAIGA_HILLS, <API key>, <API key>);
<API key>(new MesaGroundGenerator(), MESA, MESA_CLEAR_ROCK, MESA_ROCK);
<API key>(new MesaGroundGenerator(MesaType.BRYCE), MUTATED_MESA);
<API key>(new MesaGroundGenerator(MesaType.FOREST), MESA_ROCK, MUTATED_MESA_ROCK);
setBiomeHeight(BiomeHeight.OCEAN, OCEAN, FROZEN_OCEAN);
setBiomeHeight(BiomeHeight.DEEP_OCEAN, DEEP_OCEAN);
setBiomeHeight(BiomeHeight.RIVER, RIVER, FROZEN_RIVER);
setBiomeHeight(BiomeHeight.FLAT_SHORE, BEACHES, COLD_BEACH, <API key>);
setBiomeHeight(BiomeHeight.ROCKY_SHORE, STONE_BEACH);
setBiomeHeight(BiomeHeight.FLATLANDS, DESERT, ICE_FLATS, SAVANNA);
setBiomeHeight(BiomeHeight.EXTREME_HILLS, EXTREME_HILLS, <API key>, <API key>, <API key>);
setBiomeHeight(BiomeHeight.MID_PLAINS, TAIGA, TAIGA_COLD, REDWOOD_TAIGA);
setBiomeHeight(BiomeHeight.SWAMPLAND, SWAMPLAND);
setBiomeHeight(BiomeHeight.LOW_HILLS, MUSHROOM_ISLAND);
setBiomeHeight(BiomeHeight.HILLS, ICE_MOUNTAINS, DESERT_HILLS, FOREST_HILLS, TAIGA_HILLS, <API key>, JUNGLE_HILLS, BIRCH_FOREST_HILLS, TAIGA_COLD_HILLS, REDWOOD_TAIGA_HILLS, MUTATED_MESA_ROCK, <API key>);
setBiomeHeight(BiomeHeight.HIGH_PLATEAU, SAVANNA_ROCK, MESA_ROCK, MESA_CLEAR_ROCK);
setBiomeHeight(BiomeHeight.FLATLANDS_HILLS, MUTATED_DESERT);
setBiomeHeight(BiomeHeight.BIG_HILLS, MUTATED_ICE_FLATS);
setBiomeHeight(BiomeHeight.BIG_HILLS2, <API key>);
setBiomeHeight(BiomeHeight.SWAMPLAND_HILLS, MUTATED_SWAMPLAND);
setBiomeHeight(BiomeHeight.DEFAULT_HILLS, MUTATED_JUNGLE, MUTATED_JUNGLE_EDGE, <API key>, <API key>);
setBiomeHeight(BiomeHeight.MID_HILLS, MUTATED_TAIGA, MUTATED_TAIGA_COLD, <API key>, <API key>);
setBiomeHeight(BiomeHeight.MID_HILLS2, MUTATED_FOREST);
setBiomeHeight(BiomeHeight.LOW_SPIKES, MUTATED_SAVANNA);
setBiomeHeight(BiomeHeight.HIGH_SPIKES, <API key>);
// fill a 5x5 array with values that acts as elevation weight on chunk neighboring,
// this can be viewed as a parabolic field: the center gets the more weight, and the
// weight decreases as distance increases from the center. This is applied on the
// lower scale biome grid.
for (int x = 0; x < 5; x++) {
for (int z = 0; z < 5; z++) {
int sqX = x - 2;
sqX *= sqX;
int sqZ = z - 2;
sqZ *= sqZ;
ELEVATION_WEIGHT[x][z] = 10.0D / Math.sqrt(sqX + sqZ + 0.2D);
}
}
}
private final double[][][] density = new double[5][5][33];
private final GroundGenerator groundGen = new GroundGenerator();
private final BiomeHeight defaultHeight = BiomeHeight.DEFAULT;
public OverworldGenerator() {
super(new OverworldPopulator(),
new StructurePopulator(),
new SnowPopulator());
}
private static void <API key>(GroundGenerator gen, Biome... biomes) {
for (Biome biome : biomes) {
GROUND_MAP.put(biome, gen);
}
}
private static void setBiomeHeight(BiomeHeight height, Biome... biomes) {
for (Biome biome : biomes) {
HEIGHT_MAP.put(biome, height);
}
}
@Override
public ChunkData generateChunkData(World world, Random random, int chunkX, int chunkZ, BiomeGrid biomes) {
ChunkData chunkData = generateRawTerrain(world, chunkX, chunkZ);
int cx = chunkX << 4;
int cz = chunkZ << 4;
double[] surfaceNoise = ((<API key>) getWorldOctaves(world).get("surface")).fBm(cx, cz, 0.5D, 0.5D);
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
if (GROUND_MAP.containsKey(biomes.getBiome(x, z))) {
GROUND_MAP.get(biomes.getBiome(x, z)).<API key>(chunkData, world, random, cx + x, cz + z, biomes.getBiome(x, z), surfaceNoise[x | z << 4]);
} else {
groundGen.<API key>(chunkData, world, random, cx + x, cz + z, biomes.getBiome(x, z), surfaceNoise[x | z << 4]);
}
}
}
return chunkData;
}
@Override
protected void createWorldOctaves(World world, Map<String, OctaveGenerator> octaves) {
Random seed = new Random(world.getSeed());
OctaveGenerator gen = new <API key>(seed, 16, 5, 5);
gen.setXScale(<API key>);
gen.setZScale(<API key>);
octaves.put("height", gen);
gen = new <API key>(seed, 16, 5, 33, 5);
gen.setXScale(COORDINATE_SCALE);
gen.setYScale(HEIGHT_SCALE);
gen.setZScale(COORDINATE_SCALE);
octaves.put("roughness", gen);
gen = new <API key>(seed, 16, 5, 33, 5);
gen.setXScale(COORDINATE_SCALE);
gen.setYScale(HEIGHT_SCALE);
gen.setZScale(COORDINATE_SCALE);
octaves.put("roughness2", gen);
gen = new <API key>(seed, 8, 5, 33, 5);
gen.setXScale(COORDINATE_SCALE / <API key>);
gen.setYScale(HEIGHT_SCALE / <API key>);
gen.setZScale(COORDINATE_SCALE / <API key>);
octaves.put("detail", gen);
gen = new <API key>(seed, 4, 16, 16);
gen.setScale(SURFACE_SCALE);
octaves.put("surface", gen);
}
private ChunkData generateRawTerrain(World world, int chunkX, int chunkZ) {
<API key>(world, chunkX, chunkZ);
int seaLevel = world.getSeaLevel();
ChunkData chunkData = createChunkData(world);
// Terrain densities where sampled at a lower res (scaled 4x along vertical, 8x along horizontal)
// so it's needed to re-scale it. Linear interpolation is used to fill in the gaps.
for (int i = 0; i < 5 - 1; i++) {
for (int j = 0; j < 5 - 1; j++) {
for (int k = 0; k < 33 - 1; k++) {
// 2x2 grid
double d1 = density[i][j][k];
double d2 = density[i + 1][j][k];
double d3 = density[i][j + 1][k];
double d4 = density[i + 1][j + 1][k];
// 2x2 grid (row above)
double d5 = (density[i][j][k + 1] - d1) / 8;
double d6 = (density[i + 1][j][k + 1] - d2) / 8;
double d7 = (density[i][j + 1][k + 1] - d3) / 8;
double d8 = (density[i + 1][j + 1][k + 1] - d4) / 8;
for (int l = 0; l < 8; l++) {
double d9 = d1;
double d10 = d3;
for (int m = 0; m < 4; m++) {
double dens = d9;
for (int n = 0; n < 4; n++) {
// any density higher than 0 is ground, any density lower or equal to 0 is air
// (or water if under the sea level).
if (dens > 0) {
chunkData.setBlock(m + (i << 2), l + (k << 3), n + (j << 2), Material.STONE);
} else if (l + (k << 3) < seaLevel - 1) {
chunkData.setBlock(m + (i << 2), l + (k << 3), n + (j << 2), Material.STATIONARY_WATER);
}
// interpolation along z
dens += (d10 - d9) / 4;
}
// interpolation along x
d9 += (d2 - d1) / 4;
// interpolate along z
d10 += (d4 - d3) / 4;
}
// interpolation along y
d1 += d5;
d3 += d7;
d2 += d6;
d4 += d8;
}
}
}
}
return chunkData;
}
private void <API key>(World world, int x, int z) {
WorldType type = world.getWorldType();
// Scaling chunk x and z coordinates (4x, see below)
x <<= 2;
z <<= 2;
// Get biome grid data at lower res (scaled 4x, at this scale a chunk is 4x4 columns of the biome grid),
// we are loosing biome detail but saving huge amount of computation.
// We need 1 chunk (4 columns) + 1 column for later needed outer edges (1 column) and at least 2 columns
// on each side to be able to cover every value.
// 4 + 1 + 2 + 2 = 9 columns but the biomegrid generator needs a multiple of 2 so we ask 10 columns wide
// to the biomegrid generator.
// This gives a total of 81 biome grid columns to work with, and this includes the chunk neighborhood.
int[] biomeGrid = ((GlowWorld) world).getChunkManager().<API key>(x - 2, z - 2, 10, 10);
Map<String, OctaveGenerator> octaves = getWorldOctaves(world);
double[] heightNoise = ((<API key>) octaves.get("height")).fBm(x, z, 0.5D, 2.0D);
double[] roughnessNoise = ((<API key>) octaves.get("roughness")).fBm(x, 0, z, 0.5D, 2.0D);
double[] roughnessNoise2 = ((<API key>) octaves.get("roughness2")).fBm(x, 0, z, 0.5D, 2.0D);
double[] detailNoise = ((<API key>) octaves.get("detail")).fBm(x, 0, z, 0.5D, 2.0D);
int index = 0;
int indexHeight = 0;
// Sampling densities.
// Ideally we would sample 512 (4x4x32) values but in reality we need 825 values (5x5x33).
// This is because linear interpolation is done later to re-scale so we need right and
// bottom edge values if we want it to be "seamless".
// You can check this picture to have a visualization of how the biomegrid is traversed (2D plan):
// The big square grid represents our lower res biomegrid columns, and the very small square grid
// represents the normal biome grid columns (at block level) and the reason why it's required to
// re-scale it and do linear interpolation before densities can be used to generate raw terrain.
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
double avgHeightScale = 0;
double avgHeightBase = 0;
double totalWeight = 0;
Biome biome = GlowBiome.getBiome(biomeGrid[i + 2 + (j + 2) * 10]);
BiomeHeight biomeHeight = HEIGHT_MAP.containsKey(biome) ? HEIGHT_MAP.get(biome) : defaultHeight;
// Sampling an average height base and scale by visiting the neighborhood
// of the current biomegrid column.
for (int m = 0; m < 5; m++) {
for (int n = 0; n < 5; n++) {
Biome nearBiome = GlowBiome.getBiome(biomeGrid[i + m + (j + n) * 10]);
BiomeHeight nearBiomeHeight = HEIGHT_MAP.containsKey(nearBiome) ? HEIGHT_MAP.get(nearBiome) : defaultHeight;
double heightBase = BIOME_HEIGHT_OFFSET + nearBiomeHeight.getHeight() * BIOME_HEIGHT_WEIGHT;
double heightScale = BIOME_SCALE_OFFSET + nearBiomeHeight.getScale() * BIOME_SCALE_WEIGHT;
if (type == WorldType.AMPLIFIED && heightBase > 0) {
heightBase = 1.0D + heightBase * 2.0D;
heightScale = 1.0D + heightScale * 4.0D;
}
double weight = ELEVATION_WEIGHT[m][n] / (heightBase + 2.0D);
if (nearBiomeHeight.getHeight() > biomeHeight.getHeight()) {
weight *= 0.5D;
}
avgHeightScale += heightScale * weight;
avgHeightBase += heightBase * weight;
totalWeight += weight;
}
}
avgHeightScale /= totalWeight;
avgHeightBase /= totalWeight;
avgHeightScale = avgHeightScale * 0.9D + 0.1D;
avgHeightBase = (avgHeightBase * 4.0D - 1.0D) / 8.0D;
double noiseH = heightNoise[indexHeight++] / 8000.0D;
if (noiseH < 0) {
noiseH = Math.abs(noiseH) * 0.3D;
}
noiseH = noiseH * 3.0D - 2.0D;
if (noiseH < 0) {
noiseH = Math.max(noiseH * 0.5D, -1) / 1.4D * 0.5D;
} else {
noiseH = Math.min(noiseH, 1) / 8.0D;
}
noiseH = (noiseH * 0.2D + avgHeightBase) * BASE_SIZE / 8.0D * 4.0D + BASE_SIZE;
for (int k = 0; k < 33; k++) {
// density should be lower and lower as we climb up, this gets a height value to
// substract from the noise.
double nH = (k - noiseH) * STRETCH_Y * 128.0D / 256.0D / avgHeightScale;
if (nH < 0.0D) {
nH *= 4.0D;
}
double noiseR = roughnessNoise[index] / 512.0D;
double noiseR2 = roughnessNoise2[index] / 512.0D;
double noiseD = (detailNoise[index] / 10.0D + 1.0D) / 2.0D;
// linear interpolation
double dens = noiseD < 0 ? noiseR : noiseD > 1 ? noiseR2 : noiseR + (noiseR2 - noiseR) * noiseD;
dens -= nH;
index++;
if (k > 29) {
double lowering = (k - 29) / 3.0D;
// linear interpolation
dens = dens * (1.0D - lowering) + -10.0D * lowering;
}
density[i][j][k] = dens;
}
}
}
}
private static class BiomeHeight {
public static final BiomeHeight DEFAULT = new BiomeHeight(0.1D, 0.2D);
public static final BiomeHeight FLAT_SHORE = new BiomeHeight(0.0D, 0.025D);
public static final BiomeHeight HIGH_PLATEAU = new BiomeHeight(1.5D, 0.025D);
public static final BiomeHeight FLATLANDS = new BiomeHeight(0.125D, 0.05D);
public static final BiomeHeight SWAMPLAND = new BiomeHeight(-0.2D, 0.1D);
public static final BiomeHeight MID_PLAINS = new BiomeHeight(0.2D, 0.2D);
public static final BiomeHeight FLATLANDS_HILLS = new BiomeHeight(0.275D, 0.25D);
public static final BiomeHeight SWAMPLAND_HILLS = new BiomeHeight(-0.1D, 0.3D);
public static final BiomeHeight LOW_HILLS = new BiomeHeight(0.2D, 0.3D);
public static final BiomeHeight HILLS = new BiomeHeight(0.45D, 0.3D);
public static final BiomeHeight MID_HILLS2 = new BiomeHeight(0.1D, 0.4D);
public static final BiomeHeight DEFAULT_HILLS = new BiomeHeight(0.2D, 0.4D);
public static final BiomeHeight MID_HILLS = new BiomeHeight(0.3D, 0.4D);
public static final BiomeHeight BIG_HILLS = new BiomeHeight(0.525D, 0.55D);
public static final BiomeHeight BIG_HILLS2 = new BiomeHeight(0.55D, 0.5D);
public static final BiomeHeight EXTREME_HILLS = new BiomeHeight(1.0D, 0.5D);
public static final BiomeHeight ROCKY_SHORE = new BiomeHeight(0.1D, 0.8D);
public static final BiomeHeight LOW_SPIKES = new BiomeHeight(0.4125D, 1.325D);
public static final BiomeHeight HIGH_SPIKES = new BiomeHeight(1.1D, 1.3125D);
public static final BiomeHeight RIVER = new BiomeHeight(-0.5D, 0.0D);
public static final BiomeHeight OCEAN = new BiomeHeight(-1.0D, 0.1D);
public static final BiomeHeight DEEP_OCEAN = new BiomeHeight(-1.8D, 0.1D);
private final double height;
private final double scale;
public BiomeHeight(double height, double scale) {
this.height = height;
this.scale = scale;
}
public double getHeight() {
return height;
}
public double getScale() {
return scale;
}
}
}
|
# <API key>: true
module Appsignal
# {Appsignal::<API key>} wraps Ruby's `GC::Profiler` to be
# able to track garbage collection time for multiple transactions, while
# constantly clearing `GC::Profiler`'s total_time to make sure it doesn't
# leak memory by keeping garbage collection run samples in memory.
# @api private
class <API key>
def self.lock
@lock ||= Mutex.new
end
def initialize
@total_time = 0
end
# Whenever {#total_time} is called, the current `GC::Profiler#total_time`
# gets added to `@total_time`, after which `GC::Profiler.clear` is called
# to prevent it from leaking memory. A class-level lock is used to make
# sure garbage collection time is never counted more than once.
# Whenever `@total_time` gets above two billion milliseconds (about 23
# days), it's reset to make sure the result fits in a signed 32-bit
# integer.
# @return [Integer]
def total_time
lock.synchronize do
@total_time += (internal_profiler.total_time * 1000).round
internal_profiler.clear
end
@total_time = 0 if @total_time > 2_000_000_000
@total_time
end
private
def internal_profiler
GC::Profiler
end
def lock
self.class.lock
end
end
# {Appsignal::<API key>} is a dummy profiler
# that always returns 0 as the total time.
# Used when we don't want any profile information
# @api private
class <API key>
def total_time
0
end
end
end
|
// testCBHDKeys.c
// cbitcoin
// cbitcoin, including this file, may be copied, modified, propagated,
// or distributed except according to the terms contained in the
#include "CBHDKeys.h"
#include "CBChecksumBytes.h"
#include "CBAddress.h"
#include "CBWIF.h"
#define NUM_TEST_VECTORS 2
#define NUM_CHILDREN 5
typedef struct{
char privString[112];
char pubString[112];
char addr[35];
char WIF[53];
unsigned char chainCode[32];
CBHDKeyChildID childID;
} CBTestVector;
CBTestVector testVectors[NUM_TEST_VECTORS][NUM_CHILDREN+1] = {
// Test vector 1
{
{
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
"<API key>",
"<API key>",
{0x87,0x3d,0xff,0x81,0xc0,0x2f,0x52,0x56,0x23,0xfd,0x1f,0xe5,0x16,0x7e,0xac,0x3a,0x55,0xa0,0x49,0xde,0x3d,0x31,0x4b,0xb4,0x2e,0xe2,0x27,0xff,0xed,0x37,0xd5,0x08},
{
false,
0
}
},
{
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
"xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw",
"<API key>",
"<API key>",
{0x47,0xfd,0xac,0xbd,0x0f,0x10,0x97,0x04,0x3b,0x78,0xc6,0x3c,0x20,0xc3,0x4e,0xf4,0xed,0x9a,0x11,0x1d,0x98,0x00,0x47,0xad,0x16,0x28,0x2c,0x7a,0xe6,0x23,0x61,0x41},
{
true,
0
}
},
// m/0'/1
{
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
"xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ",
"<API key>",
"<API key>",
{0x2a,0x78,0x57,0x63,0x13,0x86,0xba,0x23,0xda,0xca,0xc3,0x41,0x80,0xdd,0x19,0x83,0x73,0x4e,0x44,0x4f,0xdb,0xf7,0x74,0x04,0x15,0x78,0xe9,0xb6,0xad,0xb3,0x7c,0x19},
{
false,
1
}
},
// m/0'/1/2'
{
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
"xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5",
"<API key>",
"<API key>",
{0x04,0x46,0x6b,0x9c,0xc8,0xe1,0x61,0xe9,0x66,0x40,0x9c,0xa5,0x29,0x86,0xc5,0x84,0xf0,0x7e,0x9d,0xc8,0x1f,0x73,0x5d,0xb6,0x83,0xc3,0xff,0x6e,0xc7,0xb1,0x50,0x3f},
{
true,
2
}
},
// m/0'/1/2'/2
{
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
"xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV",
"<API key>",
"<API key>",
{0xcf,0xb7,0x18,0x83,0xf0,0x16,0x76,0xf5,0x87,0xd0,0x23,0xcc,0x53,0xa3,0x5b,0xc7,0xf8,0x8f,0x72,0x4b,0x1f,0x8c,0x28,0x92,0xac,0x12,0x75,0xac,0x82,0x2a,0x3e,0xdd},
{
false,
2
}
},
// m/0'/1/2'/2/1000000000
{
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
"xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy",
"<API key>",
"<API key>",
{0xc7,0x83,0xe6,0x7b,0x92,0x1d,0x2b,0xeb,0x8f,0x6b,0x38,0x9c,0xc6,0x46,0xd7,0x26,0x3b,0x41,0x45,0x70,0x1d,0xad,0xd2,0x16,0x15,0x48,0xa8,0xb0,0x78,0xe6,0x5e,0x9e},
{
false,
1000000000
}
},
},
// Test vector 2
{
{
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
"xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
"<API key>",
"<API key>",
{0x60, 0x49, 0x9f, 0x80, 0x1b, 0x89, 0x6d, 0x83, 0x17, 0x9a, 0x43, 0x74, 0xae, 0xb7, 0x82, 0x2a, 0xae, 0xac, 0xea, 0xa0, 0xdb, 0x1f, 0x85, 0xee, 0x3e, 0x90, 0x4c, 0x4d, 0xef, 0xbd, 0x96, 0x89},
{
false,
0
}
},
{
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
"xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH",
"<API key>",
"<API key>",
{0xf0, 0x90, 0x9a, 0xff, 0xaa, 0x7e, 0xe7, 0xab, 0xe5, 0xdd, 0x4e, 0x10, 0x05, 0x98, 0xd4, 0xdc, 0x53, 0xcd, 0x70, 0x9d, 0x5a, 0x5c, 0x2c, 0xac, 0x40, 0xe7, 0x41, 0x2f, 0x23, 0x2f, 0x7c, 0x9c},
{
false,
0
}
},
// m/0/2147483647'
{
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
"xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a",
"<API key>",
"<API key>",
{0xbe, 0x17, 0xa2, 0x68, 0x47, 0x4a, 0x6b, 0xb9, 0xc6, 0x1e, 0x1d, 0x72, 0x0c, 0xf6, 0x21, 0x5e, 0x2a, 0x88, 0xc5, 0x40, 0x6c, 0x4a, 0xee, 0x7b, 0x38, 0x54, 0x7f, 0x58, 0x5c, 0x9a, 0x37, 0xd9},
{
true,
2147483647
}
},
// m/0/2147483647'/1
{
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
"xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon",
"<API key>",
"<API key>",
{0xf3, 0x66, 0xf4, 0x8f, 0x1e, 0xa9, 0xf2, 0xd1, 0xd3, 0xfe, 0x95, 0x8c, 0x95, 0xca, 0x84, 0xea, 0x18, 0xe4, 0xc4, 0xdd, 0xb9, 0x36, 0x6c, 0x33, 0x6c, 0x92, 0x7e, 0xb2, 0x46, 0xfb, 0x38, 0xcb},
{
false,
1
}
},
// m/0/2147483647'/1/2147483646'
{
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
"xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL",
"<API key>",
"<API key>",
{0x63, 0x78, 0x07, 0x03, 0x0d, 0x55, 0xd0, 0x1f, 0x9a, 0x0c, 0xb3, 0xa7, 0x83, 0x95, 0x15, 0xd7, 0x96, 0xbd, 0x07, 0x70, 0x63, 0x86, 0xa6, 0xed, 0xdf, 0x06, 0xcc, 0x29, 0xa6, 0x5a, 0x0e, 0x29},
{
true,
2147483646
}
},
// m/0/2147483647'/1/2147483646'/2
{
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
"xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt",
"<API key>",
"<API key>",
{0x94, 0x52, 0xb5, 0x49, 0xbe, 0x8c, 0xea, 0x3e, 0xcb, 0x7a, 0x84, 0xbe, 0xc1, 0x0d, 0xcf, 0xd9, 0x4a, 0xfe, 0x4d, 0x12, 0x9e, 0xbf, 0xd3, 0xb3, 0xcb, 0x58, 0xee, 0xdf, 0x39, 0x4e, 0xd2, 0x71},
{
false,
2
}
},
}
};
void checkKey(CBHDKey * key, int x, int y);
void checkKey(CBHDKey * key, int x, int y){
// Check version bytes
if (key->versionBytes != <API key>) {
printf("VERSION BYTES FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
// Check address
CBAddress * address = <API key>(CBHDKeyGetHash(key), <API key>, false);
CBByteArray * str = <API key>(CBGetChecksumBytes(address));
CBReleaseObject(address);
if (memcmp(CBByteArrayGetData(str), testVectors[x][y].addr, 34) != 0) {
printf("ADDR FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
CBReleaseObject(str);
// Check WIF
CBWIF * wif = CBHDKeyGetWIF(key);
str = <API key>(CBGetChecksumBytes(wif));
CBReleaseObject(wif);
if (memcmp(CBByteArrayGetData(str), testVectors[x][y].WIF, 52) != 0) {
printf("WIF FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
CBReleaseObject(str);
// Check chain code
if (memcmp(key->chainCode, testVectors[x][y].chainCode, 32) != 0) {
printf("CHAIN CODE FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
// Check child ID
if (memcmp(&key->childID, &testVectors[x][y].childID, sizeof(key->childID)) != 0) {
printf("CHILD ID FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
// Check depth
if (key->depth != y) {
printf("DEPTH FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
// Check serialisation of private key
unsigned char * keyData = malloc(CB_HD_KEY_STR_SIZE);
CBHDKeySerialise(key, keyData);
CBChecksumBytes * checksumBytes = <API key>(keyData, 82, false);
str = <API key>(checksumBytes);
CBReleaseObject(checksumBytes);
if (memcmp(CBByteArrayGetData(str), testVectors[x][y].privString, 111) != 0) {
printf("PRIVATE KEY STRING FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
CBReleaseObject(str);
// Check serialisation of public key
key->versionBytes = <API key>;
keyData = malloc(CB_HD_KEY_STR_SIZE);
CBHDKeySerialise(key, keyData);
checksumBytes = <API key>(keyData, 82, false);
str = <API key>(checksumBytes);
CBReleaseObject(checksumBytes);
if (memcmp(CBByteArrayGetData(str), testVectors[x][y].pubString, 111) != 0) {
printf("PUBLIC KEY STRING FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
CBReleaseObject(str);
// Make private again
key->versionBytes = <API key>;
}
int main(){
CBByteArray * walletKeyString = <API key>("xpub6DRhpXssnj7X6CwJgseK9oyFxSC8jk6nJz2SWkf5pjsQs12xv89Dfr627TtaZKkFbG6Aq23fmaNaf5KRo9iGfEXTTXvtd6gsXJTB8Sdah3B", false);
CBChecksumBytes * walletKeyData = <API key>(walletKeyString, false);
CBHDKey * cbkey = CBNewHDKeyFromData(CBByteArrayGetData(CBGetByteArray(walletKeyData)));
CBAddress * address = <API key>(CBHDKeyGetHash(cbkey), <API key>, false);
CBByteArray * str = <API key>(CBGetChecksumBytes(address));
printf("%s\n", CBByteArrayGetData(str));
CBReleaseObject(address);
// Test type
if (CBHDKeyGetType(<API key>) != <API key>) {
printf("<API key> TYPE FAIL\n");
return EXIT_FAILURE;
}
if (CBHDKeyGetType(<API key>) != <API key>) {
printf("<API key> TYPE FAIL\n");
return EXIT_FAILURE;
}
if (CBHDKeyGetType(<API key>) != <API key>) {
printf("<API key> TYPE FAIL\n");
return EXIT_FAILURE;
}
if (CBHDKeyGetType(<API key>) != <API key>) {
printf("<API key> TYPE FAIL\n");
return EXIT_FAILURE;
}
// Test HMAC-SHA512
unsigned char hash[64];
CBHDKeyHmacSha512((unsigned char [37]){0x2f, 0xf7, 0xd6, 0x9f, 0x7a, 0x59, 0x0b, 0xb0, 0x5e, 0x68, 0xd1, 0xdc, 0x0f, 0xcf, 0x8d, 0xc2, 0x17, 0x59, 0xc9, 0x39, 0xbb, 0x6b, 0x9b, 0x02, 0x0f, 0x65, 0x5d, 0x53, 0x85, 0x3c, 0xb5, 0xc2, 0x14, 0x61, 0x4b, 0x24, 0x42}, (unsigned char [32]){0xa2, 0x55, 0x21, 0xe3, 0xc5, 0x5b, 0x65, 0xd1, 0xcf, 0x25, 0x4b, 0x6c, 0x85, 0x23, 0xdc, 0xbf, 0x89, 0x46, 0x8d, 0x1f, 0x09, 0x1f, 0x15, 0x87, 0x6b, 0xbb, 0xc7, 0xfd, 0xd5, 0x44, 0x28, 0x43}, hash);
if (memcmp(hash, (unsigned char [64]){0xfa, 0xa7, 0x9d, 0x85, 0xe0, 0xe4, 0x3d, 0xae, 0x8c, 0x3f, 0x99, 0xf0, 0x70, 0xdf, 0x97, 0x56, 0x2b, 0x3f, 0xbb, 0x17, 0x35, 0x20, 0xe0, 0x87, 0x32, 0xa6, 0x64, 0xca, 0xd4, 0x55, 0x0b, 0xbe, 0xc1, 0x11, 0xe5, 0xf8, 0x80, 0xdb, 0xb7, 0x3d, 0x67, 0x74, 0xbb, 0xc2, 0x9f, 0x67, 0xd9, 0x67, 0xaa, 0x10, 0xac, 0x60, 0x18, 0x90, 0x7f, 0x35, 0x53, 0xe3, 0x21, 0x38, 0xf6, 0x5b, 0xbe, 0x69}, 64) != 0) {
printf("HMAC FAIL\n");
return EXIT_FAILURE;
}
for (int x = 0; x < NUM_TEST_VECTORS; x++) {
// Deserialise private key
CBByteArray * masterString = <API key>(testVectors[x][0].privString, true);
CBChecksumBytes * masterData = <API key>(masterString, false);
CBReleaseObject(masterString);
CBHDKey * key = CBNewHDKeyFromData(CBByteArrayGetData(CBGetByteArray(masterData)));
CBReleaseObject(masterData);
checkKey(key, x, 0);
for (int y = 0; y < NUM_CHILDREN; y++) {
if (testVectors[x][y+1].childID.priv == false) {
// Derive public child and check public key is correct by address
CBHDKey * newKey = CBNewHDKey(false);
key->versionBytes = <API key>;
CBHDKeyDeriveChild(key, testVectors[x][y+1].childID, newKey);
key->versionBytes = <API key>;
CBAddress * address = <API key>(CBHDKeyGetHash(newKey), <API key>, false);
CBByteArray * str = <API key>(CBGetChecksumBytes(address));
CBReleaseObject(address);
if (memcmp(CBByteArrayGetData(str), testVectors[x][y + 1].addr, 34) != 0) {
printf("ADDR FROM PUB FAIL AT %u - %u\n", x, y + 1);
exit(EXIT_FAILURE);
}
CBReleaseObject(str);
// Check serialisation of public key
unsigned char * keyData = malloc(CB_HD_KEY_STR_SIZE);
CBHDKeySerialise(newKey, keyData);
CBChecksumBytes * checksumBytes = <API key>(keyData, 82, false);
str = <API key>(checksumBytes);
CBReleaseObject(checksumBytes);
if (memcmp(CBByteArrayGetData(str), testVectors[x][y+1].pubString, 111) != 0) {
printf("PUBLIC KEY STRING FROM PUB FAIL AT %u - %u\n", x, y);
exit(EXIT_FAILURE);
}
CBReleaseObject(str);
free(newKey);
}
// Derive private child
CBHDKey * newKey = CBNewHDKey(true);
CBHDKeyDeriveChild(key, testVectors[x][y+1].childID, newKey);
free(key);
key = newKey;
checkKey(key, x, y+1);
}
free(key);
}
return EXIT_SUCCESS;
}
|
#include "base58.h"
#include "primitives/transaction.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/sign.h"
#include "script/standard.h"
#include "uint256.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"bitcoinaddress\" (string) bitcoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(<API key>, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
#ifdef ENABLE_WALLET
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of bitcoin addresses to filter\n"
" [\n"
" \"address\" (string) bitcoin address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the bitcoin address\n"
" \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"<API key>\\\",\\\"<API key>\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"<API key>\\\",\\\"<API key>\\\"]\"")
);
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs) {
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(<API key>, string("Invalid Bitcoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(<API key>, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<const CScriptID&>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
#endif
Value <API key>(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"<API key> [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n"
"\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the bitcoin address, the value is the btc amount\n"
" ,...\n"
" }\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("<API key>", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("<API key>", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
);
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CMutableTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs) {
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(<API key>, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(<API key>, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo) {
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(<API key>, string("Invalid Bitcoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(<API key>, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey = <API key>(address.Get());
CAmount nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
return EncodeHexTx(rawTx);
}
Value <API key>(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"<API key> \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"<API key>\" (string) bitcoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("<API key>", "\"hexstring\"")
+ HelpExampleRpc("<API key>", "\"hexstring\"")
);
RPCTypeCheck(params, list_of(str_type));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(<API key>, "TX decode failed");
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) bitcoin address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ <API key>() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n"
" \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception &) {
throw JSONRPCError(<API key>, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(<API key>, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type) {
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys) {
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(<API key>, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(<API key>, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else
<API key>();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type) {
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs) {
if (p.type() != obj_type)
throw JSONRPCError(<API key>, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(<API key>, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(<API key>, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut+1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null)) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|<API key>))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|<API key>))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|<API key>))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(<API key>, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~<API key>) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, <API key>, <API key>(&mergedTx, i)))
fComplete = false;
}
Object result;
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see <API key> and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("<API key>", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
RPCTypeCheck(params, list_of(str_type)(bool_type));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(<API key>, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
CCoinsViewCache &view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
if(state.IsInvalid())
throw JSONRPCError(<API key>, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
else
throw JSONRPCError(<API key>, state.GetRejectReason());
}
} else if (fHaveChain) {
throw JSONRPCError(<API key>, "transaction already in block chain");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
|
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 6.2.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
0600 0604
0606 061B
061E 06DC
06DE 06FF
0750 077F
08A0
08A2 08AC
08E4 08FE
FB50 FBC1
FBD3 FD3D
FD50 FD8F
FD92 FDC7
FDF0 FDFD
FE70 FE74
FE76 FEFC
10E60 10E7E
1EE00 1EE03
1EE05 1EE1F
1EE21 1EE22
1EE24
1EE27
1EE29 1EE32
1EE34 1EE37
1EE39
1EE3B
1EE42
1EE47
1EE49
1EE4B
1EE4D 1EE4F
1EE51 1EE52
1EE54
1EE57
1EE59
1EE5B
1EE5D
1EE5F
1EE61 1EE62
1EE64
1EE67 1EE6A
1EE6C 1EE72
1EE74 1EE77
1EE79 1EE7C
1EE7E
1EE80 1EE89
1EE8B 1EE9B
1EEA1 1EEA3
1EEA5 1EEA9
1EEAB 1EEBB
1EEF0 1EEF1
END
|
import { VSBuffer } from 'vs/base/common/buffer';
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { <API key>, IPCClient } from 'vs/base/parts/ipc/common/ipc';
/**
* Declare minimal `MessageEvent` and `MessagePort` interfaces here
* so that this utility can be used both from `browser` and
* `electron-main` namespace where message ports are available.
*/
export interface MessageEvent {
/**
* For our use we only consider `Uint8Array` a valid data transfer
* via message ports because our protocol implementation is buffer based.
*/
data: Uint8Array;
}
export interface MessagePort {
addEventListener(type: 'message', listener: (this: MessagePort, e: MessageEvent) => unknown): void;
removeEventListener(type: 'message', listener: (this: MessagePort, e: MessageEvent) => unknown): void;
postMessage(message: Uint8Array): void;
start(): void;
close(): void;
}
/**
* The MessagePort `Protocol` leverages MessagePort style IPC communication
* for the implementation of the `<API key>`. That style of API
* is a simple `onmessage` / `postMessage` pattern.
*/
export class Protocol implements <API key> {
readonly onMessage = Event.fromDOMEventEmitter<VSBuffer>(this.port, 'message', (e: MessageEvent) => VSBuffer.wrap(e.data));
constructor(private port: MessagePort) {
// we must call start() to ensure messages are flowing
port.start();
}
send(message: VSBuffer): void {
this.port.postMessage(message.buffer);
}
disconnect(): void {
this.port.close();
}
}
/**
* An implementation of a `IPCClient` on top of MessagePort style IPC communication.
*/
export class Client extends IPCClient implements IDisposable {
private protocol: Protocol;
constructor(port: MessagePort, clientId: string) {
const protocol = new Protocol(port);
super(protocol, clientId);
this.protocol = protocol;
}
override dispose(): void {
this.protocol.disconnect();
}
}
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var turnOrder = require('./turn-order-8e019db0.js');
require('immer');
require('./<API key>.js');
require('lodash.isplainobject');
/**
* PlayerView reducers.
*/
const PlayerView = {
/**
* STRIP_SECRETS
*
* Reducer which removes a key named `secret` and
* removes all the keys in `players`, except for the one
* corresponding to the current playerID.
*/
STRIP_SECRETS: (G, ctx, playerID) => {
const r = { ...G };
if (r.secret !== undefined) {
delete r.secret;
}
if (r.players) {
r.players = playerID
? {
[playerID]: r.players[playerID],
}
: {};
}
return r;
},
};
exports.ActivePlayers = turnOrder.ActivePlayers;
Object.defineProperty(exports, 'GameMethod', {
enumerable: true,
get: function () {
return turnOrder.GameMethod;
}
});
exports.INVALID_MOVE = turnOrder.INVALID_MOVE;
exports.Stage = turnOrder.Stage;
exports.TurnOrder = turnOrder.TurnOrder;
exports.PlayerView = PlayerView;
|
<?php
namespace Ivory\CKEditorBundle\Twig;
use Ivory\CKEditorBundle\Helper\CKEditorHelper;
/**
* CKEditorExtension
*
* @author GeLo <geloen.eric@gmail.com>
*/
class CKEditorExtension extends \Twig_Extension
{
/** @var \Ivory\CKEditorBundle\Helper\CKEditorHelper */
protected $helper;
/**
* Creates a CKEditor extension.
*
* @param \Ivory\CKEditorBundle\Helper\CKEditorHelper $helper The CKEditor helper.
*/
public function __construct(CKEditorHelper $helper)
{
$this->helper = $helper;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
$options = array('is_safe' => array('html'));
return array(
new \Twig_SimpleFunction('ckeditor_is_loaded', array($this->helper, 'isLoaded'), $options),
new \Twig_SimpleFunction('ckeditor_base_path', array($this->helper, 'renderBasePath'), $options),
new \Twig_SimpleFunction('ckeditor_js_path', array($this->helper, 'renderJsPath'), $options),
new \Twig_SimpleFunction('ckeditor_replace', array($this->helper, 'renderReplace'), $options),
new \Twig_SimpleFunction('ckeditor_destroy', array($this->helper, 'renderDestroy'), $options),
new \Twig_SimpleFunction('ckeditor_plugin', array($this->helper, 'renderPlugin'), $options),
new \Twig_SimpleFunction('ckeditor_styles_set', array($this->helper, 'renderStylesSet'), $options),
new \Twig_SimpleFunction('ckeditor_template', array($this->helper, 'renderTemplate'), $options),
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->helper->getName();
}
}
|
var fse = require( "fs-extra" ),
fs = require( "fs" ),
phpjs = require( "phpjs" ),
isFunc = function ( fn ) {
return (typeof fn === "function");
},
packStr = function ( str ) {
str = str.split( /\n|\r|\t|\v/ );
for ( var i = str.length; i
str[ i ] = str[ i ].replace( /^\s+|\s+$/, "" );
}
return str.join( "" );
},
isFile = function ( file, cb ) {
if ( cb ) {
fs.exists( file, function ( exists ) {
cb( exists );
});
} else {
return fs.existsSync( file );
}
},
readDir = function ( dir, cb ) {
if ( cb ) {
fs.readdir( dir, function ( err, files ) {
if ( !err ) {
var reals = [];
for ( var i = files.length; i
if ( !/^\./.test( files[ i ] ) ) {
reals.push( files[ i ] );
}
}
cb( reals );
} else {
cb( [] );
}
});
} else {
return fs.readdirSync( dir );
}
},
makeDir = function ( dir, cb ) {
if ( cb ) {
fs.mkdir( dir, function ( err ) {
if ( !err ) {
cb();
}
});
} else {
return fs.mkdirSync( dir );
}
},
readFile = function ( file, cb ) {
if ( cb ) {
fs.readFile( file, "utf8", function ( err, data ) {
if ( !err ) {
cb( data );
}
});
} else {
return ("" + fs.readFileSync( file ));
}
},
readJson = function ( file, cb ) {
if ( cb ) {
readFile( file, function ( data ) {
cb( JSON.parse( "" + data ) );
});
} else {
return JSON.parse( ("" + readFile( file )) );
}
},
writeFile = function ( file, cont, cb ) {
if ( cb ) {
fs.writeFile( file, cont, "utf8", function ( err ) {
if ( !err ) {
cb();
}
});
} else {
fs.writeFileSync( file, cont );
}
},
writeJson = function ( file, json, cb ) {
writeFile( file, JSON.stringify( json, null, 4 ), cb );
},
removeFile = function ( file, cb ) {
if ( cb ) {
isFile( file, function ( exists ) {
if ( exists ) {
fs.unlink( file, function ( err ) {
if ( !err ) {
cb();
}
});
}
});
} else {
if ( isFile( file ) ) {
fs.unlinkSync( file );
}
}
},
removeDir = function ( dir, cb ) {
if ( cb ) {
fse.remove( dir, function ( err ) {
if ( !err ) {
cb();
}
});
} else {
fse.removeSync( dir );
}
},
getAttrObj = function ( elem ) {
var attrs = elem.match( /(\w+)=("[^<>"]*"|'[^<>']*'|\w+)/g ),
obj = {};
if ( attrs ) {
for ( var i = attrs.length; i
var attr = attrs[ i ].split( "=" ),
val = attr[ 1 ].replace( /\'|\"/g, "" );
// Normalize values
// Empty ?
// Skip empties, they are `undefined`
if ( val === "" ) {
continue;
}
// False ?
if ( val === "false" ) {
val = false;
}
// True ?
if ( val === "true" ) {
val = true;
}
// Numeric ?
if ( phpjs.is_numeric( val ) ) {
val = parseInt( val, 10 );
}
obj[ attr[ 0 ] ] = val;
}
}
return obj;
},
getToken = function () {
return ("token-" + Date.now() + ("" + Math.floor( (Math.random() * 1000000) + 1 )));
},
copy = function ( obj ) {
var o = {};
for ( var i in obj ) {
if ( obj.hasOwnProperty( i ) ) {
o[ i ] = obj[ i ];
}
}
return o;
},
copyArr = function ( arr ) {
var a = [];
for ( var i = arr.length; i
a[ i ] = arr[ i ];
}
return a;
};
// Export
module.exports = {
isFile: isFile,
isFunc: isFunc,
readDir: readDir,
makeDir: makeDir,
readJson: readJson,
readFile: readFile,
writeJson: writeJson,
writeFile: writeFile,
removeFile: removeFile,
removeDir: removeDir,
getToken: getToken,
getAttrObj: getAttrObj,
packStr: packStr,
copy: copy,
copyArr: copyArr
};
|
# This file was automatically generated, any manual changes will be lost the
# next time this file is generated.
# Platform: rbx 2.2.3.n364
RubyLint.registry.register('Singleton') do |defs|
defs.define_constant('Singleton') do |klass|
klass.inherits(defs.constant_proxy('Object', RubyLint.registry))
klass.define_method('__init__') do |method|
method.define_argument('klass')
end
klass.<API key>('_dump') do |method|
method.<API key>('depth')
end
klass.<API key>('clone')
klass.<API key>('dup')
end
defs.define_constant('Singleton::<API key>') do |klass|
klass.inherits(defs.constant_proxy('Object', RubyLint.registry))
klass.<API key>('_load') do |method|
method.define_argument('str')
end
klass.<API key>('clone')
end
end
|
/*
* Globals
*/
body {
font-family: Georgia, "Times New Roman", Times, serif;
color: #555;
}
h1, .h1,
h2, .h2,
h3, .h3,
h4, .h4,
h5, .h5,
h6, .h6 {
margin-top: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: normal;
color: #333;
}
/*
* Override Bootstrap's default container.
*/
@media (min-width: 1200px) {
.container {
width: 970px;
}
}
/*
* Masthead for nav
*/
.blog-masthead {
background-color: #428bca;
-webkit-box-shadow: inset 0 -2px 5px rgba(0,0,0,.1);
box-shadow: inset 0 -2px 5px rgba(0,0,0,.1);
}
/* Nav links */
.blog-nav-item {
position: relative;
display: inline-block;
padding: 10px;
font-weight: 500;
color: #cdddeb;
}
.blog-nav-item:hover,
.blog-nav-item:focus {
color: #fff;
text-decoration: none;
}
/* Active state gets a caret at the bottom */
.blog-nav .active {
color: #fff;
}
.blog-nav .active:after {
position: absolute;
bottom: 0;
left: 50%;
width: 0;
height: 0;
margin-left: -5px;
vertical-align: middle;
content: " ";
border-right: 5px solid transparent;
border-bottom: 5px solid;
border-left: 5px solid transparent;
}
/*
* Blog name and description
*/
.blog-header {
padding-top: 20px;
padding-bottom: 20px;
}
.blog-title {
margin-top: 30px;
margin-bottom: 0;
font-size: 60px;
font-weight: normal;
}
.blog-description {
font-size: 20px;
color: #999;
}
/*
* Main column and sidebar layout
*/
.blog-main {
font-size: 18px;
line-height: 1.5;
}
/* Sidebar modules for boxing content */
.sidebar-module {
padding: 15px;
margin: 0 -15px 15px;
}
.<API key> {
padding: 15px;
background-color: #f5f5f5;
border-radius: 4px;
}
.<API key> p:last-child,
.<API key> ul:last-child,
.<API key> ol:last-child {
margin-bottom: 0;
}
/* Pagination */
.pager {
margin-bottom: 60px;
text-align: left;
}
.pager > li > a {
width: 140px;
padding: 10px 20px;
text-align: center;
border-radius: 30px;
}
/*
* Blog posts
*/
.blog-post {
margin-bottom: 60px;
}
.blog-post-title {
margin-bottom: 5px;
font-size: 40px;
}
.blog-post-meta {
margin-bottom: 20px;
color: #999;
}
/*
* Footer
*/
.blog-footer {
padding: 40px 0;
color: #999;
text-align: center;
background-color: #f9f9f9;
border-top: 1px solid #e5e5e5;
}
.blog-footer p:last-child {
margin-bottom: 0;
}
|
import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
let taskPath = path.join(__dirname, '..', 'gradletask.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
//escape for Windows directories
let tempDir: string = path.join(__dirname, '_temp');
let <API key>: string = path.join(tempDir, '.sqAnalysis').replace(/\\/g, '/');
let taskReportValidDir: string = path.join(__dirname, 'data', 'multimodule'); //taskreport-valid');
let <API key>: string = path.join(taskReportValidDir, 'build');
let <API key>: string = path.join(taskReportValidDir, 'build').replace(/\\/g, '/');
let <API key>: string = path.join(<API key>, 'sonar');
let <API key>: string = path.join(<API key>, 'sonar').replace(/\\/g, '/');
let <API key>: string = path.join(<API key>, 'report-task.txt').replace(/\\/g, '/');
let ccReportDirReplaced: string = path.join(__dirname, 'CCReport43F6D5EF', 'coverage.xml').replace(/\\/g, '/');
//Env vars in the mock framework must replace '.' with '_'
//replace with mock of setVariable when task-lib has the support
process.env['<API key>'] = true;
process.env['MOCK_TEMP_PATH'] = path.join(__dirname, '..', '..');
process.env['<API key>'] = true;
process.env['JAVA_HOME_8_X86'] = '/user/local/bin/Java8';
process.env['ENDPOINT_URL_ID1'] = 'http://sonarqube/end/point';
process.env['ENDPOINT_AUTH_ID1'] = '{\"scheme\":\"UsernamePassword\", \"parameters\": {\"username\": \"uname\", \"password\": \"pword\"}}';
process.env['BUILD_BUILDNUMBER'] = '211';
process.env['<API key>'] = `${taskReportValidDir}`;
process.env['<API key>'] = `${tempDir}`;
process.env['<API key>'] = `${taskReportValidDir}`;
tr.setInput('wrapperScript', 'gradlew');
tr.setInput('options', '');
tr.setInput('tasks', 'build');
tr.setInput('javaHomeSelection', 'JDKVersion');
tr.setInput('jdkVersion', 'default');
tr.setInput('publishJUnitResults', 'true');
tr.setInput('testResultsFiles', '**/build/test-results/TEST-*.xml');
tr.setInput('sqAnalysisEnabled', 'false');
// Added inputs for this test
tr.setInput('<API key>', 'true');
tr.setInput('<API key>', 'true');
tr.setInput('pmdAnalysisEnabled', 'true');
//construct a string that is JSON, call JSON.parse(string), send that to ma.TaskLibAnswers
let myAnswers: string = `{
"exec":{
"gradlew.bat build -I /Gradle/node_modules/codeanalysis-common/checkstyle.gradle -I /Gradle/node_modules/codeanalysis-common/findbugs.gradle -I /Gradle/node_modules/codeanalysis-common/pmd.gradle": {
"code": 0,
"stdout": "Sample gradle + Checkstyle + PMD + FindBugs"
},
"gradlew build -I /Gradle/node_modules/codeanalysis-common/checkstyle.gradle -I /Gradle/node_modules/codeanalysis-common/findbugs.gradle -I /Gradle/node_modules/codeanalysis-common/pmd.gradle": {
"code": 0,
"stdout": "Sample gradle + Checkstyle + PMD + FindBugs"
}
},
"checkPath":{
"gradlew":true,
"gradlew.bat":true,
"/home/repo/src":true,
"${<API key>}":true,
"${<API key>}":true,
"${<API key>}":true,
"${<API key>}":true
},
"find":{
"/user/build":[
"/user/build/fun/test-123.xml"
]
},
"match":{
"**/build/test-results/TEST-*.xml":[
"/user/build/fun/test-123.xml"
]
},
"stats":{
"${ccReportDirReplaced}":{
"isFile":true
},
"${<API key>}":{
"isFile":true
},
"${<API key>}":{
"isFile":true
},
"${<API key>}":{
"isFile":true
},
"${<API key>}":{
"isFile":true
}
},
"exist":{
"${<API key>}":true,
"${<API key>}":true,
"${<API key>}":true,
"${<API key>}":true
},
"mkdirP":{
"${<API key>}":true,
"${<API key>}":true,
"${<API key>}":true,
"${<API key>}":true
}
}`;
let json: any = JSON.parse(myAnswers);
// Cast the json blob into a TaskLibAnswers
tr.setAnswers(<ma.TaskLibAnswers>json);
tr.run();
|
<?php
defined('_HZEXEC_') or die();
$this->css()
->js();
if (!function_exists('sortDir'))
{
/**
* Filters directory
*
* @param array $filters
* @param string $current
* @param string $dir
* @return string
*/
function sortDir($filters, $current, $dir='DESC')
{
if ($filters['sortby'] == $current && $filters['sort_Dir'] == $dir)
{
$dir = ($dir == 'ASC' ? 'DESC' : 'ASC');
}
return strtolower($dir);
}
}
$this->category->set('section_alias', $this->filters['section']);
?>
<header id="content-header">
<h2><?php echo Lang::txt('COM_FORUM'); ?></h2>
<div id="<API key>">
<p>
<a class="icon-folder categories btn" href="<?php echo Route::url($this->category->link('base')); ?>">
<?php echo Lang::txt('<API key>'); ?>
</a>
</p>
</div>
</header>
<section class="main section">
<div class="section-inner <API key>">
<div class="subject">
<form action="<?php echo Route::url('index.php?option=' . $this->option . '&controller=categories&task=search'); ?>" method="get">
<div class="container data-entry">
<input class="entry-search-submit" type="submit" value="<?php echo Lang::txt('COM_FORUM_SEARCH'); ?>" />
<fieldset class="entry-search">
<legend><span><?php echo Lang::txt('<API key>'); ?></span></legend>
<label for="entry-search-field"><?php echo Lang::txt('<API key>'); ?></label>
<input type="text" name="q" id="entry-search-field" value="<?php echo $this->escape($this->filters['search']); ?>" placeholder="<?php echo Lang::txt('<API key>'); ?>" />
</fieldset>
</div><!-- / .container -->
<div class="container">
<nav class="entries-filters">
<ul class="entries-menu order-options">
<li>
<a class="<?php echo ($this->filters['sortby'] == 'created') ? 'active ' . (strtolower($this->filters['sort_Dir']) == 'desc' ? 'icon-arrow-down' : 'icon-arrow-up') : 'icon-arrow-down'; ?>" href="<?php echo Route::url($this->category->link('here', '&sortby=created&sortdir=' . sortDir($this->filters, 'created'))); ?>" title="<?php echo Lang::txt('<API key>'); ?>">
<?php echo Lang::txt('<API key>'); ?>
</a>
</li>
<li>
<a class="<?php echo ($this->filters['sortby'] == 'activity') ? 'active ' . (strtolower($this->filters['sort_Dir']) == 'desc' ? 'icon-arrow-down' : 'icon-arrow-up') : 'icon-arrow-down'; ?>" href="<?php echo Route::url($this->category->link('here', '&sortby=activity&sortdir=' . sortDir($this->filters, 'activity'))); ?>" title="<?php echo Lang::txt('<API key>'); ?>">
<?php echo Lang::txt('<API key>'); ?>
</a>
</li>
<li>
<a class="<?php echo ($this->filters['sortby'] == 'replies') ? 'active ' . (strtolower($this->filters['sort_Dir']) == 'desc' ? 'icon-arrow-down' : 'icon-arrow-up') : 'icon-arrow-down'; ?>" href="<?php echo Route::url($this->category->link('here', '&sortby=replies&sortdir=' . sortDir($this->filters, 'replies'))); ?>" title="<?php echo Lang::txt('<API key>'); ?>">
<?php echo Lang::txt('<API key>'); ?>
</a>
</li>
<li>
<a class="<?php echo ($this->filters['sortby'] == 'title') ? 'active ' . (strtolower($this->filters['sort_Dir']) == 'desc' ? 'icon-arrow-down' : 'icon-arrow-up') : 'icon-arrow-up'; ?>" href="<?php echo Route::url($this->category->link('here', '&sortby=title&sortdir=' . sortDir($this->filters, 'title', 'ASC'))); ?>" title="<?php echo Lang::txt('<API key>'); ?>">
<?php echo Lang::txt('<API key>'); ?>
</a>
</li>
</ul>
</nav>
<table class="entries">
<caption>
<?php
if ($this->filters['search'])
{
if ($this->category->get('title'))
{
echo Lang::txt('<API key>', $this->escape($this->filters['search']), $this->escape(stripslashes($this->category->get('title'))));
}
else
{
echo Lang::txt('<API key>', $this->escape($this->filters['search']));
}
} else {
echo Lang::txt('COM_FORUM_SEARCH_IN', $this->escape(stripslashes($this->category->get('title'))));
}
?>
</caption>
<tbody>
<?php
if ($this->threads->count() > 0)
{
foreach ($this->threads as $row)
{
$name = Lang::txt('JANONYMOUS');
if (!$row->get('anonymous'))
{
$name = $this->escape(stripslashes($row->creator->get('name', $name)));
if (in_array($row->creator->get('access'), User::get<API key>()))
{
$name = '<a href="' . Route::url($row->creator->link()) . '">' . $name . '</a>';
}
}
$cls = array();
$icn = 'icon-comments';
if ($row->isClosed())
{
$cls[] = 'closed';
$icn = 'icon-lock';
}
if ($row->isSticky())
{
$cls[] = 'sticky';
$icn = 'icon-asterisk';
}
$row->set('category', $this->filters['category']);
$row->set('section', $this->filters['section']);
?>
<tr<?php if (count($cls) > 0) { echo ' class="' . implode(' ', $cls) . '"'; } ?>>
<th class="priority-5" scope="row">
<span class="entry-identifier <?php echo $icn; ?>"><?php echo $this->escape($row->get('id')); ?></span>
</th>
<td>
<a class="entry-title" href="<?php echo Route::url($row->link()); ?>">
<span><?php echo $this->escape(stripslashes($row->get('title'))); ?></span>
</a>
<span class="entry-details">
<span class="entry-date">
<time datetime="<?php echo $row->created(); ?>"><?php echo $row->created('date'); ?></time>
</span>
<?php echo Lang::txt('COM_FORUM_BY_USER', '<span class="entry-author">' . $name . '</span>'); ?>
</span>
</td>
<td class="priority-4">
<span><?php
echo $row->thread()
->whereEquals('state', $row->get('state'))
->whereIn('access', $this->filters['access'])
->total();
?></span>
<span class="entry-details">
<?php echo Lang::txt('COM_FORUM_COMMENTS'); ?>
</span>
</td>
<td class="priority-3">
<span><?php echo Lang::txt('COM_FORUM_LAST_POST'); ?></span>
<span class="entry-details">
<?php
$lastpost = $row->lastActivity();
if ($lastpost->get('id'))
{
$lname = Lang::txt('JANONYMOUS');
if (!$lastpost->get('anonymous'))
{
$lname = $this->escape(stripslashes($lastpost->creator->get('name')));
if (in_array($lastpost->creator->get('access'), User::get<API key>()))
{
$lname = '<a href="' . Route::url($lastpost->creator->link()) . '">' . $lname . '</a>';
}
}
?>
<span class="entry-date">
<time datetime="<?php echo $lastpost->created(); ?>"><?php echo $lastpost->created('date'); ?></time>
</span>
<?php echo Lang::txt('COM_FORUM_BY_USER', '<span class="entry-author">' . $lname . '</span>'); ?>
<?php } else { ?>
<?php echo Lang::txt('COM_FORUM_NONE'); ?>
<?php } ?>
</span>
</td>
<?php if ($this->config->get('<API key>') || $this->config->get('access-edit-thread') || $this->config->get('<API key>')) { ?>
<td class="entry-options">
<?php if ($this->config->get('<API key>') || ($this->config->get('access-edit-thread') && $row->get('created_by') == User::get('id'))) { ?>
<a class="icon-edit edit" href="<?php echo Route::url($row->link('edit')); ?>" title="<?php echo Lang::txt('JACTION_EDIT'); ?>">
<?php echo Lang::txt('JACTION_EDIT'); ?>
</a>
<?php } ?>
<?php if ($this->config->get('<API key>') || ($this->config->get('<API key>') && $row->get('created_by') == User::get('id'))) { ?>
<a class="icon-delete delete" data-txt-confirm="<?php echo Lang::txt('<API key>'); ?>" href="<?php echo Route::url($row->link('delete')); ?>" title="<?php echo Lang::txt('JACTION_DELETE'); ?>">
<?php echo Lang::txt('JACTION_DELETE'); ?>
</a>
<?php } ?>
</td>
<?php } ?>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td><?php echo Lang::txt('<API key>'); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php
$pageNav = $this->threads->pagination;
$pageNav-><API key>('section', $this->filters['section']);
$pageNav-><API key>('category', $this->filters['category']);
$pageNav-><API key>('q', $this->filters['search']);
echo $pageNav;
?>
<div class="clearfix"></div>
</div><!-- / .container -->
</form>
</div><!-- /.subject -->
<aside class="aside">
<div class="container">
<h3><?php echo Lang::txt('COM_FORUM_LAST_POST'); ?></h3>
<p>
<?php
$last = $this->category->lastActivity();
if ($last->get('id'))
{
$lname = Lang::txt('JANONYMOUS');
if (!$last->get('anonymous'))
{
$lname = $this->escape(stripslashes($last->creator->get('name', $lname)));
if (in_array($last->creator->get('access'), User::get<API key>()))
{
$lname = '<a href="' . Route::url($last->creator->link()) . '">' . $lname . '</a>';
}
}
$last->set('category', $this->filters['category']);
$last->set('section', $this->filters['section']);
?>
<a class="entry-comment" href="<?php echo Route::url($last->link()); ?>">
<?php echo \Hubzero\Utility\Str::truncate(strip_tags($last->get('comment')), 170); ?>
</a>
<span class="entry-author">
<?php echo $lname; ?>
</span>
<span class="entry-date">
<span class="entry-date-at"><?php echo Lang::txt('COM_FORUM_AT'); ?></span>
<span class="icon-time time"><time datetime="<?php echo $last->created(); ?>"><?php echo $last->created('time'); ?></time></span>
<span class="entry-date-on"><?php echo Lang::txt('COM_FORUM_ON'); ?></span>
<span class="icon-date date"><time datetime="<?php echo $last->created(); ?>"><?php echo $last->created('date'); ?></time></span>
</span>
<?php } else { ?>
<?php echo Lang::txt('COM_FORUM_NONE'); ?>
<?php } ?>
</p>
</div><!-- / .container -->
<?php if ($this->config->get('<API key>')) { ?>
<div class="container">
<h3><?php echo Lang::txt('<API key>'); ?></h3>
<?php if (!$this->category->isClosed()) { ?>
<p>
<?php echo Lang::txt('<API key>'); ?>
</p>
<p>
<a class="icon-add add btn" href="<?php echo Route::url($this->category->link('newthread')); ?>"><?php echo Lang::txt('<API key>'); ?></a>
</p>
<?php } else { ?>
<p class="warning">
<?php echo Lang::txt('<API key>'); ?>
</p>
<?php } ?>
</div><!-- / .container -->
<?php } ?>
</aside><!-- / .aside -->
</div>
</section><!-- /.main -->
|
"use strict";
var <API key> = require("@babel/runtime/helpers/<API key>");
var <API key> = require("@babel/runtime/helpers/<API key>");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.styles = void 0;
var <API key> = <API key>(require("@babel/runtime/helpers/<API key>"));
var _extends2 = <API key>(require("@babel/runtime/helpers/extends"));
var React = <API key>(require("react"));
var _propTypes = <API key>(require("prop-types"));
var _clsx = <API key>(require("clsx"));
var _withStyles = <API key>(require("../styles/withStyles"));
var _TableContext = <API key>(require("./TableContext"));
var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
display: 'table',
width: '100%',
borderCollapse: 'collapse',
borderSpacing: 0,
'& caption': (0, _extends2.default)({}, theme.typography.body2, {
padding: theme.spacing(2),
color: theme.palette.text.secondary,
textAlign: 'left',
captionSide: 'bottom'
})
},
/* Styles applied to the root element if `stickyHeader={true}`. */
stickyHeader: {
borderCollapse: 'separate'
}
};
};
exports.styles = styles;
var Table = React.forwardRef(function Table(props, ref) {
var classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'table' : _props$component,
_props$padding = props.padding,
padding = _props$padding === void 0 ? 'default' : _props$padding,
_props$size = props.size,
size = _props$size === void 0 ? 'medium' : _props$size,
_props$stickyHeader = props.stickyHeader,
stickyHeader = _props$stickyHeader === void 0 ? false : _props$stickyHeader,
other = (0, <API key>.default)(props, ["classes", "className", "component", "padding", "size", "stickyHeader"]);
var table = React.useMemo(function () {
return {
padding: padding,
size: size,
stickyHeader: stickyHeader
};
}, [padding, size, stickyHeader]);
return React.createElement(_TableContext.default.Provider, {
value: table
}, React.createElement(Component, (0, _extends2.default)({
ref: ref,
className: (0, _clsx.default)(classes.root, className, stickyHeader && classes.stickyHeader)
}, other)));
});
process.env.NODE_ENV !== "production" ? Table.propTypes = {
/**
* The content of the table, normally `TableHead` and `TableBody`.
*/
children: _propTypes.default.node.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: _propTypes.default.object.isRequired,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: _propTypes.default.elementType,
/**
* Allows TableCells to inherit padding of the Table.
*/
padding: _propTypes.default.oneOf(['default', 'checkbox', 'none']),
/**
* Allows TableCells to inherit size of the Table.
*/
size: _propTypes.default.oneOf(['small', 'medium']),
/**
* Set the header sticky.
*
* It doesn't work with IE 11.
*/
stickyHeader: _propTypes.default.bool
} : void 0;
var _default = (0, _withStyles.default)(styles, {
name: 'MuiTable'
})(Table);
exports.default = _default;
|
var gulp = require("gulp");
var istanbul = require("gulp-istanbul");
var react = require("gulp-react");
var mocha = require("gulp-mocha");
var plumber = require("gulp-plumber");
var jshint = require("gulp-jshint");
var browserify = require("browserify");
var uglify = require("gulp-uglify");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var jscs = require("gulp-jscs");
var jshint = require("gulp-jshint");
var rename = require("gulp-rename");
var coveralls = require("gulp-coveralls");
var less = require("gulp-less");
var concat = require("gulp-concat");
var karma = require("karma").server;
var options = require("yargs").argv;
var browserSync = require("browser-sync");
var paths = {
testFiles : ["test*-test.js", "./examples*-test.js"],
appFiles : ["lib*.js"],
lessFiles : ["examples*.less"],
bsyncFiles : ["coverage*", "examples/_static/**"]
var mochaOptions = {
bail : options.bail !== 'false',
reporter : options.reporter || 'dot',
grep : options.grep || options.only
}
gulp.task("test-coverage", function (complete) {
gulp.
src(paths.appFiles).
pipe(istanbul()).
pipe(istanbul.hookRequire()).
on("finish", function () {
gulp.
src(paths.testFiles).
pipe(plumber()).
pipe(mocha(mochaOptions)).
pipe(istanbul.writeReports({
reporters: ["text","text-summary", "lcov"]
})).
on("end", complete);
});
});
gulp.task("test-coveralls", ["test-coverage"], function () {
return gulp.
src("coveragelcov.info").
pipe(coveralls());
});
gulp.task("bundle", function() {
return browserify("./lib/index.js").
bundle().
pipe(source('caplet.js')).
pipe(buffer()).
pipe(gulp.dest('./dist'));
});
gulp.task("minify", ["bundle"], function() {
return gulp.
src("./dist/caplet.js").
pipe(uglify()).
pipe(rename(function(path) {
path.basename += ".min";
})).
pipe(gulp.dest('./dist'));
});
gulp.task("test-browser", function(complete) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, complete);
});
gulp.task("lint", function() {
return gulp.run(["jshint", "jscs"]);
});
gulp.task("jscs", function() {
return gulp.
src(paths.lintFiles).
pipe(jscs({
"preset": "google",
"<API key>": true,
"maximumLineLength": 120,
"validateLineBreaks": "LF",
"validateIndentation": 2,
"validateQuoteMarks": "\"",
"disallowKeywords": ["with"],
"<API key>": null,
"<API key>": ["string"],
"requireCurlyBraces": [],
"safeContextKeyword": "self"
}));
});
gulp.task("less", function() {
return gulp.
src(paths.lessFiles).
pipe(less()).
pipe(concat("bundle.css")).
pipe(gulp.dest("./examples/_static/css"));
});
gulp.task("jshint", function() {
return gulp.
src(paths.lintFiles).
pipe(jshint()).
pipe(jshint.reporter('default'));
});
/**
* IMPORTANT: run this command AFTER watch - e.g: gulp test-coverage watch browser-sync
*/
gulp.task("browser-sync", function(complete) {
browserSync({
server: {
baseDir: "./"
},
files: paths.bsyncFiles
})
});
gulp.task("test", function (complete) {
gulp.
src(paths.testFiles, { read: false }).
pipe(plumber()).
pipe(mocha(mochaOptions)).
on("error", complete).
on("end", complete);
});
var iofwatch = process.argv.indexOf("watch");
/**
* runs previous tasks (1 or more)
*/
gulp.task("watch", function () {
gulp.watch(paths.allFiles, process.argv.slice(2, iofwatch));
});
gulp.task("default", function () {
return gulp.run("test-coverage");
});
gulp.task("example", function (complete) {
return browserify(__dirname + "/examples/" + (options.example || "default") + "/index.js", { extensions: [".jsx"],grep:/\.jsx$/,transform: [require("reactify")]}).
bundle().
pipe(source('bundle.js')).
pipe(buffer()).
pipe(gulp.dest('./examples/_static/js'));
});
gulp.doneCallback = function (err) {
// a bit hacky, but fixes issue with testing where process
// doesn't exist process. Also fixes case where timeout / interval are set (CC)
if (!~iofwatch) process.exit(err ? 1 : 0);
};
|
#include <atomic>
int main() {
std::atomic<bool> b;
bool x = b.load(std::<API key>);
b.store(true);
x = b.exchange(false, std::<API key>);
return 0;
}
|
-- Widget is based on the <API key>.lua supplied with AceGUI-3.0
LoadAddOn("LibSharedMedia-3.0")
local AceGUI = LibStub("AceGUI-3.0")
local Media = LibStub("LibSharedMedia-3.0")
<API key> = {}
do
<API key> = {
['font'] = Media:HashTable("font"),
['sound'] = Media:HashTable("sound"),
['statusbar'] = Media:HashTable("statusbar"),
['border'] = Media:HashTable("border"),
['background'] = Media:HashTable("background"),
}
local min, max, floor = math.min, math.max, math.floor
local function fixlevels(parent,...)
local i = 1
local child = select(i, ...)
while child do
child:SetFrameLevel(parent:GetFrameLevel()+1)
fixlevels(child, child:GetChildren())
i = i + 1
child = select(i, ...)
end
end
local function OnItemValueChanged(this, event, checked)
local self = this.userdata.obj
if self.multiselect then
self:Fire("OnValueChanged", this.userdata.value, checked)
else
if checked then
self:SetValue(this.userdata.value)
self:Fire("OnValueChanged", this.userdata.value)
else
this:SetValue(true)
end
self.pullout:Close()
end
end
local function SetValue(self, value)
if value then
self:SetText(value or "")
end
self.value = value
end
<API key>.fixlevels = fixlevels
<API key>.OnItemValueChanged = OnItemValueChanged
<API key>.SetValue = SetValue
end
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ratchet</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, minimal-ui" />
<meta name="<API key>" content="yes">
<meta name="<API key>" content="black">
<link href="css/ratchet.css" rel="stylesheet">
<script src="js/ratchet.js"></script>
</head>
<body>
<header class="bar bar-nav">
<a href="index.html" class="btn btn-link btn-nav pull-left" data-transition="slide-out">
<span class="icon icon-left-nav"></span>
Back
</a>
<h1 class="title">James Williamson</h1>
</header>
<div class="content">
<div class="content-padded">
<img src="imgs/Williamson.jpg" />
<p>James Williamson is a senior author for lynda.com and an Adobe Certified Instructor. He has many years of web, print, and digital video experience, and has been a featured speaker at Flashforward as well as a regular speaker at Adobe MAX. James also blogs (infrequently) about all things web at his site, Simple Primate, which can be found at <a href="http:
</div>
</div>
</body>
</html>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('regcore', '<API key>'),
]
operations = [
migrations.DeleteModel(
name='Preamble',
),
migrations.AlterUniqueTogether(
name='regulation',
unique_together=set([]),
),
migrations.AlterIndexTogether(
name='regulation',
index_together=set([]),
),
migrations.RemoveField(
model_name='regulation',
name='parent',
),
migrations.DeleteModel(
name='Regulation',
),
]
|
package org.eclipse.che.ide.part.editor.recent;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.ide.api.action.<API key>;
import org.eclipse.che.ide.api.action.ActionEvent;
import org.eclipse.che.ide.api.editor.EditorAgent;
import org.eclipse.che.ide.api.resources.File;
import javax.validation.constraints.NotNull;
import static java.util.Collections.singletonList;
import static org.eclipse.che.ide.part.editor.recent.RecentFileStore.getShortPath;
import static org.eclipse.che.ide.workspace.perspectives.project.ProjectPerspective.<API key>;
/**
* Action for the recent file. When user click on this action, recent file opens again in editor.
*
* @author Vlad Zhukovskiy
*/
public class RecentFileAction extends <API key> {
private final File file;
private final EditorAgent editorAgent;
@Inject
public RecentFileAction(@Assisted File file, EditorAgent editorAgent) {
super(singletonList(<API key>), getShortPath(file.getLocation().toString()), null, null, null);
this.file = file;
this.editorAgent = editorAgent;
}
/** {@inheritDoc} */
@Override
public void updateInPerspective(@NotNull ActionEvent event) {
event.getPresentation().<API key>(true);
}
/** {@inheritDoc} */
@Override
public void actionPerformed(ActionEvent e) {
editorAgent.openEditor(file);
}
/**
* Return an id for the registration in action manager.
* ID value forms based on file path to define unique key for this action.
*
* @return action id
*/
public String getId() {
return "recent/" + file.getLocation();
}
}
|
package org.eclipse.angularjs.internal.ui;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* Helper class to route trace output.
*/
public class Trace {
public static final byte CONFIG = 0;
public static final byte INFO = 1;
public static final byte WARNING = 2;
public static final byte SEVERE = 3;
public static final byte FINEST = 4;
public static final byte FINER = 5;
public static final byte PERFORMANCE = 6;
public static final byte EXTENSION_POINT = 7;
private static final String[] levelNames = new String[] { "CONFIG ",
"INFO ", "WARNING", "SEVERE ", "FINER ", "FINEST ", "PERF ",
"EXTENSION" };
private static final SimpleDateFormat sdf = new SimpleDateFormat(
"dd/MM/yy HH:mm.ss.SSS");
private static Set<String> logged = new HashSet<String>();
/**
* Trace constructor comment.
*/
private Trace() {
super();
}
/**
* Trace the given text.
*
* @param level
* a trace level
* @param s
* a message
*/
public static void trace(byte level, String s) {
trace(level, s, null);
}
/**
* Trace the given message and exception.
*
* @param level
* a trace level
* @param s
* a message
* @param t
* a throwable
*/
public static void trace(byte level, String s, Throwable t) {
if (s == null)
return;
if (level == SEVERE) {
// if (!logged.contains(s)) {
AngularUIPlugin
.getDefault()
.getLog()
.log(new Status(IStatus.ERROR, AngularUIPlugin.PLUGIN_ID,
s, t));
// logged.add(s);
}
if (!AngularUIPlugin.getDefault().isDebugging())
return;
StringBuilder sb = new StringBuilder(AngularUIPlugin.PLUGIN_ID);
sb.append(" ");
sb.append(levelNames[level]);
sb.append(" ");
sb.append(sdf.format(new Date()));
sb.append(" ");
sb.append(s);
System.out.println(sb.toString());
if (t != null)
t.printStackTrace();
}
}
|
package uk.co.spudsoft.birt.emitters.excel.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.xssf.usermodel.XSSFChartSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.birt.core.exception.BirtException;
import org.junit.Test;
public class <API key> extends ReportRunner {
@Test
public void testVariousOptions() throws BirtException, IOException {
InputStream inputStream = null;
inputStream = openFileStream("MannedSpaceMissions.xlsx");
try {
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
assertNotNull(workbook);
assertEquals( 3, workbook.getNumberOfSheets() );
assertTrue( workbook.getSheetAt(0) instanceof XSSFChartSheet );
assertEquals( 3, firstNullRow( workbook.getSheetAt(1) ) );
assertEquals( 5, firstNullRow( workbook.getSheetAt(2) ) );
} finally {
inputStream.close();
}
// Output to new XLSX file
inputStream = runAndRenderReport("<API key>.rptdesign", "xlsx");
assertNotNull(inputStream);
try {
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
assertNotNull(workbook);
assertEquals( 1, workbook.getNumberOfSheets() );
assertEquals( 280, firstNullRow( workbook.getSheetAt(0) ) );
} finally {
inputStream.close();
}
// Output using XLSX template
String file = deriveFilepath( "MannedSpaceMissions.xlsx" );
File template = new File( file );
assertTrue( template.exists() );
templateFile = template.getAbsolutePath();
inputStream = runAndRenderReport("<API key>.rptdesign", "xlsx");
assertNotNull(inputStream);
try {
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
assertNotNull(workbook);
assertEquals( 3, workbook.getNumberOfSheets() );
assertTrue( workbook.getSheetAt(0) instanceof XSSFChartSheet );
assertEquals( 280, firstNullRow( workbook.getSheetAt(1) ) );
assertEquals( 5, firstNullRow( workbook.getSheetAt(2) ) );
} finally {
inputStream.close();
}
}
}
|
package org.eclipse.che.api.core.rest;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.eclipse.che.api.core.rest.shared.dto.ApiInfo;
import org.eclipse.che.dto.server.DtoFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides api info by reading it from war manifest.
*
* @author Max Shaposhnyk
*/
@Singleton
public class ApiInfoProvider implements Provider<ApiInfo> {
private static final Logger LOG = LoggerFactory.getLogger(ApiInfoProvider.class);
private ApiInfo apiInfo;
@Inject
public ApiInfoProvider(@Named("che.product.build_info") String buildInfo) {
this.apiInfo = readApiInfo(buildInfo);
}
@Override
public ApiInfo get() {
return apiInfo;
}
private ApiInfo readApiInfo(String buildInfo) {
try {
// calculate path to MANIFEST.MF in the jar with ApiInfo.class
Class clazz = ApiInfo.class;
String classPath = clazz.getResource(clazz.getSimpleName() + ".class").toString();
String manifestPath =
classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
try (InputStream manifestInputStream = new URL(manifestPath).openStream()) {
final Manifest manifest = new Manifest(manifestInputStream);
final Attributes mainAttributes = manifest.getMainAttributes();
final DtoFactory dtoFactory = DtoFactory.getInstance();
return dtoFactory
.createDto(ApiInfo.class)
.<API key>(mainAttributes.getValue("<API key>"))
.<API key>(mainAttributes.getValue("<API key>"))
.<API key>("Che REST API")
.<API key>(mainAttributes.getValue("<API key>"))
.<API key>(mainAttributes.getValue("<API key>"))
.withScmRevision(mainAttributes.getValue("SCM-Revision"))
.withBuildInfo(buildInfo);
}
} catch (Exception e) {
LOG.error("Unable to read API information. Error: " + e.getMessage(), e);
throw new RuntimeException("Unable to read API information", e);
}
}
}
|
import sys
try:
try:
from _pydevd_bundle_ext import pydevd_cython as mod
except ImportError:
from _pydevd_bundle import pydevd_cython as mod
except ImportError:
import struct
try:
is_python_64bit = (struct.calcsize('P') == 8)
except:
# In Jython this call fails, but this is Ok, we don't support Jython for speedups anyways.
raise ImportError
plat = '32'
if is_python_64bit:
plat = '64'
# We also accept things as:
# _pydevd_bundle.<API key>
# _pydevd_bundle.<API key>
# to have multiple pre-compiled pyds distributed along the IDE
# (generated by build_tools/<API key>.py).
mod_name = 'pydevd_cython_%s_%s%s_%s' % (sys.platform, sys.version_info[0], sys.version_info[1], plat)
check_name = '_pydevd_bundle.%s' % (mod_name,)
mod = getattr(__import__(check_name), mod_name)
# Regardless of how it was found, make sure it's later available as the
# initial name so that the expected types from cython in frame eval
# are valid.
sys.modules['_pydevd_bundle.pydevd_cython'] = mod
trace_dispatch = mod.trace_dispatch
<API key> = mod.<API key>
<API key> = mod.<API key>
global_cache_skips = mod.global_cache_skips
<API key> = mod.<API key>
<API key> = mod.<API key>
<API key> = mod.<API key>
version = getattr(mod, 'version', 0)
|
package org.eclipse.che.ide.command.editor.page.name;
import static org.eclipse.che.ide.util.NameUtils.isValidCommandName;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.inject.Inject;
import org.eclipse.che.ide.api.command.CommandExecutor;
import org.eclipse.che.ide.command.editor.EditorMessages;
import org.eclipse.che.ide.command.editor.page.<API key>;
import org.eclipse.che.ide.command.editor.page.CommandEditorPage;
/**
* Presenter for {@link CommandEditorPage} which allows to edit command's name.
*
* @author Artem Zatsarynnyi
*/
public class NamePage extends <API key> implements NamePageView.ActionDelegate {
private final NamePageView view;
private final CommandExecutor commandExecutor;
/** Initial value of the command's name. */
private String commandNameInitial;
@Inject
public NamePage(NamePageView view, EditorMessages messages, CommandExecutor commandExecutor) {
super(messages.pageNameTitle());
this.view = view;
this.commandExecutor = commandExecutor;
view.setDelegate(this);
}
@Override
public IsWidget getView() {
return view;
}
@Override
protected void initialize() {
commandNameInitial = editedCommand.getName();
view.setCommandName(editedCommand.getName());
}
@Override
public boolean isDirty() {
if (editedCommand == null) {
return false;
}
return !(commandNameInitial.equals(editedCommand.getName()));
}
@Override
public boolean hasInvalidData() {
return !isValidCommandName(editedCommand.getName());
}
@Override
public void onNameChanged(String name) {
name = name.trim();
editedCommand.setName(name);
<API key>();
view.showWarning(!isValidCommandName(name));
}
@Override
public void onCommandRun() {
commandExecutor.executeCommand(editedCommand);
}
@Override
public void focus() {
view.setFocusOnName();
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for org.eclipse.sisu.inject." />
<!-- <link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" /> -->
<title>
org.eclipse.sisu.bean Details
| org.eclipse.sisu.inject
</title>
<link href="../../../../../assets/<API key>.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../assets/<API key>.js" type="text/javascript"></script>
<script src="../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../", "../../../../../assets/");
</script>
<script src="../../../../../assets/<API key>.js" type="text/javascript"></script>
<script src="../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title">org.eclipse.sisu.inject</span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="<API key>(this, true)"
onBlur="<API key>(this, false)"
onkeydown="return search_changed(event, true, '../../../../')"
onkeyup="return search_changed(event, false, '../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td>
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../packages.html" >Package Index</a> |
<a href="../../../../classes.html" >Class Index</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../org/eclipse/sisu/package-summary.html">org.eclipse.sisu</a></li>
<li class="selected api apilevel-">
<a href="../../../../org/eclipse/sisu/bean/package-summary.html">org.eclipse.sisu.bean</a></li>
<li class="api apilevel-">
<a href="../../../../org/eclipse/sisu/inject/package-summary.html">org.eclipse.sisu.inject</a></li>
<li class="api apilevel-">
<a href="../../../../org/eclipse/sisu/launch/package-summary.html">org.eclipse.sisu.launch</a></li>
<li class="api apilevel-">
<a href="../../../../org/eclipse/sisu/osgi/package-summary.html">org.eclipse.sisu.osgi</a></li>
<li class="api apilevel-">
<a href="../../../../org/eclipse/sisu/space/package-summary.html">org.eclipse.sisu.space</a></li>
<li class="api apilevel-">
<a href="../../../../org/eclipse/sisu/wire/package-summary.html">org.eclipse.sisu.wire</a></li>
<li class="api apilevel-">
<a href="../../../../org/sonatype/inject/package-summary.html">org.sonatype.inject</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/BeanBinder.html">BeanBinder</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/BeanManager.html">BeanManager</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/BeanProperty.html">BeanProperty</a><T></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/PropertyBinder.html">PropertyBinder</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/PropertyBinding.html">PropertyBinding</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/BeanListener.html">BeanListener</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/BeanProperties.html">BeanProperties</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/BeanScheduler.html">BeanScheduler</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/DeclaredMembers.html">DeclaredMembers</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/LifecycleManager.html">LifecycleManager</a></li>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/LifecycleModule.html">LifecycleModule</a></li>
</ul>
</li>
<li><h2>Annotations</h2>
<ul>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/IgnoreSetters.html">IgnoreSetters</a></li>
</ul>
</li>
<li><h2>Enums</h2>
<ul>
<li class="api apilevel-"><a href="../../../../org/eclipse/sisu/bean/DeclaredMembers.View.html">DeclaredMembers.View</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../packages.html" >Package Index</a> |
<a href="../../../../classes.html" >Class Index</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
<!-- $("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav"); -->
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
<API key>("../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="api-level">
</div>
</div>
<div id="jd-header">
package
<h1>org.eclipse.sisu.bean</b></h1>
<div class="jd-nav">
<a class="jd-navlink" href="package-summary.html">Classes</a> | Description
</div>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<div class="jd-descr">
<p>Customizable injection of bean properties, based on <a href="http:
<p><p>
For example:
<pre>
new AbstractModule() {
@Override protected void configure() {
bindListener( Matchers.any(), new BeanListener( new MyBeanBinder() ) );
}
}</pre>
<code>MyBeanBinder</code> will be asked to supply a <code><a href="../../../../org/eclipse/sisu/bean/PropertyBinder.html">PropertyBinder</a></code> for each bean type, say Foo.
<p><p>
That <code>PropertyBinder</code> will be asked to supply a <code><a href="../../../../org/eclipse/sisu/bean/PropertyBinding.html">PropertyBinding</a></code> for each property (field or setter) in Foo.
<p><p>
Those <code>PropertyBinding</code>s are then used to automatically configure any injected instances of Foo.
</p>
</div>
<div id="footer">
Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
</div> <!-- end footer -->
</div><!-- end jd-content -->
</div> <!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize <API key>.js */
</script>
</body>
</html>
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Thu Sep 12 10:52:56 BST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.jena.atlas.web.auth Class Hierarchy (Apache Jena ARQ)</title>
<meta name="date" content="2013-09-12">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.jena.atlas.web.auth Class Hierarchy (Apache Jena ARQ)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/jena/atlas/web/package-tree.html">Prev</a></li>
<li><a href="../../../../../../org/apache/jena/common/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/jena/atlas/web/auth/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h1 class="title">Hierarchy For Package org.apache.jena.atlas.web.auth</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a>
<ul>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/<API key>.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong"><API key></span></a> (implements org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/HttpAuthenticator.html" title="interface in org.apache.jena.atlas.web.auth">HttpAuthenticator</a>)
<ul>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/<API key>.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong"><API key></span></a><T>
<ul>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/<API key>.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong"><API key></span></a></li>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/FormsAuthenticator.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong">FormsAuthenticator</span></a></li>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/ScopedAuthenticator.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong">ScopedAuthenticator</span></a></li>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/<API key>.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong"><API key></span></a></li>
</ul>
</li>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/SimpleAuthenticator.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong">SimpleAuthenticator</span></a></li>
</ul>
</li>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/FormLogin.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong">FormLogin</span></a>
<ul>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/<API key>.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong"><API key></span></a></li>
</ul>
</li>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/<API key>.html" title="class in org.apache.jena.atlas.web.auth"><span class="strong"><API key></span></a> (implements org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/HttpAuthenticator.html" title="interface in org.apache.jena.atlas.web.auth">HttpAuthenticator</a>)</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.apache.jena.atlas.web.auth.<a href="../../../../../../org/apache/jena/atlas/web/auth/HttpAuthenticator.html" title="interface in org.apache.jena.atlas.web.auth"><span class="strong">HttpAuthenticator</span></a></li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/jena/atlas/web/package-tree.html">Prev</a></li>
<li><a href="../../../../../../org/apache/jena/common/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/jena/atlas/web/auth/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
|
package p; //7, 21, 7, 33
enum A {
X;
{
if (true)
switch (valueOf("X")) {
}
}
}
|
package org.openhab.binding.nibeuplink.internal.connector;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* callback interface to update the status of the {@link UplinkWebInterface}
*
* @author Alexander Friese - initial contribution
*/
@NonNullByDefault
public interface <API key> {
void update(CommunicationStatus status);
}
|
package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.link.LinkedPositionGroup;
import org.eclipse.jface.text.link.ProposalPosition;
public class VariablePosition extends ProposalPosition {
private MultiVariableGuess fGuess;
private MultiVariable fVariable;
public VariablePosition(IDocument document, int offset, int length, MultiVariableGuess guess, MultiVariable variable) {
this(document, offset, length, LinkedPositionGroup.NO_STOP, guess, variable);
}
public VariablePosition(IDocument document, int offset, int length, int sequence, MultiVariableGuess guess, MultiVariable variable) {
super(document, offset, length, sequence, null);
Assert.isNotNull(guess);
Assert.isNotNull(variable);
fVariable= variable;
fGuess= guess;
}
/*
* @see org.eclipse.jface.text.link.ProposalPosition#equals(java.lang.Object)
*/
public boolean equals(Object o) {
if (o instanceof VariablePosition && super.equals(o)) {
return fGuess.equals(((VariablePosition) o).fGuess);
}
return false;
}
/*
* @see org.eclipse.jface.text.link.ProposalPosition#hashCode()
*/
public int hashCode() {
return super.hashCode() | fGuess.hashCode();
}
/*
* @see org.eclipse.jface.text.link.ProposalPosition#getChoices()
*/
public ICompletionProposal[] getChoices() {
return fGuess.getProposals(fVariable, offset, length);
}
/**
* Returns the variable.
*
* @return the variable.
*/
public MultiVariable getVariable() {
return fVariable;
}
}
|
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.10.26 at 02:11:54 PM CEST
package org.eclipse.kura.configuration.metatype;
import java.util.List;
import org.osgi.annotation.versioning.ProviderType;
@ProviderType
public interface Attribute {
/**
* Gets the value of the value property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the value property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getValue();
/**
* Gets the value of the adref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAdref();
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent();
}
|
package org.eclipse.birt.report.model.api;
import java.util.List;
import org.eclipse.birt.report.model.core.DesignSession;
import org.eclipse.birt.report.model.elements.Cell;
import org.eclipse.birt.report.model.elements.TableColumn;
/**
* Tests utility for API package. These methods are provided for Model tests
* plugins since test cases need to oberserve internal states.
*
*/
public class ApiTestUtil
{
/**
* Returns the design session for the given session handle.
*
* @param sessionHandle
* the session handle
* @return the design session
*/
public static DesignSession getDesignSession( SessionHandle sessionHandle )
{
if ( sessionHandle == null )
return null;
return sessionHandle.session;
}
/**
* Returns copied cells for the given column band data.
*
* @param bandData
* the column band data
* @return a list containing copied cells
*/
public static List getCopiedCells( ColumnBandData bandData )
{
if ( bandData == null )
return null;
return bandData.getCells( );
}
/**
* Returns copied cells for the given column band data.
*
* @param bandData
* the column band data
* @return a list containing copied cells
*/
public static Cell getCopiedCell( ColumnBandData bandData, int index )
{
if ( bandData == null )
return null;
CellContextInfo contextInfo = (CellContextInfo) bandData.getCells( )
.get( index );
return contextInfo.getCell( );
}
/**
* Returns copied column for the given column band data.
*
* @param bandData
* the column band data
* @return the copied column
*/
public static TableColumn getCopiedColumn( ColumnBandData bandData )
{
if ( bandData == null )
return null;
return bandData.getColumn( );
}
/**
* Returns the font handle of the element.
*
* @param element
* the design element
* @return the font handle
*/
public static FontHandle getFontProperty( DesignElementHandle element )
{
if ( element == null )
return null;
return element.getFontProperty( );
}
}
|
package org.eclipse.che.ide.ext.java.jdi.client;
/**
* Interface to represent the messages contained in resource bundle: '<API key>.properties'.
*
* @author Artem Zatsarynnyy
*/
public interface <API key> extends com.google.gwt.i18n.client.Messages {
/* Actions */
@Key("control.debugApp.id")
String debugAppActionId();
@Key("control.debugApp.text")
String debugAppActionText();
@Key("control.debugApp.description")
String <API key>();
/* Buttons */
@Key("breakpoints")
String breakpoints();
@Key("cancelButton")
String cancelButton();
@Key("connectButton")
String connectButton();
@Key("debug")
String debug();
@Key("disconnectButton")
String disconnectButton();
@Key("host")
String host();
@Key("okButton")
String okButton();
@Key("port")
String port();
@Key("vmVersion")
String vmVersion();
@Key("vmName")
String vmName();
@Key("<API key>")
String <API key>();
@Key("resumeButton")
String resumeButton();
@Key("runButton")
String runButton();
@Key("variables")
String variables();
@Key("<API key>")
String <API key>();
@Key("stepInto")
String stepInto();
@Key("stepOver")
String stepOver();
@Key("stepReturn")
String stepReturn();
@Key("changeValue")
String changeValue();
@Key("evaluateExpression")
String evaluateExpression();
@Key("debugger.connecting")
String debuggerConnecting();
@Key("debugger.disconnecting")
String <API key>();
@Key("debugger.connected")
String debuggerConnected(String address);
@Key("debugger.disconnected")
String <API key>(String address);
@Key("debugger.runnerNotSpecified")
String <API key>();
@Key("error.<API key>")
String <API key>(String className);
/* ChangeValueView */
@Key("view.changeValue.title")
String <API key>();
@Key("view.changeValue.expressionField.title")
String <API key>(String varName);
@Key("view.changeValue.changeButton.title")
String <API key>();
@Key("view.changeValue.cancelButton.title")
String <API key>();
/* <API key> */
@Key("view.evaluateExpression.title")
String <API key>();
@Key("view.evaluateExpression.expressionField.title")
String <API key>();
@Key("view.evaluateExpression.resultField.title")
String <API key>();
@Key("view.evaluateExpression.evaluateButton.title")
String <API key>();
@Key("view.evaluateExpression.closeButton.title")
String <API key>();
@Key("<API key>")
String <API key>(String reason);
@Key("connect.to.remote")
String connectToRemote();
@Key("connect.to.remote.description")
String <API key>();
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_22) on Wed Feb 29 13:59:27 CET 2012 -->
<TITLE>
Hardware
</TITLE>
<META NAME="keywords" CONTENT="org.eclipse.papyrus.RobotML.Hardware interface">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Hardware";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Hardware.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/eclipse/papyrus/RobotML/Ground.html" title="interface in org.eclipse.papyrus.RobotML"><B>PREV CLASS</B></A>
<A HREF="../../../../org/eclipse/papyrus/RobotML/Human.html" title="interface in org.eclipse.papyrus.RobotML"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/eclipse/papyrus/RobotML/Hardware.html" target="_top"><B>FRAMES</B></A>
<A HREF="Hardware.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | METHOD</FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
org.eclipse.papyrus.RobotML</FONT>
<BR>
Interface Hardware</H2>
<DL>
<DT><B>All Superinterfaces:</B> <DD>org.eclipse.emf.ecore.EObject, org.eclipse.emf.common.notify.Notifier, <A HREF="../../../../org/eclipse/papyrus/RobotML/System.html" title="interface in org.eclipse.papyrus.RobotML">System</A></DD>
</DL>
<DL>
<DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../org/eclipse/papyrus/RobotML/impl/HardwareImpl.html" title="class in org.eclipse.papyrus.RobotML.impl">HardwareImpl</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>Hardware</B><DT>extends <A HREF="../../../../org/eclipse/papyrus/RobotML/System.html" title="interface in org.eclipse.papyrus.RobotML">System</A></DL>
</PRE>
<P>
<!-- begin-user-doc -->
A representation of the model object '<em><b>Hardware</b></em>'.
<!-- end-user-doc -->
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../org/eclipse/papyrus/RobotML/RobotMLPackage.html#getHardware()"><CODE>RobotMLPackage.getHardware()</CODE></A></DL>
<HR>
<P>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>.eclipse.papyrus.RobotML.System"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from interface org.eclipse.papyrus.RobotML.<A HREF="../../../../org/eclipse/papyrus/RobotML/System.html" title="interface in org.eclipse.papyrus.RobotML">System</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../org/eclipse/papyrus/RobotML/System.html#getBase_Class()">getBase_Class</A>, <A HREF="../../../../org/eclipse/papyrus/RobotML/System.html#setBase_Class(org.eclipse.uml2.uml.Class)">setBase_Class</A></CODE></TD>
</TR>
</TABLE>
<A NAME="<API key>.eclipse.emf.ecore.EObject"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from interface org.eclipse.emf.ecore.EObject</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>eAllContents, eClass, eContainer, eContainingFeature, eContainmentFeature, eContents, eCrossReferences, eGet, eGet, eInvoke, eIsProxy, eIsSet, eResource, eSet, eUnset</CODE></TD>
</TR>
</TABLE>
<A NAME="<API key>.eclipse.emf.common.notify.Notifier"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from interface org.eclipse.emf.common.notify.Notifier</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>eAdapters, eDeliver, eNotify, eSetDeliver</CODE></TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Hardware.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/eclipse/papyrus/RobotML/Ground.html" title="interface in org.eclipse.papyrus.RobotML"><B>PREV CLASS</B></A>
<A HREF="../../../../org/eclipse/papyrus/RobotML/Human.html" title="interface in org.eclipse.papyrus.RobotML"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/eclipse/papyrus/RobotML/Hardware.html" target="_top"><B>FRAMES</B></A>
<A HREF="Hardware.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | METHOD</FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
package org.eclipse.birt.report.model.metadata;
import java.util.Date;
import org.eclipse.birt.report.model.api.ModuleOption;
import org.eclipse.birt.report.model.api.metadata.<API key>;
import org.eclipse.birt.report.model.i18n.ThreadResources;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.ULocale;
/**
* Test case for <API key>.
*
*/
public class <API key> extends <API key>
{
<API key> type = new <API key>( );
PropertyDefn propDefn = new PropertyDefnFake( );
Calendar calendar = Calendar.getInstance( );
/*
* @see TestCase#setUp()
*/
protected void setUp( ) throws Exception
{
super.setUp( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testGetTypeCode
* ()
*/
public void testGetTypeCode( )
{
assertEquals( PropertyType.DATE_TIME_TYPE, type.getTypeCode( ) );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testGetName()
*/
public void testGetName( )
{
assertEquals( PropertyType.DATE_TIME_TYPE_NAME, type.getName( ) );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testValidateValue
* ()
*/
public void testValidateValue( ) throws <API key>
{
assertEquals( null, type.validateValue( design, null, propDefn, null ) );
assertEquals( null, type.validateValue( design, null, propDefn, "" ) ); //$NON-NLS-1$
ModuleOption options = new ModuleOption( );
design.setOptions( options );
// Date
Date date = calendar.getTime( );
assertTrue( date == type.validateValue( design, null, propDefn, date ) );
// String
options.setLocale( ULocale.ENGLISH );
Date value = (Date) type.validateValue( design, null, propDefn, "08/25/2004" ); //$NON-NLS-1$
calendar.setTime( value );
assertEquals( 2004 - 1900, calendar.get( Calendar.YEAR ) - 1900 );
assertEquals( 7, calendar.get( Calendar.MONTH ) );
assertEquals( 25, calendar.get( Calendar.DAY_OF_MONTH ) );
options.setLocale( ULocale.CHINA );
// The icu version change cause this to fail, change the input string
// (previous was "2004-08-25") to accommodate
value = (Date) type.validateValue( design, null, propDefn, "2004/08/25" ); //$NON-NLS-1$
assertEquals( 2004 - 1900, calendar.get( Calendar.YEAR ) - 1900 );
assertEquals( 7, calendar.get( Calendar.MONTH ) );
assertEquals( 25, calendar.get( Calendar.DAY_OF_MONTH ) );
try
{
type.validateValue( design, null, propDefn, "<API key>" ); //$NON-NLS-1$
fail( );
}
catch ( <API key> e )
{
assertEquals(
<API key>.<API key>, e
.getErrorCode( ) );
}
// Wrong java type
try
{
type.validateValue( design, null, propDefn, new Object( ) );
fail( );
}
catch ( <API key> e )
{
assertEquals(
<API key>.<API key>, e
.getErrorCode( ) );
}
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.<API key>#
* <API key>()
*/
public void <API key>( ) throws <API key>
{
assertEquals( null, type.validateInputString( design, null, propDefn, null ) );
assertEquals( null, type.validateInputString( design, null, propDefn, "" ) ); //$NON-NLS-1$
ModuleOption options = new ModuleOption( );
design.setOptions( options );
// String
options.setLocale( ULocale.ENGLISH );
Date value = (Date) type.validateInputString( design, null, propDefn,
"08/25/2004" ); //$NON-NLS-1$
calendar.setTime( value );
assertEquals( 2004 - 1900, calendar.get( Calendar.YEAR ) - 1900 );
assertEquals( 7, calendar.get( Calendar.MONTH ) );
assertEquals( 25, calendar.get( Calendar.DAY_OF_MONTH ) );
options.setLocale( ULocale.CHINA );
// The icu version change cause this to fail, change the input string
// (previous was "2004-08-25") to accommodate
value = (Date) type
.validateInputString( design, null, propDefn, "2004/08/25" ); //$NON-NLS-1$
assertEquals( 2004 - 1900, calendar.get( Calendar.YEAR ) - 1900 );
assertEquals( 7, calendar.get( Calendar.MONTH ) );
assertEquals( 25, calendar.get( Calendar.DAY_OF_MONTH ) );
try
{
type.validateInputString( design, null, propDefn, "<API key>" ); //$NON-NLS-1$
fail( );
}
catch ( <API key> e )
{
assertEquals(
<API key>.<API key>, e
.getErrorCode( ) );
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testValidateXml
* ()
*/
public void testValidateXml( ) throws <API key>
{
assertEquals( null, type.validateXml( design, null, propDefn, null ) );
assertEquals( null, type.validateXml( design, null, propDefn, "" ) ); //$NON-NLS-1$
Date value = (Date) type.validateXml( design, null, propDefn,
"2004-10-18 10:34:22" ); //$NON-NLS-1$
calendar.setTime( value );
assertEquals( 2004 - 1900, calendar.get( Calendar.YEAR ) - 1900 );
assertEquals( 9, calendar.get( Calendar.MONTH ) );
assertEquals( 18, calendar.get( Calendar.DAY_OF_MONTH ) );
// wrong value
try
{
type.validateXml( design, null, propDefn, "<API key>" ); //$NON-NLS-1$
fail( );
}
catch ( <API key> e )
{
assertEquals(
<API key>.<API key>, e
.getErrorCode( ) );
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testToDouble
* ()
*/
public void testToDouble( )
{
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testToInteger
* ()
*/
public void testToInteger( )
{
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testToXml()
*/
public void testToXml( )
{
assertEquals( null, type.toXml( design, propDefn, null ) );
calendar.set( 2004, Calendar.OCTOBER, 18 );
String value = type.toXml( design, propDefn, calendar.getTime( ) );
// in format "yyyy-MM-dd HH:mm:ss"
int index = value.indexOf( " " ); //$NON-NLS-1$
value = value.substring( 0, index );
assertEquals( "2004-10-18", value ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testToString
* ()
*/
public void testToString( )
{
assertEquals( null, type.toString( design, propDefn, null ) );
calendar.set( 2004, Calendar.OCTOBER, 18 );
ULocale preULocale = ULocale.getDefault( );
ULocale.setDefault( ULocale.ENGLISH );
String value = type.toString( design, propDefn, calendar.getTime( ) );
assertTrue( value.startsWith( "2004-10-18" ) ); //$NON-NLS-1$
ULocale.setDefault( ULocale.GERMAN );
value = type.toString( design, propDefn, calendar.getTime( ) );
assertTrue( value.startsWith( "2004-10-18" ) ); //$NON-NLS-1$
ULocale.setDefault( preULocale );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.<API key>#
* testToDisplayString()
*/
public void testToDisplayString( )
{
assertEquals( null, type.toDisplayString( design, propDefn, null ) );
ThreadResources.setLocale( ULocale.ENGLISH );
calendar.set( 2004, Calendar.OCTOBER, 18 );
String value = type.toDisplayString( design, propDefn, calendar
.getTime( ) );
assertEquals( "10/18/04", value ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testToNumber
* ()
*/
public void testToNumber( )
{
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.metadata.<API key>#testToBoolean
* ()
*/
public void testToBoolean( )
{
}
}
|
import defaultName from "exporter";
|
package org.eclipse.kura.internal.rest.asset;
import java.util.Set;
import org.eclipse.kura.rest.utils.Validable;
public class ReadRequest implements Validable {
private Set<String> channels;
public Set<String> getChannelNames() {
return channels;
}
@Override
public boolean isValid() {
return channels != null;
}
}
|
#include "Unit.h"
#include "<API key>.h"
#include "FollowerReference.h"
void FollowerReference::<API key>()
{
getTarget()->addFollower(this);
}
void FollowerReference::<API key>()
{
getTarget()->removeFollower(this);
}
void FollowerReference::<API key>()
{
GetSource()->stopFollowing();
}
|
#!/bin/bash
TIME=`date +\%F-\%T`
echo
echo "
echo
# COMBINATION: specify wifi driver build parameter
# CHIP PLATFORM WIFI_MODE
declare -a COMBINATION=("mt7615 PC AP "
"mt7615 PC STA"
"mt7615 MT7621 AP "
"mt7615 MT7621 STA"
"mt7622 MT7622 AP "
)
# PATH: for checking build result .ko file
RESULT_PATH="../os/linux/"
# MAIN
for combination in "${COMBINATION[@]}"
do
# parse build combination
comb_arr=($combination)
chip=${comb_arr[0]}
platform=${comb_arr[1]}
wifi_mode=${comb_arr[2]}
# compose .ko file name
driver_name=$chip\_$wifi_mode
driver_name=${driver_name,,} # cast the string to lower-case
echo "build $chip $wifi_mode mode on platform $platform"
# clean
make -f Makefile clean
# make
make -f Makefile CHIPSET=$chip PLATFORM=$platform WIFI_MODE=$wifi_mode -j8
# check
# make return code
# check ${driver_name}.ko exist
if [ -f "${RESULT_PATH}${driver_name}.ko" ]; then
echo "${driver_name} built successfully."
else
echo "${driver_name} built FAILED (ko not found)!"
exit 1
fi
done
TIME=`date +\%F-\%T`
echo
echo "
echo
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Crazyflie Nano Quadcopter Client
# This program is free software; you can redistribute it and/or
# as published by the Free Software Foundation; either version 2
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
__author__ = 'Bitcraze AB'
__all__ = ['InputMux']
import os
import glob
import logging
from cflib.utils.callbacks import Caller
logger = logging.getLogger(__name__)
MAX_THRUST = 65000
class InputMux(object):
def __init__(self, input):
self._devs = []
self.name = "N/A"
self.input = input
self._prev_values = {}
# Roll/pitch limitation
self.max_rp_angle = 0
# Thrust limitations
self.thrust_slew_enabled = True
self.thrust_slew_limit = 0
self.thrust_slew_rate = 0
self.max_thrust = 0
self.max_yaw_rate = 0
self.springy_throttle = True
self.trim_roll = 0
self.trim_pitch = 0
self.has_pressure_sensor = False
# TODO: Fix writing these values
#self._max_rp_angle = 40
#self._springy_throttle = True
#self.<API key> = True
#self._thrust_slew_limit = 30
#self._thrust_slew_rate = 30
#self._min_thrust = 20000
#self._max_thrust = 50000
#self._max_yaw_rate = 400
#self._trim_roll = 0.0
#self._trim_pitch = 0.0
# Stateful things
self._old_thrust = 0
self._old_raw_thrust = 0
self._old_alt_hold = False
# TODO: Should these really be placed here?
#self.input_updated = Caller()
#self.rp_trim_updated = Caller()
#self.<API key> = Caller()
#self.device_discovery = Caller()
#self.device_error = Caller()
#self.althold_updated = Caller()
#self.alt1_updated = Caller()
#self.alt2_updated = Caller()
def <API key>(self):
return 1
def add_device(self, dev, parameters):
logger.info("Adding device and opening it")
dev.open()
self._devs.append(dev)
def remove_device(self, dev):
self._devs.remove(dev)
dev.close()
def close(self):
"""Close down the MUX and close all it's devices"""
for d in self._devs:
d.close()
self._devs = []
def _cap_rp(self, rp):
ret = rp * self.max_rp_angle
if ret > self.max_rp_angle:
ret = self.max_rp_angle
elif ret < -1 * self.max_rp_angle:
ret = -1 * self.max_rp_angle
return ret
def _scale_rp(self, roll, pitch):
return [self._cap_rp(roll), self._cap_rp(pitch)]
def <API key>(self, yaw):
return InputMux.deadband(yaw, 0.2) * self.max_yaw_rate
def _limit_thrust(self, thrust, althold, emergency_stop):
# Thust limiting (slew, minimum and emergency stop)
if self.springy_throttle:
if althold and self.has_pressure_sensor:
thrust = int(round(InputMux.deadband(thrust, 0.2)*32767 + 32767)) #Convert to uint16
else:
if thrust < 0.05 or emergency_stop:
thrust = 0
else:
thrust = self.min_thrust + thrust * (self.max_thrust -
self.min_thrust)
if (self.thrust_slew_enabled == True and
self.thrust_slew_limit > thrust and not
emergency_stop):
if self._old_thrust > self.thrust_slew_limit:
self._old_thrust = self.thrust_slew_limit
if thrust < (self._old_thrust - (self.thrust_slew_rate / 100)):
thrust = self._old_thrust - self.thrust_slew_rate / 100
if thrust < 0 or thrust < self.min_thrust:
thrust = 0
else:
thrust = thrust / 2 + 0.5
if althold and self.has_pressure_sensor:
#thrust = int(round(JoystickReader.deadband(thrust,0.2)*32767 + 32767)) #Convert to uint16
thrust = 32767
else:
if thrust < -0.90 or emergency_stop:
thrust = 0
else:
thrust = self.min_thrust + thrust * (self.max_thrust -
self.min_thrust)
if (self.thrust_slew_enabled == True and
self.thrust_slew_limit > thrust and not
emergency_stop):
if self._old_thrust > self.thrust_slew_limit:
self._old_thrust = self.thrust_slew_limit
if thrust < (self._old_thrust - (self.thrust_slew_rate / 100)):
thrust = self._old_thrust - self.thrust_slew_rate / 100
if thrust < -1 or thrust < self.min_thrust:
thrust = 0
self._old_thrust = thrust
self._old_raw_thrust = thrust
return thrust
def <API key>(self, available):
"""Set if altitude hold is available or not (depending on HW)"""
self.input.<API key> = available
def enable_alt_hold(self, althold):
"""Enable or disable altitude hold"""
self._old_alt_hold = althold
def _check_toggle(self, key, data):
if not key in self._prev_values:
self._prev_values[key] = data
elif self._prev_values[key] != data:
self._prev_values[key] = data
return True
return False
def _update_alt_hold(self, value):
if self._check_toggle("althold", value):
self.input.althold_updated.call(str(value))
def _update_em_stop(self, value):
if self._check_toggle("estop", value):
self.input.<API key>.call(value)
def _update_alt1(self, value):
if self._check_toggle("alt1", value):
self.input.alt1_updated.call(value)
def _update_alt2(self, value):
if self._check_toggle("alt2", value):
self.input.alt2_updated.call(value)
def _trim_rp(self, roll, pitch):
return [roll + self.trim_roll, pitch + self.trim_pitch]
@staticmethod
def p2t(percentage):
"""Convert a percentage to raw thrust"""
return int(MAX_THRUST * (percentage / 100.0))
@staticmethod
def deadband(value, threshold):
if abs(value) < threshold:
value = 0
elif value > 0:
value -= threshold
elif value < 0:
value += threshold
return value/(1-threshold)
def read(self):
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.