answer stringlengths 15 1.25M |
|---|
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class REST
{
protected $_ci;
protected $supported_formats = array(
'xml' => 'application/xml',
'json' => 'application/json',
'serialize' => 'application/vnd.php.serialized',
'php' => 'text/plain',
'csv' => 'text/csv'
);
protected $auto_detect_formats = array(
'application/xml' => 'xml',
'text/xml' => 'xml',
'application/json' => 'json',
'text/json' => 'json',
'text/csv' => 'csv',
'application/csv' => 'csv',
'application/vnd.php.serialized' => 'serialize'
);
protected $rest_server;
protected $format;
protected $mime_type;
protected $http_auth = null;
protected $http_user = null;
protected $http_pass = null;
protected $api_name = 'X-API-KEY';
protected $api_key = null;
protected $ssl_verify_peer = null;
protected $ssl_cainfo = null;
protected $send_cookies = null;
protected $response_string;
function __construct($config = array())
{
$this->_ci =& get_instance();
log_message('debug', 'REST Class Initialized');
$this->_ci->load->library('curl');
// If a URL was passed to the library
empty($config) OR $this->initialize($config);
}
function __destruct()
{
$this->_ci->curl->set_defaults();
}
/**
* initialize
*
* @access public
* @author Phil Sturgeon
* @author Chris Kacerguis
* @version 1.0
*/
public function initialize($config)
{
$this->rest_server = @$config['server'];
if (substr($this->rest_server, -1, 1) != '/')
{
$this->rest_server .= '/';
}
isset($config['send_cookies']) && $this->send_cookies = $config['send_cookies'];
isset($config['api_name']) && $this->api_name = $config['api_name'];
isset($config['api_key']) && $this->api_key = $config['api_key'];
isset($config['http_auth']) && $this->http_auth = $config['http_auth'];
isset($config['http_user']) && $this->http_user = $config['http_user'];
isset($config['http_pass']) && $this->http_pass = $config['http_pass'];
isset($config['ssl_verify_peer']) && $this->ssl_verify_peer = $config['ssl_verify_peer'];
isset($config['ssl_cainfo']) && $this->ssl_cainfo = $config['ssl_cainfo'];
}
/**
* get
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function get($uri, $params = array(), $format = NULL)
{
if ($params)
{
$uri .= '?'.(is_array($params) ? http_build_query($params) : $params);
}
return $this->_call('get', $uri, NULL, $format);
}
/**
* post
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function post($uri, $params = array(), $format = NULL)
{
return $this->_call('post', $uri, $params, $format);
}
/**
* put
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function put($uri, $params = array(), $format = NULL)
{
return $this->_call('put', $uri, $params, $format);
}
/**
* patch
*
* @access public
* @author Dmitry Serzhenko
* @version 1.0
*/
public function patch($uri, $params = array(), $format = NULL)
{
return $this->_call('patch', $uri, $params, $format);
}
/**
* delete
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function delete($uri, $params = array(), $format = NULL)
{
return $this->_call('delete', $uri, $params, $format);
}
/**
* api_key
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function api_key($key, $name = FALSE)
{
$this->api_key = $key;
if ($name !== FALSE)
{
$this->api_name = $name;
}
}
/**
* language
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function language($lang)
{
if (is_array($lang))
{
$lang = implode(', ', $lang);
}
$this->_ci->curl->http_header('Accept-Language', $lang);
}
/**
* header
*
* @access public
* @author David Genelid
* @version 1.0
*/
public function header($header)
{
$this->_ci->curl->http_header($header);
}
/**
* _call
*
* @access protected
* @author Phil Sturgeon
* @version 1.0
*/
protected function _call($method, $uri, $params = array(), $format = NULL)
{
if ($format !== NULL)
{
$this->format($format);
}
$this->http_header('Accept', $this->mime_type);
// Initialize cURL session
$this->_ci->curl->create($this->rest_server.$uri);
// If using ssl set the ssl verification value and cainfo
if ($this->ssl_verify_peer === FALSE)
{
$this->_ci->curl->ssl(FALSE);
}
elseif ($this->ssl_verify_peer === TRUE)
{
$this->ssl_cainfo = getcwd() . $this->ssl_cainfo;
$this->_ci->curl->ssl(TRUE, 2, $this->ssl_cainfo);
}
// If authentication is enabled use it
if ($this->http_auth != '' && $this->http_user != '')
{
$this->_ci->curl->http_login($this->http_user, $this->http_pass, $this->http_auth);
}
// If we have an API Key, then use it
if ($this->api_key != '')
{
$this->_ci->curl->http_header($this->api_name, $this->api_key);
}
// Send cookies with curl
if ($this->send_cookies != '')
{
$this->_ci->curl->set_cookies( $_COOKIE );
}
$this->http_header('Content-type', $this->mime_type);
// We still want the response even if there is an error code over 400
$this->_ci->curl->option('failonerror', FALSE);
// Call the correct method with parameters
$this->_ci->curl->{$method}($params);
// Execute and return the response from the REST server
$response = $this->_ci->curl->execute();
// Format and return
return $this->_format_response($response);
}
/**
* initialize
*
* If a type is passed in that is not supported, use it as a mime type
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function format($format)
{
if (array_key_exists($format, $this->supported_formats))
{
$this->format = $format;
$this->mime_type = $this->supported_formats[$format];
}
else
{
$this->mime_type = $format;
}
return $this;
}
/**
* debug
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function debug()
{
$request = $this->_ci->curl->debug_request();
echo "=============================================<br/>\n";
echo "<h2>REST Test</h2>\n";
echo "=============================================<br/>\n";
echo "<h3>Request</h3>\n";
echo $request['url']."<br/>\n";
echo "=============================================<br/>\n";
echo "<h3>Response</h3>\n";
if ($this->response_string)
{
echo "<code>".nl2br(htmlentities($this->response_string))."</code><br/>\n\n";
}
else
{
echo "No response<br/>\n\n";
}
echo "=============================================<br/>\n";
if ($this->_ci->curl->error_string)
{
echo "<h3>Errors</h3>";
echo "<strong>Code:</strong> ".$this->_ci->curl->error_code."<br/>\n";
echo "<strong>Message:</strong> ".$this->_ci->curl->error_string."<br/>\n";
echo "=============================================<br/>\n";
}
echo "<h3>Call details</h3>";
echo "<pre>";
print_r($this->_ci->curl->info);
echo "</pre>";
}
/**
* status
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
// Return HTTP status code
public function status()
{
return $this->info('http_code');
}
/**
* info
*
* Return curl info by specified key, or whole array
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function info($key = null)
{
return $key === null ? $this->_ci->curl->info : @$this->_ci->curl->info[$key];
}
/**
* option
*
* Set custom CURL options
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function option($code, $value)
{
$this->_ci->curl->option($code, $value);
}
/**
* http_header
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
public function http_header($header, $content = NULL)
{
// Did they use a single argument or two?
$params = $content ? array($header, $content) : array($header);
// Pass these attributes on to the curl library
<API key>(array($this->_ci->curl, 'http_header'), $params);
}
/**
* _format_response
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
protected function _format_response($response)
{
$this->response_string =& $response;
// It is a supported format, so just run its formatting method
if (array_key_exists($this->format, $this->supported_formats))
{
return $this->{"_".$this->format}($response);
}
// Find out what format the data was returned in
$returned_mime = @$this->_ci->curl->info['content_type'];
// If they sent through more than just mime, strip it off
if (strpos($returned_mime, ';'))
{
list($returned_mime) = explode(';', $returned_mime);
}
$returned_mime = trim($returned_mime);
if (array_key_exists($returned_mime, $this->auto_detect_formats))
{
return $this->{'_'.$this->auto_detect_formats[$returned_mime]}($response);
}
return $response;
}
/**
* _xml
*
* Format XML for output
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
protected function _xml($string)
{
return $string ? (array) <API key>($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array();
}
protected function _csv($string)
{
$data = array();
// Splits
$rows = explode("\n", trim($string));
$headings = explode(',', array_shift($rows));
foreach( $rows as $row )
{
// The substr removes " from start and end
$data_fields = explode('","', trim(substr($row, 1, -1)));
if (count($data_fields) === count($headings))
{
$data[] = array_combine($headings, $data_fields);
}
}
return $data;
}
/**
* _json
*
* Encode as JSON
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
protected function _json($string)
{
return json_decode(trim($string));
}
/**
* _serialize
*
* Encode as Serialized array
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
protected function _serialize($string)
{
return unserialize(trim($string));
}
/**
* _php
*
* Encode raw PHP
*
* @access public
* @author Phil Sturgeon
* @version 1.0
*/
protected function _php($string)
{
$string = trim($string);
$populated = array();
eval("\$populated = \"$string\";");
return $populated;
}
}
/* End of file REST.php */
/* Location: ./application/libraries/REST.php */ |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc on Sun May 07 10:20:01 EDT 2006 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
HttpClient 3.0.1 API: API Help
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<A NAME="navbar_top"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<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"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Help</B></FONT> </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
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="help-doc.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<HR>
<CENTER>
<H1>
How This API Document Is Organized</H1>
</CENTER>
This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.<H3>
Overview</H3>
<BLOCKQUOTE>
<P>
The <A HREF="overview-summary.html">Overview</A> page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.</BLOCKQUOTE>
<H3>
Package</H3>
<BLOCKQUOTE>
<P>
Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:<UL>
<LI>Interfaces (italic)<LI>Classes<LI>Exceptions<LI>Errors</UL>
</BLOCKQUOTE>
<H3>
Class/Interface</H3>
<BLOCKQUOTE>
<P>
Each class, interface, inner class and inner interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:<UL>
<LI>Class inheritance diagram<LI>Direct Subclasses<LI>All Known Subinterfaces<LI>All Known Implementing Classes<LI>Class/interface declaration<LI>Class/interface description
<P>
<LI>Inner Class Summary<LI>Field Summary<LI>Constructor Summary<LI>Method Summary
<P>
<LI>Field Detail<LI>Constructor Detail<LI>Method Detail</UL>
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.</BLOCKQUOTE>
<H3>
Use</H3>
<BLOCKQUOTE>
Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.</BLOCKQUOTE>
<H3>
Tree (Class Hierarchy)</H3>
<BLOCKQUOTE>
There is a <A HREF="overview-tree.html">Class Hierarchy</A> page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with <code>java.lang.Object</code>. The interfaces do not inherit from <code>java.lang.Object</code>.<UL>
<LI>When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.<LI>When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.</UL>
</BLOCKQUOTE>
<H3>
Deprecated API</H3>
<BLOCKQUOTE>
The <A HREF="deprecated-list.html">Deprecated API</A> page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.</BLOCKQUOTE>
<H3>
Index</H3>
<BLOCKQUOTE>
The <A HREF="index-all.html">Index</A> contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.</BLOCKQUOTE>
<H3>
Prev/Next</H3>
These links take you to the next or previous class, interface, package, or related page.<H3>
Frames/No Frames</H3>
These links show and hide the HTML frames. All pages are available with or without frames.
<P>
<H3>
Serialized Form</H3>
Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.
<P>
<FONT SIZE="-1">
<EM>
This help file applies to API documentation generated using the standard doclet. </EM>
</FONT>
<BR>
<HR>
<A NAME="navbar_bottom"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<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"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Help</B></FONT> </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
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="help-doc.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<HR>
Copyright © 2001-2006 Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML> |
from django.test import TestCase
from mock import NonCallableMock
from silk.collector import DataCollector
from silk.middleware import SilkyMiddleware
from .util import delete_all_models
from silk.config import SilkyConfig
from silk.models import Request
def fake_get_response():
def fake_response():
return 'hello world'
return fake_response
class TestConfigMeta(TestCase):
def _mock_response(self):
response = NonCallableMock()
response._headers = {}
response.status_code = 200
response.queries = []
response.get = response._headers.get
response.content = ''
return response
def _execute_request(self):
delete_all_models(Request)
DataCollector().configure(Request.objects.create())
response = self._mock_response()
SilkyMiddleware(fake_get_response)._process_response('', response)
self.assertTrue(response.status_code == 200)
objs = Request.objects.all()
self.assertEqual(objs.count(), 1)
r = objs[0]
return r
def test_enabled(self):
SilkyConfig().SILKY_META = True
r = self._execute_request()
self.assertTrue(r.meta_time is not None or
r.meta_num_queries is not None or
r.<API key> is not None)
def test_disabled(self):
SilkyConfig().SILKY_META = False
r = self._execute_request()
self.assertFalse(r.meta_time) |
<section data-ng-controller="<API key>>
<style type="text/css">
body {
background-color:#000000;
background-image: url("modules/core/img/pics/gator_band.jpg");
background-repeat: no-repeat;
background-position: center top;
background-size: 100%;
}
h1 {
font-family: 'Muli', sans-serif;
}
</style>
<div class="row text-center">
<img alt="UFBands" class="img" src="modules/core/img/brand/logo_white_blue.png" width="200" height="50"/>
</div>
<div class="well centerOfScreen">
<div class="row">
<!-- <div class="col-md-4 col-sm-offset-4">
<img alt="UFBands" class="img-responsive text-center" src="modules/core/img/brand/logo.png" />
</div>
<h1 class="text-center"><font color="black">Sign Up</font></h1>
</div>
<div class="col-md-12">
<form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off">
<fieldset>
<div class="col-md-6">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-star text-warning" aria-hidden="true"></i>
</span>
<input type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="First Name">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-star text-warning" aria-hidden="true"></i>
</span>
<input type="text" id="lastName" name="lastName" class="form-control" data-ng-model="credentials.lastName" placeholder="Last Name">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon <API key> text-warning" aria-hidden="true"></i>
</span>
<input type="text" id="nickName" name="nickName" class="form-control" data-ng-model="credentials.nickName" placeholder="Nickname">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-envelope text-info" aria-hidden="true"></i>
</span>
<input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Email">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-envelope text-info" aria-hidden="true"></i>
</span>
<input type="email" id="gatorlink" name="gatorlink" class="form-control" data-ng-model="credentials.gatorlink" placeholder="Gatorlink (e.g. blah@ufl.edu)">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-plus text-success" aria-hidden="true"></i>
</span>
<input type="text" id="ufid" name="ufid" class="form-control" data-ng-model="credentials.ufid" placeholder="UFID (e.g. 12345678)">
</div>
<div class="input-group ">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-check text-primary" aria-hidden="true"></i>
</span>
<label for="buttonProspective">  Prospective  </label>
<input type="radio" id="buttonProspective" name="userType" data-ng-model="credentials.userType" value="Prospective" ng-click="prospectiveUser()" title="If you would like to join a band">
<br>
<label for="buttonCurrent">  Current  </label>
<input type="radio" id="buttonCurrent" name="userType" data-ng-model="credentials.userType" value="Current" ng-click="currentUser()" title="If you are currently in a band">
<br>
<label for="buttonAlumni">  Alumni  </label>
<input type="radio" id="buttonAlumni" name="userType" data-ng-model="credentials.userType" value="Alumni" ng-click="alumniUser()" title="If you have previously been in a band">
</div>
<div class="input-group" >
<span class="input-group-addon">
<i class="glyphicon glyphicon-music" aria-hidden="true"></i>
</span>
<select name="mydropdown" data-ng-model="credentials.primary" id="primary" class="form-control" placeholder="primary" required>
<option ng-repeat="instruments in instruments" value="{{instruments}}" placeholder="Instrument">{{instruments}}</option>
</select>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-fire text-danger" aria-hidden="true"></i>
</span>
<input type="text" data-ng-model="credentials.primaryYears" id="primaryYears" class="form-control" placeholder="Years Experience" required>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-phone text-primary" aria-hidden="true"></i>
</span>
<input type="text" id="phoneNumber" name="phoneNumber" class="form-control" data-ng-model="credentials.phoneNumber" placeholder="Phone Number">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-apple text-danger" aria-hidden="true"></i>
</span>
<input type="text" id="highSchool" name="highSchool" class="form-control" data-ng-model="credentials.highSchool" placeholder="High School and Grad Year">
</div>
<div class="input-group" >
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-user text-primary" aria-hidden="true"></i>
</span>
<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-asterisk text-danger" aria-hidden="true"></i>
</span>
<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password">
</div>
</div>
<div class="col-md-6">
<div class="input-group" title="For communication purposes">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-home text-success" aria-hidden="true"></i>
</span>
<input type="text" data-ng-model="credentials.permanentAddress.line1" id="permanentLine1" class="form-control" placeholder="Permanent Address line 1" required>
<input type="text" data-ng-model="credentials.permanentAddress.line2" id="permanentLine2" class="form-control" placeholder="Permanent Address line 2" >
<input type="text" data-ng-model="credentials.permanentAddress.city" id="permanentCity" class="form-control" placeholder="City" required>
<input type="text" data-ng-model="credentials.permanentAddress.state" id="permanentState" class="form-control" placeholder="State" required>
<input type="text" data-ng-model="credentials.permanentAddress.zip" id="permanentZip" class="form-control" placeholder="Zip code" required>
</div>
<div class="input-group" title="For communication purposes">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-tent text-warning" aria-hidden="true"></i>
</span>
<input type="text" data-ng-model="credentials.localAddress.line1" id="localLine1" class="form-control" placeholder="Local Address line 1" required>
<input type="text" data-ng-model="credentials.localAddress.line2" id="localLine2" class="form-control" placeholder="Local Address line 2" >
<input type="text" data-ng-model="credentials.localAddress.city" id="localCity" class="form-control" placeholder="City" required>
<input type="text" data-ng-model="credentials.localAddress.state" id="localState" class="form-control" placeholder="State" required>
<input type="text" data-ng-model="credentials.localAddress.zip" id="localZip" class="form-control" placeholder="Zip code" required>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon <API key> text-warning" aria-hidden="true"></i>
</span>
<input type="text" id="major" name="major" class="form-control" data-ng-model="credentials.major" placeholder="Major">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-bell text-warning" aria-hidden="true"></i>
</span>
<input type="text" id="class" name="class" class="form-control" data-ng-model="credentials.class" placeholder="Class (e.g. 1EG)">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-pawn " aria-hidden="true"></i>
</span>
<input type="text" id="year" name="year" class="form-control" data-ng-model="credentials.year" placeholder="Year (e.g. freshman)">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="text-muted glyphicon glyphicon-calendar text-primary" aria-hidden="true"></i>
</span>
<input type="text" id="graduationDate" name="graduationDate" class="form-control" data-ng-model="credentials.graduationDate" placeholder="College Graduation Date">
</div>
</div>
<div class="text-center form-group center col-md-12">
<br>
<div data-ng-show="error" class="text-center text-danger alert alert-danger">
<strong data-ng-bind="error"></strong>
</div>
<button type="submit" class="btn btn-large btn-primary" id = "signup">Sign up</button> or
<a href="/#!/signin" class="show-signup">Sign in</a>
</div>
</fieldset>
</form>
</div>
</div>
</section> |
/**
* class WysiHat.Selection
**/
WysiHat.Selection = Class.create((function() {
/**
* new WysiHat.Selection(editor)
* - editor (WysiHat.Editor): the editor object that you want to bind to
**/
function initialize(editor) {
this.window = editor.getWindow();
this.document = editor.getDocument();
}
/**
* WysiHat.Selection#getSelection() -> Selection
* Get selected text.
**/
function getSelection() {
return this.window.getSelection ? this.window.getSelection() : this.document.selection;
}
/**
* WysiHat.Selection#getRange() -> Range
* Get range for selected text.
**/
function getRange() {
var selection = this.getSelection();
try {
var range;
if (selection.getRangeAt)
range = selection.getRangeAt(0);
else
range = selection.createRange();
} catch(e) { return null; }
if (Prototype.Browser.WebKit) {
range.setStart(selection.baseNode, selection.baseOffset);
range.setEnd(selection.extentNode, selection.extentOffset);
}
return range;
}
/**
* WysiHat.Selection#selectNode(node) -> undefined
* - node (Element): Element or node to select
**/
function selectNode(node) {
var selection = this.getSelection();
if (Prototype.Browser.IE) {
var range = <API key>(this.document, node);
range.select();
} else if (Prototype.Browser.WebKit) {
selection.setBaseAndExtent(node, 0, node, node.innerText.length);
} else if (Prototype.Browser.Opera) {
range = this.document.createRange();
range.selectNode(node);
selection.removeAllRanges();
selection.addRange(range);
} else {
var range = <API key>(this.document, node);
selection.removeAllRanges();
selection.addRange(range);
}
}
/**
* WysiHat.Selection#getNode() -> Element
* Returns selected node.
**/
function getNode() {
var nodes = null, candidates = [], children, el;
var range = this.getRange();
if (!range)
return null;
var parent;
if (range.parentElement)
parent = range.parentElement();
else
parent = range.<API key>;
if (parent) {
while (parent.nodeType != 1) parent = parent.parentNode;
if (parent.nodeName.toLowerCase() != "body") {
el = parent;
do {
el = el.parentNode;
candidates[candidates.length] = el;
} while (el.nodeName.toLowerCase() != "body");
}
children = parent.all || parent.<API key>("*");
for (var j = 0; j < children.length; j++)
candidates[candidates.length] = children[j];
nodes = [parent];
for (var ii = 0, r2; ii < candidates.length; ii++) {
r2 = <API key>(this.document, candidates[ii]);
if (r2 && compareRanges(range, r2))
nodes[nodes.length] = candidates[ii];
}
}
return nodes.last();
}
function <API key>(document, node) {
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(node);
} else if (document.createRange) {
var range = document.createRange();
range.selectNodeContents(node);
}
return range;
}
function compareRanges(r1, r2) {
if (r1.compareEndPoints) {
return !(
r2.compareEndPoints('StartToStart', r1) == 1 &&
r2.compareEndPoints('EndToEnd', r1) == 1 &&
r2.compareEndPoints('StartToEnd', r1) == 1 &&
r2.compareEndPoints('EndToStart', r1) == 1
||
r2.compareEndPoints('StartToStart', r1) == -1 &&
r2.compareEndPoints('EndToEnd', r1) == -1 &&
r2.compareEndPoints('StartToEnd', r1) == -1 &&
r2.compareEndPoints('EndToStart', r1) == -1
);
} else if (r1.<API key>) {
return !(
r2.<API key>(0, r1) == 1 &&
r2.<API key>(2, r1) == 1 &&
r2.<API key>(1, r1) == 1 &&
r2.<API key>(3, r1) == 1
||
r2.<API key>(0, r1) == -1 &&
r2.<API key>(2, r1) == -1 &&
r2.<API key>(1, r1) == -1 &&
r2.<API key>(3, r1) == -1
);
}
return null;
};
function setBookmark() {
var bookmark = this.document.getElementById('bookmark');
if (bookmark)
bookmark.parentNode.removeChild(bookmark);
bookmark = this.document.createElement('span');
bookmark.id = 'bookmark';
bookmark.innerHTML = ' ';
var range;
if (Prototype.Browser.IE)
range = new Range(this.document);
else
range = this.getRange();
range.insertNode(bookmark);
}
function moveToBookmark() {
var bookmark = this.document.getElementById('bookmark');
if (!bookmark)
return;
if (Prototype.Browser.IE) {
var range = this.getRange();
range.moveToElementText(bookmark);
range.collapse();
range.select();
} else if (Prototype.Browser.WebKit) {
var selection = this.getSelection();
selection.setBaseAndExtent(bookmark, 0, bookmark, 0);
} else {
var range = this.getRange();
range.setStartBefore(bookmark);
}
bookmark.parentNode.removeChild(bookmark);
}
return {
initialize: initialize,
getSelection: getSelection,
getRange: getRange,
getNode: getNode,
selectNode: selectNode,
setBookmark: setBookmark,
moveToBookmark: moveToBookmark
};
})()); |
<?php
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
/**
* Shortcode attributes
* @var $title
* @var $el_class
* @var $el_id
* @var $type
* @var $style
* @var $legend
* @var $animation
* @var $tooltips
* @var $stroke_color
* @var $custom_stroke_color
* @var $stroke_width
* @var $values
* @var $css
* @var $css_animation
* Shortcode class
* @var <API key> $this
*/
$el_class = $el_id = $title = $type = $style = $legend = $animation = $tooltips = $stroke_color = $stroke_width = $values = $css = $css_animation = $custom_stroke_color = '';
$atts = <API key>( $this->getShortcode(), $atts );
extract( $atts );
$base_colors = array(
'normal' => array(
'blue' => '#5472d2',
'turquoise' => '#00c1cf',
'pink' => '#fe6c61',
'violet' => '#8d6dc4',
'peacoc' => '#4cadc9',
'chino' => '#cec2ab',
'mulled-wine' => '#50485b',
'vista-blue' => '#75d69c',
'orange' => '#f7be68',
'sky' => '#5aa1e3',
'green' => '#6dab3c',
'juicy-pink' => '#f4524d',
'sandy-brown' => '#f79468',
'purple' => '#b97ebb',
'black' => '#2a2a2a',
'grey' => '#ebebeb',
'white' => '#ffffff',
'default' => '#f7f7f7',
'primary' => '#0088cc',
'info' => '#58b9da',
'success' => '#6ab165',
'warning' => '#ff9900',
'danger' => '#ff675b',
'inverse' => '#555555',
),
'active' => array(
'blue' => '#3c5ecc',
'turquoise' => '#00a4b0',
'pink' => '#fe5043',
'violet' => '#7c57bb',
'peacoc' => '#39a0bd',
'chino' => '#c3b498',
'mulled-wine' => '#413a4a',
'vista-blue' => '#5dcf8b',
'orange' => '#f5b14b',
'sky' => '#4092df',
'green' => '#5f9434',
'juicy-pink' => '#f23630',
'sandy-brown' => '#f57f4b',
'purple' => '#ae6ab0',
'black' => '#1b1b1b',
'grey' => '#dcdcdc',
'white' => '#f0f0f0',
'default' => '#e8e8e8',
'primary' => '#0074ad',
'info' => '#3fafd4',
'success' => '#59a453',
'warning' => '#e08700',
'danger' => '#ff4b3c',
'inverse' => '#464646',
),
);
$colors = array(
'flat' => array(
'normal' => $base_colors['normal'],
'active' => $base_colors['active'],
),
);
foreach ( $base_colors['normal'] as $name => $color ) {
$colors['modern']['normal'][ $name ] = array( vc_colorCreator( $color, 7 ), $color );
}
foreach ( $base_colors['active'] as $name => $color ) {
$colors['modern']['active'][ $name ] = array( vc_colorCreator( $color, 7 ), $color );
}
wp_enqueue_script( 'vc_round_chart' );
$class_to_filter = 'vc_chart vc_round-chart wpb_content_element';
$class_to_filter .= <API key>( $css, ' ' ) . $this->getExtraClass( $el_class ) . $this->getCSSAnimation( $css_animation );
$css_class = apply_filters( <API key>, $class_to_filter, $this->settings['base'], $atts );
$options = array();
if ( ! empty( $legend ) ) {
$options[] = 'data-vc-legend="1"';
}
if ( ! empty( $tooltips ) ) {
$options[] = 'data-vc-tooltips="1"';
}
if ( ! empty( $animation ) ) {
$options[] = 'data-vc-animation="' . esc_attr( str_replace( 'easein', 'easeIn', $animation ) ) . '"';
}
if ( ! empty( $stroke_color ) ) {
if ( 'custom' === $stroke_color ) {
if ( $custom_stroke_color ) {
$color = $custom_stroke_color;
} else {
$color = $base_colors['normal']['white'];
}
} else {
$color = $base_colors['normal'][ $stroke_color ];
}
$options[] = '<API key>="' . esc_attr( $color ) . '"';
}
if ( ! empty( $stroke_width ) ) {
$options[] = '<API key>="' . esc_attr( $stroke_width ) . '"';
}
$values = (array) <API key>( $values );
$data = array();
foreach ( $values as $k => $v ) {
if ( 'custom' === $style ) {
if ( ! empty( $v['custom_color'] ) ) {
$color = $v['custom_color'];
$highlight = vc_colorCreator( $v['custom_color'], - 10 ); // 10% darker
} else {
$color = $base_colors['normal']['grey'];
$highlight = $base_colors['active']['grey'];
}
} else {
$color = isset( $colors[ $style ]['normal'][ $v['color'] ] ) ? $colors[ $style ]['normal'][ $v['color'] ] : $v['normal']['color'];
$highlight = isset( $colors[ $style ]['active'][ $v['color'] ] ) ? $colors[ $style ]['active'][ $v['color'] ] : $v['active']['color'];
}
$data[] = array(
'value' => intval( isset( $v['value'] ) ? $v['value'] : 0 ),
'color' => $color,
'highlight' => $highlight,
'label' => isset( $v['title'] ) ? $v['title'] : '',
);
}
$options[] = 'data-vc-type="' . esc_attr( $type ) . '"';
$options[] = 'data-vc-values="' . esc_attr( wp_json_encode( $data ) ) . '"';
if ( '' !== $title ) {
$title = '<h2 class="wpb_heading">' . $title . '</h4>';
}
$canvas_html = '<canvas class="<API key>" width="1" height="1"></canvas>';
$legend_html = '';
if ( $legend ) {
foreach ( $data as $v ) {
$color = is_array( $v['color'] ) ? current( $v['color'] ) : $v['color'];
$legend_html .= '<li><span style="background-color:' . $color . '"></span>' . $v['label'] . '</li>';
}
$legend_html = '<ul class="vc_chart-legend">' . $legend_html . '</ul>';
$canvas_html = '<div class="<API key>">' . $canvas_html . '</div>';
}
if ( ! empty( $el_id ) ) {
$options[] = 'id="' . esc_attr( $el_id ) . '"';
}
$output = '
<div class="' . esc_attr( $css_class ) . '" ' . implode( ' ', $options ) . '>
' . $title . '
<div class="wpb_wrapper">
' . $canvas_html . $legend_html . '
</div>' . '
</div>' . '
';
return $output; |
import angular from 'angular';
import template from './gifs.template.html';
angular
.module('single-spa-app')
.component('gifs', {
template,
controllerAs: 'vm',
controller($http) {
const vm = this;
$http
.get('https://api.giphy.com/v1/gifs/search?q=ping+pong&<TwitterConsumerkey>')
.then(response => {
vm.gifs = response.data.data;
})
.catch(err => {
setTimeout(() => {
throw err;
}, 0)
});
},
}); |
package com.dubture.symfony.core.model;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.core.index2.search.ISearchEngine.MatchRule;
import org.eclipse.dltk.core.search.IDLTKSearchScope;
import org.eclipse.dltk.core.search.SearchEngine;
import org.eclipse.dltk.internal.core.ModelElement;
import org.eclipse.dltk.internal.core.SourceType;
import org.eclipse.php.internal.core.PHPLanguageToolkit;
import org.eclipse.php.core.compiler.ast.nodes.Scalar;
import org.eclipse.php.internal.core.model.PHPModelAccess;
import org.eclipse.php.internal.core.typeinference.PHPModelUtils;
/**
*
* The Service class represents a Symfony2 Service
* retrievable from the DependencyInjection container.
*
*
* @author Robert Gruendler <r.gruendler@gmail.com>
*
*/
@SuppressWarnings("restriction")
public class Service extends SourceType {
// just for bc purposec
public static final String NAME = com.dubture.symfony.index.model.Service.NAME;
public static final String CLASS = com.dubture.symfony.index.model.Service.CLASS;
public static final Object SYNTHETIC = com.dubture.symfony.index.model.Service.SYNTHETIC;
private IFile file;
/**
* The fully qualified class name.
*/
private String fqcn;
/***
* The namespace only.
*/
private String namespace;
private Scalar scalar;
/**
* The name of the PHP class
*/
private String className;
private String id;
private boolean _isPublic = true;
private List<String> tags = new ArrayList<String>();
private List<String> aliases = new ArrayList<String>();
private IPath path;
private String _stringTags;
private String _stringAliases;
public Service(ModelElement parent, String name) {
super(parent, name);
}
public void setId(String id) {
this.id = id;
}
public Service(IFile resource, String id, String clazz) {
super(null, id);
file = resource;
setFqcn(clazz);
this.id = id;
int lastPart = clazz.lastIndexOf("\\");
if (lastPart == -1) {
namespace = "";
className = clazz;
} else {
namespace = clazz.substring(0,lastPart);
className = clazz.substring(lastPart + 1);
}
}
@Override
public String getElementName() {
if (className != null)
return className;
return super.getElementName();
}
public Service(String id, String phpClass, String path, Scalar scalar) {
super(null, id);
this.namespace = PHPModelUtils.<API key>(phpClass);
this.className = PHPModelUtils.extractElementName(phpClass);
setFqcn(phpClass);
this.id = id;
this.path = new Path(path);
this.scalar = scalar;
}
public Service(String id2, String phpClass, String path2) {
this(id2,phpClass,path2, null);
}
public void setFqcn(String fqcn) {
this.fqcn = fqcn;
}
public Scalar getScalar() {
return scalar;
}
public IFile getFile() {
return file;
}
public String <API key>() {
return fqcn;
}
public String getId() {
return id;
}
// public INamespace getNamespace() {
// return namespace;
public String getClassName() {
return className;
}
public static Service fromIndex(com.dubture.symfony.index.model.Service s) {
Service service = new Service(s.id, s.phpClass, s.path, null);
return service;
}
public IPath getPath() {
return path;
}
@Override
public Object getElementInfo() throws ModelException {
return new FakeTypeElementInfo();
}
@Override
protected Object openWhenClosed(Object info, IProgressMonitor monitor)
throws ModelException {
return new FakeTypeElementInfo();
}
public String getSimpleNamespace() {
return namespace;
}
@Override
public ISourceModule getSourceModule()
{
if (className != null && namespace != null) {
IScriptProject project = getScriptProject();
IDLTKSearchScope scope = project != null ? SearchEngine.createSearchScope(project) : SearchEngine.<API key>(PHPLanguageToolkit.getDefault());
IType[] types = PHPModelAccess.getDefault().findTypes(namespace, className, MatchRule.EXACT, 0, 0, scope, null);
if (types.length >= 1) {
return types[0].getSourceModule();
}
}
return super.getSourceModule();
}
public void setTags(String tags) {
_stringTags = tags;
String[] _tags = tags.split(",");
for (String tag : _tags) {
this.tags.add(tag);
}
}
public void setAliases(String aliases) {
_stringAliases = aliases;
String[] _aliases = aliases.split(",");
for (String alias : _aliases) {
this.aliases.add(alias);
}
}
public List<String> getTags() {
return tags;
}
public String getStringAliases() {
return _stringAliases;
}
public String getStringTags() {
return _stringTags;
}
public String getPublicString() {
return _isPublic ? "true" : "false";
}
public void setPublic(String _public)
{
_isPublic = true;
if (_public != null && _public.equals("false"))
_isPublic = false;
}
public boolean isPublic() {
return _isPublic;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Service))
return false;
Service other = (Service) o;
return id.equals(other.getId());
}
@Override
public int hashCode()
{
return id.hashCode();
}
} |
<?php
namespace SocialiteProviders\Tumblr;
use League\OAuth1\Client\Credentials\TokenCredentials;
use SocialiteProviders\Manager\OAuth1\Server as BaseServer;
use SocialiteProviders\Manager\OAuth1\User;
class Server extends BaseServer
{
/**
* {@inheritdoc}
*/
public function <API key>()
{
return 'https:
}
/**
* {@inheritdoc}
*/
public function urlAuthorization()
{
return 'https:
}
/**
* {@inheritdoc}
*/
public function urlTokenCredentials()
{
return 'https:
}
/**
* {@inheritdoc}
*/
public function urlUserDetails()
{
return 'https://api.tumblr.com/v2/user/info';
}
/**
* {@inheritdoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
// If the API has broke, return nothing
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
}
$data = $data['response']['user'];
$user = new User();
$user->nickname = $data['name'];
// Save all extra data
$used = ['name'];
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* {@inheritdoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
}
$data = $data['response']['user'];
return $data['name'];
}
/**
* {@inheritdoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
}
/**
* {@inheritdoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
}
$data = $data['response']['user'];
return $data['name'];
}
} |
""" import the necessary modules """
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text
# Create a class that will give us an object that we can use to connect to a database
class MySQLConnection(object):
def __init__(self, app, db):
config = {
'host': 'localhost',
'database': 'friends', # we got db as an argument
# my note: The database name above is the only db from the original copy of this document that changes
'user': 'root',
'password': '',
# password is blank because I never set it
'port': '3306' # change the port to match the port your SQL server is running on
}
# this will use the above values to generate the path to connect to your sql database
DATABASE_URI = "mysql://{}:{}@127.0.0.1:{}/{}".format(config['user'], config['password'], config['port'], config['database'])
app.config['<API key>'] = DATABASE_URI
app.config['<API key>'] = True
# establish the connection to database
self.db = SQLAlchemy(app)
# this is the method we will use to query the database
def query_db(self, query, data=None):
result = self.db.session.execute(text(query), data)
if query[0:6].lower() == 'select':
# if the query was a select
# convert the result to a list of dictionaries
list_result = [dict(r) for r in result]
# return the results as a list of dictionaries
return list_result
elif query[0:6].lower() == 'insert':
# if the query was an insert, return the id of the
# commit changes
self.db.session.commit()
# row that was inserted
return result.lastrowid
else:
# if the query was an update or delete, return nothing and commit changes
self.db.session.commit()
# This is the module method to be called by the user in server.py. Make sure to provide the db name!
# My note: best I can tell, these two db's don't change, only the middle one
def MySQLConnector(app, db):
return MySQLConnection(app, db) |
/**
Class with static TDS info
*/
exports.TdsConstants = (function() {
var i, key, value, _len, _len2, _ref, _ref2, _ref3, _ref4;
function TdsConstants() {}
/**
* Versions indexed by the TDS protocol version
*/
TdsConstants.versionsByVersion = {
'7.0': 0x70000000,
'7.1': 0x71000000,
'7.1.1': 0x71000001,
'7.2': 0x72090002,
'7.3.A': 0x730A0003,
'7.3.B': 0x730B0003,
'7.4': 0x74000004
};
/**
* Versions indexed by the server-number in the spec
*/
TdsConstants.versionsByNumber = {};
_ref = TdsConstants.versionsByVersion;
for (value = 0, _len = _ref.length; value < _len; value++) {
key = _ref[value];
TdsConstants.versionsByNumber[value] = key;
}
/**
* States by their number
*/
TdsConstants.statesByNumber = ['INITIAL', 'CONNECTING', 'CONNECTED', 'LOGGING IN', 'LOGGED IN'];
TdsConstants.statesByName = {};
_ref2 = TdsConstants.statesByNumber;
for (value = 0, _len2 = _ref2.length; value < _len2; value++) {
key = _ref2[value];
TdsConstants.statesByName[key] = value;
}
/**
* Data types, indexed by the type in the spec
*/
TdsConstants.dataTypesByType = {
0x1F: {
name: 'NULLTYPE',
sqlType: 'Null',
length: 0
},
0x22: {
name: 'IMAGETYPE',
sqlType: 'Image',
lengthType: 'int32LE',
hasTableName: true,
emptyPossible: true,
hasTextPointer: true
},
0x23: {
name: 'TEXTTYPE',
sqlType: 'Text',
lengthType: 'int32LE',
hasCollation: true,
hasTableName: true,
emptyPossible: true,
hasTextPointer: true
},
0x24: {
name: 'GUIDTYPE',
sqlType: 'UniqueIdentifier'
},
0x25: {
name: 'VARBINARYTYPE',
sqlType: 'VarBinary',
lengthType: 'uint16LE',
legacy: true,
emptyPossible: true
},
0x26: {
name: 'INTNTYPE',
lengthSubstitutes: {
0x01: 0x30,
0x02: 0x34,
0x04: 0x38,
0x08: 0x7F
}
},
0x27: {
name: 'VARCHARTYPE',
sqlType: 'VarChar',
lengthType: 'uint16LE',
legacy: true,
emptyPossible: true
},
0x28: {
name: 'DATENTYPE',
sqlType: 'Date',
length: 3
},
0x29: {
name: 'TIMENTYPE',
sqlType: 'Time',
<API key>: true
},
0x2A: {
name: 'DATETIME2NTYPE',
sqlType: 'DateTime2',
<API key>: true
},
0x2B: {
name: 'DATETIMEOFFSETNTYPE',
sqlType: 'DateTimeOffset',
<API key>: true
},
0x2D: {
name: 'BINARYTYPE',
sqlType: 'Binary',
lengthType: 'uint16LE',
legacy: true,
emptyPossible: true
},
0x2F: {
name: 'CHARTYPE',
sqlType: 'Char',
lengthType: 'uint16LE',
legacy: true,
emptyPossible: true
},
0x30: {
name: 'INT1TYPE',
sqlType: 'TinyInt',
length: 1
},
0x32: {
name: 'BITTYPE',
sqlType: 'Bit',
length: 1
},
0x34: {
name: 'INT2TYPE',
sqlType: 'SmallInt',
length: 2
},
0x37: {
name: 'DECIMALTYPE',
sqlType: 'Decimal',
legacy: true,
<API key>: true
},
0x38: {
name: 'INT4TYPE',
sqlType: 'Int',
length: 4
},
0x3A: {
name: 'DATETIM4TYPE',
sqlType: 'SmallDateTime',
length: 4
},
0x3B: {
name: 'FLT4TYPE',
sqlType: 'Real',
length: 4
},
0x3C: {
name: 'MONEYTYPE',
sqlType: 'Money',
length: 8
},
0x3D: {
name: 'DATETIMETYPE',
sqlType: 'DateTime',
length: 8
},
0x3E: {
name: 'FLT8TYPE',
sqlType: 'Float',
length: 8
},
0x3F: {
name: 'NUMERICTYPE',
sqlType: 'Numeric',
legacy: true,
<API key>: true
},
0x62: {
name: 'SSVARIANTTYPE',
sqlType: 'Sql_Variant',
lengthType: 'int32LE'
},
0x63: {
name: 'NTEXTTYPE',
sqlType: 'NText',
lengthType: 'int32LE',
hasCollation: true,
hasTableName: true,
emptyPossible: true,
hasTextPointer: true
},
0x68: {
name: 'BITNTYPE',
lengthSubstitutes: {
0x00: 0x1F,
0x01: 0x32
}
},
0x6A: {
name: 'DECIMALNTYPE',
sqlType: 'Decimal',
<API key>: true
},
0x6C: {
name: 'NUMERICNTYPE',
sqlType: 'Numeric',
<API key>: true
},
0x6D: {
name: 'FLTNTYPE',
lengthSubstitutes: {
0x04: 0x3B,
0x08: 0x3E
}
},
0x6E: {
name: 'MONEYNTYPE',
lengthSubstitutes: {
0x04: 0x7A,
0x08: 0x3C
}
},
0x6F: {
name: 'DATETIMNTYPE',
lengthSubstitutes: {
0x04: 0x3A,
0x08: 0x3D
}
},
0x7A: {
name: 'MONEY4TYPE',
sqlType: 'SmallMoney',
length: 4
},
0x7F: {
name: 'INT8TYPE',
sqlType: 'BigInt',
length: 8
},
0xA5: {
name: 'BIGVARBINTYPE',
sqlType: 'VarBinary',
lengthType: 'uint16LE',
emptyPossible: true
},
0xA7: {
name: 'BIGVARCHRTYPE',
sqlType: 'VarChar',
lengthType: 'uint16LE',
emptyPossible: true,
hasCollation: true
},
0xAD: {
name: 'BIGBINARYTYPE',
sqlType: 'Binary',
lengthType: 'uint16LE',
emptyPossible: true
},
0xAF: {
name: 'BIGCHARTYPE',
sqlType: 'Char',
lengthType: 'uint16LE',
hasCollation: true,
emptyPossible: true
},
0xE7: {
name: 'NVARCHARTYPE',
sqlType: 'NVarChar',
lengthType: 'uint16LE',
hasCollation: true,
emptyPossible: true
},
0xEF: {
name: 'NCHARTYPE',
sqlType: 'NChar',
lengthType: 'uint16LE',
hasCollation: true,
emptyPossible: true
},
0xF0: {
name: 'UDTTYPE',
sqlType: 'CLR-UDT'
},
0xF1: {
name: 'XMLTYPE',
sqlType: 'XML'
}
};
/**
* Data types indexed be the name in the spec (all-caps)
*/
TdsConstants.dataTypesByName = {};
/**
* Data types indexed by the sql type in the spec (regular and lowercase)
*/
TdsConstants.dataTypesBySqlType = {};
_ref3 = TdsConstants.dataTypesByType;
for (key in _ref3) {
value = _ref3[key];
value.type = key;
TdsConstants.dataTypesByName[value.name] = value;
if ((value.lengthSubstitute != null) && !value.legacy) {
TdsConstants.dataTypesBySqlType[value.sqlType] = value;
TdsConstants.dataTypesBySqlType[value.sqlType.toLowerCase()] = value;
}
}
/**
* RPC special procedures array, by id in the spec
*/
TdsConstants.<API key> = ['None', 'Sp_Cursor', 'Sp_CursorOpen', 'Sp_CursorPrepare', 'Sp_CursorExecute', 'Sp_CursorPrepExec', 'Sp_CursorUnprepare', 'Sp_CursorFetch', 'Sp_CursorOption', 'Sp_CursorClose', 'Sp_ExecuteSql', 'Sp_Prepare', 'Sp_Execute', 'Sp_PrepExec', 'Sp_PrepExecRpc', 'Sp_Unprepare'];
/**
* RPC special procedures by name (regular and lower cased) in the spec
*/
TdsConstants.<API key> = {};
for (i = 0, _ref4 = TdsConstants.<API key>.length - 1; 0 <= _ref4 ? i <= _ref4 : i >= _ref4; 0 <= _ref4 ? i++ : i
TdsConstants.<API key>[TdsConstants.<API key>[i]] = i;
TdsConstants.<API key>[TdsConstants.<API key>[i].toLowerCase()] = i;
}
TdsConstants.<API key> = {
1: {
name: 'Database',
oldValue: 'string',
newValue: 'string'
},
2: {
name: 'Language',
oldValue: 'string',
newValue: 'string'
},
3: {
name: 'Character Set',
oldValue: 'string',
newValue: 'string'
},
4: {
name: 'Packet Size',
oldValue: 'string',
newValue: 'string'
},
5: {
name: 'Unicode data sorting local id',
newValue: 'string'
},
6: {
name: 'Unicode data sorting comparison flags',
newValue: 'string'
},
7: {
name: 'SQL Collation',
oldValue: 'bytes',
newValue: 'bytes'
},
8: {
name: 'Begin Transaction',
newValue: 'bytes'
},
9: {
name: 'Commit Transaction',
oldValue: 'bytes',
newValue: 'byte'
},
10: {
name: 'Rollback Transaction',
oldValue: 'bytes'
},
11: {
name: 'Enlist DTC Transaction',
oldValue: 'bytes'
},
12: {
name: 'Defect Transaction',
newValue: 'bytes'
},
13: {
name: 'Database Mirroring Partner',
newValue: 'string'
},
15: {
name: 'Promote Transaction',
newValue: 'longbytes'
},
16: {
name: 'Transaction Manager Address',
newValue: 'bytes'
},
17: {
name: 'Transaction Ended',
oldValue: 'bytes'
},
18: {
name: 'Reset Completion Acknowledgement'
},
19: {
name: 'User Instance Name',
newValue: 'string'
},
20: {
name: 'Routing',
oldValue: '2byteskip',
newValue: 'shortbytes'
}
};
return TdsConstants;
})(); |
const jsonSchema = require('../utils/json-schema');
const models = require('../../../../../models');
const {ValidationError} = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');
const messages = {
<API key>: 'Invalid filter in visibility_filter property'
};
const validateVisibility = async function (frame) {
if (!frame.data.pages || !frame.data.pages[0]) {
return Promise.resolve();
}
// validate visibility - not done at schema level because this can be an NQL query so needs model access
const visibility = frame.data.pages[0].visibility;
const visibilityFilter = frame.data.pages[0].visibility_filter;
if (visibility) {
if (!['public', 'members', 'paid'].includes(visibility)) {
// check filter is valid
try {
await models.Member.findPage({filter: visibilityFilter, limit: 1});
return Promise.resolve();
} catch (err) {
return Promise.reject(new ValidationError({
message: tpl(messages.<API key>),
property: 'visibility_filter'
}));
}
}
return Promise.resolve();
}
};
module.exports = {
add(apiConfig, frame) {
return jsonSchema.validate(...arguments).then(() => {
return validateVisibility(frame);
});
},
edit(apiConfig, frame) {
return jsonSchema.validate(...arguments).then(() => {
return validateVisibility(frame);
});
}
}; |
// ViewController.h
// BFRadialWaveView
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end |
package jenkins.model;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Descriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import edu.umd.cs.findbugs.annotations.NonNull;
/**
* Convenient base class for extensions that contributes to the system configuration page but nothing
* else, or to manage the global configuration of a plugin implementing several extension points.
*
* <p>
* All {@link Descriptor}s are capable of contributing fragment to the system config page. If you are
* implementing other extension points that need to expose some global configuration, you can do so
* with {@code global.groovy} or {@code global.jelly} from your {@link Descriptor} instance. However
* each {@code global.*} file will appear as its own section in the global configuration page.
*
* <p>
* An option to present a single section for your plugin in the Jenkins global configuration page is
* to use this class to manage the configuration for your plugin and its extension points. To access
* properties defined in your GlobalConfiguration subclass, here are two possibilities:
* <ul><li>@{@link javax.inject.Inject} into your other {@link hudson.Extension}s (so this does <i>not</i> work
* for classes not annotated with {@link hudson.Extension})</li>
* <li>access it via a call to {@code ExtensionList.lookupSingleton(<your GlobalConfiguration subclass>.class)}</li></ul>
*
* <p>
* While an implementation might store its actual configuration data in various ways,
* meaning {@link #configure(StaplerRequest, JSONObject)} must be overridden,
* in the normal case you would simply define persistable fields with getters and setters.
* The {@code config} view would use data-bound controls like {@code f:entry}.
* Then make sure your constructor calls {@link #load} and your setters call {@link #save}.
*
* <h2>Views</h2>
* <p>
* Subtypes of this class should define a {@code config.groovy} file or {@code config.jelly} file
* that gets pulled into the system configuration page.
* Typically its contents should be wrapped in an {@code f:section}.
*
* @author Kohsuke Kawaguchi
* @since 1.425
*/
public abstract class GlobalConfiguration extends Descriptor<GlobalConfiguration> implements ExtensionPoint, Describable<GlobalConfiguration> {
protected GlobalConfiguration() {
super(self());
}
@Override
public final Descriptor<GlobalConfiguration> getDescriptor() {
return this;
}
@Override
public String getGlobalConfigPage() {
return getConfigPage();
}
/**
* By default, calls {@link StaplerRequest#bindJSON(Object, JSONObject)},
* appropriate when your implementation has getters and setters for all fields.
* <p>{@inheritDoc}
*/
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
req.bindJSON(this, json);
return true;
}
/**
* Returns all the registered {@link GlobalConfiguration} descriptors.
*/
public static @NonNull ExtensionList<GlobalConfiguration> all() {
return Jenkins.get().getDescriptorList(GlobalConfiguration.class);
}
} |
(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](<API key>.md#<API key>).)
# What Is Google C++ Mocking Framework? #
When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).
**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:
* **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
* **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.
If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.
**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http:
Using Google Mock involves three basic steps:
1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.
# Why Google Mock? #
While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:
* Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distances to avoid it.
* The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad-hoc restrictions.
* The knowledge you gained from using one mock doesn't transfer to the next.
In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.
Google Mock was built to help C++ programmers. It was inspired by [jMock](http:
* You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
* Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
* Your tests are brittle as some resources they use are unreliable (e.g. the network).
* You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
* You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
* You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.
We encourage you to use Google Mock as:
* a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
* a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.
# Getting Started #
Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go.
# A Case for Mock Turtles #
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
class Turtle {
virtual ~Turtle() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
virtual void Turn(int degrees) = 0;
virtual void GoTo(int x, int y) = 0;
virtual int GetX() const = 0;
virtual int GetY() const = 0;
};
(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)
You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.
Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.
# Writing the Mock Class #
If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)
## How to Define It ##
Using the `Turtle` interface as example, here are the simple steps you need to follow:
1. Derive a class `MockTurtle` from `Turtle`.
1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](CookBook.md#<API key>), it's much more involved). Count how many arguments it has.
1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
1. Repeat until all virtual functions you want to mock are done.
After the process, you should have something like:
#include "gmock/gmock.h" // Brings in Google Mock.
class MockTurtle : public Turtle {
public:
MOCK_METHOD0(PenUp, void());
MOCK_METHOD0(PenDown, void());
MOCK_METHOD1(Forward, void(int distance));
MOCK_METHOD1(Turn, void(int degrees));
MOCK_METHOD2(GoTo, void(int x, int y));
MOCK_CONST_METHOD0(GetX, int());
MOCK_CONST_METHOD0(GetY, int());
};
You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.
**Tip:** If even this is too much work for you, you'll find the
`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line
tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it,
and it will print the definition of the mock class for you. Due to the
complexity of the C++ language, this script may not always work, but
it can be quite handy when it does. For more details, read the [user documentation](../scripts/generator/README).
## Where to Put It ##
When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.
# Using Mocks in Tests #
Once you have a mock class, using it is easy. The typical work flow is:
1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
1. Create some mock objects.
1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
Here's an example:
#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast; //
TEST(PainterTest, CanDrawSomething) {
MockTurtle turtle; //
EXPECT_CALL(turtle, PenDown()) //
.Times(AtLeast(1));
Painter painter(&turtle); //
EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
} //
int main(int argc, char** argv) {
// The following line must be executed to initialize Google Mock
// (and Google Test) before running the tests.
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:
path/to/my_test.cc:119: Failure
Actual function call count doesn't match this expectation:
Actually: never called;
Expected: called at least once.
**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.
**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.
**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.
This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.
Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.
## Using Google Mock with Any Testing Framework ##
If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or
[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to:
int main(int argc, char** argv) {
// The following line causes Google Mock to throw an exception on failure,
// which will be interpreted by your testing framework as a test failure.
::testing::GTEST_FLAG(throw_on_failure) = true;
::testing::InitGoogleMock(&argc, argv);
whatever your testing framework requires ...
}
This approach has a catch: it makes Google Mock throw an exception
from a mock object's destructor sometimes. With some compilers, this
sometimes causes the test program to crash. You'll still be able to
notice that the test has failed, but it's not a graceful failure.
A better solution is to use Google Test's
[event listener API](../../googletest/docs/AdvancedGuide.md#<API key>)
to report a test failure to your testing framework properly. You'll need to
implement the `OnTestPartResult()` method of the event listener interface, but it
should be straightforward.
If this turns out to be too much work, we suggest that you stick with
Google Test, which works with Google Mock seamlessly (in fact, it is
technically part of Google Mock.). If there is a reason that you
cannot use Google Test, please let us know.
# Setting Expectations #
The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."
## General Syntax ##
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
EXPECT_CALL(mock_object, method(matchers))
.Times(cardinality)
.WillOnce(action)
.WillRepeatedly(action);
The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)
The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.
This syntax is designed to make an expectation read like English. For example, you can probably guess that
using ::testing::Return;...
EXPECT_CALL(turtle, GetX())
.Times(5)
.WillOnce(Return(100))
.WillOnce(Return(150))
.WillRepeatedly(Return(200));
says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).
**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.
## Matchers: What Arguments Do We Expect? ##
When a mock function takes arguments, we must specify what arguments we are expecting; for example:
// Expects the turtle to move forward by 100 units.
EXPECT_CALL(turtle, Forward(100));
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
using ::testing::_;
// Expects the turtle to move forward.
EXPECT_CALL(turtle, Forward(_));
`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.
A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
using ::testing::Ge;...
EXPECT_CALL(turtle, Forward(Ge(100)));
This checks that the turtle will be told to go forward by at least 100 units.
## Cardinalities: How Many Times Will It Be Called? ##
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.
An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](CheatSheet.md).
The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
* If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
* If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.
**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?
## Actions: What Should It Do? ##
Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.
First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). In addition, in C++ 11 and above, a mock function whose return type is <API key> (i.e. has a default constructor) has a default action of returning a default-constructed value. If you don't say anything, this behavior will be used.
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
using ::testing::Return;...
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillOnce(Return(300));
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
using ::testing::Return;...
EXPECT_CALL(turtle, GetY())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillRepeatedly(Return(300));
says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.
Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](CheatSheet.md#actions).
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
int n = 100;
EXPECT_CALL(turtle, GetX())
.Times(4)
.WillRepeatedly(Return(n++));
Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](CookBook.md).
Time for another quiz! What do you think the following means?
using ::testing::Return;...
EXPECT_CALL(turtle, GetY())
.Times(4)
.WillOnce(Return(100));
Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.
## Using Multiple Expectations ##
So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an <API key> failure. Here's an example:
using ::testing::_;...
EXPECT_CALL(turtle, Forward(_)); //
EXPECT_CALL(turtle, Forward(10)) //
.Times(2);
If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.
**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.
## Ordered vs Unordered Calls ##
By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
using ::testing::InSequence;...
TEST(FooTest, DrawsLineSegment) {
{
InSequence dummy;
EXPECT_CALL(turtle, PenDown());
EXPECT_CALL(turtle, Forward(100));
EXPECT_CALL(turtle, PenUp());
}
Foo();
}
By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.
In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.
(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook.md#<API key>).)
## All Expectations Are Sticky (Unless Said Otherwise) ##
Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
using ::testing::_;...
EXPECT_CALL(turtle, GoTo(_, _)) //
.Times(AnyNumber());
EXPECT_CALL(turtle, GoTo(0, 0)) //
.Times(2);
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.
This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).
Simple? Let's see if you've really understood it: what does the following code say?
using ::testing::Return;
for (int i = n; i > 0; i
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(10*i));
}
If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
using ::testing::Return;
for (int i = n; i > 0; i
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(10*i))
.RetiresOnSaturation();
}
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
using ::testing::InSequence;
using ::testing::Return;
{
InSequence s;
for (int i = 1; i <= n; i++) {
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(10*i))
.RetiresOnSaturation();
}
}
By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).
## Uninteresting Calls ##
A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.
In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.
# What Now? #
Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.
Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. |
# Integrations
## Salesforce Fusion IAM
- The **iam-get-user** command will now try to retrieve user details by ID, then by username, then by email.
# Mappers
## User Profile - Salesforce Fusion (Incoming)
- Added mapping to `Username` Cortex XSOAR field from `Name` SalesforceFusion field.
## User Profile - Salesforce Fusion (Outgoing)
- Changed the mapping of `Name` from `displayname` to `username`. |
<?php
namespace Mougrim\Logger\Layout\Pattern;
use Mougrim\Logger\Logger;
use Mougrim\Logger\LoggerPolicy;
use Mougrim\Logger\LoggerRender;
class PatternGlobal implements PatternInterface
{
private $path = [];
public function __construct($path)
{
if ($path) {
$this->path = preg_split('/\./', $path, -1, PREG_SPLIT_NO_EMPTY);
}
if (!$this->path) {
LoggerPolicy::<API key>('path is required');
$this->path = [];
}
}
public function render(Logger $logger, $level, $message, \Exception $throwable = null)
{
$current = $GLOBALS;
foreach ($this->path as $key) {
if (!isset($current[$key])) {
$current = null;
break;
}
$current = $current[$key];
}
return LoggerRender::render($current);
}
} |
.area-selection {
background-color: rgba(74, 144, 217, 0.5);
border: 1px solid rgba(74, 144, 217, 1);
} |
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:12:"nombre_curso";s:4:"type";s:6:"string";s:6:"length";i:45;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;}}'); |
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometry - normals</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 5px;
font-family: Monospace;
font-size: 13px;
text-align: center;
color: #ffffff;
}
a {
color: #ffffff;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
<a href="https://threejs.org" target="_blank">three.js</a> - geometry - normals</a>
<p>
<span>Yellow Arrows: Face Normals</span><br>
<span>Red Arrows: Vertex Normals</span>
</p>
</div>
<script src="../build/three.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="./js/libs/dat.gui.min.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
var container, stats, gui;
var camera, controls, scene, renderer;
var mesh, geometry;
var geometries = [
{ type: 'BoxGeometry', geometry: new THREE.BoxGeometry( 200, 200, 200, 2, 2, 2 ) },
{ type: 'CircleGeometry', geometry: new THREE.CircleGeometry( 200, 32 ) },
{ type: 'CylinderGeometry', geometry: new THREE.CylinderGeometry( 75, 75, 200, 8, 8 ) } ,
{ type: 'IcosahedronGeometry', geometry: new THREE.IcosahedronGeometry( 100, 1 ) },
{ type: 'OctahedronGeometry', geometry: new THREE.OctahedronGeometry( 200, 0 ) },
{ type: 'PlaneGeometry', geometry: new THREE.PlaneGeometry( 200, 200, 4, 4 ) },
{ type: 'RingGeometry', geometry: new THREE.RingGeometry( 32, 64, 16 ) },
{ type: 'SphereGeometry', geometry: new THREE.SphereGeometry( 100, 12, 12 ) },
{ type: 'TorusGeometry', geometry: new THREE.TorusGeometry( 64, 16, 12, 12 ) },
{ type: 'TorusKnotGeometry', geometry: new THREE.TorusKnotGeometry( 64, 16 ) }
];
var options = {
Geometry: 0
};
var material = new THREE.MeshBasicMaterial( { color: 0xfefefe, wireframe: true, opacity: 0.5 } );
init();
animate();
function addMesh() {
if ( mesh !== undefined ) {
scene.remove( mesh );
geometry.dispose();
}
geometry = geometries[ options.Geometry ].geometry;
// scale geometry to a uniform size
geometry.<API key>();
var scaleFactor = 160 / geometry.boundingSphere.radius;
geometry.scale( scaleFactor, scaleFactor, scaleFactor );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
var faceNormalsHelper = new THREE.FaceNormalsHelper( mesh, 10 );
mesh.add( faceNormalsHelper );
var vertexNormalsHelper = new THREE.VertexNormalsHelper( mesh, 10 );
mesh.add( vertexNormalsHelper );
}
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 500;
scene = new THREE.Scene();
addMesh();
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
var geometries = {
BoxGeometry: 0,
CircleGeometry: 1,
CylinderGeometry: 2,
IcosahedronGeometry: 3,
OctahedronGeometry: 4,
PlaneGeometry: 5,
RingGeometry: 6,
SphereGeometry: 7,
TorusGeometry: 8,
TorusKnotGeometry: 9
};
gui = new dat.GUI( { width: 350 } );
gui.add( options, 'Geometry', geometries ).onChange( function( value ) {
addMesh();
} );
controls = new THREE.OrbitControls( camera, renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.<API key>();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
<API key>( animate );
render();
stats.update();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html> |
#include "PreProcessor.h"
#define DIMENSION 3
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <algorithm>
#include "FEMTree.h"
#include "MyMiscellany.h"
#include "CmdLineParser.h"
#include "MAT.h"
#include "Geometry.h"
#include "Ply.h"
#include "PointStreamData.h"
MessageWriter messageWriter;
cmdLineParameter< char* >
In( "in" ) ,
Out( "out" );
cmdLineParameter< int >
Smooth( "smooth" , 5 );
cmdLineParameter< float >
Trim( "trim" ) ,
IslandAreaRatio( "aRatio" , 0.001f );
cmdLineReadable
PolygonMesh( "polygonMesh" ) ,
Long( "long" ) ,
Verbose( "verbose" );
cmdLineReadable* params[] =
{
&In , &Out , &Trim , &PolygonMesh , &Smooth , &IslandAreaRatio , &Verbose , &Long ,
NULL
};
void ShowUsage( char* ex )
{
printf( "Usage: %s\n" , ex );
printf( "\t --%s <input polygon mesh>\n" , In.name );
printf( "\t --%s <trimming value>\n" , Trim.name );
printf( "\t[--%s <ouput polygon mesh>]\n" , Out.name );
printf( "\t[--%s <smoothing iterations>=%d]\n" , Smooth.name , Smooth.value );
printf( "\t[--%s <relative area of islands>=%f]\n" , IslandAreaRatio.name , IslandAreaRatio.value );
printf( "\t[--%s]\n" , PolygonMesh.name );
printf( "\t[--%s]\n" , Long.name );
printf( "\t[--%s]\n" , Verbose.name );
}
template< typename Index >
struct EdgeKey
{
Index key1 , key2;
EdgeKey( Index k1=0 , Index k2=0 ) : key1(k1) , key2(k2) {}
bool operator == ( const EdgeKey &key ) const { return key1==key.key1 && key2==key.key2; }
#if 1
struct Hasher{ size_t operator()( const EdgeKey &key ) const { return (size_t)( key.key1 * key.key2 ); } };
#else
struct Hasher{ size_t operator()( const EdgeKey &key ) const { return key.key1 ^ key.key2; } };
#endif
};
template< typename Real , typename ... VertexData >
PlyVertexWithData< float , DIMENSION , <API key>< float , PointStreamValue< float > , VertexData ... > > InterpolateVertices( const PlyVertexWithData< float , DIMENSION , <API key>< float , PointStreamValue< float > , VertexData ... > >& v1 , const PlyVertexWithData< float , DIMENSION , <API key>< float , PointStreamValue< float > , VertexData ... > >& v2 , Real value )
{
if( v1.data.template data<0>()==v2.data.template data<0>() ) return (v1+v2)/Real(2.);
Real dx = ( v1.data.template data<0>()-value ) / ( v1.data.template data<0>()-v2.data.template data<0>() );
return v1*(1.f-dx) + v2*dx;
}
template< typename Real , typename Index , typename ... VertexData >
void SmoothValues( std::vector< PlyVertexWithData< float , DIMENSION , <API key>< float , PointStreamValue< float > , VertexData ... > > >& vertices , const std::vector< std::vector< Index > >& polygons )
{
std::vector< int > count( vertices.size() );
std::vector< Real > sums( vertices.size() , 0 );
for( size_t i=0 ; i<polygons.size() ; i++ )
{
int sz = int(polygons[i].size());
for( int j=0 ; j<sz ; j++ )
{
int j1 = j , j2 = (j+1)%sz;
Index v1 = polygons[i][j1] , v2 = polygons[i][j2];
count[v1]++ , count[v2]++;
sums[v1] += vertices[v2].data.template data<0>() , sums[v2] += vertices[v1].data.template data<0>();
}
}
for( size_t i=0 ; i<vertices.size() ; i++ ) vertices[i].data.template data<0>() = ( sums[i] + vertices[i].data.template data<0>() ) / ( count[i] + 1 );
}
template< class Real , typename Index , typename ... VertexData >
void SplitPolygon
(
const std::vector< Index >& polygon ,
std::vector< PlyVertexWithData< float , DIMENSION , <API key>< float , PointStreamValue< float > , VertexData ... > > >& vertices ,
std::vector< std::vector< Index > >* ltPolygons , std::vector< std::vector< Index > >* gtPolygons ,
std::vector< bool >* ltFlags , std::vector< bool >* gtFlags ,
std::unordered_map< EdgeKey< Index > , Index , typename EdgeKey< Index >::Hasher >& vertexTable,
Real trimValue
)
{
int sz = int( polygon.size() );
std::vector< bool > gt( sz );
int gtCount = 0;
for( int j=0 ; j<sz ; j++ )
{
gt[j] = ( vertices[ polygon[j] ].data.template data<0>()>trimValue );
if( gt[j] ) gtCount++;
}
if ( gtCount==sz ){ if( gtPolygons ) gtPolygons->push_back( polygon ) ; if( gtFlags ) gtFlags->push_back( false ); }
else if( gtCount==0 ){ if( ltPolygons ) ltPolygons->push_back( polygon ) ; if( ltFlags ) ltFlags->push_back( false ); }
else
{
int start;
for( start=0 ; start<sz ; start++ ) if( gt[start] && !gt[(start+sz-1)%sz] ) break;
bool gtFlag = true;
std::vector< Index > poly;
// Add the initial vertex
{
int j1 = (start+int(sz)-1)%sz , j2 = start;
Index v1 = polygon[j1] , v2 = polygon[j2] , vIdx;
typename std::unordered_map< EdgeKey< Index > , Index , typename EdgeKey< Index >::Hasher >::iterator iter = vertexTable.find( EdgeKey< Index >(v1,v2) );
if( iter==vertexTable.end() )
{
vertexTable[ EdgeKey< Index >(v1,v2) ] = vIdx = (Index)vertices.size();
vertices.push_back( InterpolateVertices( vertices[v1] , vertices[v2] , trimValue ) );
}
else vIdx = iter->second;
poly.push_back( vIdx );
}
for( int _j=0 ; _j<=sz ; _j++ )
{
int j1 = (_j+start+sz-1)%sz , j2 = (_j+start)%sz;
Index v1 = polygon[j1] , v2 = polygon[j2];
if( gt[j2]==gtFlag ) poly.push_back( v2 );
else
{
Index vIdx;
typename std::unordered_map< EdgeKey< Index > , Index , typename EdgeKey< Index >::Hasher >::iterator iter = vertexTable.find( EdgeKey< Index >(v1,v2) );
if( iter==vertexTable.end() )
{
vertexTable[ EdgeKey< Index >(v1,v2) ] = vIdx = (Index)vertices.size();
vertices.push_back( InterpolateVertices( vertices[v1] , vertices[v2] , trimValue ) );
}
else vIdx = iter->second;
poly.push_back( vIdx );
if( gtFlag ){ if( gtPolygons ) gtPolygons->push_back( poly ) ; if( ltFlags ) ltFlags->push_back( true ); }
else { if( ltPolygons ) ltPolygons->push_back( poly ) ; if( gtFlags ) gtFlags->push_back( true ); }
poly.clear() , poly.push_back( vIdx ) , poly.push_back( v2 );
gtFlag = !gtFlag;
}
}
}
}
template< class Real , typename Index , class Vertex >
void Triangulate( const std::vector< Vertex >& vertices , const std::vector< std::vector< Index > >& polygons , std::vector< std::vector< Index > >& triangles )
{
triangles.clear();
for( size_t i=0 ; i<polygons.size() ; i++ )
if( polygons.size()>3 )
{
std::vector< Point< Real , DIMENSION > > _vertices( polygons[i].size() );
for( int j=0 ; j<int( polygons[i].size() ) ; j++ ) _vertices[j] = vertices[ polygons[i][j] ].point;
std::vector< TriangleIndex< Index > > _triangles = <API key>< Index , Real , DIMENSION >( ( ConstPointer( Point< Real , DIMENSION > ) )GetPointer( _vertices ) , _vertices.size() );
// Add the triangles to the mesh
size_t idx = triangles.size();
triangles.resize( idx+_triangles.size() );
for( int j=0 ; j<int(_triangles.size()) ; j++ )
{
triangles[idx+j].resize(3);
for( int k=0 ; k<3 ; k++ ) triangles[idx+j][k] = polygons[i][ _triangles[j].idx[k] ];
}
}
else if( polygons[i].size()==3 ) triangles.push_back( polygons[i] );
}
template< class Real , typename Index , class Vertex >
double PolygonArea( const std::vector< Vertex >& vertices , const std::vector< Index >& polygon )
{
if( polygon.size()<3 ) return 0.;
else if( polygon.size()==3 ) return Area( vertices[polygon[0]].point , vertices[polygon[1]].point , vertices[polygon[2]].point );
else
{
Point< Real , DIMENSION > center;
for( size_t i=0 ; i<polygon.size() ; i++ ) center += vertices[ polygon[i] ].point;
center /= Real( polygon.size() );
double area = 0;
for( size_t i=0 ; i<polygon.size() ; i++ ) area += Area( center , vertices[ polygon[i] ].point , vertices[ polygon[ (i+1)%polygon.size() ] ].point );
return area;
}
}
template< typename Index , class Vertex >
void <API key>( std::vector< Vertex >& vertices , std::vector< std::vector< Index > >& polygons )
{
std::unordered_map< Index, Index > vMap;
std::vector< bool > vertexFlags( vertices.size() , false );
for( size_t i=0 ; i<polygons.size() ; i++ ) for( size_t j=0 ; j<polygons[i].size() ; j++ ) vertexFlags[ polygons[i][j] ] = true;
Index vCount = 0;
for( Index i=0 ; i<(Index)vertices.size() ; i++ ) if( vertexFlags[i] ) vMap[i] = vCount++;
for( size_t i=0 ; i<polygons.size() ; i++ ) for( size_t j=0 ; j<polygons[i].size() ; j++ ) polygons[i][j] = vMap[ polygons[i][j] ];
std::vector< Vertex > _vertices( vCount );
for( Index i=0 ; i<(Index)vertices.size() ; i++ ) if( vertexFlags[i] ) _vertices[ vMap[i] ] = vertices[i];
vertices = _vertices;
}
template< typename Index >
void <API key>( const std::vector< std::vector< Index > >& polygons , std::vector< std::vector< Index > >& components )
{
std::vector< Index > polygonRoots( polygons.size() );
for( size_t i=0 ; i<polygons.size() ; i++ ) polygonRoots[i] = (Index)i;
std::unordered_map< EdgeKey< Index > , Index , typename EdgeKey< Index >::Hasher > edgeTable;
for( size_t i=0 ; i<polygons.size() ; i++ )
{
int sz = int( polygons[i].size() );
for( int j=0 ; j<sz ; j++ )
{
int j1 = j , j2 = (j+1)%sz;
Index v1 = polygons[i][j1] , v2 = polygons[i][j2];
EdgeKey< Index > eKey = EdgeKey< Index >(v1,v2);
typename std::unordered_map< EdgeKey< Index > , Index , typename EdgeKey< Index >::Hasher >::iterator iter = edgeTable.find(eKey);
if( iter==edgeTable.end() ) edgeTable[ eKey ] = (Index)i;
else
{
Index p = iter->second;
while( polygonRoots[p]!=p )
{
Index temp = polygonRoots[p];
polygonRoots[p] = (Index)i;
p = temp;
}
polygonRoots[p] = (Index)i;
}
}
}
for( size_t i=0 ; i<polygonRoots.size() ; i++ )
{
Index p = (Index)i;
while( polygonRoots[p]!=p ) p = polygonRoots[p];
Index root = p;
p = (Index)i;
while( polygonRoots[p]!=p )
{
Index temp = polygonRoots[p];
polygonRoots[p] = root;
p = temp;
}
}
int cCount = 0;
std::unordered_map< Index , Index > vMap;
for( Index i=0 ; i<(Index)polygonRoots.size() ; i++ ) if( polygonRoots[i]==i ) vMap[i] = cCount++;
components.resize( cCount );
for( Index i=0 ; i<(Index)polygonRoots.size() ; i++ ) components[ vMap[ polygonRoots[i] ] ].push_back(i);
}
template< typename Index , typename ... VertexData >
int Execute( void )
{
typedef PlyVertexWithData< float , DIMENSION , <API key>< float , PointStreamValue< float > , VertexData ... > > Vertex;
float min , max;
std::vector< Vertex > vertices;
std::vector< std::vector< Index > > polygons;
int ft;
std::vector< std::string > comments;
PlyReadPolygons< Vertex >( In.value , vertices , polygons , Vertex::PlyReadProperties() , Vertex::PlyReadNum , ft , comments );
for( int i=0 ; i<Smooth.value ; i++ ) SmoothValues< float , Index >( vertices , polygons );
min = max = vertices[0].data.template data<0>();
for( size_t i=0 ; i<vertices.size() ; i++ ) min = std::min< float >( min , vertices[i].data.template data<0>() ) , max = std::max< float >( max , vertices[i].data.template data<0>() );
std::unordered_map< EdgeKey< Index > , Index , typename EdgeKey< Index >::Hasher > vertexTable;
std::vector< std::vector< Index > > ltPolygons , gtPolygons;
std::vector< bool > ltFlags , gtFlags;
messageWriter( comments , "*********************************************\n" );
messageWriter( comments , "*********************************************\n" );
messageWriter( comments , "** Running Surface Trimmer (Version %s) **\n" , VERSION );
messageWriter( comments , "*********************************************\n" );
messageWriter( comments , "*********************************************\n" );
char str[1024];
for( int i=0 ; params[i] ; i++ )
if( params[i]->set )
{
params[i]->writeValue( str );
if( strlen( str ) ) messageWriter( comments , "\t--%s %s\n" , params[i]->name , str );
else messageWriter( comments , "\t--%s\n" , params[i]->name );
}
if( Verbose.set ) printf( "Value Range: [%f,%f]\n" , min , max );
double t=Time();
for( size_t i=0 ; i<polygons.size() ; i++ ) SplitPolygon( polygons[i] , vertices , <Polygons , >Polygons , <Flags , >Flags , vertexTable , Trim.value );
if( IslandAreaRatio.value>0 )
{
std::vector< std::vector< Index > > _ltPolygons , _gtPolygons;
std::vector< std::vector< Index > > ltComponents , gtComponents;
<API key>( ltPolygons , ltComponents );
<API key>( gtPolygons , gtComponents );
std::vector< double > ltAreas( ltComponents.size() , 0. ) , gtAreas( gtComponents.size() , 0. );
std::vector< bool > ltComponentFlags( ltComponents.size() , false ) , gtComponentFlags( gtComponents.size() , false );
double area = 0.;
for( size_t i=0 ; i<ltComponents.size() ; i++ )
{
for( size_t j=0 ; j<ltComponents[i].size() ; j++ )
{
ltAreas[i] += PolygonArea< float , Index , Vertex >( vertices , ltPolygons[ ltComponents[i][j] ] );
ltComponentFlags[i] = ( ltComponentFlags[i] || ltFlags[ ltComponents[i][j] ] );
}
area += ltAreas[i];
}
for( size_t i=0 ; i<gtComponents.size() ; i++ )
{
for( size_t j=0 ; j<gtComponents[i].size() ; j++ )
{
gtAreas[i] += PolygonArea< float , Index , Vertex >( vertices , gtPolygons[ gtComponents[i][j] ] );
gtComponentFlags[i] = ( gtComponentFlags[i] || gtFlags[ gtComponents[i][j] ] );
}
area += gtAreas[i];
}
for( size_t i=0 ; i<ltComponents.size() ; i++ )
{
if( ltAreas[i]<area*IslandAreaRatio.value && ltComponentFlags[i] ) for( size_t j=0 ; j<ltComponents[i].size() ; j++ ) _gtPolygons.push_back( ltPolygons[ ltComponents[i][j] ] );
else for( size_t j=0 ; j<ltComponents[i].size() ; j++ ) _ltPolygons.push_back( ltPolygons[ ltComponents[i][j] ] );
}
for( size_t i=0 ; i<gtComponents.size() ; i++ )
{
if( gtAreas[i]<area*IslandAreaRatio.value && gtComponentFlags[i] ) for( size_t j=0 ; j<gtComponents[i].size() ; j++ ) _ltPolygons.push_back( gtPolygons[ gtComponents[i][j] ] );
else for( size_t j=0 ; j<gtComponents[i].size() ; j++ ) _gtPolygons.push_back( gtPolygons[ gtComponents[i][j] ] );
}
ltPolygons = _ltPolygons , gtPolygons = _gtPolygons;
}
if( !PolygonMesh.set )
{
{
std::vector< std::vector< Index > > polys = ltPolygons;
Triangulate< float , Index , Vertex >( vertices , ltPolygons , polys ) , ltPolygons = polys;
}
{
std::vector< std::vector< Index > > polys = gtPolygons;
Triangulate< float , Index , Vertex >( vertices , gtPolygons , polys ) , gtPolygons = polys;
}
}
<API key>( vertices , gtPolygons );
char comment[1024];
sprintf( comment , "#Trimmed In: %9.1f (s)" , Time()-t );
comments.push_back( comment );
if( Out.set )
if( !PlyWritePolygons< Vertex >( Out.value , vertices , gtPolygons , Vertex::PlyWriteProperties() , Vertex::PlyWriteNum , ft , comments ) )
ERROR_OUT( "Could not write mesh to: " , Out.value );
return EXIT_SUCCESS;
}
int main( int argc , char* argv[] )
{
cmdLineParse( argc-1 , &argv[1] , params );
messageWriter.echoSTDOUT = Verbose.set;
if( !In.set || !Trim.set )
{
ShowUsage( argv[0] );
return EXIT_FAILURE;
}
typedef <API key>< float , PointStreamValue< float > , PointStreamNormal< float , DIMENSION > , PointStreamColor< float > > VertexData;
typedef PlyVertexWithData< float , DIMENSION , VertexData > Vertex;
bool readFlags[ Vertex::PlyReadNum ];
if( !PlyReadHeader( In.value , Vertex::PlyReadProperties() , Vertex::PlyReadNum , readFlags ) ) ERROR_OUT( "Failed to read ply header: " , In.value );
bool hasValue = VertexData::<API key>< 0 >( readFlags + DIMENSION );
bool hasNormal = VertexData::<API key>< 1 >( readFlags + DIMENSION );
bool hasColor = VertexData::<API key>< 2 >( readFlags + DIMENSION );
if( !hasValue ) ERROR_OUT( "Ply file does not contain values" );
if( Long.set )
if( hasColor )
if( hasNormal ) return Execute< long long , PointStreamNormal< float , DIMENSION > , PointStreamColor< float > >();
else return Execute< long long , PointStreamColor< float > >();
else
if( hasNormal ) return Execute< long long , PointStreamNormal< float , DIMENSION > >();
else return Execute< long long >();
else
if( hasColor )
if( hasNormal ) return Execute< int , PointStreamNormal< float , DIMENSION > , PointStreamColor< float > >();
else return Execute< int , PointStreamColor< float > >();
else
if( hasNormal ) return Execute< int , PointStreamNormal< float , DIMENSION > >();
else return Execute< int >();
} |
/**
* @module ember-paper
*/
import Component from '@ember/component';
import { run } from '@ember/runloop';
import { computed } from '@ember/object';
import { htmlSafe } from '@ember/string';
import layout from '../templates/components/paper-toast-inner';
import TransitionMixin from '<API key>/mixins/transition-mixin';
import { invokeAction } from 'ember-invoke-action';
/* global Hammer */
/**
* @class PaperToastInner
* @extends Ember.Component
*/
export default Component.extend(TransitionMixin, {
layout,
tagName: 'md-toast',
transitionName: 'ng',
dragging: false,
x: 0,
attributeBindings: ['style'],
classNameBindings: ['left:md-left:md-right', 'top:md-top:md-bottom', 'capsule:md-capsule', 'dragging:md-dragging'],
style: computed('x', function() {
return htmlSafe(`transform:translate(${ this.get('x') }px, 0)`);
}),
setValueFromEvent(event) {
this.set('x', event);
},
_setupHammer() {
// Enable dragging the slider
let containerManager = new Hammer.Manager(this.element, {
dragLockToAxis: true,
dragBlockHorizontal: true
});
let swipe = new Hammer.Swipe({ direction: Hammer.DIRECTION_ALL, threshold: 10 });
let pan = new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 10 });
containerManager.add(swipe);
containerManager.add(pan);
containerManager
.on('panstart', run.bind(this, this.dragStart))
.on('panmove', run.bind(this, this.drag))
.on('panend', run.bind(this, this.dragEnd))
.on('swiperight swipeleft', run.bind(this, this.dragEnd));
this._hammer = containerManager;
},
didInsertElement() {
this._super(...arguments);
if (this.get('swipeToClose')) {
this._setupHammer();
}
},
didUpdateAttrs() {
this._super(...arguments);
if (this.get('swipeToClose') && !this._hammer) {
// if it is enabled and we didn't init hammer yet
this._setupHammer();
} else if (!this.get('swipeToClose') && this._hammer) {
// if it is disabled and we did init hammer already
this._teardownHammer();
}
},
willDestroyElement() {
this._super(...arguments);
if (this._hammer) {
this._teardownHammer();
}
},
_teardownHammer() {
this._hammer.destroy();
delete this._hammer;
},
dragStart(event) {
if (!this.get('swipeToClose')) {
return;
}
this.set('active', true);
this.set('dragging', true);
this.element.focus();
this.setValueFromEvent(event.center.x);
},
drag(event) {
if (!this.get('swipeToClose') || !this.get('dragging')) {
return;
}
this.setValueFromEvent(event.deltaX);
},
dragEnd() {
if (!this.get('swipeToClose')) {
return;
}
this.setProperties({
active: false,
dragging: false
});
invokeAction(this, 'onClose');
}
}
); |
define([
"angular",
// all components added in the list below will automatically
// be registered in the app's main module as <API key>
"components/navigation-menu/navigation-menu",
"components/rectangle/rectangle",
// all decorators
"decorators/draggable"
], function ( angular ) {
"use strict";
var directives = arguments;
return {
register: function ( appName ) {
var i, dir, app;
app = angular.module( appName );
for ( i = 1; i < directives.length; ++i ) {
dir = directives[i];
app.directive( dir.name, dir.def );
}
}
};
} ); |
angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', ['$timeout', function ($timeout) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
link: function (scope, element, attrs) {
scope.backdropClass = attrs.backdropClass || '';
scope.animate = false;
//trigger CSS transitions
$timeout(function () {
scope.animate = true;
});
}
};
}])
.directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
return {
restrict: 'EA',
scope: {
index: '@',
animate: '='
},
replace: true,
transclude: true,
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl || 'template/modal/window.html';
},
link: function (scope, element, attrs) {
element.addClass(attrs.windowClass || '');
scope.size = attrs.size;
$timeout(function () {
// trigger CSS transitions
scope.animate = true;
// focus a freshly-opened modal
element[0].focus();
});
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
}
};
}])
.directive('modalTransclude', function () {
return {
link: function($scope, $element, $attrs, controller, $transclude) {
$transclude($scope.$parent, function(clone) {
$element.empty();
$element.append(clone);
});
}
};
})
.factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap',
function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var $modalStack = {};
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex){
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance) {
var body = $document.find('body').eq(0);
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
//remove window DOM element
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() {
modalWindow.modalScope.$destroy();
body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
checkRemoveBackdrop();
});
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() == -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, 150, function () {
backdropScopeRef.$destroy();
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, emulateTime, done) {
// Closing animation
scope.animate = false;
var <API key> = $transition.<API key>;
if (<API key>) {
// transition out
var timeout = $timeout(afterAnimating, emulateTime);
domEl.bind(<API key>, function () {
$timeout.cancel(timeout);
afterAnimating();
scope.$apply();
});
} else {
// Ensure this call is async
$timeout(afterAnimating);
}
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
domEl.remove();
if (done) {
done();
}
}
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
evt.preventDefault();
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key, 'escape key press');
});
}
}
});
$modalStack.open = function (modalInstance, modal) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard
});
var body = $document.find('body').eq(0),
currBackdropIndex = backdropIndex();
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.index = currBackdropIndex;
var <API key> = angular.element('<div modal-backdrop></div>');
<API key>.attr('backdrop-class', modal.backdropClass);
backdropDomEl = $compile(<API key>)(backdropScope);
body.append(backdropDomEl);
}
var angularDomEl = angular.element('<div modal-window></div>');
angularDomEl.attr({
'template-url': modal.windowTemplateUrl,
'window-class': modal.windowClass,
'size': modal.size,
'index': openedWindows.length() - 1,
'animate': 'animate'
}).html(modal.content);
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
body.append(modalDomEl);
body.addClass(OPENED_MODAL_CLASS);
};
$modalStack.close = function (modalInstance, result) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.deferred.resolve(result);
removeModalWindow(modalInstance);
}
};
$modalStack.dismiss = function (modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.deferred.reject(reason);
removeModalWindow(modalInstance);
}
};
$modalStack.dismissAll = function (reason) {
var topModal = this.getTop();
while (topModal) {
this.dismiss(topModal.key, reason);
topModal = this.getTop();
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
backdrop: true, //can be also false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$http.get(options.templateUrl, {cache: $templateCache}).then(function (result) {
return result.data;
});
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
close: function (result) {
$modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
$modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var <API key> =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
<API key>.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
$controller(modalOptions.controller, ctrlLocals);
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
content: tplAndVars[0],
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
backdropClass: modalOptions.backdropClass,
windowClass: modalOptions.windowClass,
windowTemplateUrl: modalOptions.windowTemplateUrl,
size: modalOptions.size
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
<API key>.then(function () {
modalOpenedDeferred.resolve(true);
}, function () {
modalOpenedDeferred.reject(false);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
}); |
#include <<API key>.h>
// <API key>:
#include <<API key>/Include/<API key>.h>
// Local:
#include <AMDTGpuProfiling/gpBaseSessionView.h>
#include <AMDTGpuProfiling/ProfileManager.h>
#include <AMDTGpuProfiling/CodeViewerWindow.h>
#include <AMDTGpuProfiling/<API key>.h>
#include <AMDTGpuProfiling/<API key>.h>
gpBaseSessionView::gpBaseSessionView(QWidget* pParent) : SharedSessionWindow(pParent), m_pSessionDataModel(nullptr),
m_pSessionTabWidget(nullptr), <API key>(nullptr), <API key>(-1),
m_pCodeViewerWindow(nullptr), <API key>(-1), m_firstActivation(true)
{
m_pSessionTabWidget = new <API key>;
bool rc = connect(m_pSessionTabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(OnTabClose(int)));
GT_ASSERT(rc);
}
gpBaseSessionView::~gpBaseSessionView()
{
}
void gpBaseSessionView::<API key>(bool success, const QString& strError, const QString& <API key>)
{
// Disconnect from handling the generation completion:
bool rc = disconnect(ProfileManager::Instance(), SIGNAL(<API key>(bool, const QString&, const QString&)), this, SLOT(<API key>(bool, const QString&, const QString&)));
GT_ASSERT(rc);
if (success)
{
QFileInfo fileInfo;
fileInfo.setFile(<API key>);
<API key>* pSessionData = qobject_cast<<API key>*>(m_pSessionData);
if (fileInfo.exists() && pSessionData != nullptr)
{
pSessionData->AddAdditionalFile(<API key>);
QString dirPath = QString::fromWCharArray(pSessionData->SessionDir().directoryPath().asString().asCharArray());
QDir localDir(dirPath);
QStringList filterList;
filterList << "*.js";
filterList << "*.css";
QFileInfoList files = localDir.entryInfoList(filterList, QDir::Files);
foreach (QFileInfo file, files)
{
pSessionData->AddAdditionalFile(file.filePath());
}
}
if (<API key> == nullptr)
{
<API key> = new <API key>(this);
if (!<API key>)
{
QString errMsg = QString(<API key>).arg(<API key>);
errMsg += "\n";
errMsg += <API key>;
Util::ShowErrorBox(errMsg);
return;
}
// Add the kernel occupancy window
<API key> = m_pSessionTabWidget->addTab(<API key>, "");
}
// Load the file
<API key>-><API key>(<API key>);
GT_ASSERT(<API key> != -1);
// Set the text for the window
m_pSessionTabWidget->setTabText(<API key>, QString(<API key>).arg(<API key>));
m_pSessionTabWidget->setCurrentIndex(<API key>);
}
else
{
Util::ShowErrorBox(strError);
}
}
void gpBaseSessionView::OnTabClose(int index)
{
if (index != 0)
{
if (index == <API key>)
{
<API key> = -1;
SAFE_DELETE(m_pCodeViewerWindow);
if (<API key> > index)
{
<API key>
}
}
else if (index == <API key>)
{
<API key> = -1;
<API key>.clear();
SAFE_DELETE(<API key>);
if (<API key> > index)
{
<API key>
}
}
}
}
void gpBaseSessionView::OnAboutToActivate()
{
if (!m_firstActivation)
{
<API key>* <API key> = <API key>::instance();
GT_IF_WITH_ASSERT((<API key> != nullptr) && (m_pSessionData != nullptr) && (m_pSessionData->m_pParentData != nullptr))
{
afApplicationTree* pTree = <API key>->applicationTree();
GT_IF_WITH_ASSERT(pTree != nullptr)
{
const <API key>* pCurrentItemData = pTree-><API key>();
bool isSameSession = false;
if (pCurrentItemData != nullptr)
{
isSameSession = (pCurrentItemData->m_filePath == m_pSessionData->m_pParentData->m_filePath);
}
if (!isSameSession)
{
if ((m_pSessionData->m_pParentData != nullptr) && (m_pSessionData->m_pParentData->m_pTreeWidgetItem != nullptr))
{
pTree->selectItem(m_pSessionData->m_pParentData, true);
}
}
}
}
}
m_firstActivation = false;
} |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Pricing\V2\Voice;
use Twilio\Page;
class NumberPage extends Page {
public function __construct($version, $response, $solution) {
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
public function buildInstance(array $payload) {
return new NumberInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
return '[Twilio.Pricing.V2.NumberPage]';
}
} |
/*
* For simplicity we assume that there are five data types:
* - Number
* - String
* - Boolean
* - Array (containing data of types shown above)
* - Object (everything else)
*
* Object type cannot be converted.
*
* IDL attribute is a Javascript entity, backed by content attribute.
* Content attribute is a plain-old javascript string.
*/
const stringIdentity = x => `${x}`
const jsonParse = x => JSON.parse(x)
const jsonStringify = x => JSON.stringify(x)
const arrayParse = (x, elemParse) => x.split(',').map(e => elemParse(e.trim()))
const arrayStringify = (x, elemStringify) => x.map(elemStringify).join(',')
const booleanParse = x => x !== null
const booleanStringify = () => ''
const normalizeType = type => {
if (Array.isArray(type)) {
return type.map(normalizeType)
} else {
switch (type) {
case Array:
case 'Array':
case 'array': return Array
case Number:
case 'Number':
case 'number': return Number
case Boolean:
case 'Boolean':
case 'boolean': return Boolean
case String:
case 'String':
case 'string': return String
}
throw new Error(`Unsupported type ${type}.`)
}
}
export function <API key> (type) {
const ntype = normalizeType(type)
if (Array.isArray(ntype) && ntype[0] === Array) {
return x => arrayStringify(x, <API key>(ntype[1]))
} else {
switch (ntype) {
case Number: return jsonStringify
case Boolean: return booleanStringify
case String: return stringIdentity
}
throw new Error(`No converter found for ${ntype} type.`)
}
}
export function <API key> (type) {
const ntype = normalizeType(type)
if (Array.isArray(ntype) && ntype[0] === Array) {
return x => arrayParse(x, <API key>(ntype[1]))
} else {
switch (ntype) {
case Number: return jsonParse
case Boolean: return booleanParse
case String: return stringIdentity
}
throw new Error(`No converter found for ${ntype} type.`)
}
}
export function getDefaultValue (type) {
const ntype = normalizeType(type)
if (Array.isArray(ntype) && ntype[0] === Array) {
return []
} else {
switch (ntype) {
case Number: return 0
case Boolean: return false
case String: return ''
}
throw new Error(`No default value found for ${ntype} type.`)
}
} |
var UserModule;
(function (UserModule) {
var dataServiceId = "userService";
angular.module("user").service(dataServiceId, ["$http", "$q", "$rootScope", dataService]);
function dataService($http, $q, $rootScope) {
var self = this;
self.getBaseUri = function () {
if ($rootScope.configuration && $rootScope.configuration.apiVersion) {
return "api/" + $rootScope.configuration.apiVersion + "/user/";
}
else {
return "api/user/";
}
};
self.cache = {
getAll: null,
getById: null
};
$rootScope.$on("$locationChangeStart", function () {
self.clearCache();
});
self.clearCache = function () {
self.cache = {
getAll: null,
getById: null
};
};
self.getAll = function (params) {
if (self.cache.getAll) {
var deferred = $q.defer();
deferred.resolve(self.cache.getAll);
return deferred.promise;
}
;
return $http({ method: "GET", url: self.getBaseUri() + "getAll", params: params }).then(function (results) {
self.cache.getAll = results.data;
return results.data;
}).catch(function (error) {
});
};
self.getById = function (params) {
if (self.cache.getById && self.cache.getById.id == params.id) {
var deferred = $q.defer();
deferred.resolve(self.cache.getById);
return deferred.promise;
}
return $http({ method: "GET", url: self.getBaseUri() + "getbyid?id=" + params.id }).then(function (results) {
self.cache.getById = results.data;
return results.data;
}).catch(function (error) {
});
};
self.remove = function (params) {
return $http({ method: "DELETE", url: self.getBaseUri() + "remove?id=" + params.id }).then(function (results) {
self.clearCache();
return results;
}).catch(function (error) {
});
};
self.changePassword = function (params) {
return $http({ method: "POST", url: self.getBaseUri() + "changePassword", data: JSON.stringify(params.model) }).then(function (results) {
self.clearCache();
return results;
}).catch(function (error) {
});
};
self.add = function (params) {
return $http({ method: "POST", url: self.getBaseUri() + "add", data: JSON.stringify(params.model) }).then(function (results) {
self.clearCache();
return results;
}).catch(function (error) {
});
};
self.update = function (params) {
return $http({ method: "PUT", url: self.getBaseUri() + "update", data: JSON.stringify(params.model) }).then(function (results) {
self.clearCache();
return results;
}).catch(function (error) {
console.log("user service error:" + error);
});
};
return self;
}
})(UserModule || (UserModule = {}));
//# sourceMappingURL=userService.js.map |
{% extends "layout.html" %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<div class="error-box" align="center">
<img class="ui medium image error-image" src="{{ url_for('static', filename='img/error.png') }}">
<h1 class="ui header">{{ message }}<h1>
</div>
{% endblock %} |
package org.diorite.utils.reflections;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.diorite.cfg.system.ConfigField;
import org.diorite.utils.SimpleEnum;
@SuppressWarnings({"unchecked", "ObjectEquality"})
public final class <API key>
{
private <API key>()
{
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find element.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final ConfigField field)
{
return getReflectElement(field.getField(), field.getField().getDeclaringClass());
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param fieldName name of field to find element.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final String fieldName, final Class<?> clazz)
{
final ReflectGetter<T> getter = getReflectGetter(fieldName, clazz);
if (getter instanceof ReflectField)
{
final ReflectField<T> reflectField = (ReflectField<T>) getter;
return new ReflectElement<>(reflectField, reflectField);
}
else
{
return new ReflectElement<>(getter, getReflectSetter(fieldName, clazz));
}
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find element.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final Field field)
{
return getReflectElement(field, field.getDeclaringClass());
}
/**
* Method will try find simple method setter and getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find element.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Element for field value.
*/
public static <T> ReflectElement<T> getReflectElement(final Field field, final Class<?> clazz)
{
final ReflectGetter<T> getter = getReflectGetter(field, clazz);
if (getter instanceof ReflectField)
{
final ReflectField<T> reflectField = (ReflectField<T>) getter;
return new ReflectElement<>(reflectField, reflectField);
}
else
{
return new ReflectElement<>(getter, getReflectSetter(field, clazz));
}
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find setter.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(final ConfigField field)
{
return getReflectSetter(field.getField(), field.getField().getDeclaringClass());
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param fieldName name of field to find setter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(String fieldName, final Class<?> clazz)
{
final String fieldNameCpy = fieldName;
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("get" + fieldName);
} catch (final <API key> ignored1)
{
try
{
m = clazz.getMethod("is" + fieldName);
} catch (final <API key> ignored2)
{
for (final Method cm : clazz.getMethods())
{
if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
{
m = cm;
break;
}
}
}
}
if (m != null)
{
return new ReflectMethodSetter<>(m);
}
else
{
return new ReflectField<>(getField(clazz, fieldNameCpy));
}
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find setter.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(final Field field)
{
return getReflectSetter(field, field.getDeclaringClass());
}
/**
* Method will try find simple method setter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find setter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Setter for field value.
*/
public static <T> ReflectSetter<T> getReflectSetter(final Field field, final Class<?> clazz)
{
String fieldName = field.getName();
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("set" + fieldName);
} catch (final <API key> ignored1)
{
for (final Method cm : clazz.getMethods())
{
if (cm.getName().equalsIgnoreCase("set" + fieldName) && (cm.getParameterCount() == 1))
{
m = cm;
break;
}
}
}
if (m != null)
{
return new ReflectMethodSetter<>(m);
}
else
{
return new ReflectField<>(field);
}
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find getter.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(final ConfigField field)
{
return getReflectGetter(field.getField(), field.getField().getDeclaringClass());
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param fieldName name of field to find getter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(String fieldName, final Class<?> clazz)
{
final String fieldNameCpy = fieldName;
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("get" + fieldName);
} catch (final <API key> ignored1)
{
try
{
m = clazz.getMethod("is" + fieldName);
} catch (final <API key> ignored2)
{
for (final Method cm : clazz.getMethods())
{
if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
{
m = cm;
break;
}
}
}
}
if (m != null)
{
return new ReflectMethodGetter<>(m);
}
else
{
return new ReflectField<>(getField(clazz, fieldNameCpy));
}
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find getter.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(final Field field)
{
return getReflectGetter(field, field.getDeclaringClass());
}
/**
* Method will try find simple method getter for selected field,
* or directly use field if method can't be found.
*
* @param field field to find getter.
* @param clazz clazz with this field.
* @param <T> type of field.
*
* @return Getter for field value.
*/
public static <T> ReflectGetter<T> getReflectGetter(final Field field, final Class<?> clazz)
{
String fieldName = field.getName();
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
Method m = null;
try
{
m = clazz.getMethod("get" + fieldName);
} catch (final <API key> ignored1)
{
try
{
m = clazz.getMethod("is" + fieldName);
} catch (final <API key> ignored2)
{
for (final Method cm : clazz.getMethods())
{
if ((cm.getName().equalsIgnoreCase("get" + fieldName) || cm.getName().equalsIgnoreCase("is" + fieldName)) && (cm.getReturnType() != Void.class) && (cm.getReturnType() != void.class) && (cm.getParameterCount() == 0))
{
m = cm;
break;
}
}
}
}
if (m != null)
{
return new ReflectMethodGetter<>(m);
}
else
{
return new ReflectField<>(field);
}
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param enumClass class of enum.
* @param <T> type of enum.
*
* @return enum element or null.
*/
public static <T extends SimpleEnum<T>> T <API key>(final String name, final int id, final Class<? extends SimpleEnum<T>> enumClass)
{
return <API key>(name, id, enumClass, null);
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param def default value, can't be null.
* @param <T> type of enum.
*
* @return enum element or def.
*/
public static <T extends SimpleEnum<T>> T <API key>(final String name, final int id, final T def)
{
return <API key>(name, id, def.getClass(), def);
}
private static final Map<Class<?>, Method> simpleEnumMethods = new HashMap<>(40);
private static <T extends SimpleEnum<T>> T <API key>(final String name, final int id, Class<?> enumClass, final Object def)
{
do
{
try
{
Method m = simpleEnumMethods.get(enumClass);
if (m == null)
{
m = enumClass.getMethod("values");
simpleEnumMethods.put(enumClass, m);
}
final SimpleEnum<?>[] objects = (SimpleEnum<?>[]) m.invoke(null);
for (final SimpleEnum<?> object : objects)
{
if (object.name().equalsIgnoreCase(name) || (object.ordinal() == id))
{
return (T) object;
}
}
} catch (final Exception ignored)
{
}
enumClass = enumClass.getSuperclass();
} while ((enumClass != null) && ! (enumClass.equals(Object.class)));
return (T) def;
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param enumClass class of enum.
* @param <T> type of enum.
*
* @return enum element or null.
*/
public static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final Class<T> enumClass)
{
return getEnumValueSafe(name, id, enumClass, null);
}
/**
* Safe method to get one of enum values by name or ordinal,
* use -1 as id, to use only name,
* and null or empty string for name, to use only ordinal id.
*
* @param name name of enum field (ignore-case)
* @param id ordinal id.
* @param def default value, can't be null.
* @param <T> type of enum.
*
* @return enum element or def.
*/
public static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final T def)
{
return getEnumValueSafe(name, id, def.getDeclaringClass(), def);
}
private static <T extends Enum<T>> T getEnumValueSafe(final String name, final int id, final Class<T> enumClass, final T def)
{
final T[] elements = enumClass.getEnumConstants();
for (final T element : elements)
{
if (element.name().equalsIgnoreCase(name) || (element.ordinal() == id))
{
return element;
}
}
return def;
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param target - the target type.
* @param name - the name of the field, or NULL to ignore.
* @param fieldType - a compatible field type.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final Class<?> target, final String name, final Class<T> fieldType)
{
return getField(target, name, fieldType, 0);
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param name - the name of the field, or NULL to ignore.
* @param fieldType - a compatible field type.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final String className, final String name, final Class<T> fieldType)
{
return getField(getCanonicalClass(className), name, fieldType, 0);
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param target - the target type.
* @param fieldType - a compatible field type.
* @param index - the number of compatible fields to skip.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final Class<?> target, final Class<T> fieldType, final int index)
{
return getField(target, null, fieldType, index);
}
/**
* Retrieve a field accessor for a specific field type and name.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param fieldType - a compatible field type.
* @param index - the number of compatible fields to skip.
* @param <T> - type of field.
*
* @return The field accessor.
*/
public static <T> FieldAccessor<T> getField(final String className, final Class<T> fieldType, final int index)
{
return getField(getCanonicalClass(className), fieldType, index);
}
/**
* Set given accessible object as accessible if needed.
*
* @param o accessible to get access.
* @param <T> type of accessible object, used to keep type of returned value.
*
* @return this same object as given.
*/
public static <T extends AccessibleObject> T getAccess(final T o)
{
if (! o.isAccessible())
{
o.setAccessible(true);
}
return o;
}
/**
* Set field as accessible, and remove final flag if set.
*
* @param field field to get access.
*
* @return this same field.
*/
public static Field getAccess(final Field field)
{
getAccess((AccessibleObject) field);
if (Modifier.isFinal(field.getModifiers()))
{
try
{
final Field modifiersField = Field.class.getDeclaredField("modifiers");
getAccess(modifiersField);
modifiersField.setInt(field, field.getModifiers() & ~ Modifier.FINAL);
} catch (<API key> | SecurityException | <API key> | <API key> e)
{
throw new <API key>("That shouldn't happend (0)");
}
}
return field;
}
/**
* Search for the first publically and privately defined field of thie given name.
*
* @param target class to search in.
* @param name name of field.
* @param <T> type of field.
*
* @return field accessor for this field.
*
* @throws <API key> If we cannot find this field.
*/
public static <T> FieldAccessor<T> getField(final Class<?> target, final String name)
{
for (final Field field : target.getDeclaredFields())
{
if (((name == null) || field.getName().equals(name)))
{
getAccess(field);
return new FieldAccessor<>(field);
}
}
// Search in parent classes
if (target.getSuperclass() != null)
{
return getField(target.getSuperclass(), name);
}
throw new <API key>("Cannot find field with name " + name);
}
// Common method
private static <T> FieldAccessor<T> getField(final Class<?> target, final String name, final Class<T> fieldType, int index)
{
for (final Field field : target.getDeclaredFields())
{
if (((name == null) || field.getName().equals(name)) && (fieldType.isAssignableFrom(field.getType()) && (index
{
getAccess(field);
return new FieldAccessor<>(field);
}
}
// Search in parent classes
if (target.getSuperclass() != null)
{
return getField(target.getSuperclass(), name, fieldType, index);
}
throw new <API key>("Cannot find field with type " + fieldType + " in " + target + ", index: " + index);
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws <API key> If we cannot find this method.
*/
public static MethodInvoker getMethod(final String className, final String methodName, final Class<?>... params)
{
return getSimpleMethod(getCanonicalClass(className), methodName, null, params);
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws <API key> If we cannot find this method.
*/
public static MethodInvoker getMethod(final Class<?> clazz, final String methodName, final Class<?>... params)
{
return getSimpleMethod(clazz, methodName, null, params);
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param returnType - the expected return type, or NULL to ignore.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws <API key> If we cannot find this method.
*/
public static MethodInvoker getTypedMethod(final Class<?> clazz, final String methodName, final Class<?> returnType, final Class<?>... params)
{
for (final Method method : clazz.getDeclaredMethods())
{
if (((methodName == null) || method.getName().equals(methodName)) && ((returnType == null) || method.getReturnType().equals(returnType)) && Arrays.equals(method.getParameterTypes(), params))
{
getAccess(method);
return new MethodInvoker(method);
}
}
// Search in every superclass
if (clazz.getSuperclass() != null)
{
return getMethod(clazz.getSuperclass(), methodName, params);
}
throw new <API key>(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param methodName - the method name, or NULL to skip.
* @param returnType - the expected return type, or NULL to ignore.
* @param params - the expected parameters.
*
* @return An object that invokes this specific method.
*
* @throws <API key> If we cannot find this method.
*/
private static MethodInvoker getSimpleMethod(final Class<?> clazz, final String methodName, final Class<?> returnType, final Class<?>... params)
{
for (final Method method : clazz.getDeclaredMethods())
{
if (((params.length == 0) || Arrays.equals(method.getParameterTypes(), params)) && ((methodName == null) || method.getName().equals(methodName)) && ((returnType == null) || method.getReturnType().equals(returnType)))
{
getAccess(method);
return new MethodInvoker(method);
}
}
// Search in every superclass
if (clazz.getSuperclass() != null)
{
return getMethod(clazz.getSuperclass(), methodName, params);
}
throw new <API key>(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
/**
* Search for the first publically and privately defined constructor of the given name and parameter count.
*
* @param className - lookup name of the class, see {@link #getCanonicalClass(String)}.
* @param params - the expected parameters.
*
* @return An object that invokes this constructor.
*
* @throws <API key> If we cannot find this method.
*/
public static ConstructorInvoker getConstructor(final String className, final Class<?>... params)
{
return getConstructor(getCanonicalClass(className), params);
}
/**
* Search for the first publically and privately defined constructor of the given name and parameter count.
*
* @param clazz - a class to start with.
* @param params - the expected parameters.
*
* @return An object that invokes this constructor.
*
* @throws <API key> If we cannot find this method.
*/
public static ConstructorInvoker getConstructor(final Class<?> clazz, final Class<?>... params)
{
for (final Constructor<?> constructor : clazz.<API key>())
{
if (Arrays.equals(constructor.getParameterTypes(), params))
{
getAccess(constructor);
return new ConstructorInvoker(constructor);
}
}
throw new <API key>(String.format("Unable to find constructor for %s (%s).", clazz, Arrays.asList(params)));
}
/**
* Search for nested class with givan name.
*
* @param clazz - a class to start with.
* @param name - name of class.
*
* @return nested class form given class.
*/
public static Class<?> getNestedClass(final Class<?> clazz, final String name)
{
for (final Class<?> nc : clazz.getDeclaredClasses())
{
if ((name == null) || nc.getSimpleName().equals(name))
{
return nc;
}
}
if (clazz.getSuperclass() != null)
{
return getNestedClass(clazz.getSuperclass(), name);
}
throw new <API key>("Unable to find nested class: " + name + " in " + clazz.getName());
}
/**
* If given class is non-primitive type {@link Class#isPrimitive()} then it will return
* privitive class for it. Like: Boolean.class {@literal ->} boolean.class
* If given class is primitive, then it will return given class.
* If given class can't be primitive (like {@link String}) then it will return given class.
*
* @param clazz class to get primitive of it.
*
* @return primitive class if possible.
*/
@SuppressWarnings("ObjectEquality")
public static Class<?> getPrimitive(final Class<?> clazz)
{
if (clazz.isPrimitive())
{
return clazz;
}
if (clazz == Boolean.class)
{
return boolean.class;
}
if (clazz == Byte.class)
{
return byte.class;
}
if (clazz == Short.class)
{
return short.class;
}
if (clazz == Character.class)
{
return char.class;
}
if (clazz == Integer.class)
{
return int.class;
}
if (clazz == Long.class)
{
return long.class;
}
if (clazz == Float.class)
{
return float.class;
}
if (clazz == Double.class)
{
return double.class;
}
return clazz;
}
/**
* If given class is primitive type {@link Class#isPrimitive()} then it will return
* wrapper class for it. Like: boolean.class {@literal ->} Boolean.class
* If given class isn't primitive, then it will return given class.
*
* @param clazz class to get wrapper of it.
*
* @return non-primitive class.
*/
@SuppressWarnings("ObjectEquality")
public static Class<?> getWrapperClass(final Class<?> clazz)
{
if (! clazz.isPrimitive())
{
return clazz;
}
if (clazz == boolean.class)
{
return Boolean.class;
}
if (clazz == byte.class)
{
return Byte.class;
}
if (clazz == short.class)
{
return Short.class;
}
if (clazz == char.class)
{
return Character.class;
}
if (clazz == int.class)
{
return Integer.class;
}
if (clazz == long.class)
{
return Long.class;
}
if (clazz == float.class)
{
return Float.class;
}
if (clazz == double.class)
{
return Double.class;
}
throw new Error("Unknown primitive type?"); // not possible?
}
/**
* Get array class for given class.
*
* @param clazz class to get array type of it.
*
* @return array version of class.
*/
@SuppressWarnings("ObjectEquality")
public static Class<?> getArrayClass(final Class<?> clazz)
{
if (clazz.isPrimitive())
{
if (clazz == boolean.class)
{
return boolean[].class;
}
if (clazz == byte.class)
{
return byte[].class;
}
if (clazz == short.class)
{
return short[].class;
}
if (clazz == char.class)
{
return char[].class;
}
if (clazz == int.class)
{
return int[].class;
}
if (clazz == long.class)
{
return long[].class;
}
if (clazz == float.class)
{
return float[].class;
}
if (clazz == double.class)
{
return double[].class;
}
}
if (clazz.isArray())
{
return getCanonicalClass("[" + clazz.getName());
}
return getCanonicalClass("[L" + clazz.getName() + ";");
}
/**
* Return class for given name or throw exception.
*
* @param canonicalName name of class to find.
*
* @return class for given name.
*
* @throws <API key> if there is no class with given name.
*/
public static Class<?> getCanonicalClass(final String canonicalName) throws <API key>
{
try
{
return Class.forName(canonicalName);
} catch (final <API key> e)
{
throw new <API key>("Cannot find " + canonicalName, e);
}
}
/**
* Return class for given name or null.
*
* @param canonicalName name of class to find.
*
* @return class for given name or null.
*/
public static Class<?> <API key>(final String canonicalName)
{
try
{
return Class.forName(canonicalName);
} catch (final <API key> e)
{
return null;
}
}
} |
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Management.Network.Models;
namespace Azure.Management.Network
{
<summary> The NetworkProfiles service client. </summary>
public partial class <API key>
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal <API key> RestClient { get; }
<summary> Initializes a new instance of <API key> for mocking. </summary>
protected <API key>()
{
}
<summary> Initializes a new instance of <API key>. </summary>
<param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
<param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
<param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
<param name="endpoint"> server parameter. </param>
internal <API key>(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
RestClient = new <API key>(clientDiagnostics, pipeline, subscriptionId, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
<summary> Gets the specified network profile in a specified resource group. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the public IP prefix. </param>
<param name="expand"> Expands referenced resources. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<NetworkProfile>> GetAsync(string resourceGroupName, string networkProfileName, string expand = null, Cancellation<API key> = default)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.Get");
scope.Start();
try
{
return await RestClient.GetAsync(resourceGroupName, networkProfileName, expand, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Gets the specified network profile in a specified resource group. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the public IP prefix. </param>
<param name="expand"> Expands referenced resources. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<NetworkProfile> Get(string resourceGroupName, string networkProfileName, string expand = null, Cancellation<API key> = default)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.Get");
scope.Start();
try
{
return RestClient.Get(resourceGroupName, networkProfileName, expand, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Creates or updates a network profile. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the network profile. </param>
<param name="parameters"> Parameters supplied to the create or update network profile operation. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<NetworkProfile>> CreateOrUpdateAsync(string resourceGroupName, string networkProfileName, NetworkProfile parameters, Cancellation<API key> = default)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.CreateOrUpdate");
scope.Start();
try
{
return await RestClient.CreateOrUpdateAsync(resourceGroupName, networkProfileName, parameters, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Creates or updates a network profile. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the network profile. </param>
<param name="parameters"> Parameters supplied to the create or update network profile operation. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<NetworkProfile> CreateOrUpdate(string resourceGroupName, string networkProfileName, NetworkProfile parameters, Cancellation<API key> = default)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.CreateOrUpdate");
scope.Start();
try
{
return RestClient.CreateOrUpdate(resourceGroupName, networkProfileName, parameters, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Updates network profile tags. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the network profile. </param>
<param name="parameters"> Parameters supplied to update network profile tags. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<NetworkProfile>> UpdateTagsAsync(string resourceGroupName, string networkProfileName, TagsObject parameters, Cancellation<API key> = default)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.UpdateTags");
scope.Start();
try
{
return await RestClient.UpdateTagsAsync(resourceGroupName, networkProfileName, parameters, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Updates network profile tags. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the network profile. </param>
<param name="parameters"> Parameters supplied to update network profile tags. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<NetworkProfile> UpdateTags(string resourceGroupName, string networkProfileName, TagsObject parameters, Cancellation<API key> = default)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.UpdateTags");
scope.Start();
try
{
return RestClient.UpdateTags(resourceGroupName, networkProfileName, parameters, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Gets all the network profiles in a subscription. </summary>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<NetworkProfile> ListAllAsync(Cancellation<API key> = default)
{
async Task<Page<NetworkProfile>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.ListAll");
scope.Start();
try
{
var response = await RestClient.ListAllAsync(cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<NetworkProfile>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.ListAll");
scope.Start();
try
{
var response = await RestClient.<API key>(nextLink, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.<API key>(FirstPageFunc, NextPageFunc);
}
<summary> Gets all the network profiles in a subscription. </summary>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<NetworkProfile> ListAll(Cancellation<API key> = default)
{
Page<NetworkProfile> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.ListAll");
scope.Start();
try
{
var response = RestClient.ListAll(cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<NetworkProfile> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.ListAll");
scope.Start();
try
{
var response = RestClient.ListAllNextPage(nextLink, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
<summary> Gets all network profiles in a resource group. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<NetworkProfile> ListAsync(string resourceGroupName, Cancellation<API key> = default)
{
if (resourceGroupName == null)
{
throw new <API key>(nameof(resourceGroupName));
}
async Task<Page<NetworkProfile>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.List");
scope.Start();
try
{
var response = await RestClient.ListAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<NetworkProfile>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.List");
scope.Start();
try
{
var response = await RestClient.ListNextPageAsync(nextLink, resourceGroupName, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.<API key>(FirstPageFunc, NextPageFunc);
}
<summary> Gets all network profiles in a resource group. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<NetworkProfile> List(string resourceGroupName, Cancellation<API key> = default)
{
if (resourceGroupName == null)
{
throw new <API key>(nameof(resourceGroupName));
}
Page<NetworkProfile> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.List");
scope.Start();
try
{
var response = RestClient.List(resourceGroupName, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<NetworkProfile> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("<API key>.List");
scope.Start();
try
{
var response = RestClient.ListNextPage(nextLink, resourceGroupName, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
<summary> Deletes the specified network profile. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the NetworkProfile. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual async ValueTask<<API key>> StartDeleteAsync(string resourceGroupName, string networkProfileName, Cancellation<API key> = default)
{
if (resourceGroupName == null)
{
throw new <API key>(nameof(resourceGroupName));
}
if (networkProfileName == null)
{
throw new <API key>(nameof(networkProfileName));
}
using var scope = _clientDiagnostics.CreateScope("<API key>.StartDelete");
scope.Start();
try
{
var originalResponse = await RestClient.DeleteAsync(resourceGroupName, networkProfileName, cancellationToken).ConfigureAwait(false);
return new <API key>(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, networkProfileName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
<summary> Deletes the specified network profile. </summary>
<param name="resourceGroupName"> The name of the resource group. </param>
<param name="networkProfileName"> The name of the NetworkProfile. </param>
<param name="cancellationToken"> The cancellation token to use. </param>
public virtual <API key> StartDelete(string resourceGroupName, string networkProfileName, Cancellation<API key> = default)
{
if (resourceGroupName == null)
{
throw new <API key>(nameof(resourceGroupName));
}
if (networkProfileName == null)
{
throw new <API key>(nameof(networkProfileName));
}
using var scope = _clientDiagnostics.CreateScope("<API key>.StartDelete");
scope.Start();
try
{
var originalResponse = RestClient.Delete(resourceGroupName, networkProfileName, cancellationToken);
return new <API key>(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, networkProfileName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
} |
{% load staticfiles %}
{% load main_image %}
{% if offers %}
<table class="table table-striped offer-table">
<tr>
<th></th>
<th>Tytuł</th>
<th>Miejsce</th>
<th>Czas obowiązywania</th>
<th>Status</th>
<th class="text-right"></th>
</tr>
{% for o in offers %}
<tr>
<td>
<a class="crop-circle" href="{% url 'offers_view' o.title|slugify o.id %}">
<img src="/media/{{ o.images.all|main_image }}" alt="{{o.images.all|main_image|slugify|default:''}}" />
</a>
</td>
<td>
<a class="btn btn-link" href="{% url 'offers_view' o.title|slugify o.id %}">{{ o.title }}</a>
</td>
<td>
<div class="form-control-static">
{{ o.location }}
</div>
</td>
<td>
<div class="form-control-static">
<span class="is-inline_block">{{ o.started_at|date:'j E Y, G:m'|default:' teraz' }}</span> -
<span class="is-inline_block">{{ o.finished_at|date:'j E Y, G:m'|default:' do ustalenia' }}</span>
</div>
</td>
<td>
<div class="form-control-static">
{# <span class="is-inline_block">{{ Offer.OFFER_STATUS[o.offer_status].value | default:' unavailable'}}</span> #}
<span class="is-inline_block">{% include 'common/labeled_status.html' with status=o.offer_status %}</span>
</div>
</td>
<td class="text-right">
{% if o.status_old == 'STAGED' %}
<a href="{% url 'offers_view' o.title|slugify o.id %}" class="btn btn-primary">Włącz się</a>
{% endif %}
{# Only the user that can edit the organization can edit its offers #}
{% if allow_edit %}
<a href="{% url 'offers_edit' o.title|slugify o.id %}" class="btn btn-info">Edytuj</a>
{% endif %}
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>Ta organizacja nie utworzyła jeszcze żadnych ofert.</p>
{% endif %} |
cordova.define("<API key>.CallNumber", function(require, exports, module) { var CallNumber = function(){};
CallNumber.prototype.callNumber = function(success, failure, number, bypassAppChooser){
cordova.exec(success, failure, "CallNumber", "callNumber", [number, bypassAppChooser]);
};
//Plug in to Cordova
cordova.addConstructor(function() {
if (!window.Cordova) {
window.Cordova = cordova;
};
if(!window.plugins) window.plugins = {};
window.plugins.CallNumber = new CallNumber();
});
}); |
<?php
namespace vowserDB\Storage;
abstract class AbstractStorage implements StorageInterface
{
/**
* File extension used for table files.
*
* @var string
*/
public $extension;
/**
* Read a CSV file and remove the first row as it is used for column decleration.
*
* @param string $file Path to the file that should be read
* @param array $columns Array of column names that will be applied to the data array
*
* @return array Data from the file associated with the given column names
*/
abstract public function read(string $file, array $columns): array;
/**
* Get an array with the name of the columns in a given file.
*
* @param string $file Path to a table file
*
* @return array Array of the columns in the file
*/
abstract public function columns(string $file): array;
/**
* Save data from data array to the table file.
*
* @param string $file Path to the table file
* @param array $columns Array of column names of the table
* @param array $data Data that will be saved to the table
*/
abstract public function save(string $file, array $columns, array $data);
/**
* Delete a table file.
*
* @param string $file Path to the table file to delete
*/
public function delete(string $file)
{
unlink($file);
}
} |
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// der Code erneut generiert wird.
// </auto-generated>
namespace VFS.Application.Properties {
using System;
<summary>
Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
</summary>
// Diese Klasse wurde von der <API key> automatisch generiert
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "15.0.0.0")]
[global::System.Diagnostics.<API key>()]
[global::System.Runtime.CompilerServices.<API key>()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")]
internal Resources() {
}
<summary>
Gibt die <API key> <API key> zurück, die von dieser Klasse verwendet wird.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("VFS.Application.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
<summary>
Überschreibt die <API key> des aktuellen Threads für alle
<API key>, die diese stark typisierte Ressourcenklasse verwenden.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Abort {
get {
object obj = ResourceManager.GetObject("Abort", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap About {
get {
object obj = ResourceManager.GetObject("About", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap AboutBig {
get {
object obj = ResourceManager.GetObject("AboutBig", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Add {
get {
object obj = ResourceManager.GetObject("Add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap AddFile {
get {
object obj = ResourceManager.GetObject("AddFile", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap AddFolder {
get {
object obj = ResourceManager.GetObject("AddFolder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap AllAps {
get {
object obj = ResourceManager.GetObject("AllAps", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Back {
get {
object obj = ResourceManager.GetObject("Back", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap BackBig {
get {
object obj = ResourceManager.GetObject("BackBig", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap BackLittle {
get {
object obj = ResourceManager.GetObject("BackLittle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap checklist_icon {
get {
object obj = ResourceManager.GetObject("checklist_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap CloseIcon {
get {
object obj = ResourceManager.GetObject("CloseIcon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Copy {
get {
object obj = ResourceManager.GetObject("Copy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap DeleteFile {
get {
object obj = ResourceManager.GetObject("DeleteFile", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap DeleteFolder {
get {
object obj = ResourceManager.GetObject("DeleteFolder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap File {
get {
object obj = ResourceManager.GetObject("File", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Folder {
get {
object obj = ResourceManager.GetObject("Folder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap FolderIcon {
get {
object obj = ResourceManager.GetObject("FolderIcon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap ForwardBig {
get {
object obj = ResourceManager.GetObject("ForwardBig", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap ForwardLittle {
get {
object obj = ResourceManager.GetObject("ForwardLittle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Hinzufügen {
get {
object obj = ResourceManager.GetObject("Hinzufügen", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Logo {
get {
object obj = ResourceManager.GetObject("Logo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Open {
get {
object obj = ResourceManager.GetObject("Open", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Paste {
get {
object obj = ResourceManager.GetObject("Paste", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Rename {
get {
object obj = ResourceManager.GetObject("Rename", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Save {
get {
object obj = ResourceManager.GetObject("Save", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Settings {
get {
object obj = ResourceManager.GetObject("Settings", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Über ähnelt.
</summary>
internal static string strAbout {
get {
return ResourceManager.GetString("strAbout", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Hinzufügen ähnelt.
</summary>
internal static string strAdd {
get {
return ResourceManager.GetString("strAdd", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Zurück ähnelt.
</summary>
internal static string strBack {
get {
return ResourceManager.GetString("strBack", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Tab schließen ähnelt.
</summary>
internal static string strCloseTab {
get {
return ResourceManager.GetString("strCloseTab", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Datei erstellen ähnelt.
</summary>
internal static string strCreateFile {
get {
return ResourceManager.GetString("strCreateFile", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Strg+E ähnelt.
</summary>
internal static string strCreateFileKey {
get {
return ResourceManager.GetString("strCreateFileKey", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Ausgewählte Datei ähnelt.
</summary>
internal static string strCurrentFile {
get {
return ResourceManager.GetString("strCurrentFile", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Löschen ähnelt.
</summary>
internal static string strDelete {
get {
return ResourceManager.GetString("strDelete", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Ordner ähnelt.
</summary>
internal static string strDirectory {
get {
return ResourceManager.GetString("strDirectory", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Beenden ähnelt.
</summary>
internal static string strExit {
get {
return ResourceManager.GetString("strExit", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Alles entpacken ähnelt.
</summary>
internal static string strExtractAll {
get {
return ResourceManager.GetString("strExtractAll", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Strg+W ähnelt.
</summary>
internal static string strExtractAllKey {
get {
return ResourceManager.GetString("strExtractAllKey", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Ausgewählten Ordner entpacken ähnelt.
</summary>
internal static string <API key> {
get {
return ResourceManager.GetString("<API key>", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Ausgewählte Datei entpacken ähnelt.
</summary>
internal static string <API key> {
get {
return ResourceManager.GetString("<API key>", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Datei ähnelt.
</summary>
internal static string strFile {
get {
return ResourceManager.GetString("strFile", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Dateien ähnelt.
</summary>
internal static string strFiles {
get {
return ResourceManager.GetString("strFiles", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Größe ähnelt.
</summary>
internal static string strFileSize {
get {
return ResourceManager.GetString("strFileSize", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die von ähnelt.
</summary>
internal static string strFrom {
get {
return ResourceManager.GetString("strFrom", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Öffnen ähnelt.
</summary>
internal static string strOpenFile {
get {
return ResourceManager.GetString("strOpenFile", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Datei öffnen ähnelt.
</summary>
internal static string strOpenFiles {
get {
return ResourceManager.GetString("strOpenFiles", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Strg+O ähnelt.
</summary>
internal static string strOpenFilesKey {
get {
return ResourceManager.GetString("strOpenFilesKey", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Seite ähnelt.
</summary>
internal static string strPage {
get {
return ResourceManager.GetString("strPage", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Seite zurück ähnelt.
</summary>
internal static string strPageBack {
get {
return ResourceManager.GetString("strPageBack", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Seite vor ähnelt.
</summary>
internal static string strPageForward {
get {
return ResourceManager.GetString("strPageForward", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Umbenennen ähnelt.
</summary>
internal static string strRename {
get {
return ResourceManager.GetString("strRename", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Zeichenfolge, die Einstellungen ähnelt.
</summary>
internal static string strSettings {
get {
return ResourceManager.GetString("strSettings", resourceCulture);
}
}
<summary>
Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
</summary>
internal static System.Drawing.Bitmap Unmount {
get {
object obj = ResourceManager.GetObject("Unmount", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
} |
<?php
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
class PdoSessionHandler extends <API key>
{
/**
* No locking is done. This means sessions are prone to loss of data due to
* race conditions of concurrent requests to the same session. The last session
* write will win in this case. It might be useful when you implement your own
* logic to deal with this like an optimistic approach.
*/
public const LOCK_NONE = 0;
/**
* Creates an application-level lock on a session. The disadvantage is that the
* lock is not enforced by the database and thus other, unaware parts of the
* application could still concurrently modify the session. The advantage is it
* does not require a transaction.
* This mode is not available for SQLite and not yet implemented for oci and sqlsrv.
*/
public const LOCK_ADVISORY = 1;
/**
* Issues a real row lock. Since it uses a transaction between opening and
* closing a session, you have to be careful when you use same database connection
* that you also use for your application logic. This mode is the default because
* it's the only reliable solution across DBMSs.
*/
public const LOCK_TRANSACTIONAL = 2;
private \PDO $pdo;
/**
* DSN string or null for session.save_path or false when lazy connection disabled.
*/
private string|false|null $dsn = false;
private string $driver;
private string $table = 'sessions';
private string $idCol = 'sess_id';
private string $dataCol = 'sess_data';
private string $lifetimeCol = 'sess_lifetime';
private string $timeCol = 'sess_time';
/**
* Username when lazy-connect.
*/
private string $username = '';
/**
* Password when lazy-connect.
*/
private string $password = '';
/**
* Connection options when lazy-connect.
*/
private array $connectionOptions = [];
/**
* The strategy for locking, see constants.
*/
private int $lockMode = self::LOCK_TRANSACTIONAL;
/**
* It's an array to support multiple reads before closing which is manual, non-standard usage.
*
* @var \PDOStatement[] An array of statements to release advisory locks
*/
private array $unlockStatements = [];
/**
* True when the current session exists but expired according to session.gc_maxlifetime.
*/
private bool $sessionExpired = false;
/**
* Whether a transaction is active.
*/
private bool $inTransaction = false;
/**
* Whether gc() has been called.
*/
private bool $gcCalled = false;
/**
* You can either pass an existing database connection as PDO instance or
* pass a DSN string that will be used to lazy-connect to the database
* when the session is actually used. Furthermore it's possible to pass null
* which will then use the session.save_path ini setting as PDO DSN parameter.
*
* List of available options:
* * db_table: The name of the table [default: sessions]
* * db_id_col: The column where to store the session id [default: sess_id]
* * db_data_col: The column where to store the session data [default: sess_data]
* * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime]
* * db_time_col: The column where to store the timestamp [default: sess_time]
* * db_username: The username when lazy-connect [default: '']
* * db_password: The password when lazy-connect [default: '']
* * <API key>: An array of driver-specific connection options [default: []]
* * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
*
* @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null
*
* @throws \<API key> When PDO error mode is not PDO::ERRMODE_EXCEPTION
*/
public function __construct(\PDO|string $pdoOrDsn = null, array $options = [])
{
if ($pdoOrDsn instanceof \PDO) {
if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
throw new \<API key>(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__));
}
$this->pdo = $pdoOrDsn;
$this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
} elseif (\is_string($pdoOrDsn) && str_contains($pdoOrDsn, ':
$this->dsn = $this->buildDsnFromUrl($pdoOrDsn);
} else {
$this->dsn = $pdoOrDsn;
}
$this->table = $options['db_table'] ?? $this->table;
$this->idCol = $options['db_id_col'] ?? $this->idCol;
$this->dataCol = $options['db_data_col'] ?? $this->dataCol;
$this->lifetimeCol = $options['db_lifetime_col'] ?? $this->lifetimeCol;
$this->timeCol = $options['db_time_col'] ?? $this->timeCol;
$this->username = $options['db_username'] ?? $this->username;
$this->password = $options['db_password'] ?? $this->password;
$this->connectionOptions = $options['<API key>'] ?? $this->connectionOptions;
$this->lockMode = $options['lock_mode'] ?? $this->lockMode;
}
/**
* Creates the table to store sessions which can be called once for setup.
*
* Session ID is saved in a column of maximum length 128 because that is enough even
* for a 512 bit configured session.hash_function like Whirlpool. Session data is
* saved in a BLOB. One could also use a shorter inlined varbinary column
* if one was sure the data fits into it.
*
* @throws \PDOException When the table already exists
* @throws \DomainException When an unsupported PDO driver is used
*/
public function createTable()
{
// connect if we are not yet
$this->getConnection();
switch ($this->driver) {
case 'mysql':
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
$sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB";
break;
case 'sqlite':
$sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'pgsql':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'oci':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'sqlsrv':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
default:
throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
}
try {
$this->pdo->exec($sql);
$this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)");
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
}
/**
* Returns true when the current session exists but expired according to session.gc_maxlifetime.
*
* Can be used to distinguish between a new session and one that expired due to inactivity.
*/
public function isSessionExpired(): bool
{
return $this->sessionExpired;
}
public function open(string $savePath, string $sessionName): bool
{
$this->sessionExpired = false;
if (!isset($this->pdo)) {
$this->connect($this->dsn ?: $savePath);
}
return parent::open($savePath, $sessionName);
}
public function read(string $sessionId): string
{
try {
return parent::read($sessionId);
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
}
public function gc(int $maxlifetime): int|false
{
// We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
// This way, pruning expired sessions does not block them from being started while the current session is used.
$this->gcCalled = true;
return 0;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId): bool
{
// delete the record associated with this id
$sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
try {
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$stmt->execute();
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
return true;
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data): bool
{
$maxlifetime = (int) ini_get('session.gc_maxlifetime');
try {
// We use a single MERGE SQL query when supported by the database.
$mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime);
if (null !== $mergeStmt) {
$mergeStmt->execute();
return true;
}
$updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime);
$updateStmt->execute();
// When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
// duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior).
// We can just catch such an error and re-execute the update. This is similar to a serializable
// transaction with retry logic on serialization failures but without the overhead and without possible
// false positives due to longer gap locking.
if (!$updateStmt->rowCount()) {
try {
$insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime);
$insertStmt->execute();
} catch (\PDOException $e) {
// Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
if (str_starts_with($e->getCode(), '23')) {
$updateStmt->execute();
} else {
throw $e;
}
}
}
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
return true;
}
public function updateTimestamp(string $sessionId, string $data): bool
{
$expiry = time() + (int) ini_get('session.gc_maxlifetime');
try {
$updateStmt = $this->pdo->prepare(
"UPDATE $this->table SET $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id"
);
$updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$updateStmt->bindParam(':expiry', $expiry, \PDO::PARAM_INT);
$updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
$updateStmt->execute();
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
return true;
}
public function close(): bool
{
$this->commit();
while ($unlockStmt = array_shift($this->unlockStatements)) {
$unlockStmt->execute();
}
if ($this->gcCalled) {
$this->gcCalled = false;
// delete the session records that have expired
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->execute();
}
if (false !== $this->dsn) {
unset($this->pdo, $this->driver); // only close lazy-connection
}
return true;
}
/**
* Lazy-connects to the database.
*/
private function connect(string $dsn): void
{
$this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
}
/**
* Builds a PDO DSN from a URL-like connection string.
*
* @todo implement missing support for oci DSN (which look totally different from other PDO ones)
*/
private function buildDsnFromUrl(string $dsnOrUrl): string
{
// (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
$url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl);
$params = parse_url($url);
if (false === $params) {
return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already.
}
$params = array_map('rawurldecode', $params);
// Override the default username and password. Values passed through options will still win over these in the constructor.
if (isset($params['user'])) {
$this->username = $params['user'];
}
if (isset($params['pass'])) {
$this->password = $params['pass'];
}
if (!isset($params['scheme'])) {
throw new \<API key>('URLs without scheme are not supported to configure the PdoSessionHandler.');
}
$driverAliasMap = [
'mssql' => 'sqlsrv',
'mysql2' => 'mysql', // Amazon RDS, for some weird reason
'postgres' => 'pgsql',
'postgresql' => 'pgsql',
'sqlite3' => 'sqlite',
];
$driver = $driverAliasMap[$params['scheme']] ?? $params['scheme'];
// Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here.
if (str_starts_with($driver, 'pdo_') || str_starts_with($driver, 'pdo-')) {
$driver = substr($driver, 4);
}
$dsn = null;
switch ($driver) {
case 'mysql':
$dsn = 'mysql:';
if ('' !== ($params['query'] ?? '')) {
$queryParams = [];
parse_str($params['query'], $queryParams);
if ('' !== ($queryParams['charset'] ?? '')) {
$dsn .= 'charset='.$queryParams['charset'].';';
}
if ('' !== ($queryParams['unix_socket'] ?? '')) {
$dsn .= 'unix_socket='.$queryParams['unix_socket'].';';
if (isset($params['path'])) {
$dbName = substr($params['path'], 1); // Remove the leading slash
$dsn .= 'dbname='.$dbName.';';
}
return $dsn;
}
}
// If "unix_socket" is not in the query, we continue with the same process as pgsql
// no break
case 'pgsql':
$dsn ?? $dsn = 'pgsql:';
if (isset($params['host']) && '' !== $params['host']) {
$dsn .= 'host='.$params['host'].';';
}
if (isset($params['port']) && '' !== $params['port']) {
$dsn .= 'port='.$params['port'].';';
}
if (isset($params['path'])) {
$dbName = substr($params['path'], 1); // Remove the leading slash
$dsn .= 'dbname='.$dbName.';';
}
return $dsn;
case 'sqlite':
return 'sqlite:'.substr($params['path'], 1);
case 'sqlsrv':
$dsn = 'sqlsrv:server=';
if (isset($params['host'])) {
$dsn .= $params['host'];
}
if (isset($params['port']) && '' !== $params['port']) {
$dsn .= ','.$params['port'];
}
if (isset($params['path'])) {
$dbName = substr($params['path'], 1); // Remove the leading slash
$dsn .= ';Database='.$dbName;
}
return $dsn;
default:
throw new \<API key>(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme']));
}
}
private function beginTransaction(): void
{
if (!$this->inTransaction) {
if ('sqlite' === $this->driver) {
$this->pdo->exec('BEGIN IMMEDIATE TRANSACTION');
} else {
if ('mysql' === $this->driver) {
$this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
}
$this->pdo->beginTransaction();
}
$this->inTransaction = true;
}
}
/**
* Helper method to commit a transaction.
*/
private function commit(): void
{
if ($this->inTransaction) {
try {
// commit read-write transaction which also releases the lock
if ('sqlite' === $this->driver) {
$this->pdo->exec('COMMIT');
} else {
$this->pdo->commit();
}
$this->inTransaction = false;
} catch (\PDOException $e) {
$this->rollback();
throw $e;
}
}
}
/**
* Helper method to rollback a transaction.
*/
private function rollback(): void
{
// We only need to rollback if we are in a transaction. Otherwise the resulting
// error would hide the real problem why rollback was called. We might not be
// in a transaction when not using the transactional locking behavior or when
// two callbacks (e.g. destroy and write) are invoked that both fail.
if ($this->inTransaction) {
if ('sqlite' === $this->driver) {
$this->pdo->exec('ROLLBACK');
} else {
$this->pdo->rollBack();
}
$this->inTransaction = false;
}
}
/**
* Reads the session data in respect to the different locking strategies.
*
* We need to make sure we do not return session data that is already considered garbage according
* to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
*/
protected function doRead(string $sessionId): string
{
if (self::LOCK_ADVISORY === $this->lockMode) {
$this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
}
$selectSql = $this->getSelectSql();
$selectStmt = $this->pdo->prepare($selectSql);
$selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$insertStmt = null;
do {
$selectStmt->execute();
$sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
if ($sessionRows) {
$expiry = (int) $sessionRows[0][1];
if ($expiry < time()) {
$this->sessionExpired = true;
return '';
}
return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
}
if (null !== $insertStmt) {
$this->rollback();
throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.');
}
if (!filter_var(ini_get('session.use_strict_mode'), \<API key>) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
// In strict mode, session fixation is not possible: new sessions always start with a unique
// random id, so that concurrency is not possible and this code path can be skipped.
// Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
// until other connections to the session are committed.
try {
$insertStmt = $this->getInsertStatement($sessionId, '', 0);
$insertStmt->execute();
} catch (\PDOException $e) {
// Catch duplicate key error because other connection created the session already.
// It would only not be the case when the other connection destroyed the session.
if (str_starts_with($e->getCode(), '23')) {
// Retrieve finished session data written by concurrent connection by restarting the loop.
// We have to start a new transaction as a failed query will mark the current transaction as
// aborted in PostgreSQL and disallow further queries within it.
$this->rollback();
$this->beginTransaction();
continue;
}
throw $e;
}
}
return '';
} while (true);
}
/**
* Executes an application-level lock on the database.
*
* @return \PDOStatement The statement that needs to be executed later to release the lock
*
* @throws \DomainException When an unsupported PDO driver is used
*
* @todo implement missing advisory locks
* - for oci using DBMS_LOCK.REQUEST
* - for sqlsrv using sp_getapplock with LockOwner = Session
*/
private function doAdvisoryLock(string $sessionId): \PDOStatement
{
switch ($this->driver) {
case 'mysql':
// MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced.
$lockId = substr($sessionId, 0, 64);
// should we handle the return value? 0 on timeout, null on error
// we use a timeout of 50 seconds which is also the default for <API key>
$stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
$stmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
$stmt->execute();
$releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
$releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
return $releaseStmt;
case 'pgsql':
// Obtaining an exclusive session level advisory lock requires an integer key.
// When session.<API key> > 4, the session id can contain non-hex-characters.
// So we cannot just use hexdec().
if (4 === \PHP_INT_SIZE) {
$sessionInt1 = $this->convertStringToInt($sessionId);
$sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4));
$stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
$stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
$stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
$stmt->execute();
$releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
$releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
$releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
} else {
$sessionBigInt = $this->convertStringToInt($sessionId);
$stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
$stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
$stmt->execute();
$releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)');
$releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
}
return $releaseStmt;
case 'sqlite':
throw new \DomainException('SQLite does not support advisory locks.');
default:
throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver));
}
}
/**
* Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer.
*
* Keep in mind, PHP integers are signed.
*/
private function convertStringToInt(string $string): int
{
if (4 === \PHP_INT_SIZE) {
return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
}
$int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]);
$int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
return $int2 + ($int1 << 32);
}
/**
* Return a locking or nonlocking SQL query to read session information.
*
* @throws \DomainException When an unsupported PDO driver is used
*/
private function getSelectSql(): string
{
if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
$this->beginTransaction();
switch ($this->driver) {
case 'mysql':
case 'oci':
case 'pgsql':
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
case 'sqlsrv':
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
case 'sqlite':
// we already locked when starting transaction
break;
default:
throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
}
}
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id";
}
/**
* Returns an insert statement supported by the database for writing session data.
*/
private function getInsertStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
{
switch ($this->driver) {
case 'oci':
$data = fopen('php://memory', 'r+');
fwrite($data, $sessionData);
rewind($data);
$sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :expiry, :time) RETURNING $this->dataCol into :data";
break;
default:
$data = $sessionData;
$sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)";
break;
}
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
$stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
return $stmt;
}
/**
* Returns an update statement supported by the database for writing session data.
*/
private function getUpdateStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
{
switch ($this->driver) {
case 'oci':
$data = fopen('php://memory', 'r+');
fwrite($data, $sessionData);
rewind($data);
$sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data";
break;
default:
$data = $sessionData;
$sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id";
break;
}
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
$stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
return $stmt;
}
/**
* Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data.
*/
private function getMergeStatement(string $sessionId, string $data, int $maxlifetime): ?\PDOStatement
{
switch (true) {
case 'mysql' === $this->driver:
$mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ".
"ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
break;
case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
// MERGE is only available since SQL Server 2008 and must be terminated by semicolon
$mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
"WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
"WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
break;
case 'sqlite' === $this->driver:
$mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)";
break;
case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='):
$mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ".
"ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
break;
default:
return null;
}
$mergeStmt = $this->pdo->prepare($mergeSql);
if ('sqlsrv' === $this->driver) {
$mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
$mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
$mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
$mergeStmt->bindValue(4, time() + $maxlifetime, \PDO::PARAM_INT);
$mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
$mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
$mergeStmt->bindValue(7, time() + $maxlifetime, \PDO::PARAM_INT);
$mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
} else {
$mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
$mergeStmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
$mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
}
return $mergeStmt;
}
/**
* Return a PDO instance.
*/
protected function getConnection(): \PDO
{
if (!isset($this->pdo)) {
$this->connect($this->dsn ?: ini_get('session.save_path'));
}
return $this->pdo;
}
} |
package hudson.cli;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import hudson.model.<API key>;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import hudson.Extension;
import java.io.<API key>;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.<API key>;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.util.<API key>;
import jenkins.websocket.WebSocketSession;
import jenkins.websocket.WebSockets;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.springframework.security.core.Authentication;
/**
* Shows usage of CLI and commands.
*
* @author ogondza
*/
@Extension @Symbol("cli")
@Restricted(NoExternalUse.class)
public class CLIAction implements <API key>, StaplerProxy {
private static final Logger LOGGER = Logger.getLogger(CLIAction.class.getName());
private transient final Map<UUID, <API key>> duplexServices = new HashMap<>();
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return "Jenkins CLI";
}
public String getUrlName() {
return "cli";
}
public void doCommand(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
final Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(Jenkins.READ);
// Strip trailing slash
final String commandName = req.getRestOfPath().substring(1);
CLICommand command = CLICommand.clone(commandName);
if (command == null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND, "No such command");
return;
}
req.setAttribute("command", command);
req.getView(this, "command.jelly").forward(req, rsp);
}
/** for Jelly */
public boolean <API key>() {
return WebSockets.isSupported();
}
/**
* WebSocket endpoint.
*/
public HttpResponse doWs() {
if (!WebSockets.isSupported()) {
return HttpResponses.notFound();
}
Authentication authentication = Jenkins.getAuthentication2();
return WebSockets.upgrade(new WebSocketSession() {
ServerSideImpl connection;
class OutputImpl implements PlainCLIProtocol.Output {
@Override
public void send(byte[] data) throws IOException {
sendBinary(ByteBuffer.wrap(data));
}
@Override
public void close() throws IOException {
doClose();
}
}
private void doClose() {
close();
}
@Override
protected void opened() {
try {
connection = new ServerSideImpl(new OutputImpl(), authentication);
} catch (IOException x) {
error(x);
return;
}
new Thread(() -> {
try {
try {
connection.run();
} finally {
connection.close();
}
} catch (Exception x) {
error(x);
}
}, "CLI handler for " + authentication.getName()).start();
}
@Override
protected void binary(byte[] payload, int offset, int len) {
try {
connection.handle(new DataInputStream(new <API key>(payload, offset, len)));
} catch (IOException x) {
error(x);
}
}
@Override
protected void error(Throwable cause) {
LOGGER.log(Level.WARNING, null, cause);
}
@Override
protected void closed(int statusCode, String reason) {
LOGGER.fine(() -> "closed: " + statusCode + ": " + reason);
connection.handleClose();
}
});
}
@Override
public Object getTarget() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req.getRestOfPath().length()==0 && "POST".equals(req.getMethod())) {
// CLI connection request
if ("false".equals(req.getParameter("remoting"))) {
throw new <API key>();
} else {
// remoting=true (the historical default) no longer supported.
throw HttpResponses.forbidden();
}
} else {
return this;
}
}
static class ServerSideImpl extends PlainCLIProtocol.ServerSide {
private Thread runningThread;
private boolean ready;
private final List<String> args = new ArrayList<>();
private Locale locale = Locale.getDefault();
private Charset encoding = Charset.defaultCharset();
private final PipedInputStream stdin = new PipedInputStream();
private final PipedOutputStream stdinMatch = new PipedOutputStream();
private final Authentication authentication;
ServerSideImpl(PlainCLIProtocol.Output out, Authentication authentication) throws IOException {
super(out);
stdinMatch.connect(stdin);
this.authentication = authentication;
}
@Override
protected void onArg(String text) {
args.add(text);
}
@Override
protected void onLocale(String text) {
for (Locale _locale : Locale.getAvailableLocales()) {
if (_locale.toString().equals(text)) {
locale = _locale;
return;
}
}
LOGGER.log(Level.WARNING, "unknown client locale {0}", text);
}
@Override
protected void onEncoding(String text) {
try {
encoding = Charset.forName(text);
} catch (<API key> x) {
LOGGER.log(Level.WARNING, "unknown client charset {0}", text);
}
}
@Override
protected void onStart() {
ready();
}
@Override
protected void onStdin(byte[] chunk) throws IOException {
stdinMatch.write(chunk);
}
@Override
protected void onEndStdin() throws IOException {
stdinMatch.close();
}
@Override
protected void handleClose() {
ready();
if (runningThread != null) {
runningThread.interrupt();
}
}
private synchronized void ready() {
ready = true;
notifyAll();
}
void run() throws IOException, <API key> {
synchronized (this) {
while (!ready) {
wait();
}
}
PrintStream stdout = new PrintStream(streamStdout(), false, encoding.name());
PrintStream stderr = new PrintStream(streamStderr(), true, encoding.name());
if (args.isEmpty()) {
stderr.println("Connection closed before arguments received");
sendExit(2);
return;
}
String commandName = args.get(0);
CLICommand command = CLICommand.clone(commandName);
if (command == null) {
stderr.println("No such command " + commandName);
sendExit(2);
return;
}
command.setTransportAuth2(authentication);
command.setClientCharset(encoding);
CLICommand orig = CLICommand.setCurrent(command);
try {
runningThread = Thread.currentThread();
int exit = command.main(args.subList(1, args.size()), locale, stdin, stdout, stderr);
stdout.flush();
sendExit(exit);
try { // seems to avoid <API key> from Jetty
Thread.sleep(1000);
} catch (<API key> x) {
// expected; ignore
}
} finally {
CLICommand.setCurrent(orig);
runningThread = null;
}
}
}
/**
* Serves {@link PlainCLIProtocol} response.
*/
private class <API key> extends <API key>.Response {
<API key>() {
super(duplexServices);
}
@Override
protected <API key> createService(StaplerRequest req, UUID uuid) throws IOException {
return new <API key>(uuid) {
@Override
protected void run(InputStream upload, OutputStream download) throws IOException, <API key> {
try (ServerSideImpl connection = new ServerSideImpl(new PlainCLIProtocol.FramedOutput(download), Jenkins.getAuthentication2())) {
new PlainCLIProtocol.FramedReader(connection, upload).start();
connection.run();
}
}
};
}
}
} |
# <API key>: true
require "hanami/utils/string"
RSpec.describe "hanami generate", type: :integration do
describe "model" do
context "with model name" do
it_behaves_like "a new model" do
let(:input) { "user" }
end
end
context "with underscored name" do
it_behaves_like "a new model" do
let(:input) { "discounted_book" }
end
end
context "with dashed name" do
it_behaves_like "a new model" do
let(:input) { "user-event" }
end
end
context "with camel case name" do
it_behaves_like "a new model" do
let(:input) { "VerifiedUser" }
end
end
context "with missing argument" do
it "fails" do
with_project('<API key>') do
output = <<-END
ERROR: "hanami generate model" was called with no arguments
Usage: "hanami generate model MODEL"
END
run_cmd "hanami generate model", output, exit_status: 1
end
end
end
context "with missing migrations directory" do
it "will create directory and migration" do
with_project do
model_name = "book"
directory = Pathname.new("db").join("migrations")
FileUtils.rm_rf(directory)
run_cmd "hanami generate model #{model_name}"
expect(directory).to be_directory
migration = directory.children.find do |m|
m.to_s.include?(model_name)
end
expect(migration).to_not be(nil)
end
end
end
context "with skip-migration" do
it "doesn't create a migration file" do
model_name = "user"
table_name = "users"
project = "<API key>"
with_project(project) do
run_cmd "hanami generate model #{model_name} --skip-migration"
# db/migrations/<timestamp>_create_<models>.rb
migrations = Pathname.new("db").join("migrations").children
file = migrations.find do |child|
child.to_s.include?("create_#{table_name}")
end
expect(file).to be_nil, "Expected to not find a migration matching: create_#{table_name}. Found #{file&.to_s}"
end
end
it "doesn't create a migration file when --relation is used" do
model_name = "user"
table_name = "accounts"
project = "<API key>"
with_project(project) do
run_cmd "hanami generate model #{model_name} --skip-migration --relation=#{table_name}"
# db/migrations/<timestamp>_create_<models>.rb
migrations = Pathname.new("db").join("migrations").children
file = migrations.find do |child|
child.to_s.include?("create_#{table_name}")
end
expect(file).to be_nil, "Expected to not find a migration matching: create_#{table_name}. Found #{file&.to_s}"
end
end
end
context "with relation option" do
let(:project) { "<API key>" }
let(:model_name) { "stimulus" }
let(:class_name) { "Stimulus" }
let(:relation_name) { "stimuli" }
it "creates correct entity, repository, and migration" do
with_project(project) do
output = [
"create lib/#{project}/entities/#{model_name}.rb",
"create lib/#{project}/repositories/#{model_name}_repository.rb",
/create db\/migrations\/(\d+)_create_#{relation_name}.rb/
]
run_cmd "hanami generate model #{model_name} --relation=#{relation_name}", output
expect("lib/#{project}/repositories/#{model_name}_repository.rb").to have_file_content <<~END
class #{class_name}Repository < Hanami::Repository
self.relation = :#{relation_name}
end
END
migration = Pathname.new("db").join("migrations").children.find do |child|
child.to_s.include?("create_#{relation_name}")
end
expect(migration.to_s).to have_file_content <<~END
Hanami::Model.migration do
change do
create_table :#{relation_name} do
primary_key :id
column :created_at, DateTime, null: false
column :updated_at, DateTime, null: false
end
end
end
END
end
end
it "handles CamelCase arguments" do
with_project(project) do
model = "sheep"
relation_name = "black_sheeps"
output = [
"create lib/#{project}/entities/#{model}.rb",
"create lib/#{project}/repositories/#{model}_repository.rb",
/create db\/migrations\/(\d+)_create_#{relation_name}.rb/
]
run_cmd "hanami generate model #{model} --relation=BlackSheeps", output
expect("lib/#{project}/repositories/sheep_repository.rb").to have_file_content <<~END
class SheepRepository < Hanami::Repository
self.relation = :#{relation_name}
end
END
migration = Pathname.new("db").join("migrations").children.find do |child|
child.to_s.include?("create_#{relation_name}")
end
expect(migration.to_s).to have_file_content <<~END
Hanami::Model.migration do
change do
create_table :#{relation_name} do
primary_key :id
column :created_at, DateTime, null: false
column :updated_at, DateTime, null: false
end
end
end
END
end
end
it "returns error for blank option" do
with_project(project) do
run_cmd "hanami generate model #{model_name} --relation=", "`' is not a valid relation name", exit_status: 1
end
end
end
context "minitest" do
it "generates model" do
project = "<API key>"
with_project(project, test: :minitest) do
model = "book"
class_name = Hanami::Utils::String.new(model).classify
output = [
"create spec/#{project}/entities/#{model}_spec.rb",
"create spec/#{project}/repositories/#{model}_repository_spec.rb"
]
run_cmd "hanami generate model #{model}", output
# spec/<project>/entities/<model>_spec.rb
expect("spec/#{project}/entities/#{model}_spec.rb").to have_file_content <<~END
require_relative '../../spec_helper'
describe #{class_name} do
# place your tests here
end
END
# spec/<project>/repositories/<model>_repository_spec.rb
expect("spec/#{project}/repositories/#{model}_repository_spec.rb").to have_file_content <<~END
require_relative '../../spec_helper'
describe #{class_name}Repository do
# place your tests here
end
END
end
end
end # minitest
context "rspec" do
it "generates model" do
project = "<API key>"
with_project(project, test: :rspec) do
model = "book"
class_name = Hanami::Utils::String.new(model).classify
output = [
"create spec/#{project}/entities/#{model}_spec.rb",
"create spec/#{project}/repositories/#{model}_repository_spec.rb"
]
run_cmd "hanami generate model #{model}", output
# spec/<project>/entities/<model>_spec.rb
expect("spec/#{project}/entities/#{model}_spec.rb").to have_file_content <<~END
RSpec.describe #{class_name}, type: :entity do
# place your tests here
end
END
# spec/<project>/repositories/<model>_repository_spec.rb
expect("spec/#{project}/repositories/#{model}_repository_spec.rb").to have_file_content <<~END
RSpec.describe BookRepository, type: :repository do
# place your tests here
end
END
end
end
end # rspec
it "prints help message" do
with_project do
output = <<~OUT
Command:
hanami generate model
Usage:
hanami generate model MODEL
Description:
Generate a model
Arguments:
MODEL # REQUIRED Model name (eg. `user`)
Options:
--[no-]skip-migration # Skip migration, default: false
--relation=VALUE # Name of the database relation, default: pluralized model name
--help, -h # Print this help
Examples:
hanami generate model user # Generate `User` entity, `UserRepository` repository, and the migration
hanami generate model user --skip-migration # Generate `User` entity and `UserRepository` repository
hanami generate model user --relation=accounts # Generate `User` entity, `UserRepository` and migration to create `accounts` table
OUT
run_cmd 'hanami generate model --help', output
end
end
end # model
end |
#pragma once
#include <bond/core/config.h>
namespace bond
{
template <typename Protocols, typename X, typename Key, typename T>
typename boost::enable_if<is_map_key_matching<Key, X> >::type
inline <API key>(X& var, const Key& key, const T& element, uint32_t size);
template <typename Protocols, typename X, typename Key, typename T>
typename boost::disable_if<is_map_key_matching<Key, X> >::type
inline <API key>(X&, const Key& key, const T& element, uint32_t size);
template <typename Protocols, typename Transform, typename Key, typename T>
inline void <API key>(const Transform& transform, const Key& key, const T& element, uint32_t size);
template <typename Protocols, typename X, typename T>
typename boost::enable_if_c<is_list_container<X>::value
&& is_element_matching<T, X>::value>::type
inline DeserializeElements(X& var, const T& element, uint32_t size);
template <typename Protocols, typename X, typename T>
typename boost::enable_if<is_matching<T, X> >::type
inline DeserializeElements(nullable<X>& var, const T& element, uint32_t size);
template <typename Protocols, typename Reader>
inline void DeserializeElements(blob& var, const value<blob::value_type, Reader&>& element, uint32_t size);
template <typename Protocols, typename X, typename T>
typename boost::enable_if_c<is_set_container<X>::value
&& is_element_matching<T, X>::value>::type
inline DeserializeElements(X& var, const T& element, uint32_t size);
template <typename Protocols, typename X, typename T>
typename boost::disable_if<is_element_matching<T, X> >::type
inline DeserializeElements(X&, const T& element, uint32_t size);
template <typename Protocols, typename Transform, typename T>
inline void DeserializeElements(const Transform& transform, const T& element, uint32_t size);
namespace detail
{
// Sanity check to assert that manually expended switch statement are consistent
// with the canonical definition of type promotion in is_matching metafunction.
template <typename T>
bool IsMatching(BondDataType type)
{
switch (type)
{
case bond::BT_BOOL:
return is_matching<bool, T>::value;
case bond::BT_UINT8:
return is_matching<uint8_t, T>::value;
case bond::BT_UINT16:
return is_matching<uint16_t, T>::value;
case bond::BT_UINT32:
return is_matching<uint32_t, T>::value;
case bond::BT_UINT64:
return is_matching<uint64_t, T>::value;
case bond::BT_FLOAT:
return is_matching<float, T>::value;
case bond::BT_DOUBLE:
return is_matching<double, T>::value;
case bond::BT_STRING:
return is_matching<std::string, T>::value;
case bond::BT_WSTRING:
return is_matching<std::wstring, T>::value;
case bond::BT_INT8:
return is_matching<int8_t, T>::value;
case bond::BT_INT16:
return is_matching<int16_t, T>::value;
case bond::BT_INT32:
return is_matching<int32_t, T>::value;
case bond::BT_INT64:
return is_matching<int64_t, T>::value;
default:
BOOST_ASSERT(false);
return false;
}
}
template <typename Transform, typename Reader>
inline bool BasicTypeField(uint16_t id, const Metadata& metadata, BondDataType type, const Transform& transform, Reader& input)
{
switch (type)
{
case bond::BT_BOOL:
return transform.Field(id, metadata, value<bool, Reader&>(input));
case bond::BT_UINT8:
return transform.Field(id, metadata, value<uint8_t, Reader&>(input));
case bond::BT_UINT16:
return transform.Field(id, metadata, value<uint16_t, Reader&>(input));
case bond::BT_UINT32:
return transform.Field(id, metadata, value<uint32_t, Reader&>(input));
case bond::BT_UINT64:
return transform.Field(id, metadata, value<uint64_t, Reader&>(input));
case bond::BT_FLOAT:
return transform.Field(id, metadata, value<float, Reader&>(input));
case bond::BT_DOUBLE:
return transform.Field(id, metadata, value<double, Reader&>(input));
case bond::BT_STRING:
return transform.Field(id, metadata, value<std::string, Reader&>(input));
case bond::BT_WSTRING:
return transform.Field(id, metadata, value<std::wstring, Reader&>(input));
case bond::BT_INT8:
return transform.Field(id, metadata, value<int8_t, Reader&>(input));
case bond::BT_INT16:
return transform.Field(id, metadata, value<int16_t, Reader&>(input));
case bond::BT_INT32:
return transform.Field(id, metadata, value<int32_t, Reader&>(input));
case bond::BT_INT64:
return transform.Field(id, metadata, value<int64_t, Reader&>(input));
default:
BOOST_ASSERT(false);
return false;
}
}
template <typename Protocols, typename T, typename Reader>
inline void BasicTypeContainer(T& var, BondDataType type, Reader& input, uint32_t size)
{
BOOST_STATIC_ASSERT(!is_container<T>::value);
switch (type)
{
case bond::BT_BOOL:
return DeserializeElements<Protocols>(var, value<bool, Reader&>(input, false), size);
case bond::BT_UINT8:
return DeserializeElements<Protocols>(var, value<uint8_t, Reader&>(input, false), size);
case bond::BT_UINT16:
return DeserializeElements<Protocols>(var, value<uint16_t, Reader&>(input, false), size);
case bond::BT_UINT32:
return DeserializeElements<Protocols>(var, value<uint32_t, Reader&>(input, false), size);
case bond::BT_UINT64:
return DeserializeElements<Protocols>(var, value<uint64_t, Reader&>(input, false), size);
case bond::BT_FLOAT:
return DeserializeElements<Protocols>(var, value<float, Reader&>(input, false), size);
case bond::BT_DOUBLE:
return DeserializeElements<Protocols>(var, value<double, Reader&>(input, false), size);
case bond::BT_STRING:
return DeserializeElements<Protocols>(var, value<std::string, Reader&>(input, false), size);
case bond::BT_WSTRING:
return DeserializeElements<Protocols>(var, value<std::wstring, Reader&>(input, false), size);
case bond::BT_INT8:
return DeserializeElements<Protocols>(var, value<int8_t, Reader&>(input, false), size);
case bond::BT_INT16:
return DeserializeElements<Protocols>(var, value<int16_t, Reader&>(input, false), size);
case bond::BT_INT32:
return DeserializeElements<Protocols>(var, value<int32_t, Reader&>(input, false), size);
case bond::BT_INT64:
return DeserializeElements<Protocols>(var, value<int64_t, Reader&>(input, false), size);
default:
BOOST_ASSERT(false);
return;
}
}
template <typename E>
inline void SkipElements(const E& element, uint32_t size)
{
while (size
element.Skip();
}
template <typename Reader>
inline void SkipElements(BondDataType type, Reader& input, uint32_t size)
{
while (size
input.Skip(type);
}
// <API key> function are manually expended versions of BasicTypeContainer
// using the type information about destination container. This helps with compilation speed.
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_type_alias<typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
if (type == get_type_id<typename element_type<T>::type>::value)
{
DeserializeElements<Protocols>(var, value<typename element_type<T>::type, Reader&>(input, false), size);
}
else
{
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<std::is_same<bool, typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
switch (type)
{
case bond::BT_BOOL:
return DeserializeElements<Protocols>(var, value<bool, Reader&>(input, false), size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_string<typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
switch (type)
{
case bond::BT_STRING:
return DeserializeElements<Protocols>(var, value<std::string, Reader&>(input, false), size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_wstring<typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
switch (type)
{
case bond::BT_WSTRING:
return DeserializeElements<Protocols>(var, value<std::wstring, Reader&>(input, false), size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<std::is_floating_point<typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
switch (type)
{
case bond::BT_FLOAT:
return DeserializeElements<Protocols>(var, value<float, Reader&>(input, false), size);
case bond::BT_DOUBLE:
return DeserializeElements<Protocols>(var, value<double, Reader&>(input, false), size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_matching<uint8_t, typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
switch (type)
{
case bond::BT_UINT8:
return DeserializeElements<Protocols>(var, value<uint8_t, Reader&>(input, false), size);
case bond::BT_UINT16:
return DeserializeElements<Protocols>(var, value<uint16_t, Reader&>(input, false), size);
case bond::BT_UINT32:
return DeserializeElements<Protocols>(var, value<uint32_t, Reader&>(input, false), size);
case bond::BT_UINT64:
return DeserializeElements<Protocols>(var, value<uint64_t, Reader&>(input, false), size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_matching<int8_t, typename element_type<T>::type> >::type
inline <API key>(T& var, BondDataType type, Reader& input, uint32_t size)
{
switch (type)
{
case bond::BT_INT8:
return DeserializeElements<Protocols>(var, value<int8_t, Reader&>(input, false), size);
case bond::BT_INT16:
return DeserializeElements<Protocols>(var, value<int16_t, Reader&>(input, false), size);
case bond::BT_INT32:
return DeserializeElements<Protocols>(var, value<int32_t, Reader&>(input, false), size);
case bond::BT_INT64:
return DeserializeElements<Protocols>(var, value<int64_t, Reader&>(input, false), size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type>(type));
SkipElements(type, input, size);
break;
}
}
// MatchingMapByKey function are manually expended versions of MapByKey using the type
// information about destination container. This helps with compilation speed.
template <typename E, typename Reader>
inline void SkipElements(BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
while (size
{
input.Skip(keyType);
element.Skip();
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<is_type_alias<typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
if (keyType == get_type_id<typename element_type<T>::type::first_type>::value)
{
return <API key><Protocols>(var, value<typename element_type<T>::type::first_type, Reader&>(input, false), element, size);
}
else
{
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<std::is_same<bool, typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_BOOL:
return <API key><Protocols>(var, value<bool, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
break;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<is_string<typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_STRING:
return <API key><Protocols>(var, value<std::string, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
break;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<is_wstring<typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_WSTRING:
return <API key><Protocols>(var, value<std::wstring, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
break;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<std::is_floating_point<typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_FLOAT:
return <API key><Protocols>(var, value<float, Reader&>(input, false), element, size);
case bond::BT_DOUBLE:
return <API key><Protocols>(var, value<double, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
break;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<is_matching<uint8_t, typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_UINT8:
return <API key><Protocols>(var, value<uint8_t, Reader&>(input, false), element, size);
case bond::BT_UINT16:
return <API key><Protocols>(var, value<uint16_t, Reader&>(input, false), element, size);
case bond::BT_UINT32:
return <API key><Protocols>(var, value<uint32_t, Reader&>(input, false), element, size);
case bond::BT_UINT64:
return <API key><Protocols>(var, value<uint64_t, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
break;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<is_matching<int8_t, typename element_type<T>::type::first_type> >::type
inline MatchingMapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_INT8:
return <API key><Protocols>(var, value<int8_t, Reader&>(input, false), element, size);
case bond::BT_INT16:
return <API key><Protocols>(var, value<int16_t, Reader&>(input, false), element, size);
case bond::BT_INT32:
return <API key><Protocols>(var, value<int32_t, Reader&>(input, false), element, size);
case bond::BT_INT64:
return <API key><Protocols>(var, value<int64_t, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::first_type>(keyType));
SkipElements(keyType, element, input, size);
break;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::disable_if<is_map_container<T> >::type
inline MapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
switch (keyType)
{
case bond::BT_BOOL:
return <API key><Protocols>(var, value<bool, Reader&>(input, false), element, size);
case bond::BT_UINT8:
return <API key><Protocols>(var, value<uint8_t, Reader&>(input, false), element, size);
case bond::BT_UINT16:
return <API key><Protocols>(var, value<uint16_t, Reader&>(input, false), element, size);
case bond::BT_UINT32:
return <API key><Protocols>(var, value<uint32_t, Reader&>(input, false), element, size);
case bond::BT_UINT64:
return <API key><Protocols>(var, value<uint64_t, Reader&>(input, false), element, size);
case bond::BT_FLOAT:
return <API key><Protocols>(var, value<float, Reader&>(input, false), element, size);
case bond::BT_DOUBLE:
return <API key><Protocols>(var, value<double, Reader&>(input, false), element, size);
case bond::BT_STRING:
return <API key><Protocols>(var, value<std::string, Reader&>(input, false), element, size);
case bond::BT_WSTRING:
return <API key><Protocols>(var, value<std::wstring, Reader&>(input, false), element, size);
case bond::BT_INT8:
return <API key><Protocols>(var, value<int8_t, Reader&>(input, false), element, size);
case bond::BT_INT16:
return <API key><Protocols>(var, value<int16_t, Reader&>(input, false), element, size);
case bond::BT_INT32:
return <API key><Protocols>(var, value<int32_t, Reader&>(input, false), element, size);
case bond::BT_INT64:
return <API key><Protocols>(var, value<int64_t, Reader&>(input, false), element, size);
default:
BOOST_ASSERT(false);
return;
}
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::enable_if<<API key><E, T> >::type
inline MapByKey(T& var, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
return MatchingMapByKey<Protocols>(var, keyType, element, input, size);
}
template <typename Protocols, typename T, typename E, typename Reader>
typename boost::disable_if_c<!is_map_container<T>::value || <API key><E, T>::value>::type
inline MapByKey(T&, BondDataType keyType, const E& element, Reader& input, uint32_t size)
{
while (size
{
input.Skip(keyType);
element.Skip();
}
}
template <typename Protocols, typename T, typename Reader>
inline void MapByElement(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_BOOL:
return MapByKey<Protocols>(var, keyType, value<bool, Reader&>(input, false), input, size);
case bond::BT_UINT8:
return MapByKey<Protocols>(var, keyType, value<uint8_t, Reader&>(input, false), input, size);
case bond::BT_UINT16:
return MapByKey<Protocols>(var, keyType, value<uint16_t, Reader&>(input, false), input, size);
case bond::BT_UINT32:
return MapByKey<Protocols>(var, keyType, value<uint32_t, Reader&>(input, false), input, size);
case bond::BT_UINT64:
return MapByKey<Protocols>(var, keyType, value<uint64_t, Reader&>(input, false), input, size);
case bond::BT_FLOAT:
return MapByKey<Protocols>(var, keyType, value<float, Reader&>(input, false), input, size);
case bond::BT_DOUBLE:
return MapByKey<Protocols>(var, keyType, value<double, Reader&>(input, false), input, size);
case bond::BT_STRING:
return MapByKey<Protocols>(var, keyType, value<std::string, Reader&>(input, false), input, size);
case bond::BT_WSTRING:
return MapByKey<Protocols>(var, keyType, value<std::wstring, Reader&>(input, false), input, size);
case bond::BT_INT8:
return MapByKey<Protocols>(var, keyType, value<int8_t, Reader&>(input, false), input, size);
case bond::BT_INT16:
return MapByKey<Protocols>(var, keyType, value<int16_t, Reader&>(input, false), input, size);
case bond::BT_INT32:
return MapByKey<Protocols>(var, keyType, value<int32_t, Reader&>(input, false), input, size);
case bond::BT_INT64:
return MapByKey<Protocols>(var, keyType, value<int64_t, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(false);
break;
}
}
// <API key> function are manually expended versions of MapByElement using
// the type information about destination container. This helps with compilation speed.
template <typename Reader>
inline void SkipElements(BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
while (size
{
input.Skip(keyType);
input.Skip(elementType);
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_type_alias<typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
if (elementType == get_type_id<typename element_type<T>::type::second_type>::value)
{
MapByKey<Protocols>(var, keyType, value<typename element_type<T>::type::second_type, Reader&>(input, false), input, size);
}
else
{
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<std::is_same<bool, typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_BOOL:
return MapByKey<Protocols>(var, keyType, value<bool, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_string<typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_STRING:
return MapByKey<Protocols>(var, keyType, value<std::string, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_wstring<typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_WSTRING:
return MapByKey<Protocols>(var, keyType, value<std::wstring, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<std::is_floating_point<typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_FLOAT:
return MapByKey<Protocols>(var, keyType, value<float, Reader&>(input, false), input, size);
case bond::BT_DOUBLE:
return MapByKey<Protocols>(var, keyType, value<double, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_matching<uint8_t, typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_UINT8:
return MapByKey<Protocols>(var, keyType, value<uint8_t, Reader&>(input, false), input, size);
case bond::BT_UINT16:
return MapByKey<Protocols>(var, keyType, value<uint16_t, Reader&>(input, false), input, size);
case bond::BT_UINT32:
return MapByKey<Protocols>(var, keyType, value<uint32_t, Reader&>(input, false), input, size);
case bond::BT_UINT64:
return MapByKey<Protocols>(var, keyType, value<uint64_t, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
break;
}
}
template <typename Protocols, typename T, typename Reader>
typename boost::enable_if<is_matching<int8_t, typename element_type<T>::type::second_type> >::type
inline <API key>(T& var, BondDataType keyType, BondDataType elementType, Reader& input, uint32_t size)
{
switch (elementType)
{
case bond::BT_INT8:
return MapByKey<Protocols>(var, keyType, value<int8_t, Reader&>(input, false), input, size);
case bond::BT_INT16:
return MapByKey<Protocols>(var, keyType, value<int16_t, Reader&>(input, false), input, size);
case bond::BT_INT32:
return MapByKey<Protocols>(var, keyType, value<int32_t, Reader&>(input, false), input, size);
case bond::BT_INT64:
return MapByKey<Protocols>(var, keyType, value<int64_t, Reader&>(input, false), input, size);
default:
BOOST_ASSERT(!IsMatching<typename element_type<T>::type::second_type>(elementType));
SkipElements(keyType, elementType, input, size);
break;
}
}
} // namespace detail
} // namespace bond
#ifdef BOND_LIB_TYPE
#if BOND_LIB_TYPE != <API key>
#include "typeid_value_extern.h"
#endif
#else
#error BOND_LIB_TYPE is undefined
#endif |
using System.Collections.Generic;
using Spect.Net.Assembler.SyntaxTree;
namespace Spect.Net.Assembler.Assembler
{
<summary>
Represents the definition of an IF section to process
</summary>
public class IfDefinition
{
<summary>
The entire IF section
</summary>
public DefinitionSection FullSection { get; set; }
<summary>
List of if sections
</summary>
public List<IfSection> IfSections { get; } = new List<IfSection>();
<summary>
Optional else section
</summary>
public IfSection ElseSection { get; set; } = null;
}
<summary>
Represents a section of the If definition
</summary>
public class IfSection
{
<summary>
The statement of the section
</summary>
public StatementBase IfStatement { get; }
<summary>
The section boundaries
</summary>
public DefinitionSection Section { get; }
public IfSection(StatementBase stmt, int firstLine, int lastLine)
{
IfStatement = stmt;
Section = new DefinitionSection(firstLine, lastLine);
}
}
} |
<?php
namespace TwigIntegratorKit;
class TwigIntegratorKit
{
const VERSION = '0.1.5';
} |
<?php
namespace JasonRoman\NbaApi\Request\Data\Cms\Schedule;
use JasonRoman\NbaApi\Constraints as ApiAssert;
use JasonRoman\NbaApi\Params\TeamSlugParam;
use JasonRoman\NbaApi\Request\Data\Cms\<API key>;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Get a team's summer league schedule.
*/
class <API key> extends <API key>
{
const ENDPOINT = '/json/sl/cms/{year}/team/{teamSlug}/schedule.json';
/**
* @Assert\NotBlank()
* @Assert\Type("int")
* @Assert\Range(min = 2015)
*
* @var int
*/
public $year;
/**
* @Assert\NotBlank()
* @Assert\Type("string")
* @ApiAssert\ApiChoice(TeamSlugParam::OPTIONS)
*
* @var string
*/
public $teamSlug;
} |
<!DOCTYPE html>
<html>
<head>
<body style="background-color:#E52826;">
<text style="color:#00EADC;">
<style>
h1{ text-align: center;}
p{ text-align: center;}
h2{ text-align: center;}
h3{ text-align: center;}
a{ text-align: center;}
ol{ text-align: center;}
img {
display: block;
margin: auto;
width: 40%;
}
body{ cursor: url('alsobestcursor.cur'), auto;}
</style>
<title>
Run The Conrardy
</title>
</head>
<body>
<audio controls autoplay>
<source src="Run The Jewels - Blockbuster Night Part 1.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<h1>
Ryan Conrardy
</h1>
<img src="http:
<h2>PERSONAL:</h2>
<p>
From outside Chi-raq, Illinois. <br/>
Biggest G in the computer science program. <br/>
Double major in biology and computer, already graduated with a bachlor in biology so I've pristeged back to a freshman. <br/>
Dank memes and crippling depression. </br></br>
Favorite programming languages:</br>
1. Profanity</br>
2. Profanity++</br>
3. Java</br>
4. C++
</p>
<p>
<a href="meme.html">Dank Memes</a></br>
</p>
<h2>NOTES:</h2>
<p>
<a href="<API key>.html">Hierarchy of Abstractions</a></br>
<a href="Definitions.html">Definitions</a></br>
</p>
<h3><u>Class Notes</u></h3>
<!--/home/local/CORNELL-COLLEGE/rconrardy17/network-notes/team/ryan/ (school computer)-->
<!--C:\Users\Ryan\network-notes\team\ryan\ (laptop)
<!-- (Desktop>-->
<p>
<a href="Oct3.html">October 3rd</a></br>
<a href="Oct5.html">October 5th</a></br>
<a href="Oct6.html">October 6th</a></br>
<a href="Oct7.html">October 7th</a></br>
<a href="Oct10.html">October 10th</a></br>
<a href="Oct11.html">October 11th</a></br>
<a href="Oct12.html">October 12th</a></br>
<a href="Oct13.html">October 13th</a></br>
<a href="Oct14.html">October 14th</a></br>
<a href="Oct17.html">October 17th</a></br>
<a href="Oct18.html">October 18th</a></br>
<a href="Oct19.html">October 19th</a></br>
<a href="Oct20.html">October 20th</a></br>
<a href="Oct21.html">October 21st</a></br>
<a href="Oct24.html">October 24th</a></br>
<a href="Oct25.html">October 25th</a></br>
<a href="Oct26.html">October 26th</a></br>
</p>
<h2>LABS:</h2>
<p>
<a href="Wireshark.html">Wireshark</a></br>
</P>
<h2>GRADED EXERCIZES:</h2>
<p>
<a href="gradedexercize0.html">Graded Exercize 0</a></br>
<a href="gradedexercize1.html">Graded Exercize 1</a></br>
<a href="gradedexercize2.html">Graded Exercize 2</a></br>
</p>
</body>
</html> |
#include "converter/smr2rdox/pch.h"
#include "converter/smr2rdox/rdoparser_rdo.h"
#include "converter/smr2rdox/rdoparser_lexer.h"
#include "converter/smr2rdox/rdoparser.h"
#include "converter/smr2rdox/rdosmr.h"
#include "converter/smr2rdox/rdorss.h"
#include "converter/smr2rdox/rdortp.h"
#include "converter/smr2rdox/rdofun.h"
#include "converter/smr2rdox/rdosmr.h"
#include "converter/smr2rdox/rdopat.h"
#include "simulator/runtime/rdo_pattern.h"
#include "kernel/rdokernel.h"
#include "repository/rdorepository.h"
#include "simulator/runtime/calc/function/<API key>.h"
<API key>
RDOParserRDOItem::RDOParserRDOItem(rdo::converter::smr2rdox::FileTypeIn type, t_bison_parse_fun parser_fun, t_flex_lexer_fun lexer_fun)
: RDOParserItem(type, parser_fun, lexer_fun)
, m_pLexer(NULL)
{}
RDOParserRDOItem::~RDOParserRDOItem()
{
if (m_pLexer)
{
delete m_pLexer;
m_pLexer = NULL;
}
}
void RDOParserRDOItem::parse(Converter* pParser, std::istream& streamIn)
{
ASSERT(pParser);
if (!streamIn.good())
return;
if (m_pLexer)
delete m_pLexer;
std::ostringstream streamOut;
m_pLexer = getLexer(pParser, &streamIn, &streamOut);
if (m_pLexer && m_parser_fun)
m_parser_fun(m_pLexer);
}
RDOLexer* RDOParserRDOItem::getLexer(Converter* pParser, std::istream* streamIn, std::ostream* streamOut)
{
ASSERT(pParser);
return new RDOLexer(pParser, streamIn, streamOut);
}
std::size_t RDOParserRDOItem::lexer_loc_line()
{
if (m_pLexer)
{
return m_pLexer->m_lploc ? m_pLexer->m_lploc->m_first_line : m_pLexer->lineno();
}
else
{
return std::size_t(rdo::runtime::RDOSrcInfo::Position::UNDEFINE_LINE);
}
}
std::size_t RDOParserRDOItem::lexer_loc_pos()
{
return m_pLexer && m_pLexer->m_lploc ? m_pLexer->m_lploc->m_first_pos : 0;
}
RDOParserRSS::RDOParserRSS()
: RDOParserRDOItem(rdo::converter::smr2rdox::FileTypeIn::RSS, cnv_rssparse, cnv_rsslex)
{}
void RDOParserRSS::parse(Converter* pParser, std::istream& streamIn)
{
ASSERT(pParser);
pParser->setHaveKWResources (false);
pParser-><API key>(false);
RDOParserRDOItem::parse(pParser, streamIn);
}
RDOParserRSSPost::RDOParserRSSPost()
: RDOParserItem(rdo::converter::smr2rdox::FileTypeIn::RSS, NULL, NULL)
{
m_needStream = false;
}
void RDOParserRSSPost::parse(Converter* pParser)
{
ASSERT(pParser);
#ifdef RDOSIM_COMPATIBLE
for (const auto& rtp: pParser->getRTPResTypes())
{
#endif
for (const auto& rss: pParser->getRSSResources())
{
#ifdef RDOSIM_COMPATIBLE
if (rss->getType() == rtp)
{
#endif
rdo::runtime::LPRDOCalc calc = rss->createCalc();
pParser->runtime()->addInitCalc(calc);
#ifdef RDOSIM_COMPATIBLE
}
#endif
}
#ifdef RDOSIM_COMPATIBLE
}
#endif
}
RDOParserSTDFUN::RDOParserSTDFUN()
: RDOParserItem(rdo::converter::smr2rdox::FileTypeIn::FUN, NULL, NULL)
{
m_needStream = false;
}
double cotan(double value)
{
return 1.0 / tan(value);
}
int intLocal(int value)
{
return value;
}
double log2Local(double value)
{
return log(value) / log(2.0);
}
double logNLocal(double value1, double value2)
{
return log(value1) / log(value2);
}
template <class T>
T maxLocal(T value1, T value2)
{
return value1 > value2 ? value1 : value2;
}
template <class T>
T minLocal(T value1, T value2)
{
return value1 < value2 ? value1 : value2;
}
double modf(double value)
{
double tmp;
return ::modf(value, &tmp);
}
int roundLocal(double value)
{
return (int)floor(value + 0.5);
}
void RDOParserSTDFUN::parse(Converter* /*pParser*/)
{
typedef rdo::runtime::std_fun1<double, double> StdFun_D_D;
typedef rdo::runtime::std_fun2<double, double, double> StdFun_D_DD;
typedef rdo::runtime::std_fun2<double, double, int> StdFun_D_DI;
typedef rdo::runtime::std_fun1<int, int> StdFun_I_I;
typedef rdo::runtime::std_fun2<int, int, int> StdFun_I_II;
typedef rdo::runtime::std_fun1<int, double> StdFun_I_D;
typedef rdo::runtime::RDOFunCalcStd<StdFun_D_D> Function_D_D;
typedef rdo::runtime::RDOFunCalcStd<StdFun_D_DD> Function_D_DD;
typedef rdo::runtime::RDOFunCalcStd<StdFun_D_DI> Function_D_DI;
typedef rdo::runtime::RDOFunCalcStd<StdFun_I_I> Function_I_I;
typedef rdo::runtime::RDOFunCalcStd<StdFun_I_II> Function_I_II;
typedef rdo::runtime::RDOFunCalcStd<StdFun_I_D> Function_I_D;
LPRDOTypeParam intType = rdo::Factory<RDOTypeParam>::create(rdo::Factory<RDOType__INT>::create(), RDOParserSrcInfo());
LPRDOTypeParam realType = rdo::Factory<RDOTypeParam>::create(rdo::Factory<RDOType__REAL>::create(), RDOParserSrcInfo());
LPRDOParam pIntReturn = rdo::Factory<RDOParam>::create(RDOParserSrcInfo(), intType );
LPRDOParam pRealReturn = rdo::Factory<RDOParam>::create(RDOParserSrcInfo(), realType);
LPRDOFUNFunction fun = rdo::Factory<RDOFUNFunction>::create("Abs", pRealReturn);
LPRDOParam param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(fabs));
fun = rdo::Factory<RDOFUNFunction>::create("ArcCos", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(acos));
fun = rdo::Factory<RDOFUNFunction>::create("ArcSin", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(asin));
fun = rdo::Factory<RDOFUNFunction>::create("ArcTan", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(atan));
fun = rdo::Factory<RDOFUNFunction>::create("Cos", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(cos));
fun = rdo::Factory<RDOFUNFunction>::create("Cotan", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D ::function_type>(cotan));
fun = rdo::Factory<RDOFUNFunction>::create("Exp", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(exp));
fun = rdo::Factory<RDOFUNFunction>::create("Floor", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(floor));
fun = rdo::Factory<RDOFUNFunction>::create("Frac", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(modf));
fun = rdo::Factory<RDOFUNFunction>::create("IAbs", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_I>::create<Function_I_I::function_type>(static_cast<Function_I_I::function_type>(abs)));
fun = rdo::Factory<RDOFUNFunction>::create("IMax", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", intType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_II>::create<Function_I_II::function_type>(maxLocal<int>));
fun = rdo::Factory<RDOFUNFunction>::create("IMin", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", intType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_II>::create<Function_I_II::function_type>(minLocal<int>));
fun = rdo::Factory<RDOFUNFunction>::create("Int", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_I>::create<Function_I_I::function_type>(intLocal));
fun = rdo::Factory<RDOFUNFunction>::create("IntPower", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DI>::create<Function_D_DI::function_type>(static_cast<Function_D_DI::function_type>(std::pow)));
fun = rdo::Factory<RDOFUNFunction>::create("Ln", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(log));
fun = rdo::Factory<RDOFUNFunction>::create("Log10", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(log10));
fun = rdo::Factory<RDOFUNFunction>::create("Log2", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(log2Local));
fun = rdo::Factory<RDOFUNFunction>::create("LogN", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(logNLocal));
fun = rdo::Factory<RDOFUNFunction>::create("Max", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(maxLocal<double>));
fun = rdo::Factory<RDOFUNFunction>::create("Min", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(minLocal<double>));
fun = rdo::Factory<RDOFUNFunction>::create("Power", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(static_cast<Function_D_DD::function_type>(pow)));
fun = rdo::Factory<RDOFUNFunction>::create("Round", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_D>::create(roundLocal));
fun = rdo::Factory<RDOFUNFunction>::create("Sin", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(sin));
fun = rdo::Factory<RDOFUNFunction>::create("Sqrt", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(sqrt));
fun = rdo::Factory<RDOFUNFunction>::create("Tan", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(tan));
fun = rdo::Factory<RDOFUNFunction>::create("abs", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(fabs));
fun = rdo::Factory<RDOFUNFunction>::create("arccos", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(acos));
fun = rdo::Factory<RDOFUNFunction>::create("arcsin", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(asin));
fun = rdo::Factory<RDOFUNFunction>::create("arctan", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(atan));
fun = rdo::Factory<RDOFUNFunction>::create("cos", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(cos));
fun = rdo::Factory<RDOFUNFunction>::create("cotan", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(cotan));
fun = rdo::Factory<RDOFUNFunction>::create("exp", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(exp));
fun = rdo::Factory<RDOFUNFunction>::create("floor", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(floor));
fun = rdo::Factory<RDOFUNFunction>::create("frac", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(modf));
fun = rdo::Factory<RDOFUNFunction>::create("iabs", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_I>::create<Function_I_I::function_type>(static_cast<Function_I_I::function_type>(abs)));
fun = rdo::Factory<RDOFUNFunction>::create("imax", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", intType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_II>::create<Function_I_II::function_type>(maxLocal<int>));
fun = rdo::Factory<RDOFUNFunction>::create("imin", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", intType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_II>::create<Function_I_II::function_type>(minLocal<int>));
fun = rdo::Factory<RDOFUNFunction>::create("int", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_I>::create<Function_I_I::function_type>(intLocal));
fun = rdo::Factory<RDOFUNFunction>::create("intpower", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", intType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DI>::create<Function_D_DI::function_type>(static_cast<Function_D_DI::function_type>(std::pow)));
fun = rdo::Factory<RDOFUNFunction>::create("ln", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(log));
fun = rdo::Factory<RDOFUNFunction>::create("log10", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(log10));
fun = rdo::Factory<RDOFUNFunction>::create("log2", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(log2Local));
fun = rdo::Factory<RDOFUNFunction>::create("logn", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(logNLocal));
fun = rdo::Factory<RDOFUNFunction>::create("max", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(maxLocal<double>));
fun = rdo::Factory<RDOFUNFunction>::create("min", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(minLocal<double>));
fun = rdo::Factory<RDOFUNFunction>::create("power", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
param = rdo::Factory<RDOParam>::create("p2", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_DD>::create<Function_D_DD::function_type>(static_cast<Function_D_DD::function_type>(pow)));
fun = rdo::Factory<RDOFUNFunction>::create("round", pIntReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_I_D>::create<Function_I_D::function_type>(roundLocal));
fun = rdo::Factory<RDOFUNFunction>::create("sin", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(sin));
fun = rdo::Factory<RDOFUNFunction>::create("sqrt", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(sqrt));
fun = rdo::Factory<RDOFUNFunction>::create("tan", pRealReturn);
param = rdo::Factory<RDOParam>::create("p1", realType);
fun->add(param);
fun->setFunctionCalc(rdo::Factory<Function_D_D>::create<Function_D_D::function_type>(tan));
}
<API key> |
<!DOCTYPE html>
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if IE 9]> <html class="no-js lt-ie10"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>ProUI - Responsive Bootstrap Admin Template</title>
<meta name="description" content="ProUI is a Responsive Bootstrap Admin Template created by pixelcave and published on Themeforest.">
<meta name="author" content="pixelcave">
<meta name="robots" content="noindex, nofollow">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0">
<!-- Icons -->
<!-- The following icons can be replaced with your own, they are used by desktop and mobile browsers -->
<link rel="shortcut icon" href="img/favicon.ico">
<link rel="apple-touch-icon" href="img/icon57.png" sizes="57x57">
<link rel="apple-touch-icon" href="img/icon72.png" sizes="72x72">
<link rel="apple-touch-icon" href="img/icon76.png" sizes="76x76">
<link rel="apple-touch-icon" href="img/icon114.png" sizes="114x114">
<link rel="apple-touch-icon" href="img/icon120.png" sizes="120x120">
<link rel="apple-touch-icon" href="img/icon144.png" sizes="144x144">
<link rel="apple-touch-icon" href="img/icon152.png" sizes="152x152">
<!-- END Icons -->
<!-- Stylesheets -->
<!-- Bootstrap is included in its original form, unaltered -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Related styles of various icon packs and plugins -->
<link rel="stylesheet" href="css/plugins.css">
<!-- The main stylesheet of this template. All Bootstrap overwrites are defined in here -->
<link rel="stylesheet" href="css/main.css">
<!-- Include a specific file here from css/themes/ folder to alter the default theme of the template -->
<!-- The themes stylesheet of this template (for using specific theme color in individual elements - must included last) -->
<link rel="stylesheet" href="css/themes.css">
<!-- END Stylesheets -->
<!-- Modernizr (browser feature detection library) & Respond.js (Enable responsive CSS code on browsers that don't support it, eg IE8) -->
<script src="js/vendor/modernizr-2.7.1-respond-1.4.2.min.js"></script>
</head>
<!-- In the PHP version you can set the following options from inc/config file -->
<!
Available body classes:
'page-loading' enables page preloader
<body>
<!-- Preloader -->
<!-- Preloader functionality (initialized in js/app.js) - pageLoading() -->
<!-- Used only if page preloader is enabled from inc/config (PHP version) or the class 'page-loading' is added in body element (HTML version) -->
<div class="preloader themed-background">
<h1 class="push-top-bottom text-light text-center"><strong>Pro</strong>UI</h1>
<div class="inner">
<h3 class="text-light visible-lt-ie9 visible-lt-ie10"><strong>Loading..</strong></h3>
<div class="preloader-spinner hidden-lt-ie9 hidden-lt-ie10"></div>
</div>
</div>
<!-- END Preloader -->
<!-- Page Container -->
<!-- In the PHP version you can set the following options from inc/config file -->
<!
Available #page-container classes:
'' (None) for a full main and alternative sidebar hidden by default (> 991px)
'sidebar-visible-lg' for a full main sidebar visible by default (> 991px)
'sidebar-partial' for a partial main sidebar which opens on mouse hover, hidden by default (> 991px)
'sidebar-partial sidebar-visible-lg' for a partial main sidebar which opens on mouse hover, visible by default (> 991px)
'<API key>' for a full alternative sidebar visible by default (> 991px)
'sidebar-alt-partial' for a partial alternative sidebar which opens on mouse hover, hidden by default (> 991px)
'sidebar-alt-partial <API key>' for a partial alternative sidebar which opens on mouse hover, visible by default (> 991px)
'sidebar-partial sidebar-alt-partial' for both sidebars partial which open on mouse hover, hidden by default (> 991px)
'<API key>' add this as extra for disabling sidebar animations on large screens (> 991px) - Better performance with heavy pages!
'style-alt' for an alternative main style (without it: the default style)
'footer-fixed' for a fixed footer (without it: a static footer)
'<API key>' add this to disable the main menu auto scrolling when opening a submenu
'header-fixed-top' has to be added only if the class 'navbar-fixed-top' was added on header.navbar
'header-fixed-bottom' has to be added only if the class 'navbar-fixed-bottom' was added on header.navbar
<div id="page-container" class="sidebar-partial sidebar-alt-partial <API key>">
<!-- Alternative Sidebar -->
<div id="sidebar-alt">
<!-- Wrapper for scrolling functionality -->
<div class="sidebar-scroll">
<!-- Sidebar Content -->
<div class="sidebar-content">
<!-- Chat -->
<!-- Chat demo functionality initialized in js/app.js -> chatUi() -->
<a href="page_ready_chat.html" class="sidebar-title">
<i class="gi gi-comments pull-right"></i> <strong>Chat</strong>UI
</a>
<!-- Chat Users -->
<ul class="chat-users clearfix">
<li>
<a href="javascript:void(0)" class="chat-user-online">
<span></span>
<img src="img/placeholders/avatars/avatar12.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)" class="chat-user-online">
<span></span>
<img src="img/placeholders/avatars/avatar15.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)" class="chat-user-online">
<span></span>
<img src="img/placeholders/avatars/avatar10.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)" class="chat-user-online">
<span></span>
<img src="img/placeholders/avatars/avatar4.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)" class="chat-user-away">
<span></span>
<img src="img/placeholders/avatars/avatar7.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)" class="chat-user-away">
<span></span>
<img src="img/placeholders/avatars/avatar9.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)" class="chat-user-busy">
<span></span>
<img src="img/placeholders/avatars/avatar16.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)">
<span></span>
<img src="img/placeholders/avatars/avatar1.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)">
<span></span>
<img src="img/placeholders/avatars/avatar4.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)">
<span></span>
<img src="img/placeholders/avatars/avatar3.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)">
<span></span>
<img src="img/placeholders/avatars/avatar13.jpg" alt="avatar" class="img-circle">
</a>
</li>
<li>
<a href="javascript:void(0)">
<span></span>
<img src="img/placeholders/avatars/avatar5.jpg" alt="avatar" class="img-circle">
</a>
</li>
</ul>
<!-- END Chat Users -->
<!-- Chat Talk -->
<div class="chat-talk display-none">
<!-- Chat Info -->
<div class="chat-talk-info sidebar-section">
<img src="img/placeholders/avatars/avatar5.jpg" alt="avatar" class="img-circle pull-left">
<strong>John</strong> Doe
<button id="chat-talk-close-btn" class="btn btn-xs btn-default pull-right">
<i class="fa fa-times"></i>
</button>
</div>
<!-- END Chat Info -->
<!-- Chat Messages -->
<ul class="chat-talk-messages">
<li class="text-center"><small>Yesterday, 18:35</small></li>
<li class="chat-talk-msg <API key>">Hey admin?</li>
<li class="chat-talk-msg <API key>">How are you?</li>
<li class="text-center"><small>Today, 7:10</small></li>
<li class="chat-talk-msg <API key> themed-border animation-slideLeft">I'm fine, thanks!</li>
</ul>
<!-- END Chat Messages -->
<!-- Chat Input -->
<form action="index.html" method="post" id="sidebar-chat-form" class="chat-form">
<input type="text" id="<API key>" name="<API key>" class="form-control <API key>" placeholder="Type a message..">
</form>
<!-- END Chat Input -->
</div>
<!-- END Chat Talk -->
<!-- END Chat -->
<!-- Activity -->
<a href="javascript:void(0)" class="sidebar-title">
<i class="fa fa-globe pull-right"></i> <strong>Activity</strong>UI
</a>
<div class="sidebar-section">
<div class="alert alert-danger alert-alt">
<small>just now</small><br>
<i class="fa fa-thumbs-up fa-fw"></i> Upgraded to Pro plan
</div>
<div class="alert alert-info alert-alt">
<small>2 hours ago</small><br>
<i class="gi gi-coins fa-fw"></i> You had a new sale!
</div>
<div class="alert alert-success alert-alt">
<small>3 hours ago</small><br>
<i class="fa fa-plus fa-fw"></i> <a href="<API key>.html"><strong>John Doe</strong></a> would like to become friends!<br>
<a href="javascript:void(0)" class="btn btn-xs btn-primary"><i class="fa fa-check"></i> Accept</a>
<a href="javascript:void(0)" class="btn btn-xs btn-default"><i class="fa fa-times"></i> Ignore</a>
</div>
<div class="alert alert-warning alert-alt">
<small>2 days ago</small><br>
Running low on space<br><strong>18GB in use</strong> 2GB left<br>
<a href="<API key>.html" class="btn btn-xs btn-primary"><i class="fa fa-arrow-up"></i> Upgrade Plan</a>
</div>
</div>
<!-- END Activity -->
<!-- Messages -->
<a href="page_ready_inbox.html" class="sidebar-title">
<i class="fa fa-envelope pull-right"></i> <strong>Messages</strong>UI (5)
</a>
<div class="sidebar-section">
<div class="alert alert-alt">
Debra Stanley<small class="pull-right">just now</small><br>
<a href="<API key>.html"><strong>New Follower</strong></a>
</div>
<div class="alert alert-alt">
Sarah Cole<small class="pull-right">2 min ago</small><br>
<a href="<API key>.html"><strong>Your subscription was updated</strong></a>
</div>
<div class="alert alert-alt">
Bryan Porter<small class="pull-right">10 min ago</small><br>
<a href="<API key>.html"><strong>A great opportunity</strong></a>
</div>
<div class="alert alert-alt">
Jose Duncan<small class="pull-right">30 min ago</small><br>
<a href="<API key>.html"><strong>Account Activation</strong></a>
</div>
<div class="alert alert-alt">
Henry Ellis<small class="pull-right">40 min ago</small><br>
<a href="<API key>.html"><strong>You reached 10.000 Followers!</strong></a>
</div>
</div>
<!-- END Messages -->
</div>
<!-- END Sidebar Content -->
</div>
<!-- END Wrapper for scrolling functionality -->
</div>
<!-- END Alternative Sidebar -->
<!-- Main Sidebar -->
<div id="sidebar">
<!-- Wrapper for scrolling functionality -->
<div class="sidebar-scroll">
<!-- Sidebar Content -->
<div class="sidebar-content">
<!-- Brand -->
<a href="index.html" class="sidebar-brand">
<i class="gi gi-flash"></i><strong>Pro</strong>UI
</a>
<!-- END Brand -->
<!-- User Info -->
<div class="sidebar-section sidebar-user clearfix">
<div class="sidebar-user-avatar">
<a href="<API key>.html">
<img src="img/placeholders/avatars/avatar2.jpg" alt="avatar">
</a>
</div>
<div class="sidebar-user-name">John Doe</div>
<div class="sidebar-user-links">
<a href="<API key>.html" data-toggle="tooltip" data-placement="bottom" title="Profile"><i class="gi gi-user"></i></a>
<a href="page_ready_inbox.html" data-toggle="tooltip" data-placement="bottom" title="Messages"><i class="gi gi-envelope"></i></a>
<!-- Opens the user settings modal that can be found at the bottom of each page (page_footer.html in PHP version) -->
<a href="#modal-user-settings" data-toggle="modal" class="enable-tooltip" data-placement="bottom" title="Settings"><i class="gi gi-cogwheel"></i></a>
<a href="login.html" data-toggle="tooltip" data-placement="bottom" title="Logout"><i class="gi gi-exit"></i></a>
</div>
</div>
<!-- END User Info -->
<!-- Theme Colors -->
<!-- Change Color Theme functionality can be found in js/app.js - templateOptions() -->
<ul class="sidebar-section sidebar-themes clearfix">
<li class="active">
<a href="javascript:void(0)" class="<API key> <API key>" data-theme="default" data-toggle="tooltip" title="Default Blue"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> themed-border-night" data-theme="css/themes/night.css" data-toggle="tooltip" title="Night"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> <API key>" data-theme="css/themes/amethyst.css" data-toggle="tooltip" title="Amethyst"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> <API key>" data-theme="css/themes/modern.css" data-toggle="tooltip" title="Modern"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> <API key>" data-theme="css/themes/autumn.css" data-toggle="tooltip" title="Autumn"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> <API key>" data-theme="css/themes/flatie.css" data-toggle="tooltip" title="Flatie"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> <API key>" data-theme="css/themes/spring.css" data-toggle="tooltip" title="Spring"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> themed-border-fancy" data-theme="css/themes/fancy.css" data-toggle="tooltip" title="Fancy"></a>
</li>
<li>
<a href="javascript:void(0)" class="<API key> themed-border-fire" data-theme="css/themes/fire.css" data-toggle="tooltip" title="Fire"></a>
</li>
</ul>
<!-- END Theme Colors -->
<!-- Sidebar Navigation -->
<ul class="sidebar-nav">
<li>
<a href="index.html"><i class="gi gi-stopwatch sidebar-nav-icon"></i>Dashboard</a>
</li>
<li class="sidebar-header">
<span class="<API key> clearfix"><a href="javascript:void(0)" data-toggle="tooltip" title="Quick Settings"><i class="gi gi-settings"></i></a><a href="javascript:void(0)" data-toggle="tooltip" title="Create the most amazing pages with the widget kit!"><i class="gi gi-lightbulb"></i></a></span>
<span class="<API key>">Widget Kit</span>
</li>
<li>
<a href="page_widgets_stats.html"><i class="gi gi-charts sidebar-nav-icon"></i>Statistics</a>
</li>
<li>
<a href="page_widgets_social.html"><i class="gi gi-share_alt sidebar-nav-icon"></i>Social</a>
</li>
<li>
<a href="page_widgets_media.html"><i class="gi gi-film sidebar-nav-icon"></i>Media</a>
</li>
<li>
<a href="page_widgets_links.html"><i class="gi gi-link sidebar-nav-icon"></i>Links</a>
</li>
<li class="sidebar-header">
<span class="<API key> clearfix"><a href="javascript:void(0)" data-toggle="tooltip" title="Quick Settings"><i class="gi gi-settings"></i></a></span>
<span class="<API key>">Design Kit</span>
</li>
<li>
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="gi gi-certificate sidebar-nav-icon"></i>User Interface</a>
<ul>
<li>
<a href="page_ui_grid_blocks.html">Grid & Blocks</a>
</li>
<li>
<a href="<API key>.html">Draggable Blocks</a>
</li>
<li>
<a href="page_ui_typography.html">Typography</a>
</li>
<li>
<a href="<API key>.html">Buttons & Dropdowns</a>
</li>
<li>
<a href="<API key>.html">Navigation & More</a>
</li>
<li>
<a href="<API key>.html">Horizontal Menu</a>
</li>
<li>
<a href="<API key>.html">Progress & Loading</a>
</li>
<li>
<a href="page_ui_preloader.html">Page Preloader</a>
</li>
<li>
<a href="<API key>.html">Color Themes</a>
</li>
</ul>
</li>
<li>
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="gi gi-notes_2 sidebar-nav-icon"></i>Forms</a>
<ul>
<li>
<a href="page_forms_general.html">General</a>
</li>
<li>
<a href="<API key>.html">Components</a>
</li>
<li>
<a href="<API key>.html">Validation</a>
</li>
<li>
<a href="page_forms_wizard.html">Wizard</a>
</li>
</ul>
</li>
<li>
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="gi gi-table sidebar-nav-icon"></i>Tables</a>
<ul>
<li>
<a href="page_tables_general.html">General</a>
</li>
<li>
<a href="<API key>.html">Responsive</a>
</li>
<li>
<a href="<API key>.html">Datatables</a>
</li>
</ul>
</li>
<li>
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="gi gi-cup sidebar-nav-icon"></i>Icon Sets</a>
<ul>
<li>
<a href="<API key>.html">Font Awesome</a>
</li>
<li>
<a href="<API key>.html">Glyphicons Pro</a>
</li>
</ul>
</li>
<li class="active">
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="gi <API key> sidebar-nav-icon"></i>Page Layouts</a>
<ul>
<li>
<a href="page_layout_static.html">Static</a>
</li>
<li>
<a href="<API key>.html">Static + Fixed Footer</a>
</li>
<li>
<a href="<API key>.html">Fixed Top Header</a>
</li>
<li>
<a href="<API key>.html">Fixed Top Header + Footer</a>
</li>
<li>
<a href="<API key>.html">Fixed Bottom Header</a>
</li>
<li>
<a href="<API key>.html">Fixed Bottom Header + Footer</a>
</li>
<li>
<a href="<API key>.html">Partial Main Sidebar</a>
</li>
<li>
<a href="<API key>.html">Visible Main Sidebar</a>
</li>
<li>
<a href="<API key>.html">Partial Alternative Sidebar</a>
</li>
<li>
<a href="<API key>.html">Visible Alternative Sidebar</a>
</li>
<li>
<a href="<API key>.html">No Sidebars</a>
</li>
<li>
<a href="<API key>.html" class=" active">Both Sidebars Partial</a>
</li>
<li>
<a href="<API key>.html">Animated Sidebar Transitions</a>
</li>
</ul>
</li>
<li class="sidebar-header">
<span class="<API key> clearfix"><a href="javascript:void(0)" data-toggle="tooltip" title="Quick Settings"><i class="gi gi-settings"></i></a></span>
<span class="<API key>">Develop Kit</span>
</li>
<li>
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="fa fa-wrench sidebar-nav-icon"></i>Components</a>
<ul>
<li>
<a href="#" class="sidebar-nav-submenu"><i class="fa fa-angle-left <API key>"></i>3 Level Menu</a>
<ul>
<li>
<a href="#">Link 1</a>
</li>
<li>
<a href="#">Link 2</a>
</li>
</ul>
</li>
<li>
<a href="page_comp_maps.html">Maps</a>
</li>
<li>
<a href="page_comp_charts.html">Charts</a>
</li>
<li>
<a href="page_comp_gallery.html">Gallery</a>
</li>
<li>
<a href="page_comp_carousel.html">Carousel</a>
</li>
<li>
<a href="page_comp_calendar.html">Calendar</a>
</li>
<li>
<a href="<API key>.html">CSS3 Animations</a>
</li>
<li>
<a href="<API key>.html">Syntax Highlighting</a>
</li>
</ul>
</li>
<li>
<a href="#" class="sidebar-nav-menu"><i class="fa fa-angle-left <API key>"></i><i class="gi gi-brush sidebar-nav-icon"></i>Ready Pages</a>
<ul>
<li>
<a href="#" class="sidebar-nav-submenu"><i class="fa fa-angle-left <API key>"></i>Errors</a>
<ul>
<li>
<a href="page_ready_400.html">400</a>
</li>
<li>
<a href="page_ready_401.html">401</a>
</li>
<li>
<a href="page_ready_403.html">403</a>
</li>
<li>
<a href="page_ready_404.html">404</a>
</li>
<li>
<a href="page_ready_500.html">500</a>
</li>
<li>
<a href="page_ready_503.html">503</a>
</li>
</ul>
</li>
<li>
<a href="#" class="sidebar-nav-submenu"><i class="fa fa-angle-left <API key>"></i>Get Started</a>
<ul>
<li>
<a href="page_ready_blank.html">Blank</a>
</li>
<li>
<a href="<API key>.html">Blank Alternative</a>
</li>
</ul>
</li>
<li>
<a href="<API key>.html">Search Results (4)</a>
</li>
<li>
<a href="page_ready_article.html">Article</a>
</li>
<li>
<a href="<API key>.html">User Profile</a>
</li>
<li>
<a href="page_ready_contacts.html">Contacts</a>
</li>
<li>
<a href="#" class="sidebar-nav-submenu"><i class="fa fa-angle-left <API key>"></i>e-Learning</a>
<ul>
<li>
<a href="<API key>.html">Courses</a>
</li>
<li>
<a href="<API key>.html">Course - Lessons</a>
</li>
<li>
<a href="<API key>.html">Course - Lesson Page</a>
</li>
</ul>
</li>
<li>
<a href="#" class="sidebar-nav-submenu"><i class="fa fa-angle-left <API key>"></i>Message Center</a>
<ul>
<li>
<a href="page_ready_inbox.html">Inbox</a>
</li>
<li>
<a href="<API key>.html">Compose Message</a>
</li>
<li>
<a href="<API key>.html">View Message</a>
</li>
</ul>
</li>
<li>
<a href="page_ready_chat.html">Chat</a>
</li>
<li>
<a href="page_ready_timeline.html">Timeline</a>
</li>
<li>
<a href="page_ready_tickets.html">Tickets</a>
</li>
<li>
<a href="page_ready_tasks.html">Tasks</a>
</li>
<li>
<a href="page_ready_faq.html">FAQ</a>
</li>
<li>
<a href="<API key>.html">Pricing Tables</a>
</li>
<li>
<a href="page_ready_invoice.html">Invoice</a>
</li>
<li>
<a href="page_ready_forum.html">Forum (3)</a>
</li>
<li>
<a href="#" class="sidebar-nav-submenu"><i class="fa fa-angle-left <API key>"></i>Login, Register & Lock</a>
<ul>
<li>
<a href="login.html">Login</a>
</li>
<li>
<a href="login_full.html">Login (Full Background)</a>
</li>
<li>
<a href="login_alt.html">Login 2</a>
</li>
<li>
<a href="login.html#reminder">Password Reminder</a>
</li>
<li>
<a href="login_alt.html#reminder">Password Reminder 2</a>
</li>
<li>
<a href="login.html#register">Register</a>
</li>
<li>
<a href="login_alt.html#register">Register 2</a>
</li>
<li>
<a href="<API key>.html">Lock Screen</a>
</li>
<li>
<a href="<API key>.html">Lock Screen 2</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<!-- END Sidebar Navigation -->
<!-- Sidebar Notifications -->
<div class="sidebar-header">
<span class="<API key> clearfix">
<a href="javascript:void(0)" data-toggle="tooltip" title="Refresh"><i class="gi gi-refresh"></i></a>
</span>
<span class="<API key>">Activity</span>
</div>
<div class="sidebar-section">
<div class="alert alert-success alert-alt">
<small>5 min ago</small><br>
<i class="fa fa-thumbs-up fa-fw"></i> You had a new sale ($10)
</div>
<div class="alert alert-info alert-alt">
<small>10 min ago</small><br>
<i class="fa fa-arrow-up fa-fw"></i> Upgraded to Pro plan
</div>
<div class="alert alert-warning alert-alt">
<small>3 hours ago</small><br>
<i class="fa fa-exclamation fa-fw"></i> Running low on space<br><strong>18GB in use</strong> 2GB left
</div>
<div class="alert alert-danger alert-alt">
<small>Yesterday</small><br>
<i class="fa fa-bug fa-fw"></i> <a href="javascript:void(0)"><strong>New bug submitted</strong></a>
</div>
</div>
<!-- END Sidebar Notifications -->
</div>
<!-- END Sidebar Content -->
</div>
<!-- END Wrapper for scrolling functionality -->
</div>
<!-- END Main Sidebar -->
<!-- Main Container -->
<div id="main-container">
<!-- Header -->
<!-- In the PHP version you can set the following options from inc/config file -->
<!
Available header.navbar classes:
'navbar-default' for the default light header
'navbar-inverse' for an alternative dark header
'navbar-fixed-top' for a top fixed header (fixed sidebars with scroll will be auto initialized, functionality can be found in js/app.js - handleSidebar())
'header-fixed-top' has to be added on #page-container only if the class 'navbar-fixed-top' was added
'navbar-fixed-bottom' for a bottom fixed header (fixed sidebars with scroll will be auto initialized, functionality can be found in js/app.js - handleSidebar()))
'header-fixed-bottom' has to be added on #page-container only if the class 'navbar-fixed-bottom' was added
<header class="navbar navbar-default">
<!-- Left Header Navigation -->
<ul class="nav navbar-nav-custom">
<!-- Main Sidebar Toggle Button -->
<li>
<a href="javascript:void(0)" onclick="App.sidebar('toggle-sidebar');">
<i class="fa fa-bars fa-fw"></i>
</a>
</li>
<!-- END Main Sidebar Toggle Button -->
<!-- Template Options -->
<!-- Change Options functionality can be found in js/app.js - templateOptions() -->
<li class="dropdown">
<a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown">
<i class="gi gi-settings"></i>
</a>
<ul class="dropdown-menu dropdown-custom dropdown-options">
<li class="dropdown-header text-center">Header Style</li>
<li>
<div class="btn-group btn-group-justified btn-group-sm">
<a href="javascript:void(0)" class="btn btn-primary" id="<API key>">Light</a>
<a href="javascript:void(0)" class="btn btn-primary" id="<API key>">Dark</a>
</div>
</li>
<li class="dropdown-header text-center">Page Style</li>
<li>
<div class="btn-group btn-group-justified btn-group-sm">
<a href="javascript:void(0)" class="btn btn-primary" id="options-main-style">Default</a>
<a href="javascript:void(0)" class="btn btn-primary" id="<API key>">Alternative</a>
</div>
</li>
<li class="dropdown-header text-center">Main Layout</li>
<li>
<button class="btn btn-sm btn-block btn-primary" id="options-header-top">Fixed Side/Header (Top)</button>
<button class="btn btn-sm btn-block btn-primary" id="<API key>">Fixed Side/Header (Bottom)</button>
</li>
<li class="dropdown-header text-center">Footer</li>
<li>
<div class="btn-group btn-group-justified btn-group-sm">
<a href="javascript:void(0)" class="btn btn-primary" id="<API key>">Default</a>
<a href="javascript:void(0)" class="btn btn-primary" id="<API key>">Fixed</a>
</div>
</li>
</ul>
</li>
<!-- END Template Options -->
</ul>
<!-- END Left Header Navigation -->
<!-- Search Form -->
<form action="<API key>.html" method="post" class="navbar-form-custom" role="search">
<div class="form-group">
<input type="text" id="top-search" name="top-search" class="form-control" placeholder="Search..">
</div>
</form>
<!-- END Search Form -->
<!-- Right Header Navigation -->
<ul class="nav navbar-nav-custom pull-right">
<!-- Alternative Sidebar Toggle Button -->
<li>
<!-- If you do not want the main sidebar to open when the alternative sidebar is closed, just remove the second parameter: App.sidebar('toggle-sidebar-alt'); -->
<a href="javascript:void(0)" onclick="App.sidebar('toggle-sidebar-alt', 'toggle-other');">
<i class="gi gi-share_alt"></i>
<span class="label label-primary label-indicator animation-floating">4</span>
</a>
</li>
<!-- END Alternative Sidebar Toggle Button -->
<!-- User Dropdown -->
<li class="dropdown">
<a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown">
<img src="img/placeholders/avatars/avatar2.jpg" alt="avatar"> <i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu dropdown-custom dropdown-menu-right">
<li class="dropdown-header text-center">Account</li>
<li>
<a href="page_ready_timeline.html">
<i class="fa fa-clock-o fa-fw pull-right"></i>
<span class="badge pull-right">10</span>
Updates
</a>
<a href="page_ready_inbox.html">
<i class="fa fa-envelope-o fa-fw pull-right"></i>
<span class="badge pull-right">5</span>
Messages
</a>
<a href="<API key>.html"><i class="fa fa-magnet fa-fw pull-right"></i>
<span class="badge pull-right">3</span>
Subscriptions
</a>
<a href="page_ready_faq.html"><i class="fa fa-question fa-fw pull-right"></i>
<span class="badge pull-right">11</span>
FAQ
</a>
</li>
<li class="divider"></li>
<li>
<a href="<API key>.html">
<i class="fa fa-user fa-fw pull-right"></i>
Profile
</a>
<!-- Opens the user settings modal that can be found at the bottom of each page (page_footer.html in PHP version) -->
<a href="#modal-user-settings" data-toggle="modal">
<i class="fa fa-cog fa-fw pull-right"></i>
Settings
</a>
</li>
<li class="divider"></li>
<li>
<a href="<API key>.html"><i class="fa fa-lock fa-fw pull-right"></i> Lock Account</a>
<a href="login.html"><i class="fa fa-ban fa-fw pull-right"></i> Logout</a>
</li>
<li class="dropdown-header text-center">Activity</li>
<li>
<div class="alert alert-success alert-alt">
<small>5 min ago</small><br>
<i class="fa fa-thumbs-up fa-fw"></i> You had a new sale ($10)
</div>
<div class="alert alert-info alert-alt">
<small>10 min ago</small><br>
<i class="fa fa-arrow-up fa-fw"></i> Upgraded to Pro plan
</div>
<div class="alert alert-warning alert-alt">
<small>3 hours ago</small><br>
<i class="fa fa-exclamation fa-fw"></i> Running low on space<br><strong>18GB in use</strong> 2GB left
</div>
<div class="alert alert-danger alert-alt">
<small>Yesterday</small><br>
<i class="fa fa-bug fa-fw"></i> <a href="javascript:void(0)" class="alert-link">New bug submitted</a>
</div>
</li>
</ul>
</li>
<!-- END User Dropdown -->
</ul>
<!-- END Right Header Navigation -->
</header>
<!-- END Header -->
<!-- Page content -->
<div id="page-content">
<!-- Both Sidebars Partial Header -->
<div class="content-header">
<div class="header-section">
<h1>
<i class="gi <API key>"></i>Both Sidebars Partial<br><small>You could go crazy and have two partial sidebars which open on hover!</small>
</h1>
</div>
</div>
<ul class="breadcrumb breadcrumb-top">
<li>Page Layouts</li>
<li><a href="">Both Sidebars Partial</a></li>
</ul>
<!-- END Both Sidebars Partial Header -->
<!-- Dummy Content -->
<div class="block full block-alt-noborder">
<h3 class="sub-header text-center"><strong>Dummy Content</strong> for layout demostration</h3>
<div class="row">
<div class="col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
<article>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ultrices, justo vel imperdiet gravida, urna ligula hendrerit nibh, ac cursus nibh sapien in purus. Mauris tincidunt tincidunt turpis in porta. Integer fermentum tincidunt auctor. Vestibulum ullamcorper, odio sed rhoncus imperdiet, enim elit sollicitudin orci, eget dictum leo mi nec lectus. Nam commodo turpis id lectus scelerisque vulputate. Integer sed dolor erat. Fusce erat ipsum, varius vel euismod sed, tristique et lectus? Etiam egestas fringilla enim, id convallis lectus laoreet at. Fusce purus nisi, gravida sed consectetur ut, interdum quis nisi. Quisque egestas nisl id lectus facilisis scelerisque?</p>
<p>Proin rhoncus dui at ligula vestibulum ut facilisis ante sodales! Suspendisse potenti. Aliquam tincidunt sollicitudin sem nec ultrices. Sed at mi velit. Ut egestas tempor est, in cursus enim venenatis eget! Nulla quis ligula ipsum. Donec vitae ultrices dolor? Donec lacinia venenatis metus at bibendum? In hac habitasse platea dictumst. Proin ac nibh rutrum lectus rhoncus eleifend. Sed porttitor pretium venenatis. Suspendisse potenti. Aliquam quis ligula elit. Aliquam at orci ac neque semper dictum. Sed tincidunt scelerisque ligula, et facilisis nulla hendrerit non. Suspendisse potenti. Pellentesque non accumsan orci. Praesent at lacinia dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ultrices, justo vel imperdiet gravida, urna ligula hendrerit nibh, ac cursus nibh sapien in purus. Mauris tincidunt tincidunt turpis in porta. Integer fermentum tincidunt auctor. Vestibulum ullamcorper, odio sed rhoncus imperdiet, enim elit sollicitudin orci, eget dictum leo mi nec lectus. Nam commodo turpis id lectus scelerisque vulputate. Integer sed dolor erat. Fusce erat ipsum, varius vel euismod sed, tristique et lectus? Etiam egestas fringilla enim, id convallis lectus laoreet at. Fusce purus nisi, gravida sed consectetur ut, interdum quis nisi. Quisque egestas nisl id lectus facilisis scelerisque?</p>
<p>Proin rhoncus dui at ligula vestibulum ut facilisis ante sodales! Suspendisse potenti. Aliquam tincidunt sollicitudin sem nec ultrices. Sed at mi velit. Ut egestas tempor est, in cursus enim venenatis eget! Nulla quis ligula ipsum. Donec vitae ultrices dolor? Donec lacinia venenatis metus at bibendum? In hac habitasse platea dictumst. Proin ac nibh rutrum lectus rhoncus eleifend. Sed porttitor pretium venenatis. Suspendisse potenti. Aliquam quis ligula elit. Aliquam at orci ac neque semper dictum. Sed tincidunt scelerisque ligula, et facilisis nulla hendrerit non. Suspendisse potenti. Pellentesque non accumsan orci. Praesent at lacinia dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ultrices, justo vel imperdiet gravida, urna ligula hendrerit nibh, ac cursus nibh sapien in purus.</p>
</article>
</div>
</div>
</div>
<!-- END Dummy Content -->
</div>
<!-- END Page Content -->
<!-- Footer -->
<footer class="clearfix">
<div class="pull-right">
Crafted with <i class="fa fa-heart text-danger"></i> by <a href="http://goo.gl/vNS3I" target="_blank">pixelcave</a>
</div>
<div class="pull-left">
<span id="year-copy"></span> © <a href="http://goo.gl/TDOSuC" target="_blank">ProUI 2.1</a>
</div>
</footer>
<!-- END Footer -->
</div>
<!-- END Main Container -->
</div>
<!-- END Page Container -->
<!-- Scroll to top link, initialized in js/app.js - scrollToTop() -->
<a href="#" id="to-top"><i class="fa fa-angle-double-up"></i></a>
<!-- User Settings, modal which opens from Settings link (found in top right user menu) and the Cog link (found in sidebar user info) -->
<div id="modal-user-settings" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header text-center">
<h2 class="modal-title"><i class="fa fa-pencil"></i> Settings</h2>
</div>
<!-- END Modal Header -->
<!-- Modal Body -->
<div class="modal-body">
<form action="index.html" method="post" enctype="multipart/form-data" class="form-horizontal form-bordered" onsubmit="return false;">
<fieldset>
<legend>Vital Info</legend>
<div class="form-group">
<label class="col-md-4 control-label">Username</label>
<div class="col-md-8">
<p class="form-control-static">Admin</p>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="user-settings-email">Email</label>
<div class="col-md-8">
<input type="email" id="user-settings-email" name="user-settings-email" class="form-control" value="admin@example.com">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="<API key>">Email Notifications</label>
<div class="col-md-8">
<label class="switch switch-primary">
<input type="checkbox" id="<API key>" name="<API key>" value="1" checked>
<span></span>
</label>
</div>
</div>
</fieldset>
<fieldset>
<legend>Password Update</legend>
<div class="form-group">
<label class="col-md-4 control-label" for="<API key>">New Password</label>
<div class="col-md-8">
<input type="password" id="<API key>" name="<API key>" class="form-control" placeholder="Please choose a complex one..">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="<API key>">Confirm New Password</label>
<div class="col-md-8">
<input type="password" id="<API key>" name="<API key>" class="form-control" placeholder="..and confirm it!">
</div>
</div>
</fieldset>
<div class="form-group form-actions">
<div class="col-xs-12 text-right">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-sm btn-primary">Save Changes</button>
</div>
</div>
</form>
</div>
<!-- END Modal Body -->
</div>
</div>
</div>
<!-- END User Settings -->
<!-- Include Jquery library from Google's CDN but if something goes wrong get Jquery from local file (Remove 'http:' if you have SSL) -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(decodeURI('%3Cscript src="js/vendor/jquery-1.11.1.min.js"%3E%3C/script%3E'));</script>
<!-- Bootstrap.js, Jquery plugins and Custom JS code -->
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/app.js"></script>
</body>
</html> |
export const getActiveLoan = (loans, activeLoanId) => {
return loans.filter(loan => loan.id == activeLoanId)[0];
}
export const getUpdatedLoans = (loans, updatedLoan) => {
return loans.map(loan => loan.id == updatedLoan.id ? updatedLoan : loan)
} |
using System.Threading;
namespace System.Globalization
{
public partial class CultureInfo : IFormatProvider
{
private static CultureInfo <API key>()
{
return null; // ICU doesn't provide a user override
}
internal static CultureInfo <API key>()
{
CultureInfo cultureInfo = null;
string localeName;
if (CultureData.<API key>(out localeName))
{
cultureInfo = GetCultureByName(localeName, true);
cultureInfo._isReadOnly = true;
}
else
{
cultureInfo = CultureInfo.InvariantCulture;
}
return cultureInfo;
}
private static CultureInfo <API key>()
{
return <API key>();
}
// CurrentCulture
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
// We use the following order to return CurrentCulture and CurrentUICulture
// o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture
// o use thread culture if the user already set one using <API key>
// or <API key>
// o Use NLS default user culture
// o Use NLS default system culture
// o Use Invariant culture
public static CultureInfo CurrentCulture
{
get
{
if (Thread.m_CurrentCulture != null)
{
return Thread.m_CurrentCulture;
}
CultureInfo ci = <API key>;
if (ci != null)
{
return ci;
}
// if <API key> == null means CultureInfo statics didn't get initialized yet. this can happen if there early static
if (<API key> == null)
{
Init();
}
Debug.Assert(<API key> != null);
return <API key>;
}
set
{
if (value == null)
{
throw new <API key>(nameof(value));
}
if (<API key> == null)
{
Interlocked.CompareExchange(ref <API key>, new AsyncLocal<CultureInfo>(<API key>), null);
}
<API key>.Value = value;
}
}
public static CultureInfo CurrentUICulture
{
get
{
return <API key>();
}
set
{
if (value == null)
{
throw new <API key>(nameof(value));
}
CultureInfo.VerifyCultureName(value, true);
if (<API key> == null)
{
Interlocked.CompareExchange(ref <API key>, new AsyncLocal<CultureInfo>(<API key>), null);
}
// this one will set <API key> too
<API key>.Value = value;
}
}
}
} |
import { IHttpPromise ,IHttpService } from 'angular';
import { SentenceModel } from './sentence.model';
import { Injectable } from '<API key>';
@Injectable()
export class <API key> {
private resource_url = 'https://api.icndb.com/jokes/random';
static $inject = [ '$log', '$http' ];
constructor(
private $log,
private $http: IHttpService
) { }
getRandomJoke(limitTo? : string[]): IHttpPromise<any> {
return this.$http.get(this.resource_url, {
params: {
limitTo
}
});
}
} |
<!doctype html>
<!--[if lt IE 7 ]> <html class="no-js ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]> <html class="no-js ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]> <html class="no-js ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>rdfstore-js</title>
<meta name="author" content="Antonio Garrote">
<link rel="stylesheet" href="./css/rdfstore_frontend.css">
<link rel="stylesheet" href="./css/demo.css">
<link rel="stylesheet" href="./css/ui-lightness/jquery-ui-1.8.14.custom.css">
<!-- All JavaScript at the bottom, except for Modernizr which
enables HTML5 elements & feature detects
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript' src='./js/jquery-ui.min.js'></script>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js'></script>
<script type='text/javascript' src='./js/rdf_store.js'></script>
<script type='text/javascript' src='./js/rdfquery.js'></script>
<script type='text/javascript' src='./js/knockout-1.2.1.js'></script>
<script type='text/javascript' src='./js/rdfstore_frontend.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function(){
frontend = null;
var startDemo = function(cb) {
rdfstore.create({"communication": {
"parsers": {
"text/html" : rdfstore_frontend.rdfaParser,
"application/rdf+xml": rdfstore_frontend.rdfParser
},
"precedences": ["text/n3", "text/turtle", "application/rdf+xml", "text/html", "application/json"] }
},
function(store) {
// original network transport
var <API key> = store.getNetworkTransport();
rdfstore_frontend.<API key>.proxyUri = "http://localhost:3000/rdfstoreproxy";
store.setNetworkTransport(rdfstore_frontend.<API key>);
store.execute("PREFIX : <http://example.org/ns
INSERT DATA { \
<https://github.com/antoniogarrote/rdfstore-js> <http://purl.org/dc/elements/1.1/creator> <http://foaf.me/antoniogarrote
<https:
}", function(){
frontend = new rdfstore_frontend('#target',store);
if(cb) { cb(); }
})
});
};
jQuery("#launch").click(function() {
startDemo();
});
jQuery("#demo1").click(function() {
jQuery("#demo1").remove();
var runDemo = function() {
frontend.viewModel.newLoadGraphDialog();
jQuery("
};
if(jQuery("#rdfstore-frontend").length==0) {
startDemo(function() {
runDemo();
})
} else {
runDemo();
}
});
jQuery("#demo2").click(function() {
jQuery("#demo2").remove();
var runDemo = function() {
frontend.viewModel.newLoadGraphDialog();
jQuery("
};
if(jQuery("#rdfstore-frontend").length==0) {
startDemo(function() {
runDemo();
})
} else {
runDemo();
}
});
jQuery("#demo3").click(function() {
jQuery("#demo3").remove();
var runDemo = function() {
frontend.viewModel.newLoadGraphDialog();
jQuery("
};
if(jQuery("#rdfstore-frontend").length==0) {
startDemo(function() {
runDemo();
})
} else {
runDemo();
}
});
jQuery("#demo4").click(function() {
jQuery("#demo4").remove();
var runDemo = function() {
frontend.viewModel.newLoadGraphDialog();
jQuery("
};
if(jQuery("#rdfstore-frontend").length==0) {
startDemo(function() {
runDemo();
})
} else {
runDemo();
}
});
});
</script>
</head>
<body>
<div id='target'>
</div>
<h1>rdfstore-js frontend</h1>
<div id='about'>
<h2>About</h2>
<p>
<a href='https://github.com/antoniogarrote/rdfstore-js'>rdfstore-js</a>
is a project that tries to build a RDF Store with support for the
SPARQL query language entirely in JavaScript. The overall goal is
to provide infrastructure that will make easier to use RDF and other
semantic technologies as the data layer for complex web
applications.
</p>
<p>
This page demoes a simple HTML frontend on top of the store that
can be used to manipulate RDF graphs retrieved from the web and
stored locally in rdfstore-js.
</p>
<div id='launch'>
<a href='#'>start frontend</a>
</div>
</div>
<div id='tries'>
<h2>Things to try</h2>
<p>
You can use the the store and the frontend to store data
retrieved from the whole web of linked data. <br/>
Some examples:
<ul>
<li>
Retrieve information from a product annotated with RDFa
<a href='http://oreilly.com/catalog/9781934356333/' target='_blank'>browse</a>
<a id='demo2' href='#'>run example</a>
</li>
<li>
Check my public WebID profile:
<a href='http://foaf.me/index.php?webid=http%3A%2F%2Ffoaf.me%2Fantoniogarrote%23me' target='_blank'>browse</a>
<a id='demo4' href='#'>run example</a>
</li>
<li>
Load RDF data from DBPedia
<a href='http://dbpedia.org/data/Tim_Berners-Lee.n3' target='_blank'>browse</a>
<a id='demo1' href='#'>run example</a>
</li>
<li>
Extract meta-data from a social network like Flickr
<a href='http:
<a id='demo3' href='#'>run example</a>
</li>
</ul>
</div>
<div id='usage'>
<h2>Usage</h2>
The frontend is built using the following libraries:
<ul>
<li>jQuery 1.4.2</li>
<li>jQuery template</li>
<li>jQuery UI</li>
<li>Knockout JS 1.2.1</li>
</ul>
Additionally, it uses a modified version of RDFQuery to parse RDFa
and RDF/XML serializations of RDF.<br/>
You can download the code of the frontend
from <a href='https://github.com/antoniogarrote/rdfstore-js/tree/master/frontend'>github</a>
with all the dependencies.<br/>
In order to use it, add the JavaScript and CSS files to you HTML and start the frontend
passing as parameters a RDFStore-js instance and a target HTML DOM
node:
<pre>
new rdfstore_frontend('#target',store);
</pre>
</div>
<div id=notes'>
<h2>Notes</h2>
The functionality of the store library has been extended for this
demo. Some of the differences are:
<ul>
<li>Use of a proxy service to resolve URIs instead of using
only native XMLHTTP + CORS requests.</li>
<li>Capacity to parse RDFa and RDF/XML documents using a modified
version of <a href='http://code.google.com/p/rdfquery/'>RDFQuery</a></li>
</ul>
The store has been designed to be modular and it can be configured
to use different network transports and additional parsers. The
order of precedence for different media types when performing
content negotiation can also be configured:
<pre>
rdfstore.create({"communication": {
"parsers": {
"text/html" : rdfstore_frontend.rdfaParser,
"application/rdf+xml": rdfstore_frontend.rdfParser
},
"precedences": ["application/rdf+xml", "text/html"] }
},
function(store) {
// original network transport
var <API key> = store.getNetworkTransport();
var proxy = rdfstore_frontend.<API key>;
proxy.proxyUri = "http://antoniogarrote.com/rdfstoreproxy";
store.setNetworkTransport(proxy);
// use the store
});
</pre>
The code for the proxy and the modified version of RDFQuery are
included in the frontend code repository.
</div>
</body>
</html> |
'use strict';
angular.module('<%=angularAppName%>')
.controller('AuditsController', function ($scope, $filter, AuditsService) {
$scope.onChangeDate = function () {
var dateFormat = 'yyyy-MM-dd';
var fromDate = $filter('date')($scope.fromDate, dateFormat);
var toDate = $filter('date')($scope.toDate, dateFormat);
AuditsService.findByDates(fromDate, toDate).then(function (data) {
$scope.audits = data;
});
};
// Date picker configuration
$scope.today = function () {
// Today + 1 day - needed if the current day must be included
var today = new Date();
$scope.toDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
};
$scope.previousMonth = function () {
var fromDate = new Date();
if (fromDate.getMonth() === 0) {
fromDate = new Date(fromDate.getFullYear() - 1, 0, fromDate.getDate());
} else {
fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, fromDate.getDate());
}
$scope.fromDate = fromDate;
};
$scope.today();
$scope.previousMonth();
$scope.onChangeDate();
}); |
import primitiveSet from 'osg/primitiveSet';
/**
* DrawElements manage rendering of indexed primitives
* @class DrawElements
*/
var DrawElements = function(mode, indices) {
this.mode = primitiveSet.POINTS;
if (mode !== undefined) {
if (typeof mode === 'string') {
mode = primitiveSet[mode];
}
this.mode = mode;
}
this.count = 0;
this.offset = 0;
this.indices = indices;
this.uType = DrawElements.UNSIGNED_SHORT;
if (indices !== undefined) {
this.setIndices(indices);
}
};
DrawElements.UNSIGNED_BYTE = 0x1401;
DrawElements.UNSIGNED_SHORT = 0x1403;
DrawElements.UNSIGNED_INT = 0x1405;
/** @lends DrawElements.prototype */
DrawElements.prototype = {
getMode: function() {
return this.mode;
},
draw: function(state) {
if (this.count === 0) return;
state.setIndexArray(this.indices);
this.drawElements(state);
},
drawElements: function(state) {
var gl = state.getGraphicContext();
gl.drawElements(this.mode, this.count, this.uType, this.offset);
},
setIndices: function(indices) {
this.indices = indices;
var elts = indices.getElements();
this.count = elts.length;
var nbBytes = elts.BYTES_PER_ELEMENT;
if (nbBytes === 1) this.uType = DrawElements.UNSIGNED_BYTE;
else if (nbBytes === 2) this.uType = DrawElements.UNSIGNED_SHORT;
else if (nbBytes === 4) this.uType = DrawElements.UNSIGNED_INT;
},
getIndices: function() {
return this.indices;
},
setFirst: function(val) {
this.offset = val;
},
getFirst: function() {
return this.offset;
},
setCount: function(val) {
this.count = val;
},
getCount: function() {
return this.count;
},
getNumIndices: function() {
return this.indices.getElements().length;
},
index: function(i) {
return this.indices.getElements()[i];
}
};
export default DrawElements; |
import React from 'react'
import Icon from 'react-icon-base'
const TiCogOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m21.7 8.3l1.4 5.7 5.6-1.6 2.5 4.3-4.2 4.1 4.2 4.1-2.5 4.3-5.6-1.6-1.4 5.7h-5l-1.5-5.7-5.6 1.6-2.5-4.3 4.2-4.1-4.2-4.1 2.5-4.3 5.6 1.6 1.5-5.7h5z m0-3.3h-5c-1.6 0-2.9 1-3.3 2.5l-0.6 2.4-2.3-0.7c-0.3-0.1-0.6-0.1-0.9-0.1-1.2 0-2.3 0.6-2.9 1.7l-2.5 4.3c-0.8 1.3-0.5 3 0.6 4l1.7 1.7-1.7 1.7c-1.1 1.1-1.4 2.8-0.6 4.1l2.5 4.3c0.6 1.1 1.7 1.7 2.9 1.7 0.3 0 0.6-0.1 0.9-0.1l2.3-0.7 0.6 2.3c0.4 1.5 1.7 2.6 3.3 2.6h5c1.5 0 2.8-1.1 3.2-2.6l0.6-2.3 2.3 0.6c0.3 0.1 0.6 0.2 0.9 0.2 1.2 0 2.3-0.6 2.9-1.7l2.5-4.3c0.8-1.4 0.6-3-0.5-4.1l-1.8-1.7 1.8-1.7c1.1-1 1.3-2.7 0.5-4l-2.5-4.4c-0.6-1-1.7-1.6-2.9-1.6-0.3 0-0.6 0-0.9 0.1l-2.3 0.7-0.6-2.4c-0.4-1.5-1.7-2.5-3.2-2.5z m-2.5 12.5c1.8 0 3.3 1.5 3.3 3.3 0 1.9-1.5 3.4-3.3 3.4s-3.4-1.5-3.4-3.4c0-1.8 1.5-3.3 3.4-3.3z m0-1.7c-2.8 0-5 2.3-5 5s2.2 5 5 5 5-2.2 5-5-2.3-5-5-5z"/></g>
</Icon>
)
export default TiCogOutline |
// RUN: %check -e %s
f(int *);
g(float);
main()
{
int *pt = (void *)0;
float fp = 0;
f(fp); // CHECK: /error: mismatching types/
f(pt); // CHECK: !/error/
g(fp); // CHECK: !/error/
g(pt); // CHECK: /error: mismatching types/
} |
module Web::Controllers::Tasks
class Create
include Web::Action
include Import['tasks.interactors.create']
expose :task
params do
required(:task).schema do
required(:title).filled(:str?)
required(:md_body).filled(:str?)
required(:lang).filled(:str?)
required(:complexity).filled(:str?)
required(:time_estimate).filled(:str?)
required(:user_id).filled
optional(:issue_url).maybe(:str?)
optional(:repository_name).maybe(:str?)
optional(:first_pr).filled(:bool?)
end
end
# TODO: move to operations
def call(params)
return unless authenticated?
result = create.new(params.valid?, params).call
if result.successful?
flash[:info] = INFO_MESSAGE
redirect_to routes.tasks_path
else
self.body = Web::Views::Tasks::New.render(format: format, task: result.task,
current_user: current_user, params: params, updated_csrf_token: set_csrf_token)
end
end
private
INFO_MESSAGE = 'Task had been added to moderation. You can check your task status on profile page'.freeze
end
end |
package org.sidoh.song_recognition.signature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.sidoh.collections.TreeMapOfSets;
import org.sidoh.io.ProgressNotifier;
import org.sidoh.io.ProgressNotifier.Builder;
import org.sidoh.song_recognition.signature.ConstellationMap.Star;
import org.sidoh.song_recognition.signature.ConstellationMap.TimeStarComparator;
import org.sidoh.song_recognition.spectrogram.Spectrogram;
public class StarHashExtractor implements <API key><StarHashSignature> {
private final <API key> starExtractor;
private final Region.Builder regionBuilder;
private final int timeResolution;
private final ProgressNotifier.Builder progress;
private final Region.Builder <API key>;
public StarHashExtractor(<API key> starExtractor,
Region.Builder regionBuilder,
int timeResolution,
ProgressNotifier.Builder progress) {
this(starExtractor, regionBuilder, null, timeResolution, progress);
}
public StarHashExtractor(<API key> starExtractor,
Region.Builder regionBuilder,
Region.Builder <API key>,
int timeResolution,
ProgressNotifier.Builder progress) {
this.starExtractor = starExtractor;
this.regionBuilder = regionBuilder;
this.<API key> = <API key>;
this.timeResolution = timeResolution;
this.progress = progress;
}
@Override
public StarHashSignature extractSignature(Spectrogram spec) {
<API key> starSig = starExtractor.extractSignature(spec);
List<Star> stars = new ArrayList<Star>(starSig.getConstellationMap().getStars());
Collections.sort(stars, new TimeStarComparator());
TreeMapOfSets<Integer, Integer> starHashes = new TreeMapOfSets<Integer, Integer>();
forwardExtract(stars, starHashes, spec);
if (<API key> != null) {
reverseExtract(stars, starHashes, spec);
}
return new StarHashSignature(starSig.getConstellationMap(), starHashes);
}
protected void forwardExtract(List<Star> stars, TreeMapOfSets<Integer, Integer> hashes, Spectrogram spec) {
ProgressNotifier notifier = progress.create("Extracting hash values (forward)...", stars.size());
Set<Region> regions = new HashSet<Region>();
for (int i = 0; i < stars.size(); i++) {
Star s = stars.get(i);
Set<Region> toRemove = new HashSet<Region>();
for (Region region : regions) {
switch (region.isInRegion(s.getTick(), s.getBin())) {
case IN_REGION:
int hash = StarHashSignature.computeHash(
region.getX(), s.getTick(),
region.getY(), s.getBin(),
spec);
hashes.addFor(hash, getTime(s));
break;
case AFTER_REGION:
toRemove.add(region);
}
}
regions.removeAll(toRemove);
regions.add(regionBuilder.create(s.getTick(), s.getBin()));
notifier.update();
}
notifier.complete();
}
protected void reverseExtract(List<Star> stars, TreeMapOfSets<Integer, Integer> hashes, Spectrogram spec) {
ProgressNotifier notifier = progress.create("Extracting hash values (reverse)...", stars.size());
Set<Region> regions = new HashSet<Region>();
for (int i = stars.size()-1; i >= 0; i
Star s = stars.get(i);
Set<Region> toRemove = new HashSet<Region>();
for (Region region : regions) {
switch (region.isInRegion(s.getTick(), s.getBin())) {
case IN_REGION:
int hash = StarHashSignature.computeHash(
region.getX(), s.getTick(),
region.getY(), s.getBin(),
spec);
hashes.addFor(hash, getTime(s));
break;
case AFTER_REGION:
toRemove.add(region);
}
}
regions.removeAll(toRemove);
regions.add(<API key>.create(s.getTick(), s.getBin()));
notifier.update();
}
notifier.complete();
}
protected int getTime(Star s) {
return s.getTick();
}
} |
#include "wallet/wallet.h"
#include "base58.h"
#include "checkpoints.h"
#include "chain.h"
#include "coincontrol.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "mvf-bu.h" // MVF-BU
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
using namespace std;
CWallet* pwalletMain = NULL;
/** Transaction fee set by the user */
CFeeRate payTxFee(<API key>);
unsigned int nTxConfirmTarget = <API key>;
bool <API key> = <API key>;
bool <API key> = <API key>;
const char * DEFAULT_WALLET_DAT = "wallet.dat";
/**
* Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(<API key>);
/**
* If fee estimation does not have enough data to provide estimates, use this fee instead.
* Has no effect if not using fee estimation
* Override with -fallbackfee
*/
CFeeRate CWallet::fallbackFee = CFeeRate(<API key>);
const uint256 CMerkleTx::ABANDON_HASH(uint256S("<SHA256-like>"));
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly
{
bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
}
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return NULL;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey()
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
CKey secret;
secret.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
// Create new metadata
int64_t nCreationTime = GetTime();
mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
nTimeFirstKey = nCreationTime;
if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
return pubkey;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
return false;
// check if we need to remove from watch-only
CScript script;
script = <API key>(pubkey.GetID());
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
script = <API key>(pubkey);
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
return false;
}
bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
nTimeFirstKey = meta.nCreateTime;
mapKeyMetadata[pubkey.GetID()] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > <API key>)
{
std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), <API key>, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript &dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
nTimeFirstKey = 1; // No birthday information for watch-only keys.
<API key>(true);
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript &dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
<API key>(false);
if (fFileBacked)
if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript &dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
CCrypter crypter;
CKeyingMaterial vMasterKey;
{
LOCK(cs_wallet);
BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.<API key>(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(vMasterKey))
return true;
}
}
return false;
}
bool CWallet::<API key>(const SecureString& <API key>, const SecureString& <API key>)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.<API key>(<API key>, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked)
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
result.insert(it->second);
}
return result;
}
void CWallet::Flush(bool shutdown)
{
bitdb.Flush(shutdown);
}
bool static UIError(const std::string &str)
{
uiInterface.<API key>(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
void static UIWarning(const std::string &str)
{
uiInterface.<API key>(str, "", CClientUIInterface::MSG_WARNING);
}
static std::string AmountErrMsg(const char * const optname, const std::string& strValue)
{
return strprintf(_("Invalid amount for -%s=<amount>: '%s'"), optname, strValue);
}
bool CWallet::Verify()
{
std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
LogPrintf("Using wallet %s\n", walletFile);
uiInterface.InitMessage(_("Verifying wallet..."));
// Wallet file must be a plain filename without a directory
if (walletFile != boost::filesystem::basename(walletFile) + boost::filesystem::extension(walletFile))
return UIError(strprintf(_("Wallet %s resides outside data directory %s"), walletFile, GetDataDir().string()));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
} catch (const boost::filesystem::filesystem_error&) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
return UIError(strprintf(_("Error initializing wallet database environment %s!"), GetDataDir()));
}
}
if (GetBoolArg("-salvagewallet", false))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, walletFile, true))
return false;
}
if (boost::filesystem::exists(GetDataDir() / walletFile))
{
CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
UIWarning(strprintf(_("Warning: Wallet file corrupt, data salvaged!"
" Original %s saved as %s in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."),
walletFile, "wallet.{timestamp}.bak", GetDataDir()));
}
if (r == CDBEnv::RECOVER_FAIL)
return UIError(strprintf(_("%s corrupt, salvage failed"), walletFile));
}
return true;
}
void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = NULL;
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
int n = mapWallet[hash].nOrderPos;
if (n < nMinOrderPos)
{
nMinOrderPos = n;
copyFrom = &mapWallet[hash];
}
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// <API key> not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
{
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
return true; // Spent
}
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(make_pair(outpoint, wtxid));
pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
assert(mapWallet.count(wtxid));
CWalletTx& thisTx = mapWallet[wtxid];
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(<API key>);
GetRandBytes(&vMasterKey[0], <API key>);
CMasterKey kMasterKey;
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(<API key>);
GetRandBytes(&kMasterKey.vchSalt[0], <API key>);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.<API key>(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.<API key>(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.<API key>(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked)
{
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
}
if (!EncryptKeys(vMasterKey))
{
if (fFileBacked) {
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
}
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked)
{
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
}
NotifyStatusChanged(this);
return true;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
{
uint256 hash = wtxIn.GetHash();
if (fFromLoadWallet)
{
mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
AddToSpends(hash);
BOOST_FOREACH(const CTxIn& txin, wtx.vin) {
if (mapWallet.count(txin.prevout.hash)) {
CWalletTx& prevtx = mapWallet[txin.prevout.hash];
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
MarkConflicted(prevtx.hashBlock, wtx.GetHash());
}
}
}
}
else
{
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(pwalletdb);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
wtx.nTimeSmart = wtx.nTimeReceived;
if (!wtxIn.hashUnset())
{
if (mapBlockIndex.count(wtxIn.hashBlock))
{
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
{
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
const TxItems & txOrdered = wtxOrdered;
for (TxItems::<API key> it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx == &wtx)
continue;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t nSmartTime;
if (pwtx)
{
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime)
nSmartTime = pwtx->nTimeReceived;
}
else
nSmartTime = pacentry->nTime;
if (nSmartTime <= latestTolerated)
{
latestEntry = nSmartTime;
if (nSmartTime > latestNow)
latestNow = nSmartTime;
break;
}
}
}
int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
}
else
LogPrintf("AddToWallet(): found %s in block %s not in index\n",
wtxIn.GetHash().ToString(),
wtxIn.hashBlock.ToString());
}
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
// If no longer abandoned, update
if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
{
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
}
/ debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk(pwalletdb))
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
<API key>(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = GetArg("-walletnotify", "");
if ( !strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
}
return true;
}
/**
* Add a transaction to the wallet, or update it.
* pblock is optional, but should be provided if the transaction is known to be in a block.
* If fUpdate is true, existing transactions will be updated.
*/
bool CWallet::<API key>(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
{
AssertLockHeld(cs_wallet);
if (pblock) {
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pblock->GetHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
MarkConflicted(pblock->GetHash(), range.first->second);
}
range.first++;
}
}
}
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
CWalletTx wtx(this,tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(*pblock);
// Do not flush the wallet here for performance reasons
// this is safe, as in case of a crash, we rescan the necessary blocks on startup through our <API key>
CWalletDB walletdb(strWalletFile, "r+", false);
return AddToWallet(wtx, false, &walletdb);
}
}
return false;
}
bool CWallet::AbandonTransaction(const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(strWalletFile, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
assert(mapWallet.count(hashTx));
CWalletTx& origtx = mapWallet[hashTx];
if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
return false;
}
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
assert(mapWallet.count(now));
CWalletTx& wtx = mapWallet[now];
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
if (currentconfirm == 0 && !wtx.isAbandoned()) {
// If the orig tx was not in block/mempool, none of its spends can be in mempool
assert(!wtx.InMempool());
wtx.nIndex = -1;
wtx.setAbandoned();
wtx.MarkDirty();
wtx.WriteToDisk(&walletdb);
<API key>(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
}
return true;
}
void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
int conflictconfirms = 0;
if (mapBlockIndex.count(hashBlock)) {
CBlockIndex* pindex = mapBlockIndex[hashBlock];
if (chainActive.Contains(pindex)) {
conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
}
}
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
// for example when loading the wallet during a reindex. Do nothing in that
// case.
if (conflictconfirms >= 0)
return;
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(strWalletFile, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
assert(mapWallet.count(now));
CWalletTx& wtx = mapWallet[now];
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
// Mark transaction as conflicted with this block.
wtx.nIndex = -1;
wtx.hashBlock = hashBlock;
wtx.MarkDirty();
wtx.WriteToDisk(&walletdb);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
}
}
void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
{
LOCK2(cs_main, cs_wallet);
if (!<API key>(tx, pblock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
return IsMine(prev.vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]) & filter)
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetCredit(): value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0);
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a <API key> address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey))
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
CAmount CWallet::GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetChange(): value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
BOOST_FOREACH(const CTxOut& txout, tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
throw std::runtime_error("CWallet::GetDebit(): value out of range");
}
return nDebit;
}
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWallet::GetCredit(): value out of range");
}
return nCredit;
}
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error("CWallet::GetChange(): value out of range");
}
return nChange;
}
// MVF-BU begin auto wallet backup procedure (MVHF-BU-DES-WABU-4)
bool CWallet::BackupWalletAuto(const std::string& strDest, int BackupBlock)
{
// check if backup from previous block exists
boost::filesystem::path <API key> = <API key>(strDest, strWalletFile, BackupBlock-1, false);
std::string strBackupFile = <API key>.string();
LogPrintf("MVF: BackupWalletAuto: checking for existence of backup from previous block at location: %s\n",strBackupFile.c_str());
if (boost::filesystem::exists(strBackupFile)) {
LogPrintf("MVF: Wallet was already backed on previous block: %s\n",strBackupFile);
return true;
}
// no previous-block backup found, so carry on...
// get final backup path (and create directories for it as needed)
boost::filesystem::path pathBackupWallet = <API key>(strDest, strWalletFile, BackupBlock);
// rename with .old suffix if target already exists
strBackupFile = pathBackupWallet.string();
if (boost::filesystem::exists(strBackupFile))
boost::filesystem::rename(strBackupFile,strprintf("%s.%s.old",strBackupFile,GetTime()));
// call common backup wallet function
if (BackupWallet(*this, strBackupFile))
LogPrintf("MVF: Wallet automatically backed up to: %s\n",strBackupFile);
else
// backup failed
return false;
return true;
}
// MVF-BU end
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase())
{
// Generated block
if (!hashUnset())
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && !hashUnset())
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < vout.size(); ++i)
{
const CTxOut& txout = vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
}
else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
{
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
COutputEntry output = {address, txout.nValue, (int)i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
{
nReceived = nSent = nFee = 0;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (strAccount == strSentAccount)
{
BOOST_FOREACH(const COutputEntry& s, listSent)
nSent += s.amount;
nFee = allFee;
}
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH(const COutputEntry& r, listReceived)
{
if (pwallet->mapAddressBook.count(r.destination))
{
map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
nReceived += r.amount;
}
else if (strAccount.empty())
{
nReceived += r.amount;
}
}
}
}
bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
{
return pwalletdb->WriteTx(GetHash(), *this);
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*/
int CWallet::<API key>(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
CBlockIndex* pindex = pindexStart;
{
LOCK2(cs_main, cs_wallet);
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
pindex = chainActive.Next(pindex);
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = Checkpoints::<API key>(chainParams.Checkpoints(), pindex, false);
double dProgressTip = Checkpoints::<API key>(chainParams.Checkpoints(), chainActive.Tip(), false);
while (pindex)
{
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::<API key>(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
CBlock block;
ReadBlockFromDisk(block, pindex, Params().GetConsensus());
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
if (<API key>(tx, &block, fUpdate))
ret++;
}
pindex = chainActive.Next(pindex);
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::<API key>(chainParams.Checkpoints(), pindex));
}
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
}
return ret;
}
void CWallet::<API key>()
{
// If transactions aren't being broadcasted, don't let them into local mempool either
if (!<API key>)
return;
LOCK2(cs_main, cs_wallet);
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
}
// Try to add wallet transactions to memory pool
BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *(item.second);
LOCK(mempool.cs);
wtx.AcceptToMemoryPool(false);
SyncWithWallets(wtx,NULL);
}
}
bool CWalletTx::<API key>()
{
assert(pwallet-><API key>());
if (!IsCoinBase())
{
if (GetDepthInMainChain() == 0 && !isAbandoned() && InMempool()) {
LogPrintf("Relaying wtx %s\n", GetHash().ToString());
RelayTransaction((CTransaction)*this);
return true;
}
}
return false;
}
set<uint256> CWalletTx::GetConflicts() const
{
set<uint256> result;
if (pwallet != NULL)
{
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
CAmount CWalletTx::GetDebit(const isminefilter& filter) const
{
if (vin.empty())
return 0;
CAmount debit = 0;
if(filter & ISMINE_SPENDABLE)
{
if (fDebitCached)
debit += nDebitCached;
else
{
nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
fDebitCached = true;
debit += nDebitCached;
}
}
if(filter & ISMINE_WATCH_ONLY)
{
if(fWatchDebitCached)
debit += nWatchDebitCached;
else
{
nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
fWatchDebitCached = true;
debit += nWatchDebitCached;
}
}
return debit;
}
CAmount CWalletTx::GetCredit(const isminefilter& filter) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
int64_t credit = 0;
if (filter & ISMINE_SPENDABLE)
{
// GetBalance can assume transactions in mapWallet won't change
if (fCreditCached)
credit += nCreditCached;
else
{
nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fCreditCached = true;
credit += nCreditCached;
}
}
if (filter & ISMINE_WATCH_ONLY)
{
if (fWatchCreditCached)
credit += nWatchCreditCached;
else
{
nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fWatchCreditCached = true;
credit += nWatchCreditCached;
}
}
return credit;
}
CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && <API key>)
return <API key>;
<API key> = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
<API key> = true;
return <API key>;
}
return 0;
}
CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
{
if (pwallet == 0)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && <API key>)
return <API key>;
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < vout.size(); i++)
{
if (!pwallet->IsSpent(hashTx, i))
{
const CTxOut &txout = vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
<API key> = nCredit;
<API key> = true;
return nCredit;
}
CAmount CWalletTx::<API key>(const bool& fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && <API key>)
return <API key>;
<API key> = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
<API key> = true;
return <API key>;
}
return 0;
}
CAmount CWalletTx::<API key>(const bool& fUseCache) const
{
if (pwallet == 0)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && <API key>)
return <API key>;
CAmount nCredit = 0;
for (unsigned int i = 0; i < vout.size(); i++)
{
if (!pwallet->IsSpent(GetHash(), i))
{
const CTxOut &txout = vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
<API key> = nCredit;
<API key> = true;
return nCredit;
}
CAmount CWalletTx::GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*this);
fChangeCached = true;
return nChangeCached;
}
bool CWalletTx::InMempool() const
{
LOCK(mempool.cs);
if (mempool.exists(GetHash())) {
return true;
}
return false;
}
bool CWalletTx::IsTrusted() const
{
// Quick answer in most cases
if (!CheckFinalTx(*this))
return false;
int nDepth = GetDepthInMainChain();
if (nDepth >= 1)
return true;
if (nDepth < 0)
return false;
if (!<API key> || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
return false;
// Don't trust unconfirmed transactions from us unless they are in the mempool.
if (!InMempool())
return false;
// Trusted if all inputs are from us and are in the mempool:
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
if (parent == NULL)
return false;
const CTxOut& parentOut = parent->vout[txin.prevout.n];
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
return false;
}
return true;
}
bool CWalletTx::IsEquivalentTo(const CWalletTx& tx) const
{
CMutableTransaction tx1 = *this;
CMutableTransaction tx2 = tx;
for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
return CTransaction(tx1) == CTransaction(tx2);
}
std::vector<uint256> CWallet::<API key>(int64_t nTime)
{
std::vector<uint256> result;
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime)
continue;
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.<API key>())
result.push_back(wtx.GetHash());
}
return result;
}
void CWallet::<API key>(int64_t nBestBlockTime)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend || !<API key>)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nBestBlockTime < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast unconfirmed txes older than 5 minutes before the last
// block was found:
std::vector<uint256> relayed = <API key>(nBestBlockTime-5*60);
if (!relayed.empty())
LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
}
// end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::<API key>() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin-><API key>();
}
}
return nTotal;
}
CAmount CWallet::<API key>() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin-><API key>();
}
}
return nTotal;
}
CAmount CWallet::<API key>() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin-><API key>();
}
}
return nTotal;
}
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
{
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
if (!CheckFinalTx(*pcoin))
continue;
if (fOnlyConfirmed && !pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 0)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
isminetype mine = IsMine(pcoin->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
!IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
(!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
vCoins.push_back(COutput(pcoin, i, nDepth,
((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
(coinControl && coinControl->fAllowWatchOnly && (mine & <API key>) != ISMINE_NO)));
}
}
}
}
static void <API key>(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
seed_insecure_rand();
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
{
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
//Reduces the approximate best subset by removing any inputs that are smaller than the surplus of nTotal beyond nTargetValue.
for (unsigned int i = 0; i < vValue.size(); i++)
{
if (vfBest[i] && (nBest - vValue[i].first) >= nTargetValue )
{
vfBest[i] = false;
nBest -= vValue[i].first;
}
}
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<CAmount>::max();
coinLowestLarger.second.first = NULL;
vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
BOOST_FOREACH(const COutput &output, vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
int i = output.i;
CAmount n = pcoin->vout[i].nValue;
pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
if (n == nTargetValue)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
}
else if (n < nTargetValue + MIN_CHANGE)
{
vValue.push_back(coin);
nTotalLower += n;
}
else if (n < coinLowestLarger.first)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (unsigned int i = 0; i < vValue.size(); ++i)
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (coinLowestLarger.second.first == NULL)
return false;
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
CAmount nBest;
<API key>(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
<API key>(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
{
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
LogPrint("selectcoins", "SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
}
return true;
}
bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
{
BOOST_FOREACH(const COutput& out, vCoins)
{
if (!out.fSpendable)
continue;
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
// calculate value from preset inputs and store them
set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
CAmount <API key> = 0;
std::vector<COutPoint> vPresetInputs;
if (coinControl)
coinControl->ListSelected(vPresetInputs);
BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
{
map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
const CWalletTx* pcoin = &it->second;
// Clearly invalid input, fail
if (pcoin->vout.size() <= outpoint.n)
return false;
<API key> += pcoin->vout[outpoint.n].nValue;
setPresetCoins.insert(make_pair(pcoin, outpoint.n));
} else
return false; // TODO: Allow non-wallet inputs
}
// remove preset inputs from vCoins
for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
{
if (setPresetCoins.count(make_pair(it->tx, it->i)))
it = vCoins.erase(it);
else
++it;
}
bool res = nTargetValue <= <API key> ||
SelectCoinsMinConf(nTargetValue - <API key>, 1, 6, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue - <API key>, 1, 1, vCoins, setCoinsRet, nValueRet) ||
(<API key> && SelectCoinsMinConf(nTargetValue - <API key>, 0, 1, vCoins, setCoinsRet, nValueRet));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
// add preset inputs to the total value selected
nValueRet += <API key>;
return res;
}
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching)
{
vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector
BOOST_FOREACH(const CTxOut& txOut, tx.vout)
{
CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
vecSend.push_back(recipient);
}
CCoinControl coinControl;
coinControl.fAllowOtherInputs = true;
coinControl.fAllowWatchOnly = includeWatching;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
coinControl.Select(txin.prevout);
CReserveKey reservekey(this);
CWalletTx wtx;
if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
return false;
if (nChangePosRet != -1)
tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
// Add new txins (keeping original txin scriptSig/order)
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
bool found = false;
BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
{
if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
{
found = true;
break;
}
}
if (!found)
tx.vin.push_back(txin);
}
return true;
}
bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
{
CAmount nValue = 0;
unsigned int <API key> = 0;
BOOST_FOREACH (const CRecipient& recipient, vecSend)
{
if (nValue < 0 || recipient.nAmount < 0)
{
strFailReason = _("Transaction amounts must be positive");
return false;
}
nValue += recipient.nAmount;
if (recipient.<API key>)
<API key>++;
}
if (vecSend.empty() || nValue < 0)
{
strFailReason = _("Transaction amounts must be positive");
return false;
}
wtxNew.<API key> = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
// Discourage fee sniping.
// For a large miner the value of the transactions in the best block and
// the mempool can exceed the cost of deliberately attempting to mine two
// blocks to orphan the current best block. By setting nLockTime such that
// only the next block can include the transaction, we discourage this
// practice as the height restricted and limited blocksize gives miners
// considering fee sniping fewer options for pulling off this attack.
// A simple way to think about this is from the wallet's point of view we
// always want the blockchain to move forward. By setting nLockTime this
// way we're basically making the statement that we only want this
// transaction to appear in the next block; we don't want to potentially
// encourage reorgs by allowing transactions to appear at lower heights
// than the next block in forks of the best chain.
// Of course, the subsidy is high enough, and transaction volume low
// enough, that fee sniping isn't a problem yet, but by implementing a fix
// now we ensure code won't be written that makes assumptions about
// nLockTime that preclude a fix later.
txNew.nLockTime = chainActive.Height();
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
{
LOCK2(cs_main, cs_wallet);
{
nFeeRet = 0;
// Start with no fee and loop until there is enough fee
while (true)
{
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
nChangePosRet = -1;
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (<API key> == 0)
nValueToSelect += nFeeRet;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH (const CRecipient& recipient, vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
if (recipient.<API key>)
{
txout.nValue -= nFeeRet / <API key>; // Subtract fee equally from each selected recipient
if (fFirst) // first receiver pays the remainder not divisible by output count
{
fFirst = false;
txout.nValue -= nFeeRet % <API key>;
}
}
if (txout.IsDust(::minRelayTxFee))
{
if (recipient.<API key> && nFeeRet > 0)
{
if (txout.nValue < 0)
strFailReason = _("The transaction amount is too small to pay the fee");
else
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
}
else
strFailReason = _("Transaction amount too small");
return false;
}
txNew.vout.push_back(txout);
}
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
CAmount nValueIn = 0;
if (!SelectCoins(nValueToSelect, setCoins, nValueIn, coinControl))
{
strFailReason = _("Insufficient funds");
return false;
}
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
//The coin age after the next block (depth+1) is used instead of the current,
//reflecting an assumption the user would accept a bit more delay for
//a chance at a free transaction.
//But mempool inputs might still be in the mempool, so their age stays 0
int age = pcoin.first->GetDepthInMainChain();
assert(age >= 0);
if (age != 0)
age += 1;
dPriority += (double)nCredit * age;
}
const CAmount nChange = nValueIn - nValueToSelect;
if (nChange > 0)
{
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always <API key>
CScript scriptChange;
// coin control: send change to custom address
if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
scriptChange = <API key>(coinControl->destChange);
// no coin control: send change to newly generated address
else
{
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey);
if (!ret)
{
strFailReason = _("Keypool ran out, please call keypoolrefill first");
return false;
}
scriptChange = <API key>(vchPubKey.GetID());
}
CTxOut newTxOut(nChange, scriptChange);
// We do not move dust-change to fees, because the sender would end up paying more than requested.
// This would be against the purpose of the all-inclusive feature.
// So instead we raise the change and deduct from the recipient.
if (<API key> > 0 && newTxOut.IsDust(::minRelayTxFee))
{
CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
newTxOut.nValue += nDust; // raise change until no more dust
for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
{
if (vecSend[i].<API key>)
{
txNew.vout[i].nValue -= nDust;
if (txNew.vout[i].IsDust(::minRelayTxFee))
{
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
return false;
}
break;
}
}
}
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (newTxOut.IsDust(::minRelayTxFee))
{
nFeeRet += nChange;
reservekey.ReturnKey();
}
else
{
// Insert change txn at random position:
nChangePosRet = GetRandInt(txNew.vout.size()+1);
vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
txNew.vout.insert(position, newTxOut);
}
}
else
reservekey.ReturnKey();
// Fill vin
// Note how the sequence number is set to non-maxint so that
// the nLockTime set above actually works.
for (const auto& coin : setCoins)
txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
std::numeric_limits<unsigned int>::max() - 1));
// Sign
int nIn = 0;
CTransaction txNewConst(txNew);
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
{
bool signSuccess;
const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
CScript& scriptSigRes = txNew.vin[nIn].scriptSig;
if (sign)
signSuccess = ProduceSignature(<API key>(this, &txNewConst, nIn, SIGHASH_ALL), scriptPubKey, scriptSigRes);
else
signSuccess = ProduceSignature(<API key>(this), scriptPubKey, scriptSigRes);
if (!signSuccess)
{
strFailReason = _("Signing transaction failed");
return false;
}
nIn++;
}
unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
// Remove scriptSigs if we used dummy signatures for fee calculation
if (!sign) {
BOOST_FOREACH (CTxIn& vin, txNew.vin)
vin.scriptSig = CScript();
}
// Embed the constructed transaction data in wtxNew.
*static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
// Limit size
if (nBytes >= <API key>)
{
strFailReason = _("Transaction too large");
return false;
}
dPriority = wtxNew.ComputePriority(dPriority, nBytes);
// Can we complete this as a free transaction?
if (<API key> && nBytes <= <API key>)
{
// Not enough fee: enough priority?
double dPriorityNeeded = mempool.<API key>(nTxConfirmTarget);
// Require at least hard-coded AllowFree.
if (dPriority >= dPriorityNeeded && AllowFree(dPriority))
break;
}
CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
nFeeNeeded = coinControl->nMinimumTotalFee;
}
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
{
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded)
break; // Done, enough fee included.
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
}
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
#if 1
if (<API key>)
{
// Broadcast
if (!wtxNew.AcceptToMemoryPool(false))
{
// This must not fail. The transaction has already been signed and recorded.
LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
return false;
}
}
#endif
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew, false, pwalletdb);
// Notify that old coins are spent
set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
<API key>(this, coin.GetHash(), CT_UPDATED);
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
if (<API key>)
{
#if 0
// Broadcast
if (!wtxNew.AcceptToMemoryPool(false))
{
// This must not fail. The transaction has already been signed and recorded.
LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
return false;
}
#else
SyncWithWallets(wtxNew,NULL);
#endif
wtxNew.<API key>();
}
}
return true;
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
{
if (!pwalletdb.<API key>(acentry))
return false;
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
return true;
}
CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
{
return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
}
CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
{
// payTxFee is user-set "I want to pay this much"
CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
// User didn't set: use -txconfirmtarget to estimate...
if (nFeeNeeded == 0) {
int estimateFoundTarget = nConfirmTarget;
nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
// ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
if (nFeeNeeded == 0)
nFeeNeeded = fallbackFee.GetFee(nTxBytes);
}
// prevent user from paying a fee below minRelayTxFee or minTxFee
nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
// But always obey the maximum
if (nFeeNeeded > maxTxFee.value)
nFeeNeeded = maxTxFee.value;
return nFeeNeeded;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return DB_LOAD_OK;
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
fFirstRunRet = !vchDefaultKey.IsValid();
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapSelectTx(vector<uint256>& vHashIn, vector<uint256>& vHashOut)
{
if (!fFileBacked)
return DB_LOAD_OK;
DBErrors nZapSelectTxRet = CWalletDB(strWalletFile,"cr+").ZapSelectTx(this, vHashIn, vHashOut);
if (nZapSelectTxRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapSelectTxRet != DB_LOAD_OK)
return nZapSelectTxRet;
MarkDirty();
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
if (!fFileBacked)
return DB_LOAD_OK;
DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
<API key>(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
if (!fFileBacked)
return false;
if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
return false;
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
if(fFileBacked)
{
// Delete destdata tuples associated with address
std::string strAddress = CBitcoinAddress(address).ToString();
BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
{
CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
}
}
mapAddressBook.erase(address);
}
<API key>(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
if (!fFileBacked)
return false;
CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
{
if (fFileBacked)
{
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
}
vchDefaultKey = vchPubKey;
return true;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH(int64_t nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
if (IsLocked())
return false;
int64_t nKeys = max(GetArg("-keypool", <API key>), (int64_t)0);
for (int i = 0; i < nKeys; i++)
{
int64_t nIndex = i+1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = max(GetArg("-keypool", <API key>), (int64_t) 0);
while (setKeyPool.size() < (nTargetSize + 1))
{
int64_t nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool(): writing generated key failed");
setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
}
}
return true;
}
void CWallet::<API key>(int64_t& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("<API key>(): read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("<API key>(): unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
if (fFileBacked)
{
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
}
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex)
{
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result)
{
int64_t nIndex = 0;
CKeyPool keypool;
{
LOCK(cs_wallet);
<API key>(nIndex, keypool);
if (nIndex == -1)
{
if (IsLocked()) return false;
result = GenerateNewKey();
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64_t CWallet::<API key>()
{
int64_t nIndex = 0;
CKeyPool keypool;
<API key>(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
CWalletTx *pcoin = &walletEntry.second;
if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(pcoin->vout[i]))
continue;
if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
set< set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
set< set<CTxDestination> > groupings;
set<CTxDestination> grouping;
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
CWalletTx *pcoin = &walletEntry.second;
if (pcoin->vin.size() > 0)
{
bool any_mine = false;
// group all input addresses with each other
BOOST_FOREACH(CTxIn txin, pcoin->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine)
{
BOOST_FOREACH(CTxOut txout, pcoin->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0)
{
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (IsMine(pcoin->vout[i]))
{
CTxDestination address;
if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
BOOST_FOREACH(set<CTxDestination> grouping, groupings)
{
// make a set of all the groups hit by this new group
set< set<CTxDestination>* > hits;
map< CTxDestination, set<CTxDestination>* >::iterator it;
BOOST_FOREACH(CTxDestination address, grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
set<CTxDestination>* merged = new set<CTxDestination>(grouping);
BOOST_FOREACH(set<CTxDestination>* hit, hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
BOOST_FOREACH(CTxDestination element, *merged)
setmap[element] = merged;
}
set< set<CTxDestination> > ret;
BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
{
LOCK(cs_wallet);
set<CTxDestination> result;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey)
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet-><API key>(nIndex, keypool);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH(const int64_t& id, setKeyPool)
{
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("<API key>(): read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("<API key>(): unknown key in key pool");
setAddress.insert(keyID);
}
}
void CWallet::UpdatedTransaction(const uint256 &hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
<API key>(this, hashTx, CT_UPDATED);
}
}
void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
{
boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
CPubKey pubkey;
if (!rKey->GetReservedKey(pubkey))
return;
script = rKey;
script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
void CWallet::LockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
// end of Actions
class <API key> : public boost::static_visitor<void> {
private:
const CKeyStore &keystore;
std::vector<CKeyID> &vKeys;
public:
<API key>(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript &script) {
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
BOOST_FOREACH(const CTxDestination &dest, vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID &keyId) {
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID &scriptId) {
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const CNoDestination &none) {}
};
void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
if (it->second.nCreateTime)
mapKeyBirth[it->first] = it->second.nCreateTime;
// map in which we'll infer heights of other keys
CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys;
GetKeys(setKeys);
BOOST_FOREACH(const CKeyID &keyid, setKeys) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
setKeys.clear();
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
// iterate over all wallet transactions...
const CWalletTx &wtx = (*it).second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
// iterate over all their outputs
<API key>(*this, vAffected).Process(txout.scriptPubKey);
BOOST_FOREACH(const CKeyID &keyid, vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
}
bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
}
bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
}
bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if(i != mapAddressBook.end())
{
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if(j != i->second.destdata.end())
{
if(value)
*value = j->second;
return true;
}
}
return false;
}
bool CWallet::InitLoadWallet()
{
std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
CWallet *tempWallet = new CWallet(walletFile);
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
return UIError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
}
delete tempWallet;
tempWallet = NULL;
}
uiInterface.InitMessage(_("Loading wallet..."));
int64_t nStart = GetTimeMillis();
bool fFirstRun = true;
CWallet *walletInstance = new CWallet(walletFile);
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
return UIError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
else if (nLoadWalletRet == <API key>)
{
UIWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."),
walletFile));
}
else if (nLoadWalletRet == DB_TOO_NEW)
return UIError(strprintf(_("Error loading %s: Wallet requires newer version of %s"),
walletFile, _(PACKAGE_NAME)));
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
return UIError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
}
else
return UIError(strprintf(_("Error loading %s"), walletFile));
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < walletInstance->GetVersion())
{
return UIError(_("Cannot downgrade wallet"));
}
walletInstance->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (walletInstance->GetKeyFromPool(newDefaultKey)) {
walletInstance->SetDefaultKey(newDefaultKey);
if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive"))
return UIError(_("Cannot write default address") += "\n");
}
walletInstance->SetBestChain(chainActive.GetLocator());
}
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
<API key>(walletInstance);
CBlockIndex *pindexRescan = chainActive.Tip();
if (GetBoolArg("-rescan", false))
pindexRescan = chainActive.Genesis();
else
{
CWalletDB walletdb(walletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = <API key>(chainActive, locator);
else
pindexRescan = chainActive.Genesis();
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
//We can't rescan beyond non-pruned blocks, stop and throw an error
//this might happen if a user uses a old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
block = block->pprev;
if (pindexRescan != block)
return UIError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
}
uiInterface.InitMessage(_("Rescanning..."));
LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
walletInstance-><API key>(pindexRescan, true);
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
walletInstance->SetBestChain(chainActive.GetLocator());
nWalletDBUpdated++;
// Restore wallet transaction metadata after -zapwallettxes=1
if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
{
CWalletDB walletdb(walletFile);
BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
if (mi != walletInstance->mapWallet.end())
{
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
copyTo->WriteToDisk(&walletdb);
}
}
}
}
walletInstance-><API key>(GetBoolArg("-walletbroadcast", <API key>));
pwalletMain = walletInstance;
return true;
}
bool CWallet::<API key>()
{
if (mapArgs.count("-mintxfee"))
{
CAmount n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CWallet::minTxFee = CFeeRate(n);
else
return UIError(AmountErrMsg("mintxfee", mapArgs["-mintxfee"]));
}
if (mapArgs.count("-fallbackfee"))
{
CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-fallbackfee"], nFeePerK))
return UIError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), mapArgs["-fallbackfee"]));
if (nFeePerK > HIGH_TX_FEE_PER_KB)
UIWarning(_("-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available."));
CWallet::fallbackFee = CFeeRate(nFeePerK);
}
if (mapArgs.count("-paytxfee"))
{
CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
return UIError(AmountErrMsg("paytxfee", mapArgs["-paytxfee"]));
if (nFeePerK > HIGH_TX_FEE_PER_KB)
UIWarning(_("-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
payTxFee = CFeeRate(nFeePerK, 1000);
if (payTxFee < ::minRelayTxFee)
{
return UIError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
}
}
if (mapArgs.count("-maxtxfee"))
{
CAmount nMaxFee = 0;
if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
return UIError(AmountErrMsg("maxtxfee", mapArgs["-maxtxfee"]));
if (nMaxFee > HIGH_MAX_TX_FEE)
UIWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
maxTxFee.value = nMaxFee;
if (CFeeRate(maxTxFee.value, 1000) < ::minRelayTxFee)
{
return UIError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
}
}
nTxConfirmTarget = GetArg("-txconfirmtarget", <API key>);
<API key> = GetBoolArg("-spendzeroconfchange", <API key>);
<API key> = GetBoolArg("-<API key>", <API key>);
return true;
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
int CMerkleTx::SetMerkleBranch(const CBlock& block)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
// Update the tx's hashBlock
hashBlock = block.GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
if (block.vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)block.vtx.size())
{
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
return 0;
}
// Is the tx in a block that's in the main chain
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
const CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
{
if (hashUnset())
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
pindexRet = pindex;
return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
{
CValidationState state;
return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, false, fRejectAbsurdFee);
} |
<!DOCTYPE html PUBLIC "-
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_balance">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../class_element.html#<API key>" target="_parent">balance</a>
<span class="SRScope">Element</span>
</div>
</div>
<div class="SRResult" id="SR_baseexception">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../<API key>.html" target="_parent">BaseException</a>
</div>
</div>
<div class="SRResult" id="<API key>">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../<API key>.html" target="_parent">BaseException.php</a>
</div>
</div>
<div class="SRResult" id="SR_baseobject">
<div class="SREntry">
<a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../class_base_object.html" target="_parent">BaseObject</a>
</div>
</div>
<div class="SRResult" id="SR_baseobject_2ephp">
<div class="SREntry">
<a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../_base_object_8php.html" target="_parent">BaseObject.php</a>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html> |
<?php
declare(strict_types=1);
require __DIR__.'/../vendor/autoload.php';
use SkeletonDancer\Cli\<API key>;
\Symfony\Component\Debug\ErrorHandler::register();
\Symfony\Component\Debug\DebugClassLoader::enable();
$cli = new \Webmozart\Console\ConsoleApplication(new <API key>());
$cli->run(); |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;
namespace AlexanderTsema.Storage.Concretes.Migrations
{
public partial class FullModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<short>(
name: "SummaryId",
table: "Skill",
nullable: true);
migrationBuilder.CreateTable(
name: "Content",
columns: table => new
{
Id = table.Column<short>(nullable: false)
.Annotation("SqlServer:<API key>", <API key>.IdentityColumn),
ContactsTitle = table.Column<string>(nullable: true),
EducationTitle = table.Column<string>(nullable: true),
SummaryTitle = table.Column<string>(nullable: true),
TestimonialsTitle = table.Column<string>(nullable: true),
WorkTitle = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Content", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PortfolioItemType",
columns: table => new
{
Id = table.Column<short>(nullable: false)
.Annotation("SqlServer:<API key>", <API key>.IdentityColumn),
Desktop = table.Column<bool>(nullable: false),
Mobile = table.Column<bool>(nullable: false),
Web = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("<API key>", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ReferenceAuthor",
columns: table => new
{
Id = table.Column<short>(nullable: false)
.Annotation("SqlServer:<API key>", <API key>.IdentityColumn),
CompanyLink = table.Column<string>(nullable: true),
CompanyName = table.Column<string>(nullable: true),
Image = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
Position = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ReferenceAuthor", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Summary",
columns: table => new
{
Id = table.Column<short>(nullable: false)
.Annotation("SqlServer:<API key>", <API key>.IdentityColumn),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Summary", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PortfolioItem",
columns: table => new
{
Id = table.Column<short>(nullable: false)
.Annotation("SqlServer:<API key>", <API key>.IdentityColumn),
Description = table.Column<string>(nullable: true),
Image = table.Column<string>(nullable: true),
Link = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
PortfolioItemTypeId = table.Column<short>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PortfolioItem", x => x.Id);
table.ForeignKey(
name: "<API key>",
column: x => x.PortfolioItemTypeId,
principalTable: "PortfolioItemType",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Reference",
columns: table => new
{
Id = table.Column<short>(nullable: false)
.Annotation("SqlServer:<API key>", <API key>.IdentityColumn),
Description = table.Column<string>(nullable: true),
Pdf = table.Column<string>(nullable: true),
ReferenceAuthorId = table.Column<short>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Reference", x => x.Id);
table.ForeignKey(
name: "<API key><API key>,
column: x => x.ReferenceAuthorId,
principalTable: "ReferenceAuthor",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Skill_SummaryId",
table: "Skill",
column: "SummaryId");
migrationBuilder.CreateIndex(
name: "<API key>",
table: "PortfolioItem",
column: "PortfolioItemTypeId");
migrationBuilder.CreateIndex(
name: "<API key>",
table: "Reference",
column: "ReferenceAuthorId");
migrationBuilder.AddForeignKey(
name: "<API key>",
table: "Skill",
column: "SummaryId",
principalTable: "Summary",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "<API key>",
table: "Skill");
migrationBuilder.DropTable(
name: "Content");
migrationBuilder.DropTable(
name: "PortfolioItem");
migrationBuilder.DropTable(
name: "Reference");
migrationBuilder.DropTable(
name: "Summary");
migrationBuilder.DropTable(
name: "PortfolioItemType");
migrationBuilder.DropTable(
name: "ReferenceAuthor");
migrationBuilder.DropIndex(
name: "IX_Skill_SummaryId",
table: "Skill");
migrationBuilder.DropColumn(
name: "SummaryId",
table: "Skill");
}
}
} |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Api\V2010\Account\Usage\Record;
use Twilio\ListResource;
use Twilio\Options;
use Twilio\Serialize;
use Twilio\Stream;
use Twilio\Values;
use Twilio\Version;
class AllTimeList extends ListResource {
/**
* Construct the AllTimeList
*
* @param Version $version Version that contains the resource
* @param string $accountSid A 34 character string that uniquely identifies
* this resource.
*/
public function __construct(Version $version, string $accountSid) {
parent::__construct($version);
// Path Solution
$this->solution = ['accountSid' => $accountSid, ];
$this->uri = '/Accounts/' . \rawurlencode($accountSid) . '/Usage/Records/AllTime.json';
}
/**
* Streams AllTimeInstance records from the API as a generator stream.
* This operation lazily loads records as efficiently as possible until the
* limit
* is reached.
* The results are returned as a generator, so this operation is memory
* efficient.
*
* @param array|Options $options Optional Arguments
* @param int $limit Upper limit for the number of records to return. stream()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, stream()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return Stream stream of results
*/
public function stream(array $options = [], int $limit = null, $pageSize = null): Stream {
$limits = $this->version->readLimits($limit, $pageSize);
$page = $this->page($options, $limits['pageSize']);
return $this->version->stream($page, $limits['limit'], $limits['pageLimit']);
}
/**
* Reads AllTimeInstance records from the API as a list.
* Unlike stream(), this operation is eager and will load `limit` records into
* memory before returning.
*
* @param array|Options $options Optional Arguments
* @param int $limit Upper limit for the number of records to return. read()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, read()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return AllTimeInstance[] Array of results
*/
public function read(array $options = [], int $limit = null, $pageSize = null): array {
return \iterator_to_array($this->stream($options, $limit, $pageSize), false);
}
/**
* Retrieve a single page of AllTimeInstance records from the API.
* Request is executed immediately
*
* @param array|Options $options Optional Arguments
* @param mixed $pageSize Number of records to return, defaults to 50
* @param string $pageToken PageToken provided by the API
* @param mixed $pageNumber Page Number, this value is simply for client state
* @return AllTimePage Page of AllTimeInstance
*/
public function page(array $options = [], $pageSize = Values::NONE, string $pageToken = Values::NONE, $pageNumber = Values::NONE): AllTimePage {
$options = new Values($options);
$params = Values::of([
'Category' => $options['category'],
'StartDate' => Serialize::iso8601Date($options['startDate']),
'EndDate' => Serialize::iso8601Date($options['endDate']),
'IncludeSubaccounts' => Serialize::booleanToString($options['includeSubaccounts']),
'PageToken' => $pageToken,
'Page' => $pageNumber,
'PageSize' => $pageSize,
]);
$response = $this->version->page('GET', $this->uri, $params);
return new AllTimePage($this->version, $response, $this->solution);
}
/**
* Retrieve a specific page of AllTimeInstance records from the API.
* Request is executed immediately
*
* @param string $targetUrl API-generated URL for the requested results page
* @return AllTimePage Page of AllTimeInstance
*/
public function getPage(string $targetUrl): AllTimePage {
$response = $this->version->getDomain()->getClient()->request(
'GET',
$targetUrl
);
return new AllTimePage($this->version, $response, $this->solution);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string {
return '[Twilio.Api.V2010.AllTimeList]';
}
} |
package com.bbn.bue.common.evaluation;
import com.bbn.bue.common.symbols.Symbol;
/**
* Convenience constants for using in evaluation code.
* When building confusion matrices for binary decisions, we use these conventional constants as
* the labels.
*/
public final class EvaluationConstants {
public static final Symbol PRESENT = Symbol.from("Present");
public static final Symbol ABSENT = Symbol.from("Absent");
} |
layout: default
title: Devin McGloin
excerpt: I make products that help people to understand the world around them, and think of new solutions to difficult problems.
{% include index/lead.html %}
{% include index/currently.html %}
{% include index/projects.html %}
{% include forms/newsletter.html %}
{% include index/experiments.html %}
{% include index/writing.html %} |
// ServiceMock.h
// GKCommerce
#import <Foundation/Foundation.h>
@interface GKServiceMock : NSObject
- (NSDictionary *)loadJSON:(NSString *)jsonName;
@end |
package com.microsoft.azure.management.mediaservices.v2019_05_01_preview.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.ContentKeyPolicies;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.<API key>;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.ContentKeyPolicy;
class <API key> extends WrapperImpl<<API key>> implements ContentKeyPolicies {
private final MediaManager manager;
<API key>(MediaManager manager) {
super(manager.inner().contentKeyPolicies());
this.manager = manager;
}
public MediaManager manager() {
return this.manager;
}
@Override
public <API key> define(String name) {
return wrapModel(name);
}
private <API key> wrapModel(<API key> inner) {
return new <API key>(inner, manager());
}
private <API key> wrapModel(String name) {
return new <API key>(name, this.manager());
}
@Override
public Observable<<API key>> <API key>(String resourceGroupName, String accountName, String <API key>) {
<API key> client = this.inner();
return client.<API key>(resourceGroupName, accountName, <API key>)
.map(new Func1<<API key>, <API key>>() {
@Override
public <API key> call(<API key> inner) {
return new <API key>(inner, manager());
}
});
}
@Override
public Observable<ContentKeyPolicy> listAsync(final String resourceGroupName, final String accountName) {
<API key> client = this.inner();
return client.listAsync(resourceGroupName, accountName)
.flatMapIterable(new Func1<Page<<API key>>, Iterable<<API key>>>() {
@Override
public Iterable<<API key>> call(Page<<API key>> page) {
return page.items();
}
})
.map(new Func1<<API key>, ContentKeyPolicy>() {
@Override
public ContentKeyPolicy call(<API key> inner) {
return wrapModel(inner);
}
});
}
@Override
public Observable<ContentKeyPolicy> getAsync(String resourceGroupName, String accountName, String <API key>) {
<API key> client = this.inner();
return client.getAsync(resourceGroupName, accountName, <API key>)
.flatMap(new Func1<<API key>, Observable<ContentKeyPolicy>>() {
@Override
public Observable<ContentKeyPolicy> call(<API key> inner) {
if (inner == null) {
return Observable.empty();
} else {
return Observable.just((ContentKeyPolicy)wrapModel(inner));
}
}
});
}
@Override
public Completable deleteAsync(String resourceGroupName, String accountName, String <API key>) {
<API key> client = this.inner();
return client.deleteAsync(resourceGroupName, accountName, <API key>).toCompletable();
}
} |
import { prepareEmpty } from '@pnpm/prepare'
import { <API key>, install } from '@pnpm/core'
import {
addDistTag,
testDefaults,
} from './utils'
test('should fail to update when requests are cached', async () => {
const project = prepareEmpty()
const opts = await testDefaults()
await addDistTag('<API key>', '100.0.0', 'latest')
const manifest = await <API key>({}, ['pkg-with-1-dep'], opts)
await project.storeHas('<API key>', '100.0.0')
await addDistTag('<API key>', '100.1.0', 'latest')
await install(manifest, { ...opts, depth: 1, update: true })
await project.storeHas('<API key>', '100.0.0')
})
test('should not cache when cache is not used', async () => {
const project = prepareEmpty()
await addDistTag('<API key>', '100.0.0', 'latest')
const manifest = await <API key>({}, ['pkg-with-1-dep'], await testDefaults({ save: true }))
await project.storeHas('<API key>', '100.0.0')
await addDistTag('<API key>', '100.1.0', 'latest')
await install(manifest, await testDefaults({ depth: 1, update: true }))
await project.storeHas('<API key>', '100.1.0')
}) |
import Ember from 'ember';
import GMapsCirclesMixin from 'ember-cli-g-maps/mixins/g-maps/circles';
import { module, test } from 'qunit';
import sinon from 'sinon';
let subject;
module('Unit | Mixin | g maps/circles', {
beforeEach: function() {
const GMapsCirclesObject = Ember.Object.extend(GMapsCirclesMixin, Ember.Evented);
subject = GMapsCirclesObject.create();
}
});
test('it should trigger validate on `didInsertElement` event', function(assert) {
subject._gmapCircleValidate = sinon.spy();
subject.trigger('didInsertElement');
assert.ok(subject._gmapCircleValidate.calledOnce);
});
test('it should throw an error when `circles` property is not an Ember array', function(assert) {
subject.set('circles', {});
assert.throws(
function() { return subject._gmapCircleValidate(); },
new Error('g-maps component expects circles to be an Ember Array')
);
});
test('it should sync on `isMapLoaded` and updates to `circles` model', function(assert) {
subject.set('circles', Ember.A());
// Replace sync with spy
subject._gmapCircleSync = Ember.observer(subject._gmapCircleSync.__ember_observes__, sinon.spy());
subject.set('isMapLoaded', true);
assert.equal(subject._gmapCircleSync.callCount, 1);
subject.get('circles').pushObject({ lat: 0, lng: 0, radius: 1 });
assert.equal(subject._gmapCircleSync.callCount, 2);
});
test('it should not add circle when map is not loaded', function(assert) {
const conf = {
isMapLoaded: false, // Map is not loaded
circles: Ember.A(),
map: {
addCircle: sinon.spy()
}
};
subject.setProperties(conf);
subject.get('circles').pushObject({ lat: 0, lng: 0, radius: 1 });
assert.equal(conf.map.addCircle.called, false);
});
test('it should call `map.addCircle` with circle when map child index does not exist yet', function(assert) {
const circle = { lat: 0, lng: 0, radius: 1 };
const conf = {
isMapLoaded: true,
circles: Ember.A(),
map: {
circles: [],
addCircle: function() {}
}
};
sinon.stub(conf.map, 'addCircle', function(c) {
subject.map.circles.push(c);
return c;
});
subject.setProperties(conf);
subject.get('circles').pushObject(circle);
assert.ok(conf.map.addCircle.calledWith(circle));
});
test('it should NOT call `map.addCircle` when map child at index equals circle at same index', function(assert) {
const circle = { lat: 0, lng: 0, radius: 1 };
const conf = {
isMapLoaded: false,
circles: Ember.A(),
map: {
circles: [circle],
addCircle: sinon.spy()
}
};
subject.setProperties(conf);
subject.setProperties({
isMapLoaded: true, // allow sync to complete
circles: Ember.A([circle])
});
assert.equal(conf.map.addCircle.called, false);
});
test('it should call `map.removeCircle` & `map.addCircle` when new circle at exsiting index', function(assert) {
const circleOne = { lat: 1, lng: 1, radius: 1 };
const circleTwo = { lat: 2, lng: 2, radius: 2 };
const diffCircleTwo = { lat: 2, lng: 2, radius: 3 }; // change radius
const conf = {
isMapLoaded: true,
circles: Ember.A([circleOne, circleTwo]),
map: {
circles: [],
addCircle: function() {},
removeCircle: function() {}
}
};
sinon.stub(conf.map, 'addCircle', function(c) {
subject.map.circles.push(c);
return c;
});
sinon.stub(conf.map, 'removeCircle', function() {
subject.map.circles.splice(1, 1);
});
// Add non-existant map children
subject.setProperties(conf);
assert.equal(conf.map.addCircle.called, true);
// Add new array with new 2nd circle object
subject.set('circles', Ember.A([circleOne, diffCircleTwo]));
assert.equal(conf.map.addCircle.callCount, 3);
assert.equal(conf.map.removeCircle.callCount, 1);
// assert new circle is at correct index
assert.equal(conf.map.circles.pop().radius, diffCircleTwo.radius);
}); |
extern crate jade;
#[test]
fn test_basic_template() {
} |
app.controller('<API key>', ['$scope', function($scope){
}]) |
body,
#content-container {
background-color: #f2f6f8;
color: #595e62;
}
/* Boxed Layout */
@media (min-width: 1200px) {
#container.boxed-layout,
#container.boxed-layout.navbar-fixed #navbar {
background-color: #3f5662;
}
}
a {
color: #595e62;
}
a:hover,
a:focus {
color: #4d5155;
}
::selection {
background-color: #5aaedc;
color: #ffffff;
}
::-moz-selection {
background-color: #5aaedc;
color: #ffffff;
}
/* SEARCHBOX */
.searchbox .custom-search-form .input-group-btn:before {
background-color: #5aaedc;
}
/* SCROLLBAR */
.pace .pace-progress,
.nano > .nano-pane > .nano-slider {
background-color: #298bc1;
}
.pace .pace-progress-inner {
box-shadow: 0 0 10px #5aaedc, 0 0 5px #5aaedc;
}
.pace .pace-activity {
background-color: #5aaedc;
}
/* NAVIGATION */
/* NAVBAR ICON & BUTTON */
/* NAVBAR RESPONSIVE */
/* NAVIGATION */
/* NAVIGATION MENU */
/* NAVIGATION - SHORTCUT BUTTONS */
/* NAVIGATION - WIDGET */
/* NAVIGATION - POPOVER */
/* NAVIGATION - OFFCANVAS */
/* ASIDE */
/* Aside with tabs */
/* ASIDE : BRIGHT COLOR THEMES */
/* FOOTER */
/* BORDER */
/* TIMELINE */
/* FORM WIZARD */
/* FORM CONTROL */
/* LIST GROUP */
/* DROPDOWN */
/* PAGER */
/* PAGINATION */
/* TAB */
/* BUTTONS */
/* PANELS */ |
// navbar
angular.module('thatjs', [])
.service('data', function () {
this.navItems = {
};
})
.controller('headerNavCtrl', function ($scope) {
window.headerNav = $scope;
$scope.headerNav = [
{'name': 'About'},
{'name': 'Run'},
{'name': 'Docs'}
];
})
.directive('headerNav', function () { //header-nav
return {
restrict: 'A',
// below needs refactoring, explicit controller not needed
// scoping for directive
template: '<ul class="global-nav" ng-controller="headerNavCtrl">' +
'<li ng-repeat="item in headerNav"><a href="{{item.name | lowercase}}">{{item.name}}</a></li>' +
'</ul>'
};
}); |
console.assert();
console.count();
console.debug();
console.dir();
console.error();
console.exception();
console.group();
console.groupCollapsed();
console.groupEnd();
console.info();
console.log();
console.profile();
console.profileEnd();
console.time();
console.timeEnd();
console.trace();
console.warn(); |
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using <API key>.Model;
namespace <API key>.Response{
public class NameResponse : CommonResponse
{
public TraderName Name {get; set; }
}
} |
#include <lua_interop.hpp>
#include <entity.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== customization: vec3 as table ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
std::cout << "registering entities into Lua ..."
<< std::endl;
register_lua(lua);
std::cout << "running script ..." << std::endl;
const auto& script = R"lua(
local e = entity.new()
local pos = e.position
print("pos type", type(pos))
print("pos", pos.x, pos.y, pos.z)
e.position = { x = 52, y = 5.5, z = 47.5 }
local new_pos = e.position
print("pos", pos.x, pos.y, pos.z)
print("new_pos", new_pos.x, new_pos.y, new_pos.z)
)lua";
sol::optional<sol::error> result = lua.safe_script(script);
if (result.has_value()) {
std::cerr << "Something went horribly wrong: "
<< result.value().what() << std::endl;
}
std::cout << "finishing ..." << std::endl;
std::cout << std::endl;
return 0;
} |
public class CodeConverterTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CodeConverter c = new CodeConverter (5);
System.out.println(c.toBars());
CodeConverter c2 = new CodeConverter ("|''|'");
System.out.println(c2.toInt());
}
} |
<?php
namespace PHPExiftool\Driver\Tag\Leaf;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class PreviewImage extends AbstractTag
{
protected $Id = 'JPEG_preview_data';
protected $Name = 'PreviewImage';
protected $FullName = 'Leaf::Main';
protected $GroupName = 'Leaf';
protected $g0 = 'Leaf';
protected $g1 = 'Leaf';
protected $g2 = 'Camera';
protected $Type = 'undef';
protected $Writable = true;
protected $Description = 'Preview Image';
protected $local_g2 = 'Preview';
} |
var Reflux = require("reflux");
var InterestActions = Reflux.createActions([
"get",
"create",
"delete"
]);
module.exports = InterestActions; |
using Entitas;
public class <API key> : IComponent {
} |
// Observer.h
// Platform
#ifndef Platform_Observer_h
#define Platform_Observer_h
#include <string>
namespace MuddledManaged
{
namespace Platform
{
template <typename Sender, typename Event, typename... Args>
class Observer
{
public:
virtual ~Observer ()
{ }
virtual void notify (Event event,
Sender * pSender,
Args... args) = 0;
};
} // namespace Platform
} // namespace MuddledManaged
#endif // Platform_Observer_h |
using Abp.Dependency;
using Abp.Runtime.Caching.Configuration;
namespace Abp.Runtime.Caching.Redis
{
<summary>
Used to create <see cref="<API key>"/> instances.
</summary>
public class <API key> : CacheManagerBase<ICache>, <API key>
{
private readonly IIocManager _iocManager;
<summary>
Initializes a new instance of the <see cref="<API key>"/> class.
</summary>
public <API key>(IIocManager iocManager, <API key> configuration)
: base(configuration)
{
_iocManager = iocManager;
_iocManager.RegisterIfNot<<API key>>(DependencyLifeStyle.Transient);
}
protected override ICache <API key>(string name)
{
return _iocManager.Resolve<<API key>>(new {name});
}
protected override void DisposeCaches()
{
foreach (var cache in Caches)
{
_iocManager.Release(cache.Value);
}
}
}
} |
[
## Usage
Include the **ng-csv-import** element with its options:
html
<ng-csv-import content="csv.content"
header="csv.header"
separator="csv.separator"
result="csv.result"></ng-csv-import>
- **csv.content**
A variable which will contain the content loaded by the file input
- **csv.header**
A variable that says whether or not the source CSV file contains headers
- **csv.separator**
A variable containing the separtor used in the CSV file
- **csv.result**
A variable which will contain the result of the CSV to JSON marshalling. |
# webpack.config.js
javascript
var path = require("path");
var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin");
module.exports = {
entry: {
vendor1: ["./vendor1"],
vendor2: ["./vendor2"],
pageA: "./pageA",
pageB: "./pageB",
pageC: "./pageC"
},
output: {
path: path.join(__dirname, "js"),
filename: "[name].js"
},
plugins: [
new CommonsChunkPlugin({
names: ["vendor2", "vendor1"],
minChunks: Infinity
})
]
};
# js/vendor1.js
<details><summary><code> (function(modules) { })</code></summary>
javascript
(function(modules) { // webpackBootstrap
// install a JSONP callback for chunk loading
var parentJsonpFunction = window["webpackJsonp"];
window["webpackJsonp"] = function <API key>(chunkIds, moreModules, executeModules) {
// add "moreModules" to the modules object,
// then flag all "chunkIds" as loaded and fire callback
var moduleId, chunkId, i = 0, resolves = [], result;
for(;i < chunkIds.length; i++) {
chunkId = chunkIds[i];
if(installedChunks[chunkId]) {
resolves.push(installedChunks[chunkId][0]);
}
installedChunks[chunkId] = 0;
}
for(moduleId in moreModules) {
if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
modules[moduleId] = moreModules[moduleId];
}
}
if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);
while(resolves.length) {
resolves.shift()();
}
if(executeModules) {
for(i=0; i < executeModules.length; i++) {
result = __webpack_require__(__webpack_require__.s = executeModules[i]);
}
}
return result;
};
// The module cache
var installedModules = {};
// objects to store loaded and loading chunks
var installedChunks = {
4: 0
};
// The require function
function __webpack_require__(moduleId) {
// Check if module is in cache
if(installedModules[moduleId]) {
return installedModules[moduleId].exports;
}
// Create a new module (and put it into the cache)
var module = installedModules[moduleId] = {
i: moduleId,
l: false,
exports: {}
};
// Execute the module function
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
// Flag the module as loaded
module.l = true;
// Return the exports of the module
return module.exports;
}
// This file contains only the entry chunk.
// The chunk loading function for additional chunks
__webpack_require__.e = function requireEnsure(chunkId) {
var installedChunkData = installedChunks[chunkId];
if(installedChunkData === 0) {
return new Promise(function(resolve) { resolve(); });
}
// a Promise means "currently loading".
if(installedChunkData) {
return installedChunkData[2];
}
// setup Promise in chunk cache
var promise = new Promise(function(resolve, reject) {
installedChunkData = installedChunks[chunkId] = [resolve, reject];
});
installedChunkData[2] = promise;
// start chunk loading
var head = document.<API key>('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.async = true;
script.timeout = 120000;
if (__webpack_require__.nc) {
script.setAttribute("nonce", __webpack_require__.nc);
}
script.src = __webpack_require__.p + "" + chunkId + ".js";
var timeout = setTimeout(onScriptComplete, 120000);
script.onerror = script.onload = onScriptComplete;
function onScriptComplete() {
// avoid mem leaks in IE.
script.onerror = script.onload = null;
clearTimeout(timeout);
var chunk = installedChunks[chunkId];
if(chunk !== 0) {
if(chunk) {
chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));
}
installedChunks[chunkId] = undefined;
}
};
head.appendChild(script);
return promise;
};
// expose the modules object (__webpack_modules__)
__webpack_require__.m = modules;
// expose the module cache
__webpack_require__.c = installedModules;
// define getter function for harmony exports
__webpack_require__.d = function(exports, name, getter) {
if(!__webpack_require__.o(exports, name)) {
Object.defineProperty(exports, name, {
configurable: false,
enumerable: true,
get: getter
});
}
};
// getDefaultExport function for compatibility with non-harmony modules
__webpack_require__.n = function(module) {
var getter = module && module.__esModule ?
function getDefault() { return module['default']; } :
function getModuleExports() { return module; };
__webpack_require__.d(getter, 'a', getter);
return getter;
};
// Object.prototype.hasOwnProperty.call
__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
// <API key>
__webpack_require__.p = "js/";
// on error function for async loading
__webpack_require__.oe = function(err) { console.error(err); throw err; };
// Load entry module and return exports
return __webpack_require__(__webpack_require__.s = 2);
})
</details>
javascript
([
/*! no static exports found */
/*! all exports used */
(function(module, exports) {
module.exports = "Vendor1";
}),
,
/*! no static exports found */
/*! all exports used */
(function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./vendor1 */0);
})
]);
# js/vendor2.js
javascript
webpackJsonp([0],[
,
/*! no static exports found */
/*! all exports used */
(function(module, exports, __webpack_require__) {
module.exports = "Vendor2";
__webpack_require__(/*! ./vendor1 */ 0);
}),
,
/*! no static exports found */
/*! all exports used */
(function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./vendor2 */1);
})
],[3]);
# js/pageA.js
javascript
webpackJsonp([3],{
4:
/*! no static exports found */
/*! all exports used */
(function(module, exports, __webpack_require__) {
module.exports = "pageA";
__webpack_require__(/*! ./vendor1 */ 0);
__webpack_require__(/*! ./vendor2 */ 1);
})
},[4]);
# Info
## Uncompressed
Hash: <API key>
Version: webpack 3.5.1
Asset Size Chunks Chunk Names
vendor2.js 598 bytes 0 [emitted] vendor2
pageC.js 235 bytes 1 [emitted] pageC
pageB.js 235 bytes 2 [emitted] pageB
pageA.js 342 bytes 3 [emitted] pageA
vendor1.js 6.41 kB 4 [emitted] vendor1
Entrypoint vendor1 = vendor1.js
Entrypoint vendor2 = vendor1.js vendor2.js
Entrypoint pageA = vendor1.js vendor2.js pageA.js
Entrypoint pageB = vendor1.js vendor2.js pageB.js
Entrypoint pageC = vendor1.js vendor2.js pageC.js
chunk {0} vendor2.js (vendor2) 80 bytes {4} [initial] [rendered]
> vendor2 [3] multi ./vendor2
[1] ./vendor2.js 52 bytes {0} [built]
single entry ./vendor2 [3] multi ./vendor2 vendor2:100000
cjs require ./vendor2 [4] ./pageA.js 3:0-20
[3] multi ./vendor2 28 bytes {0} [built]
chunk {1} pageC.js (pageC) 25 bytes {0} [initial] [rendered]
> pageC [6] ./pageC.js
[6] ./pageC.js 25 bytes {1} [built]
chunk {2} pageB.js (pageB) 25 bytes {0} [initial] [rendered]
> pageB [5] ./pageB.js
[5] ./pageB.js 25 bytes {2} [built]
chunk {3} pageA.js (pageA) 73 bytes {0} [initial] [rendered]
> pageA [4] ./pageA.js
[4] ./pageA.js 73 bytes {3} [built]
chunk {4} vendor1.js (vendor1) 55 bytes [entry] [rendered]
> vendor1 [2] multi ./vendor1
[0] ./vendor1.js 27 bytes {4} [built]
cjs require ./vendor1 [1] ./vendor2.js 2:0-20
single entry ./vendor1 [2] multi ./vendor1 vendor1:100000
cjs require ./vendor1 [4] ./pageA.js 2:0-20
[2] multi ./vendor1 28 bytes {4} [built]
## Minimized (uglify-js, no zip)
Hash: <API key>
Version: webpack 3.5.1
Asset Size Chunks Chunk Names
vendor2.js 100 bytes 0 [emitted] vendor2
pageC.js 59 bytes 1 [emitted] pageC
pageB.js 59 bytes 2 [emitted] pageB
pageA.js 71 bytes 3 [emitted] pageA
vendor1.js 1.44 kB 4 [emitted] vendor1
Entrypoint vendor1 = vendor1.js
Entrypoint vendor2 = vendor1.js vendor2.js
Entrypoint pageA = vendor1.js vendor2.js pageA.js
Entrypoint pageB = vendor1.js vendor2.js pageB.js
Entrypoint pageC = vendor1.js vendor2.js pageC.js
chunk {0} vendor2.js (vendor2) 80 bytes {4} [initial] [rendered]
> vendor2 [3] multi ./vendor2
[1] ./vendor2.js 52 bytes {0} [built]
single entry ./vendor2 [3] multi ./vendor2 vendor2:100000
cjs require ./vendor2 [4] ./pageA.js 3:0-20
[3] multi ./vendor2 28 bytes {0} [built]
chunk {1} pageC.js (pageC) 25 bytes {0} [initial] [rendered]
> pageC [6] ./pageC.js
[6] ./pageC.js 25 bytes {1} [built]
chunk {2} pageB.js (pageB) 25 bytes {0} [initial] [rendered]
> pageB [5] ./pageB.js
[5] ./pageB.js 25 bytes {2} [built]
chunk {3} pageA.js (pageA) 73 bytes {0} [initial] [rendered]
> pageA [4] ./pageA.js
[4] ./pageA.js 73 bytes {3} [built]
chunk {4} vendor1.js (vendor1) 55 bytes [entry] [rendered]
> vendor1 [2] multi ./vendor1
[0] ./vendor1.js 27 bytes {4} [built]
cjs require ./vendor1 [1] ./vendor2.js 2:0-20
single entry ./vendor1 [2] multi ./vendor1 vendor1:100000
cjs require ./vendor1 [4] ./pageA.js 2:0-20
[2] multi ./vendor1 28 bytes {4} [built] |
package com.dmdirc.addons.nowplaying;
/**
* The state of a media source.
*/
public enum MediaSourceState {
/** Media Source is closed. */
CLOSED("Closed"),
/** Media Source is stopped. */
STOPPED("Stopped"),
/** Media Source is paused. */
PAUSED("Paused"),
/** Media Source is playing. */
PLAYING("Playing"),
/** Media Source is giving an unknown state. */
NOTKNOWN("Unknown");
/** Nice name for this state. */
final String niceName;
/**
* Create a new MediaSourceState
*
* @param niceName Nice name for this state.
*/
MediaSourceState(final String niceName) {
this.niceName = niceName;
}
/**
* Get the nice name for this state.
*
* @return This state's nice name
*/
public String getNiceName() {
return niceName;
}
} |
CS125 Honors
======
Finally I mady it possible!
http://mikuflk.github.io/cs125/
Filename explanation:
[branch: master]
tweet.php ==> back-end (include output format)
(Since I need to manually upload it to my server, no change in source code will effect immediately)
[branch: gh-pages]
main.js ==> fetch and location part
main.css ==> user interface
index.html ==> front-end |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Stamplay JS SDK tests">
<meta name="author" content="Stamplay developers">
<link href="../bower_components/mocha/mocha.css" rel="stylesheet">
<link rel="icon" href="https://drrjhlchpvi7e.cloudfront.net/editor/a1debe3/img/favicon32.png" sizes="32x32">
<title>Stamplay | TEST all the things</title>
</head>
<body>
<div id="mocha"></div>
<!-- Phantom JS doesn't have xmlhttprequest -->
<script src="./xmlhttprequest.js"></script>
<script src="../dist/stamplay.js"></script>
<script src="../bower_components/mocha/mocha.js"></script>
<script src="../bower_components/chai/chai.js"></script>
<script src="../bower_components/sinon/lib/sinon.js"></script>
<script src="../bower_components/sinon/lib/sinon/util/event.js"></script>
<script src="../bower_components/sinon/lib/sinon/util/<API key>.js"></script>
<script src="../bower_components/sinon/lib/sinon/assert.js"></script>
<script src="../bower_components/sinon/lib/sinon/spy.js"></script>
<script src="../bower_components/sinon/lib/sinon/call.js"></script>
<script src="../bower_components/sinon/lib/sinon/stub.js"></script>
<script>
if (navigator.userAgent.indexOf('PhantomJS') !== -1) {
window.ProgressEvent = function (type, params) {
params = params || {};
this.lengthComputable = params.lengthComputable || false;
this.loaded = params.loaded || 0;
this.total = params.total || 0;
};
}
mocha.setup('tdd');
var assert = chai.assert;
Stamplay.init('stamplay')
</script>
<script src="stamplay.js"></script>
<script src="support.js"></script>
<script src="query.js"></script>
<script src="user.js"></script>
<script src="cobject.js"></script>
<script src="webhook.js"></script>
<script src="stripe.js"></script>
<script src="codeblock.js"></script>
<script>
if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
else { mocha.run(); }
</script>
</body>
</html> |
require 'spec_helper'
describe GSA do
include Fixtures
before(:each) do
GSA.base_uri = gsa_base_uri
end
describe "#feed" do
context "add" do
context "many records" do
it "successfully adds the records to the gsa index" do
VCR.use_cassette("many_records") do
results = GSA.feed(
:records => many_records,
:searchable => [:name, :description],
:datasource_name => "products",
:datasource_uri => "https://0.0.0.0:3000/products",
:datasource_uid => "id"
)
results.should eq success_text
end
end
end
context "a single record" do
it "successfully adds the records to the gsa index" do
VCR.use_cassette("single_record") do
results = GSA.feed(
:records => many_records,
:searchable => [:name, :description],
:datasource_name => "products",
:datasource_uri => "https://0.0.0.0:3000/products",
:datasource_uid => "id"
)
results.should eq success_text
end
end
end
end
context "delete" do
context "many records" do
it "successfully deletes the records from the gsa index" do
VCR.use_cassette("delete_many_records") do
results = GSA.feed(
:records => many_records,
:searchable => [:name, :description],
:datasource_name => "products",
:datasource_uri => "https://0.0.0.0:3000/products",
:datasource_uid => "id",
:delete? => true
)
results.should eq success_text
end
end
end
context "a single record" do
it "successfully deletes the record from the gsa index" do
VCR.use_cassette("<API key>") do
results = GSA.feed(
:records => one_records,
:searchable => [:name, :description],
:datasource_name => "products",
:datasource_uri => "https://0.0.0.0:3000/products",
:datasource_uid => "id",
:delete? => true
)
results.should eq success_text
end
end
end
end
context "without a base_uri set" do
before(:each) do
GSA.base_uri = nil
end
it "raises an error" do
expect {
GSA.feed(
:records => one_records,
:searchable => [:name, :description],
:datasource_name => "products",
:datasource_uri => "https://0.0.0.0:3000/products",
:datasource_uid => "id",
:delete? => true
)
}.to raise_error GSA::URINotSetError
end
end
end
describe "#search" do
context "with no filters" do
context "with a query yielding many matches" do
let(:query) { many_query }
let(:results_set) { many_results }
it "returns many records" do
VCR.use_cassette("<API key>") do
results = GSA.search(query)
results.count.should eq results_set.count
end
end
it "returns results in the expected 'pretty' format" do
VCR.use_cassette("<API key>") do
results = GSA.search(query)
results.should eq results_set
end
end
end
context "with a query yielding no matches" do
let(:query) { none_query }
it "returns the no record flag" do
VCR.use_cassette("<API key>") do
results = GSA.search(query)
results.should eq GSA::NO_RESULTS
end
end
end
end
context "with filters" do
context "with a query yielding many results" do
let(:query) { many_query }
let(:results_set) { many_results }
let(:filter_name) { "attribute_brand" }
let(:filter_value) { "HLS" }
let(:filters) { "#{filter_name}:#{filter_value}" }
it "returns less than the unfiltered results" do
VCR.use_cassette("<API key>") do
results = GSA.search(query, :filters => filters)
results[:result_sets].count.should be < results_set[:result_sets].count
end
end
end
context "with a query yielding no results" do
let(:query) { many_query }
let(:filters) { "brand:FooBar" }
it "returns the no record flag" do
VCR.use_cassette("<API key>") do
results = GSA.search(query, :filters => filters)
results.should eq GSA::NO_RESULTS
end
end
end
context "without a base_uri set" do
let(:query) { many_query }
let(:filters) { "brand:Philips" }
before(:each) do
GSA.base_uri = nil
end
it "raises an error" do
expect {
GSA.search(query, :filters => filters)
}.to raise_error GSA::URINotSetError
end
end
end
end
describe "#uids" do
context "with multiple records passed in" do
let(:results_set) { many_results }
let(:uids) { many_uids }
it "returns multiple uids" do
results = GSA.uids(results_set[:result_sets], uid)
results.should eq uids
end
end
context "with a single record passed in" do
let(:results_set) { one_results }
let(:uids) { one_uids }
it "returns a single uid" do
results = GSA.uids(results_set[:result_sets], uid)
results.should eq uids
end
end
end
end |
(function($) {
$.event.special.mousewheel = {
setup: function() {
var handler = $.event.special.mousewheel.handler;
// Fix pageX, pageY, clientX and clientY for mozilla
if ( $.browser.mozilla )
$(this).bind('mousemove.mousewheel', function(event) {
$.data(this, 'mwcursorposdata', {
pageX: event.pageX,
pageY: event.pageY,
clientX: event.clientX,
clientY: event.clientY
});
});
if ( this.addEventListener )
this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
else
this.onmousewheel = handler;
},
teardown: function() {
var handler = $.event.special.mousewheel.handler;
$(this).unbind('mousemove.mousewheel');
if ( this.removeEventListener )
this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
else
this.onmousewheel = function(){};
$.removeData(this, 'mwcursorposdata');
},
handler: function(event) {
var args = Array.prototype.slice.call( arguments, 1 );
event = $.event.fix(event || window.event);
// Get correct pageX, pageY, clientX and clientY for mozilla
$.extend( event, $.data(this, 'mwcursorposdata') || {} );
var delta = 0, returnValue = true;
if ( event.wheelDelta ) delta = event.wheelDelta/120;
if ( event.detail ) delta = -event.detail/3;
// if ( $.browser.opera ) delta = -event.wheelDelta;
event.data = event.data || {};
event.type = "mousewheel";
// Add delta to the front of the arguments
args.unshift(delta);
// Add event to the front of the arguments
args.unshift(event);
return $.event.handle.apply(this, args);
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
})(jQuery); |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Description of Assembly
*
* @author Nick
*/
// A page for robot assembly, providing different parts to mix and match.
class Assembly extends Application
{
function __construct()
{
parent::__construct();
$this->load->model('partsdata');
$this->load->model('historydata');
}
public function index()
{
// get user roles
$user_role = $this->session->userdata('userrole');
// only allow to boss and supervisor
if ($user_role == 'boss' || $user_role == 'supervisor')
{
$allParts = $this->partsdata->getAllSortedParts();
$this->generateTable($allParts);
} else
{
$this->data['pagetitle'] = 'Assemble Robot - Boss, Supervisor';
$this->data['pagebody'] = 'blockedpage';
$this->data['message'] = '';
$this->render();
}
}
public function assembleBots()
{
// get parts data
$head = $this->input->post('head');
$torso = $this->input->post('torso');
$legs = $this->input->post('legs');
// check parts data if one of them is null
if ($head == NULL || $torso == NULL || $legs == NULL)
{
$this->data['pagebody'] = 'assemblypage';
$this->data['message'] = 'Please pick each part once';
redirect('/assembly');
}
$tempHead = explode('-', $head);
$tempTorso = explode('-', $torso);
$tempLegs = explode('-', $legs);
$headModel = $tempHead[0];
$torsoModel = $tempTorso[0];
$legsModel = $tempLegs[0];
$headId = $tempHead[1];
$torsoId = $tempTorso[1];
$legsId = $tempLegs[1];
$newRobot = array(
'head' => $headId,
'torso' => $torsoId,
'legs' => $legsId,
'headModel' => $headModel,
'torsoModel' => $torsoModel,
'legsModel' => $legsModel,
);
// delete the data from parts
$this->partsdata->deletePartById($headId);
$this->partsdata->deletePartById($torsoId);
$this->partsdata->deletePartById($legsId);
if ($this->input->post('assemble') == 'Assemble')
{
//create a robot
$this->robotsdata->createBot($newRobot);
// create history
$assembledRobot = $this->createHistory($newRobot, 'Assemble', 0);
// insert parts to history
$this->historydata->insertPartsHistory($assembledRobot);
} else if ($this->input->post('assemble') == 'Return')
{
$API_KEY = $this->managedata->getKey();
// check key validation
if ($API_KEY == '000000')
{
$this->data['pagebody'] = 'blockedpage';
$this->data['pagetitle'] = '<a class="text-danger">Please register first</a>';
$this->render();
return;
}
$response = file_get_contents("https://umbrella.jlparry.com/work/recycle/$headId/$torsoId/$legsId?key=" . $API_KEY);
$responseArray = explode(" ", $response);
// get money earn from PRC
$earned = $responseArray[1];
// if returns 'ok'
if ($responseArray[0] == 'Ok')
{
// create history
$return_robots = $this->createHistory($newRobot, 'Return', $earned);
$this->historydata->insertPartsHistory($return_robots);
}
}
redirect('/assembly');
}
// create history data
private function createHistory($part, $action, $amount)
{
$temp_array = array();
// get num of parts
$num_of_parts = count($part);
$sequence = '';
$models = '';
// get names
$sequence .= $part['head'] . ' ' . $part['torso'] . ' ' . $part['legs'];
$models .= $part['headModel'] . ' ' . $part['torsoModel'] . ' ' . $part['legsModel'];
$temp_array[] = array(
'action' => $action,
'amount' => $amount,
'quantity' => $num_of_parts,
'plant' => 'strawberry',
'model' => $models,
'seq' => $sequence,
'stamp' => date("Y-m-d H:i:s", time()),
);
return $temp_array;
}
// generate table of parts
public function generateTable($allParts)
{
$this->data['pagetitle'] = 'Assemble Robot';
$this->data['pagebody'] = 'assemblypage';
$this->data['message'] = 'Please pick each part once';
$head_parts = array();
$torso_parts = array();
$legs_parts = array();
// save parts by piece - head, torso, legs
foreach ($allParts as $part)
{
switch ($part['piece'])
{
case '1':
$head_parts[] = array(
'id' => $part['id'],
'model' => $part['model'],
'piece' => $part['piece'],
'plant' => $part['plant'],
'stamp' => $part['stamp'],
'aquired_time' => date("Y-m-d H:i:s", time()),
'file_name' => $part['model'] . $part['piece'] . '.jpeg',
'href' => '/parts/' . $part['id']);
break;
case '2':
$torso_parts[] = array(
'id' => $part['id'],
'model' => $part['model'],
'piece' => $part['piece'],
'plant' => $part['plant'],
'stamp' => $part['stamp'],
'aquired_time' => date("Y-m-d H:i:s", time()),
'file_name' => $part['model'] . $part['piece'] . '.jpeg',
'href' => '/parts/' . $part['id']);
break;
case '3':
$legs_parts[] = array(
'id' => $part['id'],
'model' => $part['model'],
'piece' => $part['piece'],
'plant' => $part['plant'],
'stamp' => $part['stamp'],
'aquired_time' => date("Y-m-d H:i:s", time()),
'file_name' => $part['model'] . $part['piece'] . '.jpeg',
'href' => '/parts/' . $part['id']);
break;
}
}
$this->data['head_parts'] = $head_parts;
$this->data['torso_parts'] = $torso_parts;
$this->data['legs_parts'] = $legs_parts;
$this->render();
}
} |
<div class="container">
<h1 class="text-block">About</h1>
<div class="text-block">
<p>Sounder Radio is a radio web app powered by the <a href="//soundcloud.com" target="_blank">SOUNDCLOUD</a> HTTP and widget APIs. It is built using <a href="//angular.io" target="_blank">Angular</a>. Sounder Radio is a work in progress.</p>
<p>Learn more at <a href="https://github.com/JavierPDev/SounderRadio" target="_blank">the project repo page.</a></p>
</div>
</div> |
#include "hb-private.hh"
#include "hb-shaper-private.hh"
#include "hb-atomic-private.hh"
static const hb_shaper_pair_t all_shapers[] = {
#define HB_SHAPER_IMPLEMENT(name) {#name, _hb_##name##_shape},
#include "hb-shaper-list.hh"
#undef HB_SHAPER_IMPLEMENT
};
/* Thread-safe, lock-free, shapers */
static const hb_shaper_pair_t *static_shapers;
#ifdef HB_USE_ATEXIT
static
void free_static_shapers (void)
{
if (unlikely (static_shapers != all_shapers))
free ((void *) static_shapers);
}
#endif
const hb_shaper_pair_t *
_hb_shapers_get (void)
{
retry:
hb_shaper_pair_t *shapers = (hb_shaper_pair_t *) hb_atomic_ptr_get (&static_shapers);
if (unlikely (!shapers))
{
char *env = getenv ("HB_SHAPER_LIST");
if (!env || !*env) {
(void) <API key> (&static_shapers, nullptr, &all_shapers[0]);
return (const hb_shaper_pair_t *) all_shapers;
}
/* Not found; allocate one. */
shapers = (hb_shaper_pair_t *) calloc (1, sizeof (all_shapers));
if (unlikely (!shapers)) {
(void) <API key> (&static_shapers, nullptr, &all_shapers[0]);
return (const hb_shaper_pair_t *) all_shapers;
}
memcpy (shapers, all_shapers, sizeof (all_shapers));
/* Reorder shaper list to prefer requested shapers. */
unsigned int i = 0;
char *end, *p = env;
for (;;) {
end = strchr (p, ',');
if (!end)
end = p + strlen (p);
for (unsigned int j = i; j < ARRAY_LENGTH (all_shapers); j++)
if (end - p == (int) strlen (shapers[j].name) &&
0 == strncmp (shapers[j].name, p, end - p))
{
/* Reorder this shaper to position i */
struct hb_shaper_pair_t t = shapers[j];
memmove (&shapers[i + 1], &shapers[i], sizeof (shapers[i]) * (j - i));
shapers[i] = t;
i++;
}
if (!*end)
break;
else
p = end + 1;
}
if (!<API key> (&static_shapers, nullptr, shapers)) {
free (shapers);
goto retry;
}
#ifdef HB_USE_ATEXIT
atexit (free_static_shapers); /* First person registers atexit() callback. */
#endif
}
return shapers;
} |
var components = {
"core": {
"meta": {
"path": "components/prism-core.js",
"option": "mandatory"
},
"core": "Core"
},
"themes": {
"meta": {
"path": "themes/{id}.css",
"link": "index.html?theme={id}",
"exclusive": true
},
"prism": {
"title": "Default",
"option": "default"
},
"prism-dark": "Dark",
"prism-funky": "Funky",
"prism-okaidia": {
"title": "Okaidia",
"owner": "ocodia"
},
"prism-twilight": {
"title": "Twilight",
"owner": "remybach"
},
"prism-coy": {
"title": "Coy",
"owner": "tshedor"
}
},
"languages": {
"meta": {
"path": "components/prism-{id}",
"noCSS": true,
"examplesPath": "examples/prism-{id}"
},
"markup": {
"title": "Markup",
"option": "default"
},
"twig": {
"title": "Twig",
"require": "markup",
"owner": "brandonkelly"
},
"css": {
"title": "CSS",
"option": "default"
},
"css-extras": {
"title": "CSS Extras",
"require": "css",
"owner": "milesj"
},
"clike": {
"title": "C-like",
"option": "default"
},
"eiffel": {
"title": "Eiffel",
"owner": "Conaclos"
},
"javascript": {
"title": "JavaScript",
"option": "default",
"require": "clike"
},
"java": {
"title": "Java",
"require": "clike",
"owner": "sherblot"
},
"php": {
"title": "PHP",
"require": "clike",
"owner": "milesj"
},
"php-extras": {
"title": "PHP Extras",
"require": "php",
"owner": "milesj"
},
"coffeescript": {
"title": "CoffeeScript",
"require": "javascript",
"owner": "R-osey"
},
"scss": {
"title": "Sass (Scss)",
"require": "css",
"owner": "MoOx"
},
"bash": {
"title": "Bash",
"require": "clike",
"owner": "zeitgeist87"
},
"c": {
"title": "C",
"require": "clike",
"owner": "zeitgeist87"
},
"cpp": {
"title": "C++",
"require": "c",
"owner": "zeitgeist87"
},
"python": {
"title": "Python",
"owner": "multipetros"
},
"julia": {
"title": "julia",
"owner": "cdagnino"
},
"sql": {
"title": "SQL",
"owner": "multipetros"
},
"groovy": {
"title": "Groovy",
"require": "clike",
"owner": "robfletcher"
},
"http": {
"title": "HTTP",
"owner": "danielgtaylor"
},
"ruby": {
"title": "Ruby",
"require": "clike",
"owner": "samflores"
},
"rip": {
"title": "Rip",
"owner": "ravinggenius"
},
"gherkin": {
"title": "Gherkin",
"owner": "mvalipour"
},
"csharp": {
"title": "C
"require": "clike",
"owner": "mvalipour"
},
"go": {
"title": "Go",
"require": "clike",
"owner": "arnehormann"
},
"nsis": {
"title": "NSIS",
"owner": "idleberg"
},
"aspnet": {
"title": "ASP.NET (C
"require": "markup",
"owner": "nauzilus"
},
"scala": {
"title": "Scala",
"require": "java",
"owner": "jozic"
},
"haskell": {
"title": "Haskell",
"owner": "bholst"
},
"swift": {
"title": "Swift",
"require": "clike",
"owner": "chrischares"
},
"objectivec": {
"title": "Objective-C",
"require": "c",
"owner": "uranusjr"
},
"autohotkey": {
"title": "AutoHotkey",
"owner": "aviaryan"
},
"ini": {
"title": "Ini",
"owner": "aviaryan"
},
"latex": {
"title": "LaTeX",
"owner": "japborst"
},
"apacheconf": {
"title": "Apache Configuration",
"owner": "GuiTeK"
},
"git": {
"title": "Git",
"owner": "lgiraudel"
},
"scheme" : {
"title": "Scheme",
"owner" : "bacchus123"
},
"nasm": {
"title": "NASM",
"owner": "rbmj"
},
"perl": {
"title": "Perl",
"owner": "Golmote"
},
"handlebars": {
"title": "Handlebars",
"require": "markup",
"owner": "Golmote"
},
"matlab": {
"title": "MATLAB",
"owner": "Golmote"
},
"less": {
"title": "Less",
"require": "css",
"owner": "Golmote"
},
"r": {
"title": "R",
"owner": "Golmote"
},
"lolcode": {
"title": "LOLCODE",
"owner": "Golmote"
},
"fortran": {
"title": "Fortran",
"owner": "Golmote"
},
"erlang": {
"title": "Erlang",
"owner": "Golmote"
},
"haml": {
"title": "Haml",
"require": "ruby",
"owner": "Golmote"
},
"jade": {
"title": "Jade",
"require": "javascript",
"owner": "Golmote"
},
"pascal": {
"title": "Pascal",
"owner": "Golmote"
},
"applescript": {
"title": "AppleScript",
"owner": "Golmote"
},
"rust": {
"title": "Rust",
"owner": "Golmote"
},
"dart": {
"title": "Dart",
"require": "clike",
"owner": "Golmote"
},
"powershell": {
"title": "PowerShell",
"owner": "nauzilus"
},
"smarty": {
"title": "Smarty",
"require": "markup",
"owner": "Golmote"
},
"actionscript": {
"title": "ActionScript",
"require": "javascript",
"owner": "Golmote"
},
"markdown": {
"title": "Markdown",
"require": "markup",
"owner": "Golmote"
},
"jsx":{
"title": "React JSX",
"require": ["markup", "javascript"],
"owner": "vkbansal"
},
"typescript":{
"title": "TypeScript",
"require": "javascript",
"owner": "vkbansal"
},
"fsharp": {
"title": "F
"require": "clike",
"owner": "simonreynolds7"
}
},
"plugins": {
"meta": {
"path": "plugins/{id}/prism-{id}",
"link": "plugins/{id}/"
},
"line-highlight": "Line Highlight",
"line-numbers": {
"title": "Line Numbers",
"owner": "kuba-kubula"
},
"show-invisibles": "Show Invisibles",
"autolinker": "Autolinker",
"wpd": "WebPlatform Docs",
"file-highlight": {
"title": "File Highlight",
"noCSS": true
},
"show-language": {
"title": "Show Language",
"owner": "nauzilus"
},
"highlight-keywords": {
"title": "Highlight Keywords",
"owner": "vkbansal",
"noCSS": true
}
}
}; |
# == Schema Information
# Table name: <API key>
# id :integer not null, primary key
# <API key> :integer
# signup_enabled :boolean
# signin_enabled :boolean
# gravatar_enabled :boolean
# sign_in_text :text
# created_at :datetime
# updated_at :datetime
# home_page_url :string(255)
# <API key> :integer default(2)
# <TwitterConsumerkey> :boolean default(TRUE)
# <API key> :text
# <API key> :boolean default(TRUE)
# max_attachment_size :integer default(10), not null
# <API key> :integer
# <API key> :integer
# <API key> :text
# <API key> :boolean default(TRUE)
# after_sign_out_path :string(255)
# <API key> :integer default(10080), not null
# import_sources :text
# help_page_text :text
# <API key> :string(255)
# <API key> :boolean default(TRUE), not null
# max_artifacts_size :integer default(100), not null
# <API key> :string(255)
class ApplicationSetting < ActiveRecord::Base
include <API key>
add_<API key> :<API key>
CACHE_KEY = 'application_setting.last'
serialize :<API key>
serialize :import_sources
serialize :<API key>, Array
attr_accessor :<API key>
validates :<API key>,
presence: true,
numericality: { only_integer: true, <API key>: 0 }
validates :home_page_url,
allow_blank: true,
url: true,
if: :<API key>
validates :after_sign_out_path,
allow_blank: true,
url: true
validates :<API key>,
allow_blank: true,
email: true
validates_each :<API key> do |record, attr, value|
unless value.nil?
value.each do |level|
unless Gitlab::VisibilityLevel.options.has_value?(level)
record.errors.add(attr, "'#{level}' is not a valid visibility level")
end
end
end
end
validates_each :import_sources do |record, attr, value|
unless value.nil?
value.each do |source|
unless Gitlab::ImportSources.options.has_value?(source)
record.errors.add(attr, "'#{source}' is not a import source")
end
end
end
end
before_save :<API key>
after_commit do
Rails.cache.write(CACHE_KEY, self)
end
def self.current
Rails.cache.fetch(CACHE_KEY) do
ApplicationSetting.last
end
end
def self.expire
Rails.cache.delete(CACHE_KEY)
end
def self.<API key>
create(
<API key>: Settings.gitlab['<API key>'],
<API key>: Settings.gitlab['<API key>'],
signup_enabled: Settings.gitlab['signup_enabled'],
signin_enabled: Settings.gitlab['signin_enabled'],
<TwitterConsumerkey>: Settings.gitlab['<TwitterConsumerkey>'],
gravatar_enabled: Settings.gravatar['enabled'],
sign_in_text: Settings.extra['sign_in_text'],
<API key>: Settings.gitlab['<API key>'],
max_attachment_size: Settings.gitlab['max_attachment_size'],
<API key>: Settings.gitlab['<API key>'],
<API key>: Settings.gitlab.<API key>['visibility_level'],
<API key>: Settings.gitlab.<API key>['visibility_level'],
<API key>: Settings.gitlab['<API key>'],
import_sources: ['github','bitbucket','gitlab','gitorious','google_code','fogbugz','git'],
<API key>: Settings.gitlab_ci['<API key>'],
max_artifacts_size: Settings.artifacts['max_size'],
)
end
def <API key>
ActiveRecord::Base.connection.column_exists?(:<API key>, :home_page_url)
end
def <API key>
self.<API key>.join("\n") unless self.<API key>.nil?
end
def <API key>=(values)
self.<API key> = []
self.<API key> = values.split(
/\s*[,;]\s* # comma or semicolon, optionally surrounded by whitespace
|
\s # any whitespace character
|
[\r\n] # any number of newline characters
/x)
self.<API key>.reject! { |d| d.empty? }
end
end |
/**
@module @ember/object
*/
import { FACTORY_FOR } from '@ember/-internals/container';
import { assign, _WeakSet as WeakSet } from '@ember/polyfills';
import {
guidFor,
getName,
setName,
makeArray,
HAS_NATIVE_PROXY,
isInternalSymbol,
} from '@ember/-internals/utils';
import { schedule } from '@ember/runloop';
import { descriptorFor, meta, peekMeta, deleteMeta } from '@ember/-internals/meta';
import {
PROXY_CONTENT,
finishChains,
sendEvent,
Mixin,
applyMixin,
defineProperty,
ComputedProperty,
InjectedProperty,
classToString,
} from '@ember/-internals/metal';
import ActionHandler from '../mixins/action_handler';
import { assert, deprecate } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
const reopen = Mixin.prototype.reopen;
const wasApplied = new WeakSet();
const factoryMap = new WeakMap();
const prototypeMixinMap = new WeakMap();
const DELAY_INIT = Object.freeze({});
let initCalled; // only used in debug builds to enable the proxy trap
// using DEBUG here to avoid the extraneous variable when not needed
if (DEBUG) {
initCalled = new WeakSet();
}
function initialize(obj, properties) {
let m = meta(obj);
if (properties !== undefined) {
assert(
'EmberObject.create only accepts objects.',
typeof properties === 'object' && properties !== null
);
assert(
'EmberObject.create no longer supports mixing in other ' +
'definitions, use .extend & .create separately instead.',
!(properties instanceof Mixin)
);
let <API key> = obj.<API key>;
let mergedProperties = obj.mergedProperties;
let <API key> =
<API key> !== undefined && <API key>.length > 0;
let hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0;
let keyNames = Object.keys(properties);
for (let i = 0; i < keyNames.length; i++) {
let keyName = keyNames[i];
let value = properties[keyName];
assert(
'EmberObject.create no longer supports defining computed ' +
'properties. Define computed properties using extend() or reopen() ' +
'before calling create().',
!(value instanceof ComputedProperty)
);
assert(
'EmberObject.create no longer supports defining methods that call _super.',
!(typeof value === 'function' && value.toString().indexOf('._super') !== -1)
);
assert(
'`actions` must be provided at extend time, not at create time, ' +
'when Ember.ActionHandler is used (i.e. views, controllers & routes).',
!(keyName === 'actions' && ActionHandler.detect(obj))
);
let possibleDesc = descriptorFor(obj, keyName, m);
let isDescriptor = possibleDesc !== undefined;
if (!isDescriptor) {
let baseValue = obj[keyName];
if (<API key> && <API key>.indexOf(keyName) > -1) {
if (baseValue) {
value = makeArray(baseValue).concat(value);
} else {
value = makeArray(value);
}
}
if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) {
value = assign({}, baseValue, value);
}
}
if (isDescriptor) {
possibleDesc.set(obj, keyName, value);
} else if (typeof obj.setUnknownProperty === 'function' && !(keyName in obj)) {
obj.setUnknownProperty(keyName, value);
} else {
if (DEBUG) {
defineProperty(obj, keyName, null, value, m); // setup mandatory setter
} else {
obj[keyName] = value;
}
}
}
}
// using DEBUG here to avoid the extraneous variable when not needed
if (DEBUG) {
initCalled.add(obj);
}
obj.init(properties);
// re-enable chains
m.unsetInitializing();
finishChains(m);
sendEvent(obj, 'init', undefined, undefined, undefined, m);
}
/**
@class CoreObject
@public
*/
class CoreObject {
static _initFactory(factory) {
factoryMap.set(this, factory);
}
constructor(properties) {
// pluck off factory
let initFactory = factoryMap.get(this.constructor);
if (initFactory !== undefined) {
factoryMap.delete(this.constructor);
FACTORY_FOR.set(this, initFactory);
}
// prepare prototype...
this.constructor.proto();
let self = this;
if (DEBUG && HAS_NATIVE_PROXY && typeof self.unknownProperty === 'function') {
let messageFor = (obj, property) => {
return (
`You attempted to access the \`${String(property)}\` property (of ${obj}).\n` +
`Since Ember 3.1, this is usually fine as you no longer need to use \`.get()\`\n` +
`to access computed properties. However, in this case, the object in question\n` +
`is a special kind of Ember object (a proxy). Therefore, it is still necessary\n` +
`to use \`.get('${String(property)}')\` in this case.\n\n` +
`If you encountered this error because of third-party code that you don't control,\n` +
`there is more information at https://github.com/emberjs/ember.js/issues/16148, and\n` +
`you can help us improve this error message by telling us more about what happened in\n` +
`this situation.`
);
};
/* globals Proxy Reflect */
self = new Proxy(this, {
get(target, property, receiver) {
if (property === PROXY_CONTENT) {
return target;
} else if (
// init called will be set on the proxy, not the target, so get with the receiver
!initCalled.has(receiver) ||
typeof property === 'symbol' ||
isInternalSymbol(property) ||
property === 'toJSON' ||
property === 'toString' ||
property === 'toStringExtension' ||
property === 'didDefineProperty' ||
property === 'willWatchProperty' ||
property === 'didUnwatchProperty' ||
property === 'didAddListener' ||
property === 'didRemoveListener' ||
property === 'isDescriptor' ||
property === '_onLookup' ||
property in target
) {
return Reflect.get(target, property, receiver);
}
let value = target.unknownProperty.call(receiver, property);
if (typeof value !== 'function') {
assert(messageFor(receiver, property), value === undefined || value === null);
}
},
});
FACTORY_FOR.set(self, initFactory);
}
// disable chains
let m = meta(self);
m.setInitializing();
if (properties !== DELAY_INIT) {
deprecate(
'using `new` with EmberObject has been deprecated. Please use `create` instead, or consider using native classes without extending from EmberObject.',
false,
{
id: 'object.new-constructor',
until: '3.9.0',
url: 'https://emberjs.com/deprecations/v3.x#<API key>',
}
);
initialize(self, properties);
}
// only return when in debug builds and `self` is the proxy created above
if (DEBUG && self !== this) {
return self;
}
}
reopen(...args) {
applyMixin(this, args);
return this;
}
/**
An overridable method called when objects are instantiated. By default,
does nothing unless it is overridden during class definition.
Example:
javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
init() {
alert(`Name is ${this.get('name')}`);
}
});
let steve = Person.create({
name: 'Steve'
});
// alerts 'Name is Steve'.
NOTE: If you do override `init` for a framework class like `Ember.View`,
be sure to call `this._super(...arguments)` in your
`init` declaration! If you don't, Ember may not have an opportunity to
do important setup work, and you'll see strange behavior in your
application.
@method init
@public
*/
init() {}
/**
Defines the properties that will be concatenated from the superclass
(instead of overridden).
By default, when you extend an Ember class a property defined in
the subclass overrides a property with the same name that is defined
in the superclass. However, there are some cases where it is preferable
to build up a property's value by combining the superclass' property
value with the subclass' value. An example of this in use within Ember
is the `classNames` property of `Ember.View`.
Here is some sample code showing the difference between a concatenated
property and a normal one:
javascript
import EmberObject from '@ember/object';
const Bar = EmberObject.extend({
// Configure which properties to concatenate
<API key>: ['<API key>'],
<API key>: ['bar'],
<API key>: ['bar']
});
const FooBar = Bar.extend({
<API key>: ['foo'],
<API key>: ['foo']
});
let fooBar = FooBar.create();
fooBar.get('<API key>'); // ['foo']
fooBar.get('<API key>'); // ['bar', 'foo']
This behavior extends to object creation as well. Continuing the
above example:
javascript
let fooBar = FooBar.create({
<API key>: ['baz'],
<API key>: ['baz']
})
fooBar.get('<API key>'); // ['baz']
fooBar.get('<API key>'); // ['bar', 'foo', 'baz']
Adding a single property that is not an array will just add it in the array:
javascript
let fooBar = FooBar.create({
<API key>: 'baz'
})
view.get('<API key>'); // ['bar', 'foo', 'baz']
Using the `<API key>` property, we can tell Ember to mix the
content of the properties.
In `Component` the `classNames`, `classNameBindings` and
`attributeBindings` properties are concatenated.
This feature is available for you to use throughout the Ember object model,
although typical app developers are likely to use it infrequently. Since
it changes expectations about behavior of properties, you should properly
document its usage in each individual concatenated property (to not
mislead your users to think they can override the property in a subclass).
@property <API key>
@type Array
@default null
@public
*/
/**
Defines the properties that will be merged from the superclass
(instead of overridden).
By default, when you extend an Ember class a property defined in
the subclass overrides a property with the same name that is defined
in the superclass. However, there are some cases where it is preferable
to build up a property's value by merging the superclass property value
with the subclass property's value. An example of this in use within Ember
is the `queryParams` property of routes.
Here is some sample code showing the difference between a merged
property and a normal one:
javascript
import EmberObject from '@ember/object';
const Bar = EmberObject.extend({
// Configure which properties are to be merged
mergedProperties: ['mergedProperty'],
<API key>: {
nonMerged: 'superclass value of nonMerged'
},
mergedProperty: {
page: { replace: false },
limit: { replace: true }
}
});
const FooBar = Bar.extend({
<API key>: {
completelyNonMerged: 'subclass value of nonMerged'
},
mergedProperty: {
limit: { replace: false }
}
});
let fooBar = FooBar.create();
fooBar.get('<API key>');
// => { completelyNonMerged: 'subclass value of nonMerged' }
//
// Note the entire object, including the nonMerged property of
// the superclass object, has been replaced
fooBar.get('mergedProperty');
// => {
// page: {replace: false},
// limit: {replace: false}
// }
//
// Note the page remains from the superclass, and the
// `limit` property's value of `false` has been merged from
// the subclass.
This behavior is not available during object `create` calls. It is only
available at `extend` time.
In `Route` the `queryParams` property is merged.
This feature is available for you to use throughout the Ember object model,
although typical app developers are likely to use it infrequently. Since
it changes expectations about behavior of properties, you should properly
document its usage in each individual merged property (to not
mislead your users to think they can override the property in a subclass).
@property mergedProperties
@type Array
@default null
@public
*/
/**
Destroyed object property flag.
if this property is `true` the observers and bindings were already
removed by the effect of calling the `destroy()` method.
@property isDestroyed
@default false
@public
*/
get isDestroyed() {
return peekMeta(this).isSourceDestroyed();
}
set isDestroyed(value) {
assert(`You cannot set \`${this}.isDestroyed\` directly, please use \`.destroy()\`.`, false);
}
/**
Destruction scheduled flag. The `destroy()` method has been called.
The object stays intact until the end of the run loop at which point
the `isDestroyed` flag is set.
@property isDestroying
@default false
@public
*/
get isDestroying() {
return peekMeta(this).isSourceDestroying();
}
set isDestroying(value) {
assert(`You cannot set \`${this}.isDestroying\` directly, please use \`.destroy()\`.`, false);
}
/**
Destroys an object by setting the `isDestroyed` flag and removing its
metadata, which effectively destroys observers and bindings.
If you try to set a property on a destroyed object, an exception will be
raised.
Note that destruction is scheduled for the end of the run loop and does not
happen immediately. It will set an isDestroying flag immediately.
@method destroy
@return {EmberObject} receiver
@public
*/
destroy() {
let m = peekMeta(this);
if (m.isSourceDestroying()) {
return;
}
m.setSourceDestroying();
schedule('actions', this, this.willDestroy);
schedule('destroy', this, this._scheduledDestroy, m);
return this;
}
/**
Override to implement teardown.
@method willDestroy
@public
*/
willDestroy() {}
/**
Invoked by the run loop to actually destroy the object. This is
scheduled for execution by the `destroy` method.
@private
@method _scheduledDestroy
*/
_scheduledDestroy(m) {
if (m.isSourceDestroyed()) {
return;
}
deleteMeta(this);
m.setSourceDestroyed();
}
/**
Returns a string representation which attempts to provide more information
than Javascript's `toString` typically does, in a generic way for all Ember
objects.
javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend();
person = Person.create();
person.toString(); //=> "<Person:ember1024>"
If the object's class is not defined on an Ember namespace, it will
indicate it is a subclass of the registered superclass:
javascript
const Student = Person.extend();
let student = Student.create();
student.toString(); //=> "<(subclass of Person):ember1025>"
If the method `toStringExtension` is defined, its return value will be
included in the output.
javascript
const Teacher = Person.extend({
toStringExtension() {
return this.get('fullName');
}
});
teacher = Teacher.create();
teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>"
@method toString
@return {String} string representation
@public
*/
toString() {
let <API key> = typeof this.toStringExtension === 'function';
let extension = <API key> ? `:${this.toStringExtension()}` : '';
let ret = `<${getName(this) || FACTORY_FOR.get(this) || this.constructor.toString()}:${guidFor(
this
)}${extension}>`;
return ret;
}
/**
Creates a new subclass.
javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
alert(thing);
}
});
This defines a new subclass of EmberObject: `Person`. It contains one method: `say()`.
You can also create a subclass from any existing class by calling its `extend()` method.
For example, you might want to create a subclass of Ember's built-in `Component` class:
javascript
import Component from '@ember/component';
const PersonComponent = Component.extend({
tagName: 'li',
classNameBindings: ['isAdministrator']
});
When defining a subclass, you can override methods but still access the
implementation of your parent class by calling the special `_super()` method:
javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
let name = this.get('name');
alert(`${name} says: ${thing}`);
}
});
const Soldier = Person.extend({
say(thing) {
this._super(`${thing}, sir!`);
},
march(numberOfHours) {
alert(`${this.get('name')} marches for ${numberOfHours} hours.`);
}
});
let yehuda = Soldier.create({
name: 'Yehuda Katz'
});
yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!"
The `create()` on line #17 creates an *instance* of the `Soldier` class.
The `extend()` on line #8 creates a *subclass* of `Person`. Any instance
of the `Person` class will *not* have the `march()` method.
You can also pass `Mixin` classes to add additional properties to the subclass.
javascript
import EmberObject from '@ember/object';
import Mixin from '@ember/object/mixin';
const Person = EmberObject.extend({
say(thing) {
alert(`${this.get('name')} says: ${thing}`);
}
});
const SingingMixin = Mixin.create({
sing(thing) {
alert(`${this.get('name')} sings: la la la ${thing}`);
}
});
const BroadwayStar = Person.extend(SingingMixin, {
dance() {
alert(`${this.get('name')} dances: tap tap tap tap `);
}
});
The `BroadwayStar` class contains three methods: `say()`, `sing()`, and `dance()`.
@method extend
@static
@for @ember/object
@param {Mixin} [mixins]* One or more Mixin classes
@param {Object} [arguments]* Object containing values to use within the new class
@public
*/
static extend() {
let Class = class extends this {};
reopen.apply(Class.PrototypeMixin, arguments);
return Class;
}
/**
Creates an instance of a class. Accepts either no arguments, or an object
containing values to initialize the newly instantiated object with.
javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
helloWorld() {
alert(`Hi, my name is ${this.get('name')}`);
}
});
let tom = Person.create({
name: 'Tom Dale'
});
tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
`create` will call the `init` function if defined during
`AnyObject.extend`
If no arguments are passed to `create`, it will not set values to the new
instance during initialization:
javascript
let noName = Person.create();
noName.helloWorld(); // alerts undefined
NOTE: For performance reasons, you cannot declare methods or computed
properties during `create`. You should instead declare methods and computed
properties when using `extend`.
@method create
@for @ember/object
@static
@param [arguments]*
@public
*/
static create(props, extra) {
let C = this;
let instance = new C(DELAY_INIT);
if (extra === undefined) {
initialize(instance, props);
} else {
initialize(instance, flattenProps.apply(this, arguments));
}
return instance;
}
/**
Augments a constructor's prototype with additional
properties and functions:
javascript
import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({
name: 'an object'
});
o = MyObject.create();
o.get('name'); // 'an object'
MyObject.reopen({
say(msg) {
console.log(msg);
}
});
o2 = MyObject.create();
o2.say('hello'); // logs "hello"
o.say('goodbye'); // logs "goodbye"
To add functions and properties to the constructor itself,
see `reopenClass`
@method reopen
@for @ember/object
@static
@public
*/
static reopen() {
this.willReopen();
reopen.apply(this.PrototypeMixin, arguments);
return this;
}
static willReopen() {
let p = this.prototype;
if (wasApplied.has(p)) {
wasApplied.delete(p);
// If the base mixin already exists and was applied, create a new mixin to
// make sure that it gets properly applied. Reusing the same mixin after
// the first `proto` call will cause it to get skipped.
if (prototypeMixinMap.has(this)) {
prototypeMixinMap.set(this, Mixin.create(this.PrototypeMixin));
}
}
}
/**
Augments a constructor's own properties and functions:
javascript
import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({
name: 'an object'
});
MyObject.reopenClass({
canBuild: false
});
MyObject.canBuild; // false
o = MyObject.create();
In other words, this creates static properties and functions for the class.
These are only available on the class and not on any instance of that class.
javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
}
});
Person.reopenClass({
species: 'Homo sapiens',
createPerson(name) {
return Person.create({ name });
}
});
let tom = Person.create({
name: 'Tom Dale'
});
let yehuda = Person.createPerson('Yehuda Katz');
tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(Person.species); // "Homo sapiens"
Note that `species` and `createPerson` are *not* valid on the `tom` and `yehuda`
variables. They are only valid on `Person`.
To add functions and properties to instances of
a constructor by extending the constructor's prototype
see `reopen`
@method reopenClass
@for @ember/object
@static
@public
*/
static reopenClass() {
applyMixin(this, arguments);
return this;
}
static detect(obj) {
if ('function' !== typeof obj) {
return false;
}
while (obj) {
if (obj === this) {
return true;
}
obj = obj.superclass;
}
return false;
}
static detectInstance(obj) {
return obj instanceof this;
}
/**
In some cases, you may want to annotate computed properties with additional
metadata about how they function or what values they operate on. For
example, computed property functions may close over variables that are then
no longer available for introspection.
You can pass a hash of these values to a computed property like this:
javascript
import { computed } from '@ember/object';
person: computed(function() {
let personId = this.get('personId');
return Person.create({ id: personId });
}).meta({ type: Person })
Once you've done this, you can retrieve the values saved to the computed
property from your class like this:
javascript
MyClass.metaForProperty('person');
This will return the original hash that was passed to `meta()`.
@static
@method metaForProperty
@param key {String} property name
@private
*/
static metaForProperty(key) {
let proto = this.proto(); // ensure prototype is initialized
let possibleDesc = descriptorFor(proto, key);
assert(
`metaForProperty() could not find a computed property with key '${key}'.`,
possibleDesc !== undefined
);
return possibleDesc._meta || {};
}
/**
Iterate over each computed property for the class, passing its name
and any associated metadata (see `metaForProperty`) to the callback.
@static
@method <API key>
@param {Function} callback
@param {Object} binding
@private
*/
static <API key>(callback, binding = this) {
this.proto(); // ensure prototype is initialized
let empty = {};
meta(this.prototype).forEachDescriptors((name, descriptor) => {
if (descriptor.enumerable) {
let meta = descriptor._meta || empty;
callback.call(binding, name, meta);
}
});
}
static get PrototypeMixin() {
let prototypeMixin = prototypeMixinMap.get(this);
if (prototypeMixin === undefined) {
prototypeMixin = Mixin.create();
prototypeMixin.ownerConstructor = this;
prototypeMixinMap.set(this, prototypeMixin);
}
return prototypeMixin;
}
static get superclass() {
let c = Object.getPrototypeOf(this);
return c !== Function.prototype ? c : undefined;
}
static proto() {
let p = this.prototype;
if (!wasApplied.has(p)) {
wasApplied.add(p);
let parent = this.superclass;
if (parent) {
parent.proto();
}
// If the prototype mixin exists, apply it. In the case of native classes,
// it will not exist (unless the class has been reopened).
if (prototypeMixinMap.has(this)) {
this.PrototypeMixin.apply(p);
}
}
return p;
}
}
CoreObject.toString = classToString;
setName(CoreObject, 'Ember.CoreObject');
CoreObject.isClass = true;
CoreObject.isMethod = false;
function flattenProps(...props) {
let { <API key>, mergedProperties } = this;
let <API key> =
<API key> !== undefined && <API key>.length > 0;
let hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0;
let initProperties = {};
for (let i = 0; i < props.length; i++) {
let properties = props[i];
assert(
'EmberObject.create no longer supports mixing in other ' +
'definitions, use .extend & .create separately instead.',
!(properties instanceof Mixin)
);
let keyNames = Object.keys(properties);
for (let j = 0, k = keyNames.length; j < k; j++) {
let keyName = keyNames[j];
let value = properties[keyName];
if (<API key> && <API key>.indexOf(keyName) > -1) {
let baseValue = initProperties[keyName];
if (baseValue) {
value = makeArray(baseValue).concat(value);
} else {
value = makeArray(value);
}
}
if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) {
let baseValue = initProperties[keyName];
value = assign({}, baseValue, value);
}
initProperties[keyName] = value;
}
}
return initProperties;
}
if (DEBUG) {
/**
Provides lookup-time type validation for injected properties.
@private
@method _onLookup
*/
CoreObject._onLookup = function <API key>(debugContainerKey) {
let [type] = debugContainerKey.split(':');
let proto = this.proto();
for (let key in proto) {
let desc = descriptorFor(proto, key);
if (desc instanceof InjectedProperty) {
assert(
`Defining \`${key}\` as an injected controller property on a non-controller (\`${debugContainerKey}\`) is not allowed.`,
type === 'controller' || desc.type !== 'controller'
);
}
}
};
/**
Returns a hash of property names and container names that injected
properties will lookup on the container lazily.
@method _lazyInjections
@return {Object} Hash of all lazy injected property keys to container names
@private
*/
CoreObject._lazyInjections = function() {
let injections = {};
let proto = this.proto();
let key;
let desc;
for (key in proto) {
desc = descriptorFor(proto, key);
if (desc instanceof InjectedProperty) {
injections[key] = {
namespace: desc.namespace,
source: desc.source,
specifier: `${desc.type}:${desc.name || key}`,
};
}
}
return injections;
};
}
export default CoreObject; |
package com.raizlabs.android.dbflow.sql.migration;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
/**
* Description: Provides the base implementation of {@link com.raizlabs.android.dbflow.sql.migration.Migration} with
* only {@link Migration#migrate(DatabaseWrapper)} needing to be implemented.
*/
public abstract class BaseMigration implements Migration {
@Override
public void onPreMigrate() {
}
@Override
public abstract void migrate(DatabaseWrapper database);
@Override
public void onPostMigrate() {
}
} |
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. .. spec_helper]))
describe '/hosts/show' do
before :each do
assigns[:host] = @host = Host.generate!(:description => 'Test Host')
end
def do_render
render '/hosts/show'
end
it 'should display the name of the host' do
do_render
response.should have_text(Regexp.new(@host.name))
end
it 'should display the description of the host' do
do_render
response.should have_text(Regexp.new(@host.description))
end
it 'should include a link to edit the host' do
do_render
response.should have_tag('a[href=?]', edit_host_path(@host))
end
it 'should include a link to delete the host if it is safe to delete the host' do
@host.stubs(:safe_to_delete?).returns(true)
do_render
response.should have_tag('a[href=?]', host_path(@host), :text => /[Dd]elete/)
end
it 'should not include a link to delete the host if it is not safe to delete the host' do
@host.stubs(:safe_to_delete?).returns(false)
do_render
response.should_not have_tag('a[href=?]', host_path(@host), :text => /[Dd]elete/)
end
it "should include a link to the host's puppet manifest" do
do_render
response.should have_tag('a[href=?]', url_for(:controller => 'hosts', :action => 'configuration', :name => @host.name, :format => 'pp'))
end
it "should include a link to a JSON version of the host's configuration" do
do_render
response.should have_tag('a[href=?]', url_for(:controller => 'hosts', :action => 'configuration', :name => @host.name, :format => 'json'))
end
it "should include a link to a YAML version of the host's configuration" do
do_render
response.should have_tag('a[href=?]', url_for(:controller => 'hosts', :action => 'configuration', :name => @host.name, :format => 'yaml'))
end
it 'should list the apps the host has deployed' do
deployed_services = Array.new(3) { DeployedService.generate!(:host => @host) }
do_render
@host.apps.each do |app|
response.should have_text(Regexp.new(app.name))
end
end
end |
"""
The controller base class
"""
from .routes import Route
from .view import View
class Controller(object):
def __init__(self, entity, env):
"""Instantiate a controller with the name of the entity and the
environment dict.
"""
self.entity = entity.strip('/^$')
if not self.entity:
self.entity = 'index'
self.routes = []
self.register_routes()
self.env = env
def register_routes(self):
"""Simple internal method to run through all of the methods of this class
and see if they've been decorated to be endpoints.
"""
for funcname in dir(self):
func = getattr(self, funcname)
if hasattr(func, '_method') and hasattr(func, '_path'):
self.update_routes(func._method, func._path, func)
def update_routes(self, method, matcher, endpoint):
"""Adds an endpoint into the possible endpoints of a path based on
its HTTP method
"""
for route in self.routes:
if route.key == matcher:
route.update(method, endpoint)
return
# If the route has not been added to the routes yet
self.routes.append(Route(method, matcher, endpoint))
def route(self, env):
"""Called by the application to route the requests to the proper endpoint
in this controller.
"""
for route in self.routes:
if self.entity == 'index':
path = '/' + '/'.join(env['PATH_INFO'].split('/')[1:])
else:
path = '/' + '/'.join(env['PATH_INFO'].split('/')[2:])
if route.match(path):
ans = route.call(env['REQUEST_METHOD'], env['PATH_INFO'], env)
if ans[1] == 'no_template':
return ans[0]
if '/' in ans[0]:
view = View(ans[0].split('/')[0])
return view.render(ans[0], ans[1])
else:
view = View(self.entity)
return view.render(ans[0], ans[1]) |
'use strict';
module.exports = function(grunt) {
// HELPERS
// Get a config property. Most useful as a directive like <config:foo.bar>.
grunt.registerHelper('config', grunt.config);
// Get a config property and process it as a template.
grunt.registerHelper('config_process', grunt.config.process);
// Read a JSON file. Most useful as a directive like <json:package.json>.
var jsons = {};
grunt.registerHelper('json', function(filepath) {
// Don't re-fetch if being called as a directive and JSON is already cached.
if (!this.directive || !(filepath in jsons)) {
jsons[filepath] = grunt.file.readJSON(filepath);
}
return jsons[filepath];
});
// Return the given source coude with any leading banner comment stripped.
grunt.registerHelper('strip_banner', function(src, options) {
if (!options) { options = {}; }
var m = [];
if (options.line) {
// Strip // ... leading banners.
m.push('(?:.*\\/\\/.*\\n)*\\s*');
}
if (options.block) {
// Strips all block comment banners.
m.push('\\/\\*[\\s\\S]*?\\*\\/');
} else {
// Strips only block comment banners, excluding .
m.push('\\/\\*[^!][\\s\\S]*?\\*\\/');
}
var re = new RegExp('^\\s*(?:' + m.join('|') + ')\\s*', '');
return src.replace(re, '');
});
// Get a source file's contents with any leading banner comment stripped. If
// used as a directive, get options from the flags object.
grunt.registerHelper('file_strip_banner', function(filepath, options) {
if (this.directive) { options = this.flags; }
var src = grunt.file.read(filepath);
return grunt.helper('strip_banner', src, options);
});
// Process a file as a template.
grunt.registerHelper('file_template', function(filepath) {
var src = grunt.file.read(filepath);
return grunt.template.process(src);
});
// Generate banner from template. This helper is deprecated.
var bannerWarned;
grunt.registerHelper('banner', function(prop) {
if (!bannerWarned) {
bannerWarned = true;
grunt.log.errorlns('Note that the "banner" helper and directive have ' +
'been deprecated. Please use the more general "config_process" ' +
'helper and/or directive (which does NOT automatically add a ' +
'trailing newline!) instead. (grunt 0.4.0+)');
// This warning shouldn't cause tasks that look at this.errorCount to fail.
// TODO: come up with a better way to do non-error warnings.
grunt.fail.errorcount
}
if (!prop) { prop = 'meta.banner'; }
var banner;
var tmpl = grunt.config(prop);
if (tmpl) {
// Now, log.
grunt.verbose.write('Generating banner...');
try {
// Compile and run template, using config object as the data source.
banner = grunt.template.process(tmpl) + grunt.util.linefeed;
grunt.verbose.ok();
} catch(e) {
banner = '';
grunt.verbose.error();
grunt.warn(e, 11);
}
} else {
grunt.warn('No "' + prop + '" banner template defined.', 11);
banner = '';
}
return banner;
});
}; |
using System;
using System.Reflection;
using Abp.Dependency;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.Orm;
using Abp.Reflection.Extensions;
namespace Abp.EntityFramework
{
public abstract class <API key> : <API key>
{
private readonly <API key> <API key>;
private readonly Type _dbContextType;
protected <API key>(Type dbContextType, <API key> <API key>)
{
_dbContextType = dbContextType;
<API key> = <API key>;
}
public abstract string OrmContextKey { get; }
public virtual void <API key>(IIocManager iocManager, <API key> <API key>)
{
<API key> autoRepositoryAttr = _dbContextType.GetTypeInfo().<API key><<API key>>()
?? <API key>;
foreach (EntityTypeInfo entityTypeInfo in <API key>.GetEntityTypeInfos(_dbContextType))
{
Type primaryKeyType = EntityHelper.GetPrimaryKeyType(entityTypeInfo.EntityType);
if (primaryKeyType == typeof(int))
{
Type <API key> = autoRepositoryAttr.RepositoryInterface.MakeGenericType(entityTypeInfo.EntityType);
if (!iocManager.IsRegistered(<API key>))
{
Type implType = autoRepositoryAttr.<API key>.GetTypeInfo().GetGenericArguments().Length == 1
? autoRepositoryAttr.<API key>.MakeGenericType(entityTypeInfo.EntityType)
: autoRepositoryAttr.<API key>.MakeGenericType(entityTypeInfo.DeclaringType, entityTypeInfo.EntityType);
iocManager.Register(
<API key>,
implType,
DependencyLifeStyle.Transient
);
}
}
Type <API key> = autoRepositoryAttr.<API key>.MakeGenericType(entityTypeInfo.EntityType, primaryKeyType);
if (!iocManager.IsRegistered(<API key>))
{
Type implType = autoRepositoryAttr.<API key>.GetTypeInfo().GetGenericArguments().Length == 2
? autoRepositoryAttr.<API key>.MakeGenericType(entityTypeInfo.EntityType, primaryKeyType)
: autoRepositoryAttr.<API key>.MakeGenericType(entityTypeInfo.DeclaringType, entityTypeInfo.EntityType, primaryKeyType);
iocManager.Register(
<API key>,
implType,
DependencyLifeStyle.Transient
);
}
}
}
}
} |
jui.defineUI("ui.progress", [ "jquery", "util.base" ], function($, _) {
/**
* @class ui.slider
* @extends core
* @alias Slider
* @requires jquery
* @requires util.base
*/
var UI = function() {
var self, $root, $area, $bar;
function min() {
return self.options.min;
}
function max() {
return self.options.max;
}
function orient() {
return self.options.orient;
}
function type() {
return self.options.type;
}
function animated() {
return self.options.animated;
}
function striped() {
return self.options.striped;
}
function value() {
return self.options.value;
}
function setBarSize(percent) {
if (orient() == "vertical") {
$bar.height(percent + "%");
} else {
$bar.width(percent + "%");
}
}
function getBarSize() {
var percent;
if (orient() == "vertical") {
percent = $bar.css("height");
} else {
percent = $bar.css("width");
}
return percent;
}
function initElement() {
$root.addClass(orient()).addClass(type());
$area = $root.find(".area");
$bar = $root.find(".bar");
if($area.size() == 0) {
$area = $("<div class='area' />");
$root.html($area);
}
if($bar.size() == 0) {
$bar = $("<div class='bar' />");
$area.html($bar);
}
self.setValue();
self.setStriped();
self.setAnimated();
}
this.init = function () {
self = this;
$root = $(this.root);
initElement();
}
this.setAnimated = function(isAnimated) {
if (typeof isAnimated == "undefined") {
$bar.toggleClass("animated", animated());
} else {
$bar.toggleClass("animated", isAnimated);
}
}
this.setStriped = function(isStriped) {
if (typeof isStriped == "undefined") {
$bar.toggleClass("striped", striped());
} else {
$bar.toggleClass("striped", isStriped);
}
}
this.setValue = function(v) {
var v = (typeof v == "undefined") ? value() : v,
percent = (v - min()) / (max() - min()) * 100;
setBarSize(percent);
}
this.getValue = function() {
return min() + (max() - min()) * (parseFloat(getBarSize().replace("%", "")) / 100);
}
}
UI.setup = function() {
return {
type: "", // simple or flat
orient : "horizontal", // or vertical,
min : 0,
max : 100,
value : 0,
striped : false, // or true
animated : false // or true
}
};
/**
* @event change
* Event that occurs when dragging on a slider
*
* @param {Object} data Data of current from
* @param {jQueryEvent} e The event object
*/
return UI;
}); |
require 'spec_helper'
describe Dandelion::Config do
let(:yaml) do
<<-YAML
foo: bar
baz: <%= ENV['BAZ'] %>
YAML
end
before(:each) do
ENV['BAZ'] = 'qux'
expect(IO).to receive(:read).with('foo').and_return(yaml)
end
let(:config) { Dandelion::Config.new(path: 'foo') }
it 'parses YAML' do
expect(config[:foo]).to eq 'bar'
end
it 'parses ERB' do
expect(config[:baz]).to eq 'qux'
end
end |
# Generic module deployment.
# ASSUMPTIONS:
# * folder structure either like:
# - RepoFolder
# - This PSDeploy file
# - ModuleName
# - ModuleName.psd1
# OR the less preferable:
# - RepoFolder
# - RepoFolder.psd1
# * Nuget key in $ENV:NugetApiKey
# * <API key> from BuildHelpers module has populated ENV:BHModulePath and related variables
# Publish to gallery with a few restrictions
if(
$env:BHModulePath -and
$env:BHBuildSystem -ne 'Unknown' -and
$env:BHBranchName -eq "master" -and
$env:BHCommitMessage -match '!deploy'
)
{
Deploy Module {
By PSGalleryModule {
FromSource $ENV:BHModulePath
To PSGallery
WithOptions @{
ApiKey = $ENV:NugetApiKey
}
}
}
}
else
{
"Skipping deployment: To deploy, ensure that...`n" +
"`t* You are in a known build system (Current: $ENV:BHBuildSystem)`n" +
"`t* You are committing to the master branch (Current: $ENV:BHBranchName) `n" +
"`t* Your commit message includes !deploy (Current: $ENV:BHCommitMessage)" |
Write-Host
}
# Publish to AppVeyor if we're in AppVeyor
if(
$env:BHModulePath -and
$env:BHBuildSystem -eq 'AppVeyor'
)
{
Deploy DeveloperBuild {
By AppVeyorModule {
FromSource $ENV:BHModulePath
To AppVeyor
WithOptions @{
Version = $env:<API key>
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.