text
stringlengths 5
1.04M
|
|---|
#include <stan/math/prim/scal.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
#include <limits>
TEST(MathFunctions, modified_bessel_second_kind) {
using stan::math::modified_bessel_second_kind;
EXPECT_FLOAT_EQ(0.011159676085853024269745195979833489225,
modified_bessel_second_kind(0, 4.0));
EXPECT_THROW(modified_bessel_second_kind(1, -3.0), std::domain_error);
EXPECT_THROW(modified_bessel_second_kind(-1, -3.0), std::domain_error);
}
TEST(MathFunctions, modified_bessel_second_kind_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::modified_bessel_second_kind(0, nan));
}
|
///////////////////////////////////////////////////////////////////////////////
//
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
//
///////////////////////////////////////////////////////////////////////////////
// constructing queues
#include <deque>
#include <list>
#include <queue>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "msgdef.h"
#include "props.h"
#include "localio.h"
#include "clio.h"
#include "sqevlog/evl_sqlog_writer.h"
#include "clusterconf.h"
#include "seabed/trace.h"
long trace_settings = 0;
#define MAX_SYNCS 10
#define MAX_TEST_NODES 6
#define SYNC_DELAY 150000 // delay (150 ms)
char MyPort[MPI_MAX_PORT_NAME];
char *MyName;
int MyRank = -1;
int MyPNid = -1;
int MyNid = -1;
int MyPid = -1;
int NumNodes = 0;
int gv_ms_su_nid = -1; // Local IO nid to make compatible w/ Seabed
SB_Verif_Type gv_ms_su_verif = -1;
char ga_ms_su_c_port[MPI_MAX_PORT_NAME] = {0}; // connect
MPI_Comm Monitor;
int trans_count = 0;
int trans_starts = 0;
int trans_abort = 0;
int trans_commit = 0;
int event_id = -1;
int trans_active = 0;
bool node_down = false;
int dead_tm_count = 0;
int down_node_count = 0;
int up_node_count = 0;
bool node_up[MAX_TEST_NODES] = {true,true,true,true,true,true};
bool IamTmLeader = false;
bool TmLeaderDied = false;
struct tm_process_def {
bool dead;
bool leader;
int pid;
char process_name[MAX_PROCESS_NAME]; // TM process's Name
char program[MAX_PROCESS_PATH];
} tmProcess[MAX_TEST_NODES];
bool Abort_transaction = false;
bool EventMsgRecv = false;
bool UnsolMsgRecv = false;
bool NoticeMsgRecv = false;
bool Test_Initialized = false;
bool TestWait = false;
bool TestShutdown = false;
int seq_number = 0;
int VirtualNodes = 0;
struct req_def {
int handle;
bool completed;
bool aborted;
} request[MAX_TEST_NODES][MAX_SYNCS];
pthread_mutex_t notice_mutex;
pthread_cond_t notice_cv;
bool notice_signaled = false;
pthread_mutex_t test_mutex;
pthread_cond_t test_cv;
bool test_signaled = false;
pthread_mutex_t unsolicited_mutex;
pthread_cond_t unsolicited_cv;
bool unsolicited_signaled = false;
struct sync_buf_def
{
int seq_number;
int length;
char string[132];
} __attribute__((__may_alias__));
queue<struct message_def> unsolicited_queue; // unsolicited msg queue
void flush_incoming_msgs( void );
FILE *shell_locio_trace_file = NULL;
int mon_log_write(int pv_event_type, posix_sqlog_severity_t pv_severity, char *pp_string)
{
pv_event_type = pv_event_type;
pv_severity = pv_severity;
int lv_err = 0;
trace_printf("%s", pp_string );
return lv_err;
}
void shell_locio_trace(const char *where, const char *format, va_list ap)
{
if (shell_locio_trace_file != NULL)
{
int ms;
int us;
struct timeval t;
struct tm tx;
char buf[BUFSIZ];
gettimeofday(&t, NULL);
localtime_r(&t.tv_sec, &tx);
ms = (int) t.tv_usec / 1000;
us = (int) t.tv_usec - ms * 1000;
sprintf(buf, "%02d:%02d:%02d.%03d.%03d %s: (%lx)",
tx.tm_hour, tx.tm_min, tx.tm_sec, ms, us, where,
pthread_self());
vsprintf(&buf[strlen(buf)], format, ap);
fprintf(shell_locio_trace_file, buf);
fflush(shell_locio_trace_file);
}
}
char *ErrorMsg (int error_code)
{
int rc;
int length;
static char buffer[MPI_MAX_ERROR_STRING];
rc = MPI_Error_string (error_code, buffer, &length);
if (rc != MPI_SUCCESS)
{
sprintf(buffer,"MPI_Error_string: Invalid error code (%d)\n", error_code);
length = strlen(buffer);
}
buffer[length] = '\0';
return buffer;
}
void lock_notice()
{
int rc = pthread_mutex_lock(¬ice_mutex);
if (rc != 0)
{
trace_printf("[%s] - Unable to lock notice mutex: %s (%d)\n",
MyName, strerror(errno), errno);
}
}
void unlock_notice()
{
int rc = pthread_mutex_unlock(¬ice_mutex);
if (rc != 0)
{
trace_printf("[%s] - Unable to unlock notice mutex: %s (%d)\n",
MyName, strerror(errno), errno);
}
}
int signal_notice()
{
int rc = 0;
notice_signaled = true;
rc = pthread_cond_broadcast(¬ice_cv);
if ( rc != 0)
{
errno = rc;
trace_printf("[%s] - Unable to signal notice: %s (%d)\n",
MyName, strerror(errno), errno);
rc = -1;
}
return( rc );
}
int wait_on_notice( void )
{
int rc = 0;
if ( ! notice_signaled )
{
rc = pthread_cond_wait(¬ice_cv, ¬ice_mutex);
if ( rc != 0)
{
errno = rc;
trace_printf("[%s] - Unable to signal notice: %s (%d)\n",
MyName, strerror(errno), errno);
rc = -1;
}
}
notice_signaled = false;
return( rc );
}
void lock_test()
{
int rc = pthread_mutex_lock(&test_mutex);
if (rc != 0)
{
trace_printf("[%s] - Unable to lock test mutex: %s (%d)\n",
MyName, strerror(errno), errno);
}
}
void unlock_test()
{
int rc = pthread_mutex_unlock(&test_mutex);
if (rc != 0)
{
trace_printf("[%s] - Unable to unlock test mutex: %s (%d)\n",
MyName, strerror(errno), errno);
}
}
int signal_test()
{
int rc = 0;
test_signaled = true;
rc = pthread_cond_broadcast(&test_cv);
if ( rc != 0)
{
errno = rc;
trace_printf("[%s] - Unable to signal test: %s (%d)\n",
MyName, strerror(errno), errno);
rc = -1;
}
return( rc );
}
int wait_on_test( void )
{
int rc = 0;
if ( ! test_signaled )
{
rc = pthread_cond_wait(&test_cv, &test_mutex);
if ( rc != 0)
{
errno = rc;
trace_printf("[%s] - Unable to signal test: %s (%d)\n",
MyName, strerror(errno), errno);
rc = -1;
}
}
test_signaled = false;
return( rc );
}
void lock_unsolicited()
{
int rc = pthread_mutex_lock(&unsolicited_mutex);
if (rc != 0)
{
trace_printf("[%s] - Unable to lock unsolicited mutex: %s (%d)\n",
MyName, strerror(errno), errno);
}
}
void unlock_unsolicited()
{
int rc = pthread_mutex_unlock(&unsolicited_mutex);
if (rc != 0)
{
trace_printf("[%s] - Unable to unlock unsolicited mutex: %s (%d)\n",
MyName, strerror(errno), errno);
}
}
int signal_unsolicited()
{
int rc = 0;
unsolicited_signaled = true;
rc = pthread_cond_broadcast(&unsolicited_cv);
if ( rc != 0)
{
errno = rc;
trace_printf("[%s] - Unable to signal unsolicited: %s (%d)\n",
MyName, strerror(errno), errno);
rc = -1;
}
return( rc );
}
int wait_on_unsolicited( void )
{
int rc = 0;
if ( ! unsolicited_signaled )
{
rc = pthread_cond_wait(&unsolicited_cv, &unsolicited_mutex);
if ( rc != 0)
{
errno = rc;
trace_printf("[%s] - Unable to signal unsolicited: %s (%d)\n",
MyName, strerror(errno), errno);
rc = -1;
}
}
unsolicited_signaled = false;
return( rc );
}
int completed_request(int nid, int handle, bool abort)
{
int j;
trace_printf("[%s] - Completing request: node=%d, handle=%d, abort=%d\n", MyName, nid, handle, abort);
for(j=0; j<MAX_SYNCS; j++)
{
//printf("[%s] - Complete request: node=%d, index=%d, handle=%d, completed=%d\n", MyName, nid, j, request[nid][j].handle, request[nid][j].completed);
if ( request[nid][j].handle == handle )
{
request[nid][j].completed = true;
request[nid][j].aborted = abort;
//printf("[%s] - Completed request: node=%d, index=%d, handle=%d, completed=%d\n", MyName, nid, j, request[nid][j].handle, request[nid][j].completed);
return j;
}
}
trace_printf("[%s] - Can't find TmSync handle=%d\n", MyName, handle);
return -1;
}
bool completed_test( void )
{
int nid;
int j;
bool done = true;
lock_test();
for( nid=0; nid<MAX_TEST_NODES; nid++)
{
for(j=0; j<MAX_SYNCS; j++)
{
if ( node_up[nid] )
{
//printf("[%s] - Complete test: node=%d, handle=%d, completed=%d\n", MyName, nid, request[nid][j].handle, request[nid][j].completed);
if (( request[nid][j].handle == -1 ) ||
( !request[nid][j].completed ) )
{
trace_printf("[%s] - Test not completed @ node=%d, handle index=%d\n",MyName,nid,j);
done = false;
}
}
}
}
unlock_test();
Test_Initialized = done ? false : true;
return( done );
}
void end_requests( int nid )
{
int j;
trace_printf( "[%s] - Ending requests for: node=%d\n", MyName, nid );
for(j=0; j<MAX_SYNCS; j++)
{
request[nid][j].completed = true;
request[nid][j].aborted = true;
}
}
int GetNumOfNode( void )
{
int count;
MPI_Status status;
struct message_def *msg;
gp_local_mon_io->acquire_msg( &msg );
msg->type = MsgType_Service;
msg->noreply = false;
msg->reply_tag = REPLY_TAG;
msg->u.request.type = ReqType_NodeInfo;
msg->u.request.u.node_info.nid = MyNid;
msg->u.request.u.node_info.pid = MyPid;
msg->u.request.u.node_info.target_nid = -1;
gp_local_mon_io->send_recv( msg );
count = sizeof (*msg);
status.MPI_TAG = msg->reply_tag;
if ((status.MPI_TAG == REPLY_TAG) &&
(count == sizeof (struct message_def)))
{
if ((msg->type == MsgType_Service) &&
(msg->u.reply.type == ReplyType_NodeInfo))
{
if ((msg->u.reply.u.node_info.return_code == MPI_SUCCESS ) ||
(msg->u.reply.u.node_info.return_code == MPI_ERR_TRUNCATE) )
{
if (msg->u.reply.u.node_info.num_returned)
{
printf ("[%s] NodeInfo, num_nodes=%d\n", MyName,
msg->u.reply.u.node_info.num_nodes);
int nodeCount = msg->u.reply.u.node_info.num_nodes;
gp_local_mon_io->release_msg(msg);
return nodeCount;
}
}
else
{
trace_printf ("[%s] NodeInfo failed, error=%s\n", MyName,
ErrorMsg(msg->u.reply.u.node_info.return_code));
}
}
else
{
trace_printf
("[%s] Invalid MsgType(%d)/ReplyType(%d) for NodeInfo message\n",
MyName, msg->type, msg->u.reply.type);
}
}
else
{
trace_printf ("[%s] NodeInfo reply message invalid\n", MyName);
}
gp_local_mon_io->release_msg(msg);
msg = NULL;
return 0;
}
int get_tm_processes( int tmCount )
{
int count;
MPI_Status status;
struct message_def *msg;
gp_local_mon_io->acquire_msg( &msg );
msg->type = MsgType_Service;
msg->noreply = false;
msg->reply_tag = REPLY_TAG;
msg->u.request.type = ReqType_ProcessInfo;
msg->u.request.u.process_info.nid = MyNid;
msg->u.request.u.process_info.pid = MyPid;
msg->u.request.u.process_info.verifier = -1;
msg->u.request.u.process_info.process_name[0] = 0;
msg->u.request.u.process_info.target_nid = -1;
msg->u.request.u.process_info.target_pid = -1;
msg->u.request.u.process_info.target_verifier = -1;
msg->u.request.u.process_info.type = ProcessType_DTM;
msg->u.request.u.process_info.target_process_name[0] = 0;
gp_local_mon_io->send_recv( msg );
count = sizeof (*msg);
status.MPI_TAG = msg->reply_tag;
if ((status.MPI_TAG == REPLY_TAG) &&
(count == sizeof (struct message_def)))
{
if ((msg->type == MsgType_Service) &&
(msg->u.reply.type == ReplyType_ProcessInfo))
{
if (msg->u.reply.u.process_info.return_code == MPI_SUCCESS)
{
if ( msg->u.reply.u.process_info.num_processes == tmCount )
{
for ( int i = 0; i < msg->u.reply.u.process_info.num_processes; i++ )
{
int nid = msg->u.reply.u.process_info.process[i].nid;
trace_printf ( "[%s] TM ProcessInfo: nid=%d, pid=%d, Name=%s, program=%s\n", MyName
, msg->u.reply.u.process_info.process[i].nid
, msg->u.reply.u.process_info.process[i].pid
, msg->u.reply.u.process_info.process[i].process_name
, msg->u.reply.u.process_info.process[i].program );
tmProcess[nid].dead = msg->u.reply.u.process_info.process[i].state == State_Up ? false : true;
tmProcess[nid].pid = msg->u.reply.u.process_info.process[i].pid;
strcpy (tmProcess[nid].process_name, msg->u.reply.u.process_info.process[i].process_name );
strcpy (tmProcess[nid].program, msg->u.reply.u.process_info.process[i].program );
}
}
else
{
trace_printf( "[%s] TM ProcessInfo failed, invalid number of TM processes, count=%d\n", MyName
, msg->u.reply.u.process_info.num_processes);
return 1;
}
}
else
{
trace_printf ("[%s] TM ProcessInfo failed, error=%s\n", MyName,
ErrorMsg(msg->u.reply.u.process_info.return_code));
return 1;
}
}
else
{
trace_printf("[%s] Invalid MsgType(%d)/ReplyType(%d) for TM ProcessInfo message\n",
MyName, msg->type, msg->u.reply.type);
return 1;
}
}
else
{
trace_printf ("[%s] TM ProcessInfo reply message invalid\n", MyName);
return 1;
}
gp_local_mon_io->release_msg(msg);
msg = NULL;
return 0;
}
int start_tm_process( int nid )
{
int count;
int rc = -1;
char outfile[MAX_PROCESS_PATH];
MPI_Status status;
struct message_def *msg;
trace_printf ("[%s] starting process %s.\n", MyName, tmProcess[nid].process_name);
fflush (stdout);
gp_local_mon_io->acquire_msg( &msg );
msg->type = MsgType_Service;
msg->noreply = false;
msg->reply_tag = REPLY_TAG;
msg->u.request.type = ReqType_NewProcess;
msg->u.request.u.new_process.nid = nid;
msg->u.request.u.new_process.type = ProcessType_DTM;
msg->u.request.u.new_process.debug = 0;
msg->u.request.u.new_process.priority = 0;
msg->u.request.u.new_process.backup = 0;
msg->u.request.u.new_process.unhooked = true;
msg->u.request.u.new_process.nowait = false;
msg->u.request.u.new_process.tag = 0;
strcpy( msg->u.request.u.new_process.process_name, tmProcess[nid].process_name );
strcpy( msg->u.request.u.new_process.path, getenv ("PATH") );
strcpy( msg->u.request.u.new_process.ldpath, getenv ("LD_LIBRARY_PATH") );
strcpy( msg->u.request.u.new_process.program, tmProcess[nid].program );
msg->u.request.u.new_process.infile[0] = '\0';
sprintf( outfile, "TM0%d.lst", nid );
strcpy( msg->u.request.u.new_process.outfile, outfile );
msg->u.request.u.new_process.argc = 0;
msg->u.request.u.new_process.argv[0][0] = '\0';
gp_local_mon_io->send_recv( msg );
count = sizeof (*msg);
status.MPI_TAG = msg->reply_tag;
if ((status.MPI_TAG == REPLY_TAG) &&
(count == sizeof (struct message_def)))
{
if ((msg->type == MsgType_Service) &&
(msg->u.reply.type == ReplyType_NewProcess))
{
if (msg->u.reply.u.new_process.return_code == MPI_SUCCESS)
{
tmProcess[msg->u.reply.u.new_process.nid].dead = false;
dead_tm_count--;
trace_printf
("[%s] started process successfully. Dead TM count =%d, Nid=%d, Pid=%d, Process_name=%s, rtn=%d\n",
MyName, dead_tm_count, msg->u.reply.u.new_process.nid,
msg->u.reply.u.new_process.pid,
msg->u.reply.u.new_process.process_name,
msg->u.reply.u.new_process.return_code);
rc = 0;
}
else
{
trace_printf ("[%s] new process failed to spawn, rc=%d\n", MyName,
msg->u.reply.u.new_process.return_code);
}
}
else
{
trace_printf
("[%s] Invalid MsgType(%d)/ReplyType(%d) for NewProcess message\n",
MyName, msg->type, msg->u.reply.type);
}
}
else
{
trace_printf ("[%s] new process reply message invalid\n", MyName);
}
fflush (stdout);
gp_local_mon_io->release_msg(msg);
return( rc );
}
int restart_all_dead_tm( void )
{
for ( int nid = 0; nid < MAX_TEST_NODES; nid++ )
{
if ( tmProcess[nid].dead )
{
if ( start_tm_process( nid ) )
{
return( -1 );
}
}
}
return( 0 );
}
void initialize_test( void )
{
int nid;
int j;
trace_printf ("[%s] Initializing for test\n",MyName);
memset( tmProcess, 0, sizeof(tmProcess) );
for( nid=0; nid<MAX_TEST_NODES; nid++)
{
for(j=0; j<MAX_SYNCS; j++)
{
request[nid][j].handle = -1;
request[nid][j].completed = false;
request[nid][j].aborted = false;
}
}
trans_count = 0;
trans_starts = 0;
trans_abort = 0;
trans_commit = 0;
trans_active=0;
dead_tm_count = 0;
Test_Initialized = true;
}
void process_startup (int argc, char *argv[])
{
int i;
struct message_def *msg;
trace_printf ("[%s] processing startup.\n", argv[5]);
fflush (stdout);
trace_printf ("[%s] - argc=%d", argv[5], argc);
for(i=0; i<argc; i++)
{
trace_printf (", argv[%d]=%s",i,argv[i]);
}
trace_printf ("\n");
fflush(stdout);
strcpy (MyName, argv[5]);
MPI_Open_port (MPI_INFO_NULL, MyPort);
#ifdef OFED_MUTEX
// free monitor.sem semaphore
trace_printf ("[%s] Opening mutex\n",MyName);
fflush(stdout);
char sem_name[MAX_PROCESS_PATH];
sprintf(sem_name,"/monitor.sem2.%s",getenv("USER"));
sem_t *mutex = sem_open(sem_name,0,0644,0);
if(mutex == SEM_FAILED)
{
trace_printf ("[%s] Can't access %s semaphore\n", MyName, sem_name);
sem_close(mutex);
abort();
}
trace_printf ("[%s] Putting mutex\n",MyName);
fflush(stdout);
sem_post(mutex);
sem_close(mutex);
#endif
MyNid = atoi(argv[3]);
MyPid = atoi(argv[4]);
gv_ms_su_verif = atoi(argv[9]);
trace_printf ("[%s] process_startup, MyNid: %d, lio: %p\n",
MyName, MyNid, (void *)gp_local_mon_io );
gp_local_mon_io->iv_pid = MyPid;
gp_local_mon_io->init_comm();
if (argc < 10)
{
printf
("Error: Invalid startup arguments, argc=%d, argv[0]=%s, argv[1]=%s, argv[2]=%s, argv[3]=%s, argv[4]=%s, argv[5]=%s, argv[6]=%s, argv[7]=%s, argv[8]=%s, argv[9]=%s\n",
argc, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9]);
exit (1);
}
else
{
gp_local_mon_io->acquire_msg( &msg );
msg->type = MsgType_Service;
msg->noreply = true;
msg->u.request.type = ReqType_Startup;
msg->u.request.u.startup.nid = MyNid;
msg->u.request.u.startup.pid = MyPid;
msg->u.request.u.startup.paired = false;
strcpy (msg->u.request.u.startup.process_name, argv[5]);
strcpy (msg->u.request.u.startup.port_name, MyPort);
msg->u.request.u.startup.os_pid = getpid ();
msg->u.request.u.startup.event_messages = true;
msg->u.request.u.startup.system_messages = true;
msg->u.request.u.startup.verifier = gv_ms_su_verif;
msg->u.request.u.startup.startup_size = sizeof(msg->u.request.u.startup);
trace_printf ("[%s] sending startup reply to monitor.\n", argv[5]);
fflush (stdout);
gp_local_mon_io->send( msg );
trace_printf ("[%s] Startup completed", argv[5]);
if (argc > 9)
{
for (i = 10; i < argc; i++)
{
trace_printf (", argv[%d]=%s", i, argv[i]);
}
}
trace_printf ("\n");
fflush (stdout);
msg = NULL;
}
}
void flush_incoming_msgs( void )
{
int count;
int complete = 0;
bool done = false;
MPI_Status status;
struct message_def *msg = NULL;
trace_printf ("[%s] flush incoming event & notices.\n", MyName);
fflush (stdout);
do
{
gp_local_mon_io->get_notice( &msg );
if (msg)
{
trace_printf("[%s] Got local IO notice\n",MyName);
complete = true;
count = sizeof( *msg );
status.MPI_TAG = msg->reply_tag;
}
else
{
trace_printf("[%s] No local IO notice\n",MyName);
complete = false;
done = true;
}
if (complete)
{
MPI_Get_count (&status, MPI_CHAR, &count);
if (((status.MPI_TAG == NOTICE_TAG) ||
(status.MPI_TAG == EVENT_TAG ) ) &&
(count == sizeof (struct message_def)) )
{
if (msg->u.request.type == ReqType_Notice)
{
switch (msg->type)
{
case MsgType_ProcessDeath:
if ( msg->u.request.u.death.aborted )
{
trace_printf ("[%s] Process %s abnormally terminated. Nid=%d, Pid=%d\n",
MyName, msg->u.request.u.death.process_name,
msg->u.request.u.death.nid, msg->u.request.u.death.pid);
}
else
{
trace_printf ("[%s] Process %s terminated normally. Nid=%d, Pid=%d\n",
MyName, msg->u.request.u.death.process_name,
msg->u.request.u.death.nid, msg->u.request.u.death.pid);
}
break;
case MsgType_NodeDown:
trace_printf ("[%s] Node %d (%s) is DOWN\n",
MyName, msg->u.request.u.down.nid, msg->u.request.u.down.node_name );
break;
case MsgType_NodeUp:
trace_printf ("[%s] Node %d (%s) is UP\n",
MyName, msg->u.request.u.up.nid, msg->u.request.u.up.node_name);
break;
case MsgType_Change:
trace_printf ("[%s] Configuration Change Notice for Group: %s Key: %s\n",
MyName,
msg->u.request.u.change.group,
msg->u.request.u.change.key);
break;
case MsgType_Open:
case MsgType_Close:
trace_printf ("[%s] Open/Close process notification\n", MyName);
break;
case MsgType_Event:
trace_printf("[%s] Event %d received\n",
MyName, msg->u.request.u.event_notice.event_id);
break;
case MsgType_Shutdown:
TestShutdown = true;
trace_printf("[%s] Shutdown notice, level=%d received\n",
MyName, msg->u.request.u.shutdown.level);
break;
default:
trace_printf("[%s] Invalid Notice Type(%d) for flush message\n",
MyName, msg->type);
}
}
else
{
trace_printf("[%s] Invalid Event received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
}
else
{
trace_printf ("[%s] Failed to flush messages\n", MyName);
done = true;
}
fflush (stdout);
}
if (msg) delete msg;
msg = NULL;
}
while (!done);
}
void exit_process (void)
{
int count;
MPI_Status status;
struct message_def *msg;
trace_printf ("[%s] sending exit process message.\n", MyName);
fflush (stdout);
gp_local_mon_io->acquire_msg( &msg );
msg->type = MsgType_Service;
msg->noreply = false;
msg->reply_tag = REPLY_TAG;
msg->u.request.type = ReqType_Exit;
msg->u.request.u.exit.nid = MyNid;
msg->u.request.u.exit.pid = MyPid;
gp_local_mon_io->send_recv( msg );
count = sizeof (*msg);
status.MPI_TAG = msg->reply_tag;
if ((status.MPI_TAG == REPLY_TAG) &&
(count == sizeof (struct message_def)))
{
if ((msg->type == MsgType_Service) &&
(msg->u.reply.type == ReplyType_Generic))
{
if (msg->u.reply.u.generic.return_code == MPI_SUCCESS)
{
trace_printf ("[%s] exited process successfully. rc=%d\n",
MyName, msg->u.reply.u.generic.return_code);
}
else
{
trace_printf ("[%s] exit process failed, rc=%d\n", MyName,
msg->u.reply.u.generic.return_code);
}
flush_incoming_msgs();
MPI_Comm_disconnect( &Monitor );
}
else
{
trace_printf
("[%s] Invalid MsgType(%d)/ReplyType(%d) for Exit message\n",
MyName, msg->type, msg->u.reply.type);
}
}
else
{
trace_printf ("[%s] exit process reply invalid.\n", MyName);
}
fflush (stdout);
gp_local_mon_io->release_msg(msg);
msg = NULL;
}
void process_unsolicited_msg( struct message_def *msg )
{
int rc;
int handle;
struct message_def *reply;
struct sync_buf_def *buf;
gp_local_mon_io->acquire_msg( &reply );
trace_printf ("[%s] Processing unsolicited tm_sync message.\n", MyName);
if( msg->u.request.type == ReqType_TmSync )
{
if( msg->type == MsgType_UnsolicitedMessage )
{
handle = msg->u.request.u.unsolicited_tm_sync.handle;
buf = (struct sync_buf_def*)msg->u.request.u.unsolicited_tm_sync.data;
request[msg->u.request.u.unsolicited_tm_sync.nid][buf->seq_number].handle = handle;
trace_printf("[%s] TmSync Unsolicited Message - nid=%d pid=%d handle=%d data='seq#=%d, len=%d string=%s'\n", MyName,
msg->u.request.u.unsolicited_tm_sync.nid,
msg->u.request.u.unsolicited_tm_sync.pid,
handle,
buf->seq_number,
buf->length,
buf->string);
seq_number = buf->seq_number;
trans_count++;
trans_active++;
// sending reply
reply->type = MsgType_UnsolicitedMessage;
reply->noreply = true;
reply->u.reply.type = ReplyType_TmSync;
reply->u.reply.u.unsolicited_tm_sync.nid = MyNid;
reply->u.reply.u.unsolicited_tm_sync.pid = MyPid;
reply->u.reply.u.unsolicited_tm_sync.handle = handle;
if (Abort_transaction)
{
trace_printf("[%s] Sending Abort to monitor.\n",MyName);
reply->u.reply.u.unsolicited_tm_sync.return_code = 99;
}
else
{
trace_printf("[%s] Sending Commit to monitor.\n",MyName);
reply->u.reply.u.unsolicited_tm_sync.return_code = MPI_SUCCESS;
}
trace_printf ("[%s] sending TmSync Unsolicited Message reply to monitor.\n", MyName);
fflush (stdout);
if (!gp_local_mon_io)
{
rc = MPI_Send (&reply, sizeof (struct message_def), MPI_CHAR, 0,
SERVICE_TAG, Monitor);
}
else
{
rc = gp_local_mon_io->send( reply );
}
if( rc != MPI_SUCCESS )
{
trace_printf ("[%s] Send failed, rc = %d\n", MyName, rc);
}
}
else
{
trace_printf("[%s] Invalid TmSync Notice received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
}
else
{
trace_printf("[%s] Invalid TmSync Notice received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
}
void process_event( struct message_def *msg )
{
trace_printf ("[%s] Processing event message.\n", MyName);
event_id = -1;
if( msg->u.request.type == ReqType_Notice )
{
if( msg->type == MsgType_Event )
{
trace_printf("[%s] Event %d (%s) received\n",
MyName,
msg->u.request.u.event_notice.event_id,
msg->u.request.u.event_notice.data);
event_id = msg->u.request.u.event_notice.event_id;
}
else
{
trace_printf("[%s] Invalid Event received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
}
else
{
trace_printf("[%s] Invalid Event received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
}
void request_to_become_TmLeader(void)
{
int count;
MPI_Status status;
struct message_def *msg;
trace_printf ("[%s] sending TmLeader request.\n", MyName);
fflush (stdout);
gp_local_mon_io->acquire_msg( &msg );
msg->type = MsgType_Service;
msg->noreply = false;
msg->reply_tag = REPLY_TAG;
msg->u.request.type = ReqType_TmLeader;
msg->u.request.u.leader.nid = MyNid;
msg->u.request.u.leader.pid = MyPid;
gp_local_mon_io->send_recv( msg );
count = sizeof (*msg);
status.MPI_TAG = msg->reply_tag;
if ((status.MPI_TAG == REPLY_TAG) &&
(count == sizeof (struct message_def)))
{
if ((msg->type == MsgType_Service) &&
(msg->u.reply.type == ReplyType_Generic))
{
if (msg->u.reply.u.generic.return_code == MPI_SUCCESS)
{
trace_printf ("[%s] I'm the new TmLeader.\n", MyName);
IamTmLeader = true;
}
else
{
trace_printf ("[%s] I'm not the TmLeader.\n", MyName);
IamTmLeader = false;
}
if (msg->u.reply.u.generic.return_code == -1)
{
trace_printf ("[%s] Failed to get the TmLeader\n", MyName);
}
else
{
trace_printf ("[%s] The new TmLeader is %s(%d,%d)\n", MyName,
msg->u.reply.u.generic.process_name,
msg->u.reply.u.generic.nid,
msg->u.reply.u.generic.pid);
}
}
else
{
trace_printf
("[%s] Invalid MsgType(%d)/ReplyType(%d) for TmLeader message\n",
MyName, msg->type, msg->u.reply.type);
}
}
else
{
trace_printf ("[%s] TmLeader process reply invalid.\n", MyName);
}
fflush (stdout);
gp_local_mon_io->release_msg(msg);
msg = NULL;
}
bool process_notice( struct message_def *msg )
{
int j;
int seq;
bool completed = false;
trace_printf ("[%s] Processing tm_sync completion notice.\n", MyName);
if( msg->u.request.type == ReqType_Notice )
{
if( msg->type == MsgType_TmSyncAbort )
{
lock_test();
trace_printf ("[%s] Processing %d Abort notice(s).\n", MyName, msg->u.request.u.tm_sync_notice.count);
for(j=0; j < msg->u.request.u.tm_sync_notice.count; j++)
{
seq=completed_request(msg->u.request.u.tm_sync_notice.nid[j],
msg->u.request.u.tm_sync_notice.handle[j],
true);
trace_printf("[%s] TmSyncAbort seq#=%d, handle=%d\n",
MyName,
seq,
msg->u.request.u.tm_sync_notice.handle[j]);
trans_abort++;
if ( trans_active && seq > -1 )
{
trans_active--;
assert( trans_active >= 0 );
completed = true;
}
}
unlock_test();
}
else if( msg->type == MsgType_TmSyncCommit )
{
lock_test();
trace_printf ("[%s] Processing %d Commit notice(s).\n", MyName, msg->u.request.u.tm_sync_notice.count);
for(j=0; j < msg->u.request.u.tm_sync_notice.count; j++)
{
seq=completed_request(msg->u.request.u.tm_sync_notice.nid[j],
msg->u.request.u.tm_sync_notice.handle[j],
false);
if ( seq > -1 )
{
trans_active--;
assert( trans_active >= 0 );
trace_printf("[%s] TmSyncCommit seq#=%d, handle=%d\n",
MyName,
seq,
msg->u.request.u.tm_sync_notice.handle[j]);
trans_commit++;
completed = true;
}
}
unlock_test();
}
else if( msg->type == MsgType_ProcessDeath )
{
if (( msg->u.request.u.death.trans_id.txid[0] == 0 ) &&
( msg->u.request.u.death.trans_id.txid[1] == 0 ) &&
( msg->u.request.u.death.trans_id.txid[2] == 0 ) &&
( msg->u.request.u.death.trans_id.txid[3] == 0 ) )
{
if ( tmProcess[msg->u.request.u.death.nid].pid ==
msg->u.request.u.death.pid )
{
tmProcess[msg->u.request.u.death.nid].dead = true;
//tmProcess[msg->u.request.u.death.nid].pid = -1;
dead_tm_count++;
if ( tmProcess[msg->u.request.u.death.nid].leader )
{
TmLeaderDied = true;
}
}
trace_printf("[%s] TM Process Death Notification for Nid=%d, Pid=%d\n",
MyName, msg->u.request.u.death.nid, msg->u.request.u.death.pid);
}
else
{
trace_printf("[%s] Transaction Process Death Notification for Nid=%d, Pid=%d, Trans_id=%lld.%lld.%lld.%lld\n",
MyName,
msg->u.request.u.death.nid,
msg->u.request.u.death.pid,
msg->u.request.u.death.trans_id.txid[0],
msg->u.request.u.death.trans_id.txid[1],
msg->u.request.u.death.trans_id.txid[2],
msg->u.request.u.death.trans_id.txid[3]);
}
}
else if ( msg->type == MsgType_NodeDown )
{
node_down=true;
trace_printf("[%s] Node %d (%s) is DOWN, Transactions aborted\n",
MyName,
msg->u.request.u.down.nid,
msg->u.request.u.down.node_name);
node_up[msg->u.request.u.down.nid]=false;
down_node_count++;
NumNodes--;
}
else if ( msg->type == MsgType_NodeUp )
{
trace_printf("[%s] Node %d (%s) is UP\n",
MyName,
msg->u.request.u.up.nid,
msg->u.request.u.up.node_name);
up_node_count++;
}
else
{
trace_printf("[%s] Invalid TmSync Notice received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
}
else
{
trace_printf("[%s] Invalid TmSync Notice received - msgtype=%d, noreply=%d, reqtype=%d\n",
MyName, msg->type, msg->noreply, msg->u.request.type);
}
return completed;
}
void MessageTypeString( char *str, MSGTYPE type )
{
switch( type )
{
case MsgType_Change:
sprintf(str, "%s", "MsgType_Change" );
break;
case MsgType_Close:
sprintf(str, "%s", "MsgType_Close" );
break;
case MsgType_Event:
sprintf(str, "%s", "MsgType_Event" );
break;
case MsgType_NodeDown:
sprintf(str, "%s", "MsgType_NodeDown" );
break;
case MsgType_Open:
sprintf(str, "%s", "MsgType_Open" );
break;
case MsgType_ProcessCreated:
sprintf(str, "%s", "MsgType_ProcessCreated" );
break;
case MsgType_ProcessDeath:
sprintf(str, "%s", "MsgType_ProcessDeath" );
break;
case MsgType_Service:
sprintf(str, "%s", "MsgType_Service" );
break;
case MsgType_Shutdown:
sprintf(str, "%s", "MsgType_Shutdown" );
break;
case MsgType_TmSyncAbort:
sprintf(str, "%s", "MsgType_TmSyncAbort" );
break;
case MsgType_TmSyncCommit:
sprintf(str, "%s", "MsgType_TmSyncCommit" );
break;
case MsgType_UnsolicitedMessage:
sprintf(str, "%s", "MsgType_UnsolicitedMessage" );
break;
default:
sprintf(str, "%s", "MsgType - Undefined" );
break;
}
}
void RequestTypeString( char *str, REQTYPE type )
{
switch( type )
{
case ReqType_Close:
sprintf(str, "%s", "ReqType_Close" );
break;
case ReqType_Exit:
sprintf(str, "%s", "ReqType_Exit" );
break;
case ReqType_Event:
sprintf(str, "%s", "ReqType_Event" );
break;
case ReqType_Get:
sprintf(str, "%s", "ReqType_Get" );
break;
case ReqType_Kill:
sprintf(str, "%s", "ReqType_Kill" );
break;
case ReqType_Mount:
sprintf(str, "%s", "ReqType_Mount" );
break;
case ReqType_NewProcess:
sprintf(str, "%s", "ReqType_NewProcess" );
break;
case ReqType_NodeDown:
sprintf(str, "%s", "ReqType_NodeDown" );
break;
case ReqType_NodeInfo:
sprintf(str, "%s", "ReqType_NodeInfo" );
break;
case ReqType_NodeUp:
sprintf(str, "%s", "ReqType_NodeUp" );
break;
case ReqType_Notice:
sprintf(str, "%s", "ReqType_Notice" );
break;
case ReqType_Notify:
sprintf(str, "%s", "ReqType_Notify" );
break;
case ReqType_Open:
sprintf(str, "%s", "ReqType_Open" );
break;
case ReqType_OpenInfo:
sprintf(str, "%s", "ReqType_OpenInfo" );
break;
case ReqType_ProcessInfo:
sprintf(str, "%s", "ReqType_ProcessInfo" );
break;
case ReqType_Set:
sprintf(str, "%s", "ReqType_Set" );
break;
case ReqType_Shutdown:
sprintf(str, "%s", "ReqType_Shutdown" );
break;
case ReqType_Startup:
sprintf(str, "%s", "ReqType_Startup" );
break;
case ReqType_TmLeader:
sprintf(str, "%s", "ReqType_TmLeader" );
break;
case ReqType_TmSeqNum:
sprintf(str, "%s", "ReqType_TmSeqNum" );
break;
case ReqType_TmSync:
sprintf(str, "%s", "ReqType_TmSync" );
break;
case ReqType_TransInfo:
sprintf(str, "%s", "ReqType_TransInfo" );
break;
case ReqType_Stfsd:
sprintf(str, "%s", "ReqType_Stfsd" );
break;
case ReqType_ProcessInfoCont:
sprintf(str, "%s", "ReqType_ProcessInfoCont" );
break;
default:
sprintf(str, "%s", "ReqType - Undefined" );
break;
}
}
void recv_localio_msg(struct message_def *recv_msg, int size)
{
int rc = -1;
char msgTypeStr[30] = {'\0'};
char reqTypeStr[30] = {'\0'};
size = size; // Avoid "unused parameter" warning
// CHECK TO SEE THAT WE HAVE STARTED THE TEST BEFORE WE CONTINUE
while ( !Test_Initialized ) usleep(1000);
trace_printf("[%s] Message received: ",MyName);
switch ( recv_msg->type )
{
case MsgType_Service:
trace_printf("Service Reply: Type=%d, ReplyType=%d\n",recv_msg->type, recv_msg->u.reply.type);
break;
case MsgType_Event:
trace_printf("Event - %d\n",recv_msg->u.request.u.event_notice.event_id);
if ( EventMsgRecv )
{
trace_printf("[%s] - Event Message overrun!\n", MyName);
abort();
}
EventMsgRecv = true;
process_event( recv_msg );
break;
case MsgType_UnsolicitedMessage:
trace_printf("Unsolicited Message:\n");
if ( UnsolMsgRecv )
{
trace_printf("[%s] - Unsolicitied Message overrun!\n", MyName);
// abort();
}
UnsolMsgRecv = true;
lock_test();
if ( TestWait )
{
int handle;
struct sync_buf_def *buf;
handle = recv_msg->u.request.u.unsolicited_tm_sync.handle;
buf = (struct sync_buf_def*)recv_msg->u.request.u.unsolicited_tm_sync.data;
trace_printf("[%s] QUEUE TmSync Unsolicited Message - nid=%d pid=%d handle=%d data='seq#=%d, len=%d string=%s'\n", MyName,
recv_msg->u.request.u.unsolicited_tm_sync.nid,
recv_msg->u.request.u.unsolicited_tm_sync.pid,
handle,
buf->seq_number,
buf->length,
buf->string);
unsolicited_queue.push( *recv_msg );
unlock_test();
}
else
{
unlock_test();
process_unsolicited_msg( recv_msg );
lock_unsolicited();
rc = signal_unsolicited();
if ( rc == -1 )
{
exit( 1);
}
unlock_unsolicited();
}
break;
default:
MessageTypeString( msgTypeStr, recv_msg->type );
RequestTypeString( reqTypeStr, recv_msg->u.request.type );
trace_printf("Notice: Type=%d(%s), RequestType=%d(%s)\n",recv_msg->type,msgTypeStr,recv_msg->u.request.type,reqTypeStr);
if ( NoticeMsgRecv )
{
printf("[%s] - Notice Message overrun!\n", MyName);
// abort();
}
NoticeMsgRecv = true;
process_notice( recv_msg );
lock_notice();
rc = signal_notice();
if ( rc == -1 )
{
exit( 1);
}
unlock_notice();
}
}
MPI_Status tm_sync( int seq_number )
{
struct sync_buf_def buf;
MPI_Status status;
struct message_def *msg;
trace_printf ("[%s] sending tm_sync request.\n", MyName);
fflush (stdout);
// check if we need a new leader
if (node_down)
{
request_to_become_TmLeader();
node_down = false;
}
gp_local_mon_io->acquire_msg( &msg );
// build seq buffer
buf.seq_number = seq_number;
sprintf(buf.string,"Master TmSync start #%d from Node %d",trans_starts,MyNid);
buf.length = strlen(buf.string);
// build monitor request
msg->type = MsgType_Service;
msg->noreply = false;
msg->reply_tag = REPLY_TAG;
msg->u.request.type = ReqType_TmSync;
msg->u.request.u.tm_sync.nid = MyNid;
msg->u.request.u.tm_sync.pid = MyPid;
msg->u.request.u.tm_sync.length = sizeof(struct sync_buf_def);
memmove(msg->u.request.u.tm_sync.data,&buf,msg->u.request.u.tm_sync.length);
trace_printf ("[%s] tm_sync data length=%d\n",MyName,msg->u.request.u.tm_sync.length);
gp_local_mon_io->send_recv( msg );
status.MPI_TAG = msg->reply_tag;
if ((msg->type == MsgType_Service) &&
(msg->u.reply.type == ReplyType_TmSync))
{
if (msg->u.reply.u.tm_sync.return_code == MPI_SUCCESS)
{
trace_printf ("[%s] tm_sync request successfully. rc=%d\n",
MyName, msg->u.reply.u.tm_sync.return_code);
trace_printf("[%s] TmSync Message - nid=%d pid=%d handle=%d data='seq#=%d, len=%d string=%s'\n", MyName,
MyNid,
MyPid,
msg->u.reply.u.tm_sync.handle,
buf.seq_number,
buf.length,
buf.string);
request[MyNid][seq_number].handle = msg->u.reply.u.tm_sync.handle;
trans_count++;
trans_active++;
status.MPI_ERROR = msg->u.reply.u.tm_sync.return_code;
}
else
{
trace_printf ("[%s] tm_sync request failed, rc=%d\n", MyName,
msg->u.reply.u.tm_sync.return_code);
status.MPI_ERROR = msg->u.reply.u.tm_sync.return_code;
}
}
else
{
status.MPI_ERROR = -1;
trace_printf ("[%s] Invalid MsgType(%d)/ReplyType(%d) for tm_sync request\n",
MyName, msg->type, msg->u.reply.type);
}
fflush (stdout);
gp_local_mon_io->release_msg(msg);
msg = NULL;
return status;
}
bool wait_for_event()
{
MPI_Status status;
struct message_def *msg;
trace_printf ("[%s] Waiting for event message.\n", MyName);
status.MPI_ERROR = gp_local_mon_io->wait_for_event( &msg );
process_event(msg);
if (status.MPI_ERROR != MPI_SUCCESS)
{
trace_printf ("[%s] Recv failed, rc = %d\n", MyName, status.MPI_ERROR);
}
delete msg;
return (status.MPI_ERROR == MPI_SUCCESS);
}
bool wait_for_notice()
{
int rc = -1;
trace_printf ("[%s] Waiting for tm_sync completion notice.\n", MyName);
lock_notice();
rc = wait_on_notice();
if ( rc == -1 )
{
exit( 1);
}
unlock_notice();
return ( rc == 0 );
}
bool wait_for_unsolicited_msg()
{
int rc = -1;
trace_printf ("[%s] Waiting for unsolicited message.\n", MyName);
lock_unsolicited();
rc = wait_on_unsolicited();
if ( rc == -1 )
{
exit( 1);
}
unlock_unsolicited();
return ( rc == 0 );
}
void InitLocalIO( void )
{
char *cmd_buffer;
if ( MyPNid == -1 )
{
CClusterConfig ClusterConfig; // 'cluster.conf' objects
CPNodeConfig *pnodeConfig;
CLNodeConfig *lnodeConfig;
if ( ClusterConfig.Initialize() )
{
if ( ! ClusterConfig.LoadConfig() )
{
trace_printf("[%s], Failed to load cluster configuration.\n", MyName);
abort();
}
}
else
{
trace_printf( "[%s] Warning: No cluster.conf found\n",MyName);
if (MyNid == -1)
{
trace_printf( "[%s] Warning: set default virtual node ID = 0\n",MyName);
MyNid = 0;
}
abort();
}
lnodeConfig = ClusterConfig.GetLNodeConfig( MyNid );
pnodeConfig = lnodeConfig->GetPNodeConfig();
gv_ms_su_nid = MyPNid = pnodeConfig->GetPNid();
trace_printf ("[%s] Local IO pnid = %d\n", MyName, MyPNid);
}
gp_local_mon_io = new Local_IO_To_Monitor( -1 );
cmd_buffer = getenv("SQ_LOCAL_IO_SHELL_TRACE");
if (cmd_buffer && *cmd_buffer == '1')
{
gp_local_mon_io->cv_trace = true;
char tracefile[MAX_SEARCH_PATH];
char *tmpDir;
tmpDir = getenv( "MPI_TMPDIR" );
if (tmpDir)
{
sprintf( tracefile, "%s/shell.trace.%d", tmpDir, getpid() );
}
else
{
sprintf( tracefile, "./shell.trace.%d", getpid() );
}
shell_locio_trace_file = fopen(tracefile, "w+");
gp_local_mon_io->cp_trace_cb = shell_locio_trace;
}
}
int main (int argc, char *argv[])
{
MPI_Status status;
bool done = false;
bool end_of_test = false;
// Setup HP_MPI software license
int key = 413675219; //413675218 to display banner
MPI_Initialized(&key);
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &MyRank);
trace_init((char *)"STDOUT", false, NULL, false);
MyName = new char [MAX_PROCESS_PATH];
strcpy( MyName, argv[5] );
MyNid = atoi(argv[3]);
int rc = pthread_mutex_init( ¬ice_mutex, NULL );
if (rc)
{
trace_printf("[%s] Error initializing notice mutex: %s (%d)\n",
MyName, strerror(errno), errno);
exit(1);
}
rc = pthread_mutex_init( &test_mutex, NULL );
if (rc)
{
trace_printf("[%s] Error initializing test mutex: %s (%d)\n",
MyName, strerror(errno), errno);
exit(1);
}
rc = pthread_mutex_init( &unsolicited_mutex, NULL );
if (rc)
{
trace_printf("[%s] Error initializing unsolicited mutex: %s (%d)\n",
MyName, strerror(errno), errno);
exit(1);
}
// Check if we are using virtual nodes
char *cmd_buffer = getenv("SQ_VIRTUAL_NODES");
if (cmd_buffer && isdigit(cmd_buffer[0]))
{
VirtualNodes = atoi(cmd_buffer);
if (VirtualNodes > 8) VirtualNodes = 8;
}
else
{
VirtualNodes = 0;
}
if ( ! gp_local_mon_io )
{
InitLocalIO();
assert (gp_local_mon_io);
}
gp_local_mon_io->set_cb(recv_localio_msg, "notice");
gp_local_mon_io->set_cb(recv_localio_msg, "recv");
gp_local_mon_io->set_cb(recv_localio_msg, "unsol");
#if 0
struct rlimit rl;
int rc = getrlimit( RLIMIT_SIGPENDING, &rl );
if ( rc == 0 )
{
trace_printf("[%s] RLIMIT_SIGPENDING cur=%d, max=%d\n", MyName, (int)rl.rlim_cur, (int)rl.rlim_max);
}
#endif
process_startup (argc, argv);
NumNodes = GetNumOfNode();
do
{
end_of_test = false;
initialize_test();
// wait for event signal to start test across all TMs
wait_for_event();
request_to_become_TmLeader();
switch ( event_id )
{
case 1:
// *** test 1 -- failed TM test w/ restart of TMs
trace_printf("[%s] Test1 - TM process death test w/restart of TM processes - Waiting to start test.\n",MyName);
if ( get_tm_processes( MAX_TEST_NODES ) )
{
abort();
}
if ( MyNid == 2 ||
(!VirtualNodes && MyNid == 3) )
{
// Wait for other TMs to start, then die!
sleep(3);
trace_printf("[%s] - Test1 - Stopping to halt node\n",MyName);
fflush (stdout);
MPI_Abort (MPI_COMM_WORLD, 99);
}
else
{
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test1 - Sending TM Sync request.\n",MyName);
status = tm_sync(trans_starts++);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test1(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] Test1(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test1 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trace_printf("[%s] Test1 - Wait to commit or abort TM sync data.\n",MyName);
}
while (((trans_commit+trans_abort)<NumNodes || trans_active) && ! end_of_test )
{
fflush (stdout);
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test1 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
trace_printf("[%s] Test1 - Dead TM count =%d\n",MyName,dead_tm_count);
if ( dead_tm_count == 2 && up_node_count == 2 )
{
up_node_count = 0;
if ( IamTmLeader )
{
trace_printf("[%s] Test1 - TM leader is restarting dead TM processes.\n",MyName);
if ( restart_all_dead_tm() )
{
trace_printf("[%s] Test1 - Failed to restart dead TM processes! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
wait_for_event(); // event 2
end_of_test = true;
}
else
{
trace_printf("[%s] Test1 - Wait for restart of dead TM processes.\n",MyName);
wait_for_event(); // event 2
end_of_test = true;
}
}
//printf("[%s] Test1 - DEBUG commit=%d, abort=%d, nodes=%d, active=%d\n",MyName,trans_commit,trans_abort,NumNodes,trans_active);
if ( TestShutdown == true )
{
end_of_test = true;
}
}
trace_printf("[%s] Test1 - TM process death test w/restart of TM processes - Completed test.\n",MyName);
break;
case 2:
// *** test 1 -- failed TM test w/ restart of TMs
// Restarted TMs execute this path (event 2), surviving TMs are in case 1: above
trace_printf("[%s] Test1 - TM process death test w/restart of TM processes - Completed test.\n",MyName);
break;
case 3:
// *** test 3 - No collision Commit test
Abort_transaction = false;
trace_printf("[%s] Test3 - No collision Commit test (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
// TM on logical node 2 to start sync
if ( MyNid == 2 )
{
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test3 - Sending TM Sync request.\n",MyName);
status = tm_sync(trans_starts++);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test3 - Started TM Sync operation.\n",MyName);
}
else
{
trace_printf("[%s] Test3 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
}
else
{
trace_printf("[%s] TM Test3 - Sync already started ... waiting for TM Sync data.\n",MyName);
if ( !wait_for_unsolicited_msg() )
{
trace_printf("[%s] Test3 - Failed to receive unsolicited message! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
trace_printf("[%s] Test3 - Wait to commit or abort TM sync data.\n",MyName);
while( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test3 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
else
{
trace_printf("[%s] Test3 - No transaction active.\n",MyName);
}
}
Test_Initialized = false;
trace_printf("[%s] Test3 - No collision Commit test - Completed test.\n",MyName);
break;
case 4:
// *** test 4 -- No collision Abort test
Abort_transaction = (MyNid==5?true:false);
trace_printf("[%s] Test4 - No collision Abort test (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
// TM on logical node 0 to start sync
if ( MyNid == 1 )
{
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test4 - Sending TM Sync request.\n",MyName);
status = tm_sync(trans_starts++);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test4 - Started TM Sync operation.\n",MyName);
}
else
{
trace_printf("[%s] Test4 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
}
else
{
trace_printf("[%s] TM Test4 - Sync already started ... waiting for TM Sync data.\n",MyName);
if ( !wait_for_unsolicited_msg() )
{
trace_printf("[%s] Test4 - Failed to receive unsolicited message! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
trace_printf("[%s] Test4 - Wait to commit or abort TM sync data.\n",MyName);
while( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test4 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
else
{
trace_printf("[%s] Test4 - No transaction active.\n",MyName);
}
}
Test_Initialized = false;
trace_printf("[%s] Test4 - No collision Abort test - Completed test.\n",MyName);
break;
case 5:
// *** test 5 -- Collision Commit test
Abort_transaction = false;
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test5 - Collision Commit test (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test5(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test5(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test5(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test5 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
if ( trans_starts%(MyNid+1) == 0 ) usleep(1000*MyNid);
}
while ( trans_starts < MAX_SYNCS );
trace_printf("[%s] Test5 - Wait to commit or abort TM sync data.\n",MyName);
while ( !completed_test() )
{
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test5 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
}
trace_printf("[%s] Test5 - Collision Commit test - Completed test.\n",MyName);
break;
case 6:
// *** test 6 -- Collision Abort test
Abort_transaction = (MyNid==2?true:false);
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test6 - Collision Abort test (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test6(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test6(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test6(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test6 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
if ( trans_starts%(MyNid+1) == 0 ) usleep(1000*MyNid);
}
while ( trans_starts < MAX_SYNCS );
trace_printf("[%s] Test6 - Wait to commit or abort TM sync data.\n",MyName);
while ( !completed_test() )
{
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test6 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
}
trace_printf("[%s] Test6 - Collision Abort test - Completed test.\n",MyName);
break;
case 7:
// *** test 7 -- failed TM test
trace_printf("[%s] Test7 - TM process death test w/ node failure - Waiting to start test.\n",MyName);
if ( MyNid == 2 ||
(!VirtualNodes && MyNid == 3) )
{
usleep(SYNC_DELAY*2); // delay to allow at least two sync cycles
trace_printf("[%s] - Test7 - Stopping to halt node\n",MyName);
fflush (stdout);
MPI_Abort (MPI_COMM_WORLD, 99);
}
else
{
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test7 - Sending TM Sync request.\n",MyName);
status = tm_sync(trans_starts++);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test7(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test7(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test7 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trace_printf("[%s] Test7 - Wait to commit or abort TM sync data.\n",MyName);
}
while ( ((trans_commit+trans_abort) < (NumNodes-1)) || trans_active )
{
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test7 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
#if 0
if ( down_node_count )
{
down_node_count = 0;
NumNodes = GetNumOfNode();
}
#endif
trace_printf("[%s] Test7 - Counters: Commit#=%d, Abort#=%d, NumNodes#=%d, Active=%d\n",
MyName,trans_commit,trans_abort,NumNodes,trans_active);
}
trace_printf("[%s] Test7 - TM process death test w/ node failure - Completed test.\n",MyName);
break;
case 8:
// *** test 8 -- failed TM test w/ restart of TMs while TmSync is in process
trace_printf("[%s] Test8 - Collision Abort TM process death test w/restart of TM processes - Waiting to start test.\n",MyName);
// suppress processing of other TmSyncs
lock_test();
TestWait = true;
// abort processing of other TmSyncs
Abort_transaction = false;
if ( get_tm_processes( MAX_TEST_NODES ) )
{
abort();
}
unlock_test();
if ( MyNid == 2 )
{
sleep(3);
// delay to allow at least three sync cycles
// and die in the middle of a TmSync
usleep(SYNC_DELAY*3);
trace_printf("[%s] - Test8 - Stopping to halt node\n",MyName);
fflush (stdout);
MPI_Abort (MPI_COMM_WORLD, 99);
}
else
{
if ( MyNid == 3 )
{
// delay to allow nid 2 to abort
sleep(3);
usleep(SYNC_DELAY*3);
if ( !VirtualNodes )
{
// on a real cluster the watchdog process
// does not know about the testtm program
usleep(SYNC_DELAY*3);
MPI_Abort (MPI_COMM_WORLD, 99);
}
}
else
{
sleep(1);
}
trace_printf("[%s] Test8 - Sending TM Sync request (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test8(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test8(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test8(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test8 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
} while ( trans_starts < MAX_SYNCS );
}
sleep(1);
if ( TestWait )
{
// Nid 2 may abort while TmSyncs are handled in this loop
while (!unsolicited_queue.empty())
{
struct message_def msg = unsolicited_queue.front();
int handle;
struct sync_buf_def *buf;
handle = msg.u.request.u.unsolicited_tm_sync.handle;
buf = (struct sync_buf_def*)msg.u.request.u.unsolicited_tm_sync.data;
trace_printf("[%s] DEQUEUE TmSync Unsolicited Message - nid=%d pid=%d handle=%d data='seq#=%d, len=%d string=%s'\n", MyName,
msg.u.request.u.unsolicited_tm_sync.nid,
msg.u.request.u.unsolicited_tm_sync.pid,
handle,
buf->seq_number,
buf->length,
buf->string);
process_unsolicited_msg( &msg );
unsolicited_queue.pop();
}
lock_test();
TestWait = false;
unlock_test();
}
sleep(2);
while ( !completed_test() && !end_of_test )
{
fflush (stdout);
// wait death notice or TmSync notice
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test8 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
trace_printf("[%s] Test8 - Dead TM count =%d\n",MyName,dead_tm_count);
if ( dead_tm_count == 2)
{
if ( IamTmLeader )
{
trace_printf("[%s] Test8 - TM leader is restarting dead TM processes.\n",MyName);
if ( restart_all_dead_tm() )
{
trace_printf("[%s] Test8 - Failed to restart dead TM processes! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
wait_for_event(); // event 9
}
else
{
trace_printf("[%s] Test8 - Wait for restart of dead TM processes.\n",MyName);
wait_for_event(); // event 9
}
trace_printf("[%s] Test8 - Start#=%d, Abort#=%d, Commit#=%d, Total Transaction=%d\n",
MyName, trans_starts,trans_abort,trans_commit,trans_count);
fflush (stdout);
initialize_test();
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test8 - Resending TM Sync request (abort=%d)\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test8(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test8(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test8(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test8 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
} while ( trans_starts < MAX_SYNCS );
}
printf("[%s] Test8 - DEBUG commit=%d, abort=%d, nodes=%d, active=%d\n",MyName,trans_commit,trans_abort,NumNodes,trans_active);
if ( TestShutdown == true )
{
end_of_test = true;
}
}
trace_printf("[%s] Test8 - Collision Abort TM process death test w/restart of TM processes - Completed test.\n",MyName);
break;
case 9:
// *** test 8 -- failed TM test w/ restart of TMs
// Restarted TMs execute this path (event 9), surviving TMs are in case 8: above
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test8 - Sending TM Sync request (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test8(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test8(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test8(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test8 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
} while ( trans_starts < MAX_SYNCS );
while ( !completed_test() )
{
fflush (stdout);
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test8 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
printf("[%s] Test8 - DEBUG commit=%d, abort=%d, nodes=%d, active=%d\n",MyName,trans_commit,trans_abort,NumNodes,trans_active);
}
trace_printf("[%s] Test8 - Collision Abort TM process death test w/restart of TM processes - Completed test.\n",MyName);
break;
case 10:
// *** test 10 -- failed TM test w/out restart of TMs
// This test must be performed after test1, so that there is no spare node
// and TmSyncs are in processs when a node goes down
trace_printf("[%s] Test10 - Collision Abort TM process death test w/ node failure - Waiting to start test.\n",MyName);
// suppress processing of other TmSyncs
lock_test();
TestWait = true;
// abort processing of other TmSyncs
Abort_transaction = false;
if ( get_tm_processes( MAX_TEST_NODES ) )
{
abort();
}
unlock_test();
if ( MyNid == 2 )
{
sleep(3);
// delay to allow at least three sync cycles
// and die in the middle of a TmSync
usleep(SYNC_DELAY*3);
trace_printf("[%s] - Test10 - Stopping to halt node\n",MyName);
fflush (stdout);
MPI_Abort (MPI_COMM_WORLD, 99);
}
else
{
if ( MyNid == 3 )
{
// delay to allow nid 2 to abort
sleep(3);
usleep(SYNC_DELAY*3);
}
else
{
sleep(1);
}
trace_printf("[%s] Test10 - Sending TM Sync request (abort=%d) - Waiting to start test.\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test10(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test10(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test10(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test10 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
} while ( trans_starts < MAX_SYNCS );
}
sleep(1);
if ( TestWait )
{
// Nid 2 may abort while TmSyncs are handled in this loop
while (!unsolicited_queue.empty())
{
struct message_def msg = unsolicited_queue.front();
int handle;
struct sync_buf_def *buf;
handle = msg.u.request.u.unsolicited_tm_sync.handle;
buf = (struct sync_buf_def*)msg.u.request.u.unsolicited_tm_sync.data;
trace_printf("[%s] DEQUEUE TmSync Unsolicited Message - nid=%d pid=%d handle=%d data='seq#=%d, len=%d string=%s'\n", MyName,
msg.u.request.u.unsolicited_tm_sync.nid,
msg.u.request.u.unsolicited_tm_sync.pid,
handle,
buf->seq_number,
buf->length,
buf->string);
process_unsolicited_msg( &msg );
unsolicited_queue.pop();
}
lock_test();
TestWait = false;
unlock_test();
}
sleep(2);
while ( !completed_test() && !end_of_test )
{
fflush (stdout);
if( !wait_for_notice() )
{
if (trans_active)
{
trace_printf("[%s] Test10 - Failed to receive notice! Aborting\n",MyName);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99 );
}
}
trace_printf("[%s] Test10 - Dead TM count =%d\n",MyName,dead_tm_count);
if ( dead_tm_count == 2)
{
trace_printf("[%s] Test10 - Waiting for node to die.\n",MyName);
wait_for_event(); // event 11
usleep(SYNC_DELAY); // delay to allow at least one sync cycle
trace_printf("[%s] Test10 - Start#=%d, Abort#=%d, Commit#=%d, Total Transaction=%d\n",
MyName, trans_starts,trans_abort,trans_commit,trans_count);
fflush (stdout);
initialize_test();
// force completion of requests from node 2 and 3 since they are dead
end_requests( 2 );
end_requests( 3 );
trace_printf("[%s] Test10 - Resending TM Sync request (abort=%d)\n",MyName, Abort_transaction);
do
{
trace_printf("[%s] Test10(%d) - Sending TM Sync request.\n",MyName,trans_starts);
status = tm_sync(trans_starts);
if( status.MPI_ERROR == MPI_SUCCESS )
{
trace_printf("[%s] Test10(%d) - Started TM Sync operation.\n",MyName,trans_starts);
}
else if( status.MPI_ERROR == MPI_ERR_PENDING )
{
trace_printf("[%s] TM Test10(%d) - Sync already started ... waiting for TM Sync data.\n",MyName,trans_starts);
}
else
{
trace_printf("[%s] Test10 - Can't start TM Sync, err=%d\n",MyName,status.MPI_ERROR);
fflush (stdout);
MPI_Abort( MPI_COMM_WORLD, 99);
}
trans_starts++;
} while ( trans_starts < MAX_SYNCS );
}
printf("[%s] Test10 - DEBUG commit=%d, abort=%d, nodes=%d, active=%d\n",MyName,trans_commit,trans_abort,NumNodes,trans_active);
if ( TestShutdown == true )
{
end_of_test = true;
}
}
trace_printf("[%s] Test10 - Collision Abort TM process death test w/ node failure - Completed test.\n",MyName);
break;
default:
trace_printf("[%s] Event = %d, No test defined, stopping\n",MyName, event_id);
done = true;
}
if (!done)
{
int test_num;
test_num = (event_id == 2) ? 1 : event_id;
test_num = (test_num == 9) ? 8 : test_num;
test_num = (test_num == 11) ? 10 : test_num;
trace_printf("[%s] Test%d - Start#=%d, Abort#=%d, Commit#=%d, Total Transaction=%d\n",
MyName, test_num, trans_starts,trans_abort,trans_commit,trans_count);
fflush (stdout);
}
}
while (!done);
// exit my process
exit_process ();
trace_printf ("[%s] calling Finalize!\n", MyName);
fflush (stdout);
MPI_Close_port( MyPort );
MPI_Finalize ();
if ( gp_local_mon_io )
{
delete gp_local_mon_io;
}
exit (0);
}
|
// Copyright (c) 2020, Christopher A. Taylor. All rights reserved.
#pragma once
#include "Tools.hpp"
namespace z16 {
//------------------------------------------------------------------------------
// Codec
class Codec
{
public:
~Codec()
{
Shutdown();
}
bool Initialize();
void Shutdown();
z16_Frame* Decode(const uint8_t* data, int32_t bytes, int32_t& error);
void Free(z16_Frame* frame);
uint8_t* Encode(const z16_Frame& frame, int32_t& bytes, int32_t& error);
protected:
// Encoder:
PredictorPicker Picker;
EncodeBuffer EncodedResiduals;
BitAccumulator EncodedChoices;
ZstdResidualContext ZstdResiduals;
std::vector<uint8_t> Output;
protected:
// Decoder:
std::vector<z16_Frame*> FreedFrames;
std::vector<uint8_t> Choices;
std::vector<uint8_t> Residuals;
z16_Frame* Allocate(int32_t format, int width, int height);
void FreeAll();
};
} // namespace z16
|
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/interviewbit/sudoku.html .
vector<set<int>> regions(9), rows(9), columns(9);
int getRegionId(int i, int j) { return (i / 3) * 3 + (j / 3); }
bool traverse(vector<vector<int>> remains, vector<int> &nums) {
if (remains.size() <= 0)
return true;
int i = remains[0][0], j = remains[0][1], regionId = getRegionId(i, j);
set<int> &row = rows[i], &column = columns[j], ®ion = regions[regionId];
remains.erase(remains.begin());
for (int num = 1; num <= 9; num++) {
if ((region.find(num) != region.end()) ||
(row.find(num) != row.end()) ||
(column.find(num) != column.end())) {
continue;
}
row.insert(num);
column.insert(num);
region.insert(num);
nums.push_back(num);
if (traverse(remains, nums)) {
return true;
}
nums.pop_back();
row.erase(num);
column.erase(num);
region.erase(num);
}
return false;
}
void Solution::solveSudoku(vector<vector<char>> &A) {
for (int i = 0; i < 9; i++) {
regions[i] = set<int>();
rows[i] = set<int>();
columns[i] = set<int>();
}
vector<vector<int>> remains;
vector<int> nums;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char ch = A[i][j];
if (isdigit(ch)) {
int num = ch - '0';
rows[i].insert(num);
columns[j].insert(num);
regions[getRegionId(i, j)].insert(num);
} else {
remains.push_back(vector<int>{i, j});
}
}
}
traverse(remains, nums);
for (int k = 0; k < remains.size(); k++) {
A[remains[k][0]][remains[k][1]] = nums[k] + '0';
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/common/credential_manager_types.h"
#include <memory>
#include "base/strings/string_number_conversions.h"
#include "components/autofill/core/common/password_form.h"
namespace password_manager {
std::string CredentialTypeToString(CredentialType value) {
switch (value) {
case CredentialType::CREDENTIAL_TYPE_EMPTY:
return "CredentialType::CREDENTIAL_TYPE_EMPTY";
case CredentialType::CREDENTIAL_TYPE_PASSWORD:
return "CredentialType::CREDENTIAL_TYPE_PASSWORD";
case CredentialType::CREDENTIAL_TYPE_FEDERATED:
return "CredentialType::CREDENTIAL_TYPE_FEDERATED";
}
return "Unknown CredentialType value: " +
base::NumberToString(static_cast<int>(value));
}
std::ostream& operator<<(std::ostream& os, CredentialType value) {
return os << CredentialTypeToString(value);
}
CredentialInfo::CredentialInfo() : type(CredentialType::CREDENTIAL_TYPE_EMPTY) {
}
CredentialInfo::CredentialInfo(const autofill::PasswordForm& form,
CredentialType form_type)
: type(form_type),
id(form.username_value),
name(form.display_name),
icon(form.icon_url),
password(form.password_value),
federation(form.federation_origin) {
switch (form_type) {
case CredentialType::CREDENTIAL_TYPE_EMPTY:
password = base::string16();
federation = url::Origin();
break;
case CredentialType::CREDENTIAL_TYPE_PASSWORD:
federation = url::Origin();
break;
case CredentialType::CREDENTIAL_TYPE_FEDERATED:
password = base::string16();
break;
}
}
CredentialInfo::CredentialInfo(const CredentialInfo& other) = default;
CredentialInfo::~CredentialInfo() = default;
bool CredentialInfo::operator==(const CredentialInfo& rhs) const {
return (type == rhs.type && id == rhs.id && name == rhs.name &&
icon == rhs.icon && password == rhs.password &&
federation.Serialize() == rhs.federation.Serialize());
}
std::unique_ptr<autofill::PasswordForm> CreatePasswordFormFromCredentialInfo(
const CredentialInfo& info,
const url::Origin& origin) {
std::unique_ptr<autofill::PasswordForm> form;
if (info.type == CredentialType::CREDENTIAL_TYPE_EMPTY)
return form;
form = std::make_unique<autofill::PasswordForm>();
form->icon_url = info.icon;
form->display_name = info.name.value_or(base::string16());
form->federation_origin = info.federation;
form->url = origin.GetURL();
form->password_value = info.password.value_or(base::string16());
form->username_value = info.id.value_or(base::string16());
form->scheme = autofill::PasswordForm::Scheme::kHtml;
form->type = autofill::PasswordForm::Type::kApi;
form->signon_realm =
info.type == CredentialType::CREDENTIAL_TYPE_PASSWORD
? form->url.spec()
: "federation://" + origin.host() + "/" + info.federation.host();
return form;
}
} // namespace password_manager
|
// Copyright (c) 2014 Sze Howe Koh
// This code is licensed under the MIT license (see LICENSE.MIT for details)
#include "gui.h"
#include <QDebug>
QTextEdit* logWidget;
static void printMessage(QtMsgType, const QMessageLogContext&, const QString &msg)
{
logWidget->append(msg);
}
Gui::Gui(QWidget* parent)
: QWidget(parent)
{
setupUi(this);
logWidget = textEdit;
qInstallMessageHandler(&printMessage);
comboBox_os->addItems({
"linux_x64",
"linux_x86",
"mac_x64",
"windows_x86"
});
#if defined(Q_OS_LINUX)
comboBox_os->setCurrentText("linux_x64");
#elif defined(Q_OS_OSX)
comboBox_os->setCurrentText("mac_x64");
#elif defined(Q_OS_WIN32)
comboBox_os->setCurrentText("windows_x86");
#endif
connect(pushButton_mirror, &QPushButton::clicked, [=]
{
pushButton_mirror->setEnabled(false);
emit mirrorSelected(comboBox_os->currentText(), comboBox_mirror->currentText());
});
}
void
Gui::setMirrorList(const QStringList& mirrors)
{
comboBox_mirror->clear();
comboBox_mirror->addItems(mirrors);
pushButton_mirror->setEnabled(mirrors.count() > 0);
}
void
Gui::setLocalRepoUrl(const QString& url)
{
lineEdit_localUrl->setText(url);
lineEdit_localUrl->setEnabled(true);
}
|
#include <cstring>
#include "d3d9_initializer.h"
namespace dxvk {
D3D9Initializer::D3D9Initializer(
const Rc<DxvkDevice>& Device)
: m_device(Device), m_context(m_device->createContext()) {
m_context->beginRecording(
m_device->createCommandList());
}
D3D9Initializer::~D3D9Initializer() {
}
void D3D9Initializer::Flush() {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_transferCommands != 0)
FlushInternal();
}
void D3D9Initializer::InitBuffer(
D3D9CommonBuffer* pBuffer) {
VkMemoryPropertyFlags memFlags = pBuffer->GetBuffer<D3D9_COMMON_BUFFER_TYPE_REAL>()->memFlags();
(memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
? InitHostVisibleBuffer(pBuffer->GetBufferSlice<D3D9_COMMON_BUFFER_TYPE_REAL>())
: InitDeviceLocalBuffer(pBuffer->GetBufferSlice<D3D9_COMMON_BUFFER_TYPE_REAL>());
if (pBuffer->GetMapMode() == D3D9_COMMON_BUFFER_MAP_MODE_BUFFER)
InitHostVisibleBuffer(pBuffer->GetBufferSlice<D3D9_COMMON_BUFFER_TYPE_STAGING>());
}
void D3D9Initializer::InitTexture(
D3D9CommonTexture* pTexture,
void* pInitialData) {
if (pTexture->GetMapMode() == D3D9_COMMON_TEXTURE_MAP_MODE_NONE)
return;
(pTexture->GetMapMode() == D3D9_COMMON_TEXTURE_MAP_MODE_BACKED)
? InitDeviceLocalTexture(pTexture)
: InitHostVisibleTexture(pTexture, pInitialData);
}
void D3D9Initializer::InitDeviceLocalBuffer(
DxvkBufferSlice Slice) {
std::lock_guard<std::mutex> lock(m_mutex);
m_transferCommands += 1;
m_context->clearBuffer(
Slice.buffer(),
Slice.offset(),
Slice.length(),
0u);
FlushImplicit();
}
void D3D9Initializer::InitHostVisibleBuffer(
DxvkBufferSlice Slice) {
// If the buffer is mapped, we can write data directly
// to the mapped memory region instead of doing it on
// the GPU. Same goes for zero-initialization.
std::memset(
Slice.mapPtr(0), 0,
Slice.length());
}
void D3D9Initializer::InitDeviceLocalTexture(
D3D9CommonTexture* pTexture) {
std::lock_guard<std::mutex> lock(m_mutex);
auto InitImage = [&](Rc<DxvkImage> image) {
if (image == nullptr)
return;
auto formatInfo = imageFormatInfo(image->info().format);
m_transferCommands += 1;
// While the Microsoft docs state that resource contents are
// undefined if no initial data is provided, some applications
// expect a resource to be pre-cleared. We can only do that
// for non-compressed images, but that should be fine.
VkImageSubresourceRange subresources;
subresources.aspectMask = formatInfo->aspectMask;
subresources.baseMipLevel = 0;
subresources.levelCount = image->info().mipLevels;
subresources.baseArrayLayer = 0;
subresources.layerCount = image->info().numLayers;
if (formatInfo->flags.test(DxvkFormatFlag::BlockCompressed)) {
m_context->clearCompressedColorImage(image, subresources);
} else {
if (subresources.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
VkClearColorValue value = { };
m_context->clearColorImage(
image, value, subresources);
} else {
VkClearDepthStencilValue value;
value.depth = 0.0f;
value.stencil = 0;
m_context->clearDepthStencilImage(
image, value, subresources);
}
}
};
InitImage(pTexture->GetImage());
FlushImplicit();
}
void D3D9Initializer::InitHostVisibleTexture(
D3D9CommonTexture* pTexture,
void* pInitialData) {
// If the buffer is mapped, we can write data directly
// to the mapped memory region instead of doing it on
// the GPU. Same goes for zero-initialization.
for (uint32_t i = 0; i < pTexture->CountSubresources(); i++) {
DxvkBufferSliceHandle mapSlice = pTexture->GetMappingBuffer(i)->getSliceHandle();
if (pInitialData != nullptr) {
std::memcpy(
mapSlice.mapPtr,
pInitialData,
mapSlice.length);
} else {
std::memset(
mapSlice.mapPtr, 0,
mapSlice.length);
}
if (pTexture->RequiresFixup())
pTexture->Device()->FixupFormat(pTexture, i);
}
}
void D3D9Initializer::FlushImplicit() {
if (m_transferCommands > MaxTransferCommands
|| m_transferMemory > MaxTransferMemory)
FlushInternal();
}
void D3D9Initializer::FlushInternal() {
m_context->flushCommandList();
m_transferCommands = 0;
m_transferMemory = 0;
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/common/common.h>
#include "NeuralNetworksWrapper.h"
namespace android {
namespace nn {
namespace wrapper {
OperandType::OperandType(Type type, const std::vector<uint32_t>& d, float scale, int32_t zeroPoint)
: type(type), dimensions(d) {
operandType = {
.type = static_cast<int32_t>(type),
.dimensionCount = static_cast<uint32_t>(dimensions.size()),
.dimensions = dimensions.size() > 0 ? dimensions.data() : nullptr,
.scale = scale,
.zeroPoint = zeroPoint,
};
}
OperandType::OperandType(Type type, const std::vector<uint32_t>& d, SymmPerChannelQuantParams&& channelQuant)
: type(type), dimensions(d), channelQuant(std::move(channelQuant)) {
operandType = {
.type = static_cast<int32_t>(type),
.dimensionCount = static_cast<uint32_t>(dimensions.size()),
.dimensions = dimensions.size() > 0 ? dimensions.data() : nullptr,
.scale = 0.0f,
.zeroPoint = 0,
};
}
OperandType::OperandType(const OperandType& other)
: operandType(other.operandType),
type(other.type),
dimensions(other.dimensions),
channelQuant(other.channelQuant) {
operandType.dimensions = dimensions.size() > 0 ? dimensions.data() : nullptr;
}
OperandType& OperandType::operator=(const OperandType& other) {
if (this != &other) {
type = other.type;
dimensions = other.dimensions;
operandType = other.operandType;
channelQuant = other.channelQuant;
operandType.dimensions = dimensions.size() > 0 ? dimensions.data() : nullptr;
}
return *this;
}
size_t OperandType::GetElementByteSize() const {
size_t element_size;
switch (type) {
case Type::TENSOR_BOOL8:
element_size = 1;
break;
case Type::TENSOR_FLOAT16:
element_size = 2;
break;
case Type::TENSOR_FLOAT32:
case Type::FLOAT32:
element_size = 4;
break;
case Type::TENSOR_INT32:
element_size = 4;
break;
case Type::TENSOR_QUANT8_SYMM_PER_CHANNEL:
element_size = 1;
break;
case Type::TENSOR_QUANT8_ASYMM:
element_size = 1;
break;
case Type::TENSOR_QUANT16_SYMM:
element_size = 2;
break;
case Type::TENSOR_QUANT16_ASYMM:
element_size = 2;
break;
default:
ORT_THROW("Wrong type: " + TypeToStr(type));
}
return element_size;
}
size_t OperandType::GetOperandBlobByteSize() const {
return Product(dimensions) * GetElementByteSize();
}
void OperandType::SetDimensions(const std::vector<uint32_t>& d) {
dimensions = d;
operandType.dimensionCount = dimensions.size();
operandType.dimensions = dimensions.size() > 0 ? dimensions.data() : nullptr;
}
} // namespace wrapper
} // namespace nn
} // namespace android
|
/// HEADER
#include <csapex_transform/transform_message.h>
/// PROJECT
#include <csapex/utility/assert.h>
#include <csapex/utility/register_msg.h>
/// SYSTEM
// clang-format off
#include <csapex/utility/suppress_warnings_start.h>
#include <tf/transform_datatypes.h>
#include <csapex/utility/suppress_warnings_end.h>
// clang-format on
CSAPEX_REGISTER_MESSAGE(csapex::connection_types::TransformMessage)
using namespace csapex;
using namespace connection_types;
TransformMessage::TransformMessage(const std::string& frame_id, const std::string& child_frame_id) : MessageTemplate<tf::Transform, TransformMessage>(frame_id), child_frame(child_frame_id)
{
sanitize();
}
TransformMessage::TransformMessage() : MessageTemplate<tf::Transform, TransformMessage>(""), child_frame("")
{
}
void TransformMessage::sanitize()
{
if (frame_id.size() > 0 && frame_id.at(0) == '/') {
frame_id = frame_id.substr(1);
}
if (child_frame.size() > 0 && child_frame.at(0) == '/') {
child_frame = child_frame.substr(1);
}
}
bool TransformMessage::cloneData(const TransformMessage& other)
{
if (!Message::cloneDataFrom(other)) {
return false;
}
child_frame = other.child_frame;
value = other.value;
return true;
}
/// YAML
namespace YAML
{
Node convert<csapex::connection_types::TransformMessage>::encode(const csapex::connection_types::TransformMessage& rhs)
{
const tf::Quaternion& q = rhs.value.getRotation();
const tf::Vector3& t = rhs.value.getOrigin();
Node node = convert<csapex::connection_types::Message>::encode(rhs);
node["child_frame"] = rhs.child_frame;
node["orientation"].push_back(q.x());
node["orientation"].push_back(q.y());
node["orientation"].push_back(q.z());
node["orientation"].push_back(q.w());
node["translation"].push_back(t.x());
node["translation"].push_back(t.y());
node["translation"].push_back(t.z());
return node;
}
bool convert<csapex::connection_types::TransformMessage>::decode(const Node& node, csapex::connection_types::TransformMessage& rhs)
{
if (!node.IsMap()) {
return false;
}
convert<csapex::connection_types::Message>::decode(node, rhs);
if (node["child_frame"].IsDefined()) {
rhs.child_frame = node["child_frame"].as<std::string>();
}
std::vector<float> o = node["orientation"].as<std::vector<float>>();
std::vector<float> t = node["translation"].as<std::vector<float>>();
if (o.size() != 4 || t.size() != 3) {
return false;
}
rhs.value = tf::Transform(tf::Quaternion(o[0], o[1], o[2], o[3]), tf::Vector3(t[0], t[1], t[2]));
rhs.sanitize();
return true;
}
} // namespace YAML
|
#include <stdio.h>
using namespace std;
#define REP(a, i, n) for (int i = a; i < n; ++i)
int max(int X, int Y) {
return X > Y ? X : Y;
}
int main() {
int N;
scanf("%d", &N);
int A[2][N];
REP(0, i, 2) REP(0, j, N) {
scanf("%d", &A[i][j]);
}
int ans = 0;
REP(0, k, N) {
int temp = 0;
REP(0, j, k + 1) {
temp += A[0][j];
}
REP(k, j, N) {
temp += A[1][j];
}
ans = max(temp, ans);
}
printf("%d\n", ans);
return 0;
}
|
// Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "perf_buildid.h"
#include <cstdint>
#include <string>
namespace quipper {
void PerfizeBuildIDString(string* build_id) {
build_id->resize(kBuildIDStringLength, '0');
}
void TrimZeroesFromBuildIDString(string* build_id) {
const size_t kPaddingSize = 8;
const string kBuildIDPadding = string(kPaddingSize, '0');
// Remove kBuildIDPadding from the end of build_id until we cannot remove any
// more. The build ID string can be reduced down to an empty string. This
// could happen if the file did not have a build ID but was given a build ID
// of all zeroes. The empty build ID string would reflect the original lack of
// build ID.
while (build_id->size() >= kPaddingSize &&
build_id->substr(build_id->size() - kPaddingSize) == kBuildIDPadding) {
build_id->resize(build_id->size() - kPaddingSize);
}
}
} // namespace quipper
|
/**
* SCILL API
* SCILL gives you the tools to activate, retain and grow your user base in your app or game by bringing you features well known in the gaming industry: Gamification. We take care of the services and technology involved so you can focus on your game and content.
*
* OpenAPI spec version: 1.0.0
* Contact: support@scillgame.com
*
* NOTE: This class is auto generated by OpenAPI Generator
* https://github.com/OpenAPITools/openapi-generator
* Do not edit the class manually.
*/
#include "ScillApiWrapper/ScillApiBattlePassLevelId.h"
#include "ScillSDK.h"
#include "ScillApiWrapper/ScillApiHelpers.h"
#include "Templates/SharedPointer.h"
namespace ScillSDK
{
void ScillApiBattlePassLevelId::WriteJson(JsonWriter& Writer) const
{
Writer->WriteObjectStart();
Writer->WriteIdentifierPrefix(TEXT("battle_pass_level_id")); WriteJsonValue(Writer, BattlePassLevelId);
Writer->WriteObjectEnd();
}
bool ScillApiBattlePassLevelId::FromJson(const TSharedPtr<FJsonValue>& JsonValue)
{
const TSharedPtr<FJsonObject>* Object;
if (!JsonValue->TryGetObject(Object))
return false;
bool ParseSuccess = true;
ParseSuccess &= TryGetJsonValue(*Object, TEXT("battle_pass_level_id"), BattlePassLevelId);
return ParseSuccess;
}
}
|
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include <list>
#include <string>
#include <memory>
#include <utility>
#include "actor/actormgr.h"
#include "actor/iomgr.h"
namespace mindspore {
ActorMgr ActorMgr::actorMgr;
std::map<std::string, std::shared_ptr<IOMgr>> ActorMgr::ioMgrs;
std::shared_ptr<IOMgr> &ActorMgr::GetIOMgrRef(const std::string &protocol) {
auto it = ioMgrs.find(protocol);
if (it != ioMgrs.end()) {
return it->second;
} else {
MS_LOG(DEBUG) << "Can't find IOMgr of protocol " << protocol.c_str();
static std::shared_ptr<IOMgr> nullIOMgr;
return nullIOMgr;
}
}
ActorMgr::ActorMgr() : actors(), procotols(), urls() {
actors.clear();
procotols.clear();
urls.clear();
}
ActorMgr::~ActorMgr() {
if (inner_pool_ != nullptr) {
delete inner_pool_;
inner_pool_ = nullptr;
}
}
int ActorMgr::Initialize(bool use_inner_pool, size_t actor_thread_num, size_t max_thread_num) {
bool expected = false;
if (!initialized_.compare_exchange_strong(expected, true)) {
MS_LOG(DEBUG) << "Actor Manager has been initialized before";
return MINDRT_OK;
}
// create inner thread pool only when specified use_inner_pool
if (use_inner_pool) {
if (max_thread_num <= actor_thread_num) {
inner_pool_ = ActorThreadPool::CreateThreadPool(actor_thread_num);
if (inner_pool_ == nullptr) {
MS_LOG(ERROR) << "ActorMgr CreateThreadPool failed";
return MINDRT_ERROR;
}
} else {
inner_pool_ = ActorThreadPool::CreateThreadPool(actor_thread_num, max_thread_num, {});
if (inner_pool_ == nullptr) {
MS_LOG(ERROR) << "ActorMgr CreateThreadPool failed";
return MINDRT_ERROR;
}
inner_pool_->SetActorThreadNum(actor_thread_num);
inner_pool_->DisableOccupiedActorThread();
inner_pool_->SetKernelThreadNum(max_thread_num - actor_thread_num);
}
if (inner_pool_ != nullptr) {
inner_pool_->SetMaxSpinCount(kDefaultSpinCount);
inner_pool_->SetSpinCountMaxValue();
}
}
return MINDRT_OK;
}
void ActorMgr::SetActorReady(const ActorReference &actor) const {
// use inner thread pool or actor thread pool created externally
// priority to use actor thread pool
MINDRT_OOM_EXIT(actor);
ActorThreadPool *pool = actor->pool_ ? actor->pool_ : inner_pool_;
if (pool == nullptr) {
MS_LOG(ERROR) << "ThreadPool is nullptr, " << actor->pool_ << ", " << inner_pool_
<< ", actor: " << actor->GetAID().Name();
return;
}
pool->PushActorToQueue(actor.get());
}
const std::string ActorMgr::GetUrl(const std::string &protocol) {
auto it = procotols.find(protocol);
if (it != procotols.end()) {
return it->second;
} else if (procotols.size() > 0) {
return procotols.begin()->second;
} else {
return "";
}
}
void ActorMgr::AddUrl(const std::string &protocol, const std::string &url) {
procotols[protocol] = url;
AID id("a@" + url);
(void)urls.insert(id.GetIp() + ":" + std::to_string(id.GetPort()));
(void)urls.insert(id.GetProtocol() + "://" + id.GetIp() + ":" + std::to_string(id.GetPort()));
(void)urls.insert(std::string("127.0.0.1:") + std::to_string(id.GetPort()));
(void)urls.insert(protocol + "://127.0.0.1:" + std::to_string(id.GetPort()));
}
void ActorMgr::AddIOMgr(const std::string &protocol, const std::shared_ptr<IOMgr> &ioMgr) { ioMgrs[protocol] = ioMgr; }
void ActorMgr::RemoveActor(const std::string &name) {
actorsMutex.lock();
(void)actors.erase(name);
actorsMutex.unlock();
}
void ActorMgr::TerminateAll() {
// copy all the actors
std::list<ActorReference> actorsWaiting;
actorsMutex.lock();
for (auto actorIt = actors.begin(); actorIt != actors.end(); ++actorIt) {
actorsWaiting.push_back(actorIt->second);
}
actorsMutex.unlock();
// send terminal msg to all actors.
for (auto actorIt = actorsWaiting.begin(); actorIt != actorsWaiting.end(); ++actorIt) {
(*actorIt)->Terminate();
}
// wait actor's thread to finish.
for (auto actorIt = actorsWaiting.begin(); actorIt != actorsWaiting.end(); ++actorIt) {
(*actorIt)->Await();
}
}
void ActorMgr::Finalize() {
this->TerminateAll();
MS_LOG(INFO) << "mindrt Actors finish exiting.";
// stop all actor threads;
MS_LOG(INFO) << "mindrt Threads finish exiting.";
// stop iomgr thread
for (auto mgrIt = ioMgrs.begin(); mgrIt != ioMgrs.end(); ++mgrIt) {
MS_LOG(INFO) << "finalize IOMgr=" << mgrIt->first.c_str();
mgrIt->second->Finish();
}
// delete actor thread pool if use_inner_pool
delete inner_pool_;
inner_pool_ = nullptr;
MS_LOG(INFO) << "mindrt IOMGRS finish exiting.";
}
ActorReference ActorMgr::GetActor(const AID &id) {
#ifndef MS_COMPILE_IOS
actorsMutex.lock_shared();
#else
actorsMutex.lock();
#endif
const auto &actorIt = actors.find(id.Name());
if (actorIt != actors.end()) {
auto &result = actorIt->second;
#ifndef MS_COMPILE_IOS
actorsMutex.unlock_shared();
#else
actorsMutex.unlock();
#endif
return result;
} else {
#ifndef MS_COMPILE_IOS
actorsMutex.unlock_shared();
#else
actorsMutex.unlock();
#endif
MS_LOG(DEBUG) << "can't find ACTOR with name=" << id.Name().c_str();
return nullptr;
}
}
int ActorMgr::EnqueueMessage(const mindspore::ActorReference actor, std::unique_ptr<mindspore::MessageBase> msg) {
return actor->EnqueMessage(std::move(msg));
}
int ActorMgr::Send(const AID &to, std::unique_ptr<MessageBase> msg, bool remoteLink, bool isExactNotRemote) {
// The destination is local
if (IsLocalAddres(to)) {
auto actor = GetActor(to);
if (actor != nullptr) {
if (to.GetProtocol() == MINDRT_UDP && msg->GetType() == MessageBase::Type::KMSG) {
msg->type = MessageBase::Type::KUDP;
}
return EnqueueMessage(actor, std::move(msg));
} else {
return ACTOR_NOT_FIND;
}
} else {
// send to remote actor
if (msg->GetType() != MessageBase::Type::KMSG) {
MS_LOG(ERROR) << "The msg is not KMSG,it can't send to remote=" << std::string(to).c_str();
return ACTOR_PARAMER_ERR;
} else {
// null
}
msg->SetTo(to);
auto &io = ActorMgr::GetIOMgrRef(to);
if (io != nullptr) {
return io->Send(std::move(msg), remoteLink, isExactNotRemote);
} else {
MS_LOG(ERROR) << "The protocol is not supported:"
<< "p=" << to.GetProtocol().c_str() << ",f=" << msg->From().Name().c_str()
<< ",t=" << to.Name().c_str() << ",m=" << msg->Name().c_str();
return IO_NOT_FIND;
}
}
}
AID ActorMgr::Spawn(const ActorReference &actor, bool shareThread) {
actorsMutex.lock();
if (actors.find(actor->GetAID().Name()) != actors.end()) {
actorsMutex.unlock();
MS_LOG(ERROR) << "The actor's name conflicts,name:" << actor->GetAID().Name().c_str();
MINDRT_EXIT("Actor name conflicts.");
}
MS_LOG(DEBUG) << "ACTOR was spawned,a=" << actor->GetAID().Name().c_str();
if (shareThread) {
auto mailbox = std::unique_ptr<MailBox>(new (std::nothrow) NonblockingMailBox());
auto hook = std::unique_ptr<std::function<void()>>(
new std::function<void()>([actor]() { ActorMgr::GetActorMgrRef()->SetActorReady(actor); }));
// the mailbox has this hook, the hook holds the actor reference, the actor has the mailbox. this is a cycle which
// will leads to memory leak. in order to fix this issue, we should explicitly free the mailbox when terminate the
// actor
mailbox->SetNotifyHook(std::move(hook));
actor->Spawn(actor, std::move(mailbox));
} else {
auto mailbox = std::unique_ptr<MailBox>(new (std::nothrow) BlockingMailBox());
actor->Spawn(actor, std::move(mailbox));
ActorMgr::GetActorMgrRef()->SetActorReady(actor);
}
(void)this->actors.emplace(actor->GetAID().Name(), actor);
actorsMutex.unlock();
// long time
actor->Init();
return actor->GetAID();
}
void ActorMgr::Terminate(const AID &id) {
auto actor = GetActor(id);
if (actor != nullptr) {
actor->Terminate();
// Wait actor's thread to finish.
actor->Await();
RemoveActor(id.Name());
}
}
void ActorMgr::Wait(const AID &id) {
auto actor = GetActor(id);
if (actor != nullptr) {
actor->Await();
}
}
}; // end of namespace mindspore
|
#include <memory>
#include <vector>
#include "common/event/dispatcher_impl.h"
#include "common/network/utility.h"
#include "common/tcp/conn_pool.h"
#include "common/tcp/original_conn_pool.h"
#include "common/upstream/upstream_impl.h"
#include "test/common/upstream/utility.h"
#include "test/mocks/common.h"
#include "test/mocks/event/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/tcp/mocks.h"
#include "test/mocks/upstream/cluster_info.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::NiceMock;
using testing::Property;
using testing::Return;
namespace Envoy {
namespace Tcp {
namespace {
struct TestConnectionState : public ConnectionPool::ConnectionState {
TestConnectionState(int id, std::function<void()> on_destructor)
: id_(id), on_destructor_(on_destructor) {}
~TestConnectionState() override { on_destructor_(); }
int id_;
std::function<void()> on_destructor_;
};
} // namespace
/**
* Mock callbacks used for conn pool testing.
*/
struct ConnPoolCallbacks : public Tcp::ConnectionPool::Callbacks {
void onPoolReady(ConnectionPool::ConnectionDataPtr&& conn,
Upstream::HostDescriptionConstSharedPtr host) override {
conn_data_ = std::move(conn);
host_ = host;
pool_ready_.ready();
}
void onPoolFailure(ConnectionPool::PoolFailureReason reason,
Upstream::HostDescriptionConstSharedPtr host) override {
reason_ = reason;
host_ = host;
pool_failure_.ready();
}
ReadyWatcher pool_failure_;
ReadyWatcher pool_ready_;
ConnectionPool::ConnectionDataPtr conn_data_{};
absl::optional<ConnectionPool::PoolFailureReason> reason_;
Upstream::HostDescriptionConstSharedPtr host_;
};
/**
* A wrapper around a ConnectionPoolImpl which tracks when the bridge between
* the pool and the consumer of the connection is released and destroyed.
*/
class ConnPoolBase : public Tcp::ConnectionPool::Instance {
public:
ConnPoolBase(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb,
bool test_new_connection_pool);
void addDrainedCallback(DrainedCb cb) override { conn_pool_->addDrainedCallback(cb); }
void drainConnections() override { conn_pool_->drainConnections(); }
void closeConnections() override { conn_pool_->closeConnections(); }
ConnectionPool::Cancellable* newConnection(Tcp::ConnectionPool::Callbacks& callbacks) override {
return conn_pool_->newConnection(callbacks);
}
Upstream::HostDescriptionConstSharedPtr host() const override { return conn_pool_->host(); }
MOCK_METHOD(void, onConnReleasedForTest, ());
MOCK_METHOD(void, onConnDestroyedForTest, ());
struct TestConnection {
Network::MockClientConnection* connection_;
Event::MockTimer* connect_timer_;
Network::ReadFilterSharedPtr filter_;
};
void expectConnCreate() {
test_conns_.emplace_back();
TestConnection& test_conn = test_conns_.back();
test_conn.connection_ = new NiceMock<Network::MockClientConnection>();
test_conn.connect_timer_ = new NiceMock<Event::MockTimer>(&mock_dispatcher_);
EXPECT_CALL(mock_dispatcher_, createClientConnection_(_, _, _, _))
.WillOnce(Return(test_conn.connection_));
EXPECT_CALL(*test_conn.connection_, addReadFilter(_))
.WillOnce(Invoke(
[&](Network::ReadFilterSharedPtr filter) -> void { test_conn.filter_ = filter; }));
EXPECT_CALL(*test_conn.connection_, connect());
EXPECT_CALL(*test_conn.connect_timer_, enableTimer(_, _));
ON_CALL(*test_conn.connection_, close(Network::ConnectionCloseType::NoFlush))
.WillByDefault(InvokeWithoutArgs([test_conn]() -> void {
test_conn.connection_->raiseEvent(Network::ConnectionEvent::LocalClose);
}));
}
void expectEnableUpstreamReady(bool run);
std::unique_ptr<Tcp::ConnectionPool::Instance> conn_pool_;
Event::MockDispatcher& mock_dispatcher_;
NiceMock<Event::MockSchedulableCallback>* mock_upstream_ready_cb_;
std::vector<TestConnection> test_conns_;
Network::ConnectionCallbacks* callbacks_ = nullptr;
bool test_new_connection_pool_;
protected:
class ConnPoolImplForTest : public ConnPoolImpl {
public:
ConnPoolImplForTest(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
ConnPoolBase& parent)
: ConnPoolImpl(dispatcher, host, Upstream::ResourcePriority::Default, nullptr, nullptr),
parent_(parent) {}
void onConnReleased(Envoy::ConnectionPool::ActiveClient& client) override {
ConnPoolImpl::onConnReleased(client);
parent_.onConnReleasedForTest();
}
void onConnDestroyed() override { parent_.onConnDestroyedForTest(); }
ConnPoolBase& parent_;
};
class OriginalConnPoolImplForTest : public OriginalConnPoolImpl {
public:
OriginalConnPoolImplForTest(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
ConnPoolBase& parent)
: OriginalConnPoolImpl(dispatcher, host, Upstream::ResourcePriority::Default, nullptr,
nullptr),
parent_(parent) {}
~OriginalConnPoolImplForTest() override {
EXPECT_EQ(0U, ready_conns_.size());
EXPECT_EQ(0U, busy_conns_.size());
EXPECT_EQ(0U, pending_requests_.size());
}
void onConnReleased(OriginalConnPoolImpl::ActiveConn& conn) override {
parent_.onConnReleasedForTest();
OriginalConnPoolImpl::onConnReleased(conn);
}
void onConnDestroyed(OriginalConnPoolImpl::ActiveConn& conn) override {
parent_.onConnDestroyedForTest();
OriginalConnPoolImpl::onConnDestroyed(conn);
}
void expectEnableUpstreamReady(bool run) {
if (!run) {
EXPECT_FALSE(upstream_ready_enabled_);
EXPECT_CALL(*parent_.mock_upstream_ready_cb_, scheduleCallbackCurrentIteration())
.Times(1)
.RetiresOnSaturation();
} else {
EXPECT_TRUE(upstream_ready_enabled_);
parent_.mock_upstream_ready_cb_->invokeCallback();
EXPECT_FALSE(upstream_ready_enabled_);
}
}
ConnPoolBase& parent_;
};
};
ConnPoolBase::ConnPoolBase(Event::MockDispatcher& dispatcher, Upstream::HostSharedPtr host,
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb,
bool test_new_connection_pool)
: mock_dispatcher_(dispatcher), mock_upstream_ready_cb_(upstream_ready_cb),
test_new_connection_pool_(test_new_connection_pool) {
if (test_new_connection_pool_) {
conn_pool_ = std::make_unique<ConnPoolImplForTest>(dispatcher, host, *this);
} else {
conn_pool_ = std::make_unique<OriginalConnPoolImplForTest>(dispatcher, host, *this);
}
}
void ConnPoolBase::expectEnableUpstreamReady(bool run) {
if (!test_new_connection_pool_) {
dynamic_cast<OriginalConnPoolImplForTest*>(conn_pool_.get())->expectEnableUpstreamReady(run);
} else {
if (!run) {
EXPECT_CALL(*mock_upstream_ready_cb_, scheduleCallbackCurrentIteration())
.Times(1)
.RetiresOnSaturation();
} else {
mock_upstream_ready_cb_->invokeCallback();
}
}
}
/**
* Test fixture for connection pool tests.
*/
class TcpConnPoolImplTest : public testing::TestWithParam<bool> {
public:
TcpConnPoolImplTest()
: test_new_connection_pool_(GetParam()),
upstream_ready_cb_(new NiceMock<Event::MockSchedulableCallback>(&dispatcher_)),
host_(Upstream::makeTestHost(cluster_, "tcp://127.0.0.1:9000")),
conn_pool_(dispatcher_, host_, upstream_ready_cb_, test_new_connection_pool_) {}
~TcpConnPoolImplTest() override {
EXPECT_TRUE(TestUtility::gaugesZeroed(cluster_->stats_store_.gauges()))
<< TestUtility::nonZeroedGauges(cluster_->stats_store_.gauges());
}
bool test_new_connection_pool_;
NiceMock<Event::MockDispatcher> dispatcher_;
std::shared_ptr<Upstream::MockClusterInfo> cluster_{new NiceMock<Upstream::MockClusterInfo>()};
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb_;
Upstream::HostSharedPtr host_;
ConnPoolBase conn_pool_;
NiceMock<Runtime::MockLoader> runtime_;
};
/**
* Test fixture for connection pool destructor tests.
*/
class TcpConnPoolImplDestructorTest : public testing::TestWithParam<bool> {
public:
TcpConnPoolImplDestructorTest()
: test_new_connection_pool_(GetParam()),
upstream_ready_cb_(new NiceMock<Event::MockSchedulableCallback>(&dispatcher_)) {
host_ = Upstream::makeTestHost(cluster_, "tcp://127.0.0.1:9000");
if (test_new_connection_pool_) {
conn_pool_ = std::make_unique<ConnPoolImpl>(
dispatcher_, host_, Upstream::ResourcePriority::Default, nullptr, nullptr);
} else {
conn_pool_ = std::make_unique<OriginalConnPoolImpl>(
dispatcher_, host_, Upstream::ResourcePriority::Default, nullptr, nullptr);
}
}
~TcpConnPoolImplDestructorTest() override = default;
void prepareConn() {
connection_ = new NiceMock<Network::MockClientConnection>();
connect_timer_ = new NiceMock<Event::MockTimer>(&dispatcher_);
EXPECT_CALL(dispatcher_, createClientConnection_(_, _, _, _)).WillOnce(Return(connection_));
EXPECT_CALL(*connect_timer_, enableTimer(_, _));
callbacks_ = std::make_unique<ConnPoolCallbacks>();
ConnectionPool::Cancellable* handle = conn_pool_->newConnection(*callbacks_);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(*connect_timer_, disableTimer());
EXPECT_CALL(callbacks_->pool_ready_, ready());
connection_->raiseEvent(Network::ConnectionEvent::Connected);
}
bool test_new_connection_pool_;
Upstream::HostConstSharedPtr host_;
NiceMock<Event::MockDispatcher> dispatcher_;
std::shared_ptr<Upstream::MockClusterInfo> cluster_{new NiceMock<Upstream::MockClusterInfo>()};
NiceMock<Event::MockSchedulableCallback>* upstream_ready_cb_;
NiceMock<Event::MockTimer>* connect_timer_;
NiceMock<Network::MockClientConnection>* connection_;
std::unique_ptr<Tcp::ConnectionPool::Instance> conn_pool_;
std::unique_ptr<ConnPoolCallbacks> callbacks_;
};
/**
* Helper for dealing with an active test connection.
*/
struct ActiveTestConn {
enum class Type {
Pending, // pending request, waiting for free connection
InProgress, // connection created, no callback
CreateConnection, // connection callback occurs after newConnection
Immediate, // connection callback occurs during newConnection
};
ActiveTestConn(TcpConnPoolImplTest& parent, size_t conn_index, Type type)
: parent_(parent), conn_index_(conn_index) {
if (type == Type::CreateConnection || type == Type::InProgress) {
parent.conn_pool_.expectConnCreate();
}
if (type == Type::Immediate) {
expectNewConn();
}
handle_ = parent.conn_pool_.newConnection(callbacks_);
if (type == Type::Immediate) {
EXPECT_EQ(nullptr, handle_);
verifyConn();
} else {
EXPECT_NE(nullptr, handle_);
}
if (type == Type::CreateConnection) {
completeConnection();
}
}
void completeConnection() {
ASSERT_FALSE(completed_);
EXPECT_CALL(*parent_.conn_pool_.test_conns_[conn_index_].connect_timer_, disableTimer());
expectNewConn();
parent_.conn_pool_.test_conns_[conn_index_].connection_->raiseEvent(
Network::ConnectionEvent::Connected);
verifyConn();
completed_ = true;
}
void expectNewConn() { EXPECT_CALL(callbacks_.pool_ready_, ready()); }
void releaseConn() { callbacks_.conn_data_.reset(); }
void verifyConn() {
EXPECT_EQ(&callbacks_.conn_data_->connection(),
parent_.conn_pool_.test_conns_[conn_index_].connection_);
}
TcpConnPoolImplTest& parent_;
size_t conn_index_;
Tcp::ConnectionPool::Cancellable* handle_{};
ConnPoolCallbacks callbacks_;
bool completed_{};
};
TEST_P(TcpConnPoolImplTest, HostAccessor) { EXPECT_EQ(conn_pool_.host(), host_); }
/**
* Verify that connections are drained when requested.
*/
TEST_P(TcpConnPoolImplTest, DrainConnections) {
cluster_->resetResourceManager(3, 1024, 1024, 1, 1);
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c2(*this, 1, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c3(*this, 2, ActiveTestConn::Type::InProgress);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c1.releaseConn();
{
// This will destroy the ready connection and set requests remaining to 1 on the busy and
// pending connections.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.drainConnections();
dispatcher_.clearDeferredDeleteList();
}
{
// This will destroy the busy connection when the response finishes.
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
c2.releaseConn();
dispatcher_.clearDeferredDeleteList();
}
{
// This will destroy the pending connection when the response finishes.
c3.completeConnection();
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
c3.releaseConn();
dispatcher_.clearDeferredDeleteList();
}
}
/**
* Test all timing stats are set.
*/
TEST_P(TcpConnPoolImplTest, VerifyTimingStats) {
EXPECT_CALL(cluster_->stats_store_,
deliverHistogramToSinks(Property(&Stats::Metric::name, "upstream_cx_connect_ms"), _));
EXPECT_CALL(cluster_->stats_store_,
deliverHistogramToSinks(Property(&Stats::Metric::name, "upstream_cx_length_ms"), _));
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c1.releaseConn();
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that buffer limits are set.
*/
TEST_P(TcpConnPoolImplTest, VerifyBufferLimits) {
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
EXPECT_CALL(*cluster_, perConnectionBufferLimitBytes()).WillOnce(Return(8192));
EXPECT_CALL(*conn_pool_.test_conns_.back().connection_, setBufferLimits(8192));
EXPECT_CALL(callbacks.pool_failure_, ready());
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that upstream callback fire for assigned connections.
*/
TEST_P(TcpConnPoolImplTest, UpstreamCallbacks) {
Buffer::OwnedImpl buffer;
ConnectionPool::MockUpstreamCallbacks callbacks;
// Create connection, set UpstreamCallbacks
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
c1.callbacks_.conn_data_->addUpstreamCallbacks(callbacks);
// Expect invocation when connection's ReadFilter::onData is invoked
EXPECT_CALL(callbacks, onUpstreamData(_, _));
EXPECT_EQ(Network::FilterStatus::StopIteration,
conn_pool_.test_conns_[0].filter_->onData(buffer, false));
EXPECT_CALL(callbacks, onAboveWriteBufferHighWatermark());
for (auto* cb : conn_pool_.test_conns_[0].connection_->callbacks_) {
cb->onAboveWriteBufferHighWatermark();
}
EXPECT_CALL(callbacks, onBelowWriteBufferLowWatermark());
for (auto* cb : conn_pool_.test_conns_[0].connection_->callbacks_) {
cb->onBelowWriteBufferLowWatermark();
}
// Shutdown normally.
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c1.releaseConn();
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that upstream callback close event fires for assigned connections.
*/
TEST_P(TcpConnPoolImplTest, UpstreamCallbacksCloseEvent) {
Buffer::OwnedImpl buffer;
ConnectionPool::MockUpstreamCallbacks callbacks;
// Create connection, set UpstreamCallbacks
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
c1.callbacks_.conn_data_->addUpstreamCallbacks(callbacks);
EXPECT_CALL(callbacks, onEvent(Network::ConnectionEvent::RemoteClose));
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that a connection pool functions without upstream callbacks.
*/
TEST_P(TcpConnPoolImplTest, NoUpstreamCallbacks) {
Buffer::OwnedImpl buffer;
// Create connection.
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
// Trigger connection's ReadFilter::onData -- connection pool closes connection.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
EXPECT_EQ(Network::FilterStatus::StopIteration,
conn_pool_.test_conns_[0].filter_->onData(buffer, false));
dispatcher_.clearDeferredDeleteList();
}
/**
* Tests a request that generates a new connection, completes, and then a second request that uses
* the same connection.
*/
TEST_P(TcpConnPoolImplTest, MultipleRequestAndResponse) {
// Request 1 should kick off a new connection.
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c1.releaseConn();
// Request 2 should not.
ActiveTestConn c2(*this, 0, ActiveTestConn::Type::Immediate);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c2.releaseConn();
// Cause the connection to go away.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Tests ConnectionState assignment, lookup and destruction.
*/
TEST_P(TcpConnPoolImplTest, ConnectionStateLifecycle) {
bool state_destroyed = false;
// Request 1 should kick off a new connection.
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
auto* state = new TestConnectionState(1, [&]() -> void { state_destroyed = true; });
c1.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(state));
EXPECT_EQ(state, c1.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c1.releaseConn();
EXPECT_FALSE(state_destroyed);
// Request 2 should not.
ActiveTestConn c2(*this, 0, ActiveTestConn::Type::Immediate);
EXPECT_EQ(state, c2.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
c2.releaseConn();
EXPECT_FALSE(state_destroyed);
// Cause the connection to go away.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_TRUE(state_destroyed);
}
/**
* Test when we overflow max pending requests.
*/
TEST_P(TcpConnPoolImplTest, MaxPendingRequests) {
cluster_->resetResourceManager(1, 1, 1024, 1, 1);
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
ConnPoolCallbacks callbacks2;
EXPECT_CALL(callbacks2.pool_failure_, ready());
Tcp::ConnectionPool::Cancellable* handle2 = conn_pool_.newConnection(callbacks2);
EXPECT_EQ(nullptr, handle2);
handle->cancel(ConnectionPool::CancelPolicy::Default);
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::Overflow, callbacks2.reason_);
EXPECT_EQ(1U, cluster_->stats_.upstream_rq_pending_overflow_.value());
}
/**
* Tests a connection failure before a request is bound which should result in the pending request
* getting purged.
*/
TEST_P(TcpConnPoolImplTest, RemoteConnectFailure) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_failure_, ready());
EXPECT_CALL(*conn_pool_.test_conns_[0].connect_timer_, disableTimer());
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::RemoteConnectionFailure, callbacks.reason_);
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_connect_fail_.value());
EXPECT_EQ(1U, cluster_->stats_.upstream_rq_pending_failure_eject_.value());
}
/**
* Tests a connection failure before a request is bound which should result in the pending request
* getting purged.
*/
TEST_P(TcpConnPoolImplTest, LocalConnectFailure) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_failure_, ready());
EXPECT_CALL(*conn_pool_.test_conns_[0].connect_timer_, disableTimer());
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::LocalClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::LocalConnectionFailure, callbacks.reason_);
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_connect_fail_.value());
EXPECT_EQ(1U, cluster_->stats_.upstream_rq_pending_failure_eject_.value());
}
/**
* Tests a connect timeout. Also test that we can add a new request during ejection processing.
*/
TEST_P(TcpConnPoolImplTest, ConnectTimeout) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks1;
conn_pool_.expectConnCreate();
EXPECT_NE(nullptr, conn_pool_.newConnection(callbacks1));
ConnPoolCallbacks callbacks2;
EXPECT_CALL(callbacks1.pool_failure_, ready()).WillOnce(Invoke([&]() -> void {
conn_pool_.expectConnCreate();
EXPECT_NE(nullptr, conn_pool_.newConnection(callbacks2));
}));
conn_pool_.test_conns_[0].connect_timer_->invokeCallback();
EXPECT_CALL(callbacks2.pool_failure_, ready());
conn_pool_.test_conns_[1].connect_timer_->invokeCallback();
EXPECT_CALL(conn_pool_, onConnDestroyedForTest()).Times(2);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(ConnectionPool::PoolFailureReason::Timeout, callbacks1.reason_);
EXPECT_EQ(ConnectionPool::PoolFailureReason::Timeout, callbacks2.reason_);
EXPECT_EQ(2U, cluster_->stats_.upstream_cx_connect_fail_.value());
EXPECT_EQ(2U, cluster_->stats_.upstream_cx_connect_timeout_.value());
}
/**
* Test cancelling before the request is bound to a connection.
*/
TEST_P(TcpConnPoolImplTest, CancelBeforeBound) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
handle->cancel(ConnectionPool::CancelPolicy::Default);
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Cause the connection to go away.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test cancelling before the request is bound to a connection, with connection close.
*/
TEST_P(TcpConnPoolImplTest, CancelAndCloseBeforeBound) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
// Expect the connection is closed.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
handle->cancel(ConnectionPool::CancelPolicy::CloseExcess);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test an upstream disconnection while there is a bound request.
*/
TEST_P(TcpConnPoolImplTest, DisconnectWhileBound) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_ready_, ready());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Kill the connection while it has an active request.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test upstream disconnection of one request while another is pending.
*/
TEST_P(TcpConnPoolImplTest, DisconnectWhilePending) {
cluster_->resetResourceManager(1, 1024, 1024, 1, 1);
// First request connected.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(*conn_pool_.test_conns_[0].connect_timer_, disableTimer());
EXPECT_CALL(callbacks.pool_ready_, ready());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Second request pending.
ConnPoolCallbacks callbacks2;
ConnectionPool::Cancellable* handle2 = conn_pool_.newConnection(callbacks2);
EXPECT_NE(nullptr, handle2);
// Connection closed, triggering new connection for pending request.
conn_pool_.expectConnCreate();
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::LocalClose);
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
dispatcher_.clearDeferredDeleteList();
// test_conns_[1] is the new connection
EXPECT_CALL(*conn_pool_.test_conns_[1].connect_timer_, disableTimer());
EXPECT_CALL(callbacks2.pool_ready_, ready());
conn_pool_.test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
callbacks2.conn_data_.reset();
// Disconnect
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that we correctly handle reaching max connections.
*/
TEST_P(TcpConnPoolImplTest, MaxConnections) {
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
// Request 2 should not kick off a new connection.
ConnPoolCallbacks callbacks2;
handle = conn_pool_.newConnection(callbacks2);
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_overflow_.value());
EXPECT_NE(nullptr, handle);
// Connect event will bind to request 1.
EXPECT_CALL(callbacks.pool_ready_, ready());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
// Finishing request 1 will immediately bind to request 2.
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
conn_pool_.expectEnableUpstreamReady(false);
EXPECT_CALL(callbacks2.pool_ready_, ready());
callbacks.conn_data_.reset();
conn_pool_.expectEnableUpstreamReady(true);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
callbacks2.conn_data_.reset();
// Cause the connection to go away.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test when we reach max requests per connection.
*/
TEST_P(TcpConnPoolImplTest, MaxRequestsPerConnection) {
cluster_->max_requests_per_connection_ = 1;
// Request 1 should kick off a new connection.
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks.pool_ready_, ready());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
callbacks.conn_data_.reset();
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(0U, cluster_->stats_.upstream_cx_destroy_with_active_rq_.value());
EXPECT_EQ(1U, cluster_->stats_.upstream_cx_max_requests_.value());
}
/*
* Test that multiple connections can be assigned at once.
*/
TEST_P(TcpConnPoolImplTest, ConcurrentConnections) {
cluster_->resetResourceManager(2, 1024, 1024, 1, 1);
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c2(*this, 1, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c3(*this, 0, ActiveTestConn::Type::Pending);
// Finish c1, which gets c3 going.
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
conn_pool_.expectEnableUpstreamReady(false);
c3.expectNewConn();
c1.releaseConn();
conn_pool_.expectEnableUpstreamReady(true);
EXPECT_CALL(conn_pool_, onConnReleasedForTest()).Times(2);
c2.releaseConn();
c3.releaseConn();
// Disconnect both connections.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest()).Times(2);
conn_pool_.test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Tests ConnectionState lifecycle with multiple concurrent connections.
*/
TEST_P(TcpConnPoolImplTest, ConnectionStateWithConcurrentConnections) {
int state_destroyed = 0;
auto* s1 = new TestConnectionState(1, [&]() -> void { state_destroyed |= 1; });
auto* s2 = new TestConnectionState(2, [&]() -> void { state_destroyed |= 2; });
auto* s3 = new TestConnectionState(2, [&]() -> void { state_destroyed |= 4; });
cluster_->resetResourceManager(2, 1024, 1024, 1, 1);
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
c1.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(s1));
ActiveTestConn c2(*this, 1, ActiveTestConn::Type::CreateConnection);
c2.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(s2));
ActiveTestConn c3(*this, 0, ActiveTestConn::Type::Pending);
EXPECT_EQ(0, state_destroyed);
// Finish c1, which gets c3 going.
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
conn_pool_.expectEnableUpstreamReady(false);
c3.expectNewConn();
c1.releaseConn();
conn_pool_.expectEnableUpstreamReady(true);
// c3 now has the state set by c1.
EXPECT_EQ(s1, c3.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
EXPECT_EQ(s2, c2.callbacks_.conn_data_->connectionStateTyped<TestConnectionState>());
// replace c3's state
c3.callbacks_.conn_data_->setConnectionState(std::unique_ptr<TestConnectionState>(s3));
EXPECT_EQ(1, state_destroyed);
EXPECT_CALL(conn_pool_, onConnReleasedForTest()).Times(2);
c2.releaseConn();
c3.releaseConn();
EXPECT_EQ(1, state_destroyed);
// Disconnect both connections.
EXPECT_CALL(conn_pool_, onConnDestroyedForTest()).Times(2);
conn_pool_.test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
EXPECT_EQ(7, state_destroyed);
}
/**
* Tests that the DrainCallback is invoked when the number of connections goes to zero.
*/
TEST_P(TcpConnPoolImplTest, DrainCallback) {
ReadyWatcher drained;
EXPECT_CALL(drained, ready());
conn_pool_.addDrainedCallback([&]() -> void { drained.ready(); });
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ActiveTestConn c2(*this, 0, ActiveTestConn::Type::Pending);
c2.handle_->cancel(ConnectionPool::CancelPolicy::Default);
EXPECT_CALL(conn_pool_, onConnReleasedForTest());
EXPECT_CALL(drained, ready());
c1.releaseConn();
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
dispatcher_.clearDeferredDeleteList();
}
/**
* Test draining a connection pool that has a pending connection.
*/
TEST_P(TcpConnPoolImplTest, DrainWhileConnecting) {
ReadyWatcher drained;
ConnPoolCallbacks callbacks;
conn_pool_.expectConnCreate();
Tcp::ConnectionPool::Cancellable* handle = conn_pool_.newConnection(callbacks);
EXPECT_NE(nullptr, handle);
conn_pool_.addDrainedCallback([&]() -> void { drained.ready(); });
if (test_new_connection_pool_) {
// The shared connection pool removes and closes connecting clients if there are no
// pending requests.
EXPECT_CALL(drained, ready());
handle->cancel(ConnectionPool::CancelPolicy::Default);
} else {
handle->cancel(ConnectionPool::CancelPolicy::Default);
EXPECT_CALL(*conn_pool_.test_conns_[0].connection_,
close(Network::ConnectionCloseType::NoFlush));
EXPECT_CALL(drained, ready());
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::Connected);
}
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
dispatcher_.clearDeferredDeleteList();
}
/**
* Test that the DrainCallback is invoked when a connection is closed.
*/
TEST_P(TcpConnPoolImplTest, DrainOnClose) {
ReadyWatcher drained;
EXPECT_CALL(drained, ready());
conn_pool_.addDrainedCallback([&]() -> void { drained.ready(); });
ActiveTestConn c1(*this, 0, ActiveTestConn::Type::CreateConnection);
ConnectionPool::MockUpstreamCallbacks callbacks;
c1.callbacks_.conn_data_->addUpstreamCallbacks(callbacks);
EXPECT_CALL(drained, ready());
EXPECT_CALL(callbacks, onEvent(Network::ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent event) -> void {
EXPECT_EQ(Network::ConnectionEvent::RemoteClose, event);
c1.releaseConn();
}));
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_CALL(conn_pool_, onConnDestroyedForTest());
dispatcher_.clearDeferredDeleteList();
}
/**
* Test connecting_request_capacity logic.
*/
TEST_P(TcpConnPoolImplTest, RequestCapacity) {
if (!test_new_connection_pool_) {
return;
}
cluster_->resetResourceManager(5, 1024, 1024, 1, 1);
cluster_->max_requests_per_connection_ = 100;
ConnPoolCallbacks callbacks1;
ConnPoolCallbacks callbacks2;
Tcp::ConnectionPool::Cancellable* handle1;
Tcp::ConnectionPool::Cancellable* handle2;
{
// Request 1 should kick off a new connection.
conn_pool_.expectConnCreate();
handle1 = conn_pool_.newConnection(callbacks1);
EXPECT_NE(nullptr, handle1);
}
{
// Request 2 should kick off a new connection.
conn_pool_.expectConnCreate();
handle2 = conn_pool_.newConnection(callbacks2);
EXPECT_NE(nullptr, handle2);
}
// This should set the number of requests remaining to 1 on the active
// connections, and the connecting_request_capacity to 2 as well.
conn_pool_.drainConnections();
// Cancel the connections. Because neither used CloseExcess, the two connections should persist.
handle1->cancel(ConnectionPool::CancelPolicy::Default);
handle2->cancel(ConnectionPool::CancelPolicy::Default);
Tcp::ConnectionPool::Cancellable* handle3;
Tcp::ConnectionPool::Cancellable* handle4;
Tcp::ConnectionPool::Cancellable* handle5;
ConnPoolCallbacks callbacks3;
ConnPoolCallbacks callbacks4;
ConnPoolCallbacks callbacks5;
{
// The next two requests will use the connections in progress, bringing
// connecting_request_capacity to zero.
handle3 = conn_pool_.newConnection(callbacks3);
EXPECT_NE(nullptr, handle3);
handle4 = conn_pool_.newConnection(callbacks4);
EXPECT_NE(nullptr, handle4);
}
{
// With connecting_request_capacity zero, a request for a new connection
// will kick off connection #3.
conn_pool_.expectConnCreate();
handle5 = conn_pool_.newConnection(callbacks5);
EXPECT_NE(nullptr, handle5);
}
// Clean up remaining connections.
handle3->cancel(ConnectionPool::CancelPolicy::Default);
handle4->cancel(ConnectionPool::CancelPolicy::Default);
handle5->cancel(ConnectionPool::CancelPolicy::Default);
conn_pool_.test_conns_[0].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
conn_pool_.test_conns_[1].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
conn_pool_.test_conns_[2].connection_->raiseEvent(Network::ConnectionEvent::RemoteClose);
}
/**
* Test that pending connections are closed when the connection pool is destroyed.
*/
TEST_P(TcpConnPoolImplDestructorTest, TestPendingConnectionsAreClosed) {
connection_ = new NiceMock<Network::MockClientConnection>();
connect_timer_ = new NiceMock<Event::MockTimer>(&dispatcher_);
EXPECT_CALL(dispatcher_, createClientConnection_(_, _, _, _)).WillOnce(Return(connection_));
EXPECT_CALL(*connect_timer_, enableTimer(_, _));
callbacks_ = std::make_unique<ConnPoolCallbacks>();
ConnectionPool::Cancellable* handle = conn_pool_->newConnection(*callbacks_);
EXPECT_NE(nullptr, handle);
EXPECT_CALL(callbacks_->pool_failure_, ready());
EXPECT_CALL(*connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_CALL(dispatcher_, clearDeferredDeleteList());
conn_pool_.reset();
}
/**
* Test that busy connections are closed when the connection pool is destroyed.
*/
TEST_P(TcpConnPoolImplDestructorTest, TestBusyConnectionsAreClosed) {
prepareConn();
EXPECT_CALL(*connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_CALL(dispatcher_, clearDeferredDeleteList());
conn_pool_.reset();
}
/**
* Test that ready connections are closed when the connection pool is destroyed.
*/
TEST_P(TcpConnPoolImplDestructorTest, TestReadyConnectionsAreClosed) {
prepareConn();
// Transition connection to ready list
callbacks_->conn_data_.reset();
EXPECT_CALL(*connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_CALL(dispatcher_, clearDeferredDeleteList());
conn_pool_.reset();
}
INSTANTIATE_TEST_SUITE_P(ConnectionPools, TcpConnPoolImplTest, testing::Bool());
INSTANTIATE_TEST_SUITE_P(ConnectionPools, TcpConnPoolImplDestructorTest, testing::Bool());
} // namespace Tcp
} // namespace Envoy
|
// Copyright (c) 2014 The Sippet Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sippet/ua/auth_handler_digest.h"
#include <string>
#include "base/i18n/icu_string_conversions.h"
#include "base/logging.h"
#include "base/md5.h"
#include "base/rand_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "sippet/ua/auth.h"
#include "sippet/message/request.h"
#include "url/gurl.h"
namespace sippet {
// Based on net/http/http_auth_handler_digest.cc,
// revision 238260
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Digest authentication is specified in RFC 2617.
// The expanded derivations are listed in the tables below.
//==========+==========+==========================================+
// qop |algorithm | response |
//==========+==========+==========================================+
// ? | ?, md5, | MD5(MD5(A1):nonce:MD5(A2)) |
// | md5-sess | |
//--------- +----------+------------------------------------------+
// auth, | ?, md5, | MD5(MD5(A1):nonce:nc:cnonce:qop:MD5(A2)) |
// auth-int | md5-sess | |
//==========+==========+==========================================+
// qop |algorithm | A1 |
//==========+==========+==========================================+
// | ?, md5 | user:realm:password |
//----------+----------+------------------------------------------+
// | md5-sess | MD5(user:realm:password):nonce:cnonce |
//==========+==========+==========================================+
// qop |algorithm | A2 |
//==========+==========+==========================================+
// ?, auth | | req-method:req-uri |
//----------+----------+------------------------------------------+
// auth-int | | req-method:req-uri:MD5(req-entity-body) |
//=====================+==========================================+
AuthHandlerDigest::NonceGenerator::NonceGenerator() {
}
AuthHandlerDigest::NonceGenerator::~NonceGenerator() {
}
AuthHandlerDigest::DynamicNonceGenerator::DynamicNonceGenerator() {
}
std::string AuthHandlerDigest::DynamicNonceGenerator::GenerateNonce() const {
// This is how mozilla generates their cnonce -- a 16 digit hex string.
static const char domain[] = "0123456789abcdef";
std::string cnonce;
cnonce.reserve(16);
for (int i = 0; i < 16; ++i)
cnonce.push_back(domain[base::RandInt(0, 15)]);
return cnonce;
}
AuthHandlerDigest::FixedNonceGenerator::FixedNonceGenerator(
const std::string& nonce)
: nonce_(nonce) {
}
std::string AuthHandlerDigest::FixedNonceGenerator::GenerateNonce() const {
return nonce_;
}
AuthHandlerDigest::Factory::Factory()
: nonce_generator_(new DynamicNonceGenerator()) {
}
AuthHandlerDigest::Factory::~Factory() {
}
void AuthHandlerDigest::Factory::set_nonce_generator(
const NonceGenerator* nonce_generator) {
nonce_generator_.reset(nonce_generator);
}
int AuthHandlerDigest::Factory::CreateAuthHandler(
const Challenge &challenge,
Auth::Target target,
const GURL& origin,
CreateReason create_reason,
int digest_nonce_count,
const net::BoundNetLog& net_log,
scoped_ptr<AuthHandler>* handler) {
scoped_ptr<AuthHandler> tmp_handler(
new AuthHandlerDigest(digest_nonce_count, nonce_generator_.get()));
if (!tmp_handler->InitFromChallenge(challenge, target, origin, net_log))
return net::ERR_INVALID_RESPONSE;
handler->swap(tmp_handler);
return net::OK;
}
Auth::AuthorizationResult AuthHandlerDigest::HandleAnotherChallenge(
const Challenge& challenge) {
// Even though Digest is not connection based, a "second round" is parsed
// to differentiate between stale and rejected responses.
// Note that the state of the current handler is not mutated - this way if
// there is a rejection the realm hasn't changed.
if (!base::LowerCaseEqualsASCII(challenge.scheme(), "digest"))
return net::HttpAuth::AUTHORIZATION_RESULT_INVALID;
// Try to find the "stale" value, and also keep track of the realm
// for the new challenge.
std::string original_realm;
if (challenge.HasStale() && challenge.stale())
return net::HttpAuth::AUTHORIZATION_RESULT_STALE;
if (challenge.HasRealm())
original_realm = challenge.realm();
return (original_realm_ != original_realm) ?
net::HttpAuth::AUTHORIZATION_RESULT_DIFFERENT_REALM :
net::HttpAuth::AUTHORIZATION_RESULT_REJECT;
}
bool AuthHandlerDigest::Init(const Challenge& challenge) {
return ParseChallenge(challenge);
}
int AuthHandlerDigest::GenerateAuthImpl(
const net::AuthCredentials* credentials,
const scoped_refptr<Request> &request,
const net::CompletionCallback& callback) {
// Generate a random client nonce.
std::string cnonce = nonce_generator_->GenerateNonce();
// Extract the request method and path -- the meaning of 'path' is overloaded
// in certain cases, to be a hostname.
std::string method;
std::string request_uri;
GetRequestMethodAndRequestUri(request, &method, &request_uri);
AssembleCredentials(method, request_uri, *credentials,
cnonce, nonce_count_, request);
return net::OK;
}
AuthHandlerDigest::AuthHandlerDigest(
int nonce_count, const NonceGenerator* nonce_generator)
: stale_(false),
algorithm_(ALGORITHM_UNSPECIFIED),
qop_(QOP_UNSPECIFIED),
nonce_count_(nonce_count),
nonce_generator_(nonce_generator) {
DCHECK(nonce_generator_);
}
AuthHandlerDigest::~AuthHandlerDigest() {
}
// The digest challenge header looks like:
// WWW-Authenticate: Digest
// [realm="<realm-value>"]
// nonce="<nonce-value>"
// [domain="<list-of-URIs>"]
// [opaque="<opaque-token-value>"]
// [stale="<true-or-false>"]
// [algorithm="<digest-algorithm>"]
// [qop="<list-of-qop-values>"]
// [<extension-directive>]
//
// Note that according to RFC 2617 (section 1.2) the realm is required.
// However we allow it to be omitted, in which case it will default to the
// empty string.
//
// This allowance breaks the default SIP RFC recommendations, though.
bool AuthHandlerDigest::ParseChallenge(
const Challenge& challenge) {
auth_scheme_ = net::HttpAuth::AUTH_SCHEME_DIGEST;
score_ = 2;
// Initialize to defaults.
stale_ = false;
algorithm_ = ALGORITHM_UNSPECIFIED;
qop_ = QOP_UNSPECIFIED;
realm_ = original_realm_ = nonce_ = domain_ = opaque_ = std::string();
// FAIL -- Couldn't match auth-scheme.
if (!base::LowerCaseEqualsASCII(challenge.scheme(), "digest"))
return false;
// Get all properties.
if (challenge.HasRealm()) {
std::string realm;
if (!base::ConvertToUtf8AndNormalize(challenge.realm(),
base::kCodepageLatin1, &realm))
return false;
original_realm_ = challenge.realm();
realm_ = realm;
}
if (challenge.HasNonce()) {
nonce_ = challenge.nonce();
}
if (challenge.HasDomain()) {
domain_ = challenge.domain();
}
if (challenge.HasOpaque()) {
opaque_ = challenge.opaque();
}
if (challenge.HasStale()) {
stale_ = challenge.stale();
}
if (challenge.HasAlgorithm()) {
std::string algorithm(challenge.algorithm());
if (base::LowerCaseEqualsASCII(algorithm, "md5")) {
algorithm_ = ALGORITHM_MD5;
} else if (base::LowerCaseEqualsASCII(algorithm, "md5-sess")) {
algorithm_ = ALGORITHM_MD5_SESS;
} else {
DVLOG(1) << "Unknown value of algorithm";
return false; // FAIL -- unsupported value of algorithm.
}
}
if (challenge.HasQop()) {
// Parse the comma separated list of qops.
// auth is the preferred qop.
std::string value(challenge.qop());
net::HttpUtil::ValuesIterator qop_values(value.begin(), value.end(), ',');
qop_ = QOP_UNSPECIFIED;
while (qop_values.GetNext()) {
if (base::LowerCaseEqualsASCII(qop_values.value(), "auth")) {
qop_ = QOP_AUTH;
break;
} else if (base::LowerCaseEqualsASCII(qop_values.value(), "auth-int")) {
qop_ = QOP_AUTH_INT;
continue;
}
}
}
// Check that a minimum set of properties were provided.
if (nonce_.empty())
return false;
return true;
}
// static
std::string AuthHandlerDigest::QopToString(QualityOfProtection qop) {
switch (qop) {
case QOP_UNSPECIFIED:
return std::string();
case QOP_AUTH:
return "auth";
case QOP_AUTH_INT:
return "auth-int";
default:
NOTREACHED();
return std::string();
}
}
// static
Credentials::Algorithm AuthHandlerDigest::AlgorithmToCredentials(
DigestAlgorithm algorithm) {
switch (algorithm) {
case ALGORITHM_MD5:
return Credentials::MD5;
case ALGORITHM_MD5_SESS:
return Credentials::MD5_sess;
default:
NOTREACHED();
return Credentials::Algorithm(-1);
}
}
void AuthHandlerDigest::GetRequestMethodAndRequestUri(
const scoped_refptr<Request> &request,
std::string* method,
std::string* request_uri) const {
DCHECK(request);
const GURL& uri = request->request_uri();
*request_uri = uri.spec();
*method = request->method().str();
}
std::string AuthHandlerDigest::AssembleResponseDigest(
const std::string& method,
const std::string& request_uri,
const std::string& body,
const net::AuthCredentials& credentials,
const std::string& cnonce,
int nonce_count) const {
// the nonce-count is an 8 digit hex string.
std::string nc = base::StringPrintf("%08x", nonce_count);
// ha1 = MD5(A1)
std::string ha1 = base::MD5String(base::UTF16ToUTF8(credentials.username())
+ ":" + original_realm_ + ":" +
base::UTF16ToUTF8(credentials.password()));
if (algorithm_ == AuthHandlerDigest::ALGORITHM_MD5_SESS)
ha1 = base::MD5String(ha1 + ":" + nonce_ + ":" + cnonce);
// ha2 = MD5(A2)
std::string a2 = method + ":" + request_uri;
if (qop_ == AuthHandlerDigest::QOP_AUTH_INT)
a2 += ":" + base::MD5String(body);
std::string ha2 = base::MD5String(a2);
std::string nc_part;
if (qop_ != AuthHandlerDigest::QOP_UNSPECIFIED) {
nc_part = nc + ":" + cnonce + ":" + QopToString(qop_) + ":";
}
return base::MD5String(ha1 + ":" + nonce_ + ":" + nc_part + ha2);
}
void AuthHandlerDigest::AssembleCredentials(
const std::string& method,
const std::string& request_uri,
const net::AuthCredentials& credentials,
const std::string& cnonce,
int nonce_count,
const scoped_refptr<Request> &request) const {
Credentials *cred;
scoped_ptr<Header> credentials_header;
if (net::HttpAuth::AUTH_PROXY == target_) {
ProxyAuthorization *proxy_authorization = new ProxyAuthorization;
credentials_header.reset(proxy_authorization);
cred = proxy_authorization;
} else {
Authorization *authorization = new Authorization;
credentials_header.reset(authorization);
cred = authorization;
}
cred->set_scheme(Credentials::Digest);
cred->set_username(base::UTF16ToUTF8(credentials.username()));
cred->set_realm(original_realm_);
cred->set_nonce(nonce_);
cred->set_uri(request_uri);
if (algorithm_ != ALGORITHM_UNSPECIFIED) {
cred->set_algorithm(AlgorithmToCredentials(algorithm_));
}
std::string response = AssembleResponseDigest(method, request_uri,
request->content(), credentials, cnonce, nonce_count);
cred->set_response(response);
if (!opaque_.empty()) {
cred->set_opaque(opaque_);
}
if (qop_ != QOP_UNSPECIFIED) {
cred->set_qop(QopToString(qop_));
cred->set_nc(nonce_count);
cred->set_cnonce(cnonce);
}
request->push_back(credentials_header.Pass());
}
} // namespace sippet
|
/* file: kdtree_knn_classification_predict_dense_default_batch_fpt_cpu_v1.cpp */
/*******************************************************************************
* Copyright 2014-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of prediction stage of K-Nearest Neighbors algorithm.
//--
*/
#include "algorithms/kernel/k_nearest_neighbors/kdtree_knn_classification_predict_dense_default_batch.h"
#include "algorithms/kernel/k_nearest_neighbors/kdtree_knn_classification_predict_dense_default_batch_impl.i"
#include "algorithms/kernel/k_nearest_neighbors/inner/kdtree_knn_classification_predict_dense_default_batch_container_v1.h"
namespace daal
{
namespace algorithms
{
namespace kdtree_knn_classification
{
namespace prediction
{
namespace interface1
{
template class BatchContainer<DAAL_FPTYPE, defaultDense, DAAL_CPU>;
}
} // namespace prediction
} // namespace kdtree_knn_classification
} // namespace algorithms
} // namespace daal
|
#include "amici/symbolic_functions.h"
#include "amici/defines.h" //realtype definition
typedef amici::realtype realtype;
#include <cmath>
using namespace amici;
namespace amici {
namespace model_model_neuron_o2{
void rz_model_neuron_o2(double *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) {
switch(ie) {
case 0: {
rz[0] = x[0]-3.0E1;
rz[1] = x[2];
rz[2] = x[4];
rz[3] = x[6];
rz[4] = x[8];
} break;
}
}
} // namespace model_model_neuron_o2
} // namespace amici
|
/******************************Module*Header*******************************\
* Module Name: wndstuff.cpp
*
* This file contains the code to support a simple window that has
* a menu with a single item called "Test". When "Test" is selected
* vTest(HWND) is called.
*
* Created: 09-Dec-1992 10:44:31
* Author: Kirk Olynyk [kirko]
*
* Copyright (c) 1991 Microsoft Corporation
*
\**************************************************************************/
#include "stdafx.h"
// for Win95 compile
//#undef UNICODE
//#undef _UNICODE
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <objbase.h>
#include <gdiplus.h>
#include "wndstuff.h"
#include "../../gpinit.inc"
HINSTANCE ghInstance;
HWND ghwndMain;
HWND ghwndDebug;
HWND ghwndList;
HBRUSH ghbrWhite;
/***************************************************************************\
* lMainWindowProc(hwnd, message, wParam, lParam)
*
* Processes all messages for the main window.
*
* History:
* 04-07-91 -by- KentD
* Wrote it.
\***************************************************************************/
LRESULT
_stdcall lMainWindowProc(
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
switch (message)
{
case WM_CREATE:
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case MM_TEST:
Test(hwnd);
break;
default:
break;
}
break;
case WM_DESTROY:
// UninitializeEngine();
DeleteObject(ghbrWhite);
PostQuitMessage(0);
return(DefWindowProc(hwnd, message, wParam, lParam));
default:
return(DefWindowProc(hwnd, message, wParam, lParam));
}
return(0);
}
/******************************Public*Routine******************************\
* DebugWndProc
*
* List box is maintained here.
*
\**************************************************************************/
LRESULT FAR PASCAL DebugWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
RECT rcl;
LRESULT lRet = 0;
// Process window message.
switch (message)
{
case WM_SIZE:
lRet = (LONG) DefWindowProc(ghwndList, message, wParam, lParam);
GetClientRect(ghwndMain, &rcl);
MoveWindow(
ghwndList,
rcl.left, rcl.top,
(rcl.right - rcl.left), (rcl.bottom - rcl.top),
TRUE
);
UpdateWindow(ghwndList);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
lRet = DefWindowProc(hwnd, message, wParam, lParam);
break;
}
return lRet;
}
/******************************Public*Routine******************************\
* LBprintf
*
* ListBox printf implementation.
*
* History:
* 15-Dec-1994 -by- Gilman Wong [gilmanw]
* Wrote it.
\**************************************************************************/
void LBprintf(PCH msg, ...)
{
if (ghwndList)
{
va_list ap;
char buffer[256];
va_start(ap, msg);
vsprintf(buffer, msg, ap);
SendMessage(ghwndList, LB_ADDSTRING, (WPARAM) 0, (LPARAM) buffer);
SendMessage(ghwndList, WM_SETREDRAW, (WPARAM) TRUE, (LPARAM) 0);
InvalidateRect(ghwndList, NULL, TRUE);
UpdateWindow(ghwndList);
va_end(ap);
}
}
/******************************Public*Routine******************************\
* LBreset
*
* Reset ListBox state (clear).
*
* History:
* 15-Dec-1994 -by- Gilman Wong [gilmanw]
* Wrote it.
\**************************************************************************/
void LBreset()
{
if (ghwndList)
SendMessage(ghwndList, LB_RESETCONTENT, (WPARAM) FALSE, (LPARAM) 0);
}
/***************************************************************************\
* bInitApp()
*
* Initializes app.
*
* History:
* 04-07-91 -by- KentD
* Wrote it.
\***************************************************************************/
BOOL bInitApp(BOOL debug)
{
WNDCLASS wc;
ghbrWhite = CreateSolidBrush(RGB(0xFF,0xFF,0xFF));
wc.style = 0;
wc.lpfnWndProc = lMainWindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = ghInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = ghbrWhite;
wc.lpszMenuName = _T("MainMenu");
wc.lpszClassName = _T("TestClass");
if (!RegisterClass(&wc))
{
return(FALSE);
}
ghwndMain =
CreateWindowEx(
0,
_T("TestClass"),
_T("Win32 Test"),
WS_OVERLAPPED |
WS_CAPTION |
WS_BORDER |
WS_THICKFRAME |
WS_MAXIMIZEBOX |
WS_MINIMIZEBOX |
WS_CLIPCHILDREN |
WS_VISIBLE |
WS_SYSMENU,
80,
70,
500,
500,
NULL,
NULL,
ghInstance,
NULL);
if (ghwndMain == NULL)
{
return(FALSE);
}
if (debug)
{
RECT rcl;
memset(&wc, 0, sizeof(wc));
wc.style = 0;
wc.lpfnWndProc = DebugWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = ghInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = ghbrWhite;
wc.lpszClassName = _T("DebugWClass");
RegisterClass(&wc);
ghwndDebug = CreateWindow(
_T("DebugWClass"),
_T("Debug output"),
WS_OVERLAPPEDWINDOW|WS_MAXIMIZE,
600,
70,
300,
500,
NULL,
NULL,
ghInstance,
NULL
);
if (ghwndDebug)
{
ShowWindow(ghwndDebug, SW_NORMAL);
UpdateWindow(ghwndDebug);
// Create the list box to fill the main window.
GetClientRect(ghwndDebug, &rcl);
ghwndList = CreateWindow(
_T("LISTBOX"),
_T("Debug output"),
WS_CHILD | WS_VISIBLE | WS_VSCROLL
| WS_HSCROLL | LBS_NOINTEGRALHEIGHT,
rcl.left, rcl.top,
(rcl.right - rcl.left), (rcl.bottom - rcl.top),
ghwndDebug,
NULL,
ghInstance,
NULL
);
if (ghwndList)
{
SendMessage(
ghwndList,
WM_SETFONT,
(WPARAM) GetStockObject(ANSI_FIXED_FONT),
(LPARAM) FALSE
);
LBreset();
ShowWindow(ghwndList, SW_NORMAL);
UpdateWindow(ghwndList);
}
}
}
SetFocus(ghwndMain);
return(TRUE);
}
/***************************************************************************\
* main(argc, argv[])
*
* Sets up the message loop.
*
* History:
* 04-07-91 -by- KentD
* Wrote it.
\***************************************************************************/
_cdecl main(
INT argc,
PTCHAR argv[])
{
MSG msg;
HACCEL haccel;
if (!gGdiplusInitHelper.IsValid())
{
return 0;
}
BOOL wantDebugWindow = FALSE;
CoInitialize(NULL);
// Parse arguments
for (argc--, argv++ ; argc && '-' == **argv ; argc--, argv++ )
{
switch ( *(++(*argv)) )
{
case 'd':
case 'D':
wantDebugWindow = TRUE;
break;
}
}
ghInstance = GetModuleHandle(NULL);
if (!bInitApp(wantDebugWindow))
{
return(0);
}
haccel = LoadAccelerators(ghInstance, MAKEINTRESOURCE(1));
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, haccel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
CoUninitialize();
return(1);
}
|
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/format.h>
#include <units/isq/si/fps/density.h>
#include <units/isq/si/fps/length.h>
#include <units/isq/si/fps/mass.h>
#include <units/isq/si/fps/power.h>
#include <units/isq/si/fps/speed.h>
#include <units/isq/si/length.h>
#include <units/isq/si/mass.h>
#include <units/isq/si/power.h>
#include <units/isq/si/speed.h>
#include <units/isq/si/volume.h>
#include <iostream>
#include <string_view>
using namespace units::aliases::isq;
// Some basic specs for the warship
struct Ship {
si::fps::length::ft<> length;
si::fps::length::ft<> draft;
si::fps::length::ft<> beam;
si::fps::speed::ft_per_s<> speed;
si::fps::mass::lb<> mass;
si::fps::length::in<> mainGuns;
si::fps::mass::lb<> shellMass;
si::fps::speed::ft_per_s<> shellSpeed;
si::fps::power::ft_pdl_per_s<> power;
};
// Print 'a' in its current units and print its value cast to the units in each of Args
template<class ...Args, units::Quantity Q>
auto fmt_line(const Q a)
{
return fmt::format("{:22}", a) + (fmt::format(",{:20}", units::quantity_cast<Args>(a)) + ...);
}
// Print the ship details in the units as defined in the Ship struct, in other si::imperial units, and in SI
void print_details(std::string_view description, const Ship& ship)
{
const auto waterDensity = si::fps::density::lb_per_ft3<>(62.4);
std::cout << fmt::format("{}\n", description);
std::cout << fmt::format("{:20} : {}\n", "length", fmt_line<si::fps::length::yd<>, si::length::m<>>(ship.length))
<< fmt::format("{:20} : {}\n", "draft", fmt_line<si::fps::length::yd<>, si::length::m<>>(ship.draft))
<< fmt::format("{:20} : {}\n", "beam", fmt_line<si::fps::length::yd<>, si::length::m<>>(ship.beam))
<< fmt::format("{:20} : {}\n", "mass", fmt_line<si::fps::mass::lton<>, si::mass::t<>>(ship.mass))
<< fmt::format("{:20} : {}\n", "speed", fmt_line<si::fps::speed::knot<>, si::speed::km_per_h<>>(ship.speed))
<< fmt::format("{:20} : {}\n", "power", fmt_line<si::fps::power::hp<>, si::power::kW<>>(ship.power))
<< fmt::format("{:20} : {}\n", "main guns", fmt_line<si::fps::length::in<>, si::length::mm<>>(ship.mainGuns))
<< fmt::format("{:20} : {}\n", "fire shells weighing",fmt_line<si::fps::mass::lton<>, si::mass::kg<>>(ship.shellMass))
<< fmt::format("{:20} : {}\n", "fire shells at",fmt_line<si::fps::speed::mph<>, si::speed::km_per_h<>>(ship.shellSpeed))
<< fmt::format("{:20} : {}\n", "volume underwater", fmt_line<si::volume::m3<>, si::volume::l<>>(ship.mass / waterDensity));
}
int main()
{
using namespace units::aliases::isq::si;
using namespace units::aliases::isq::si::fps;
using units::aliases::isq::si::fps::length::ft; // to disambiguate from si::femptotonne
// KMS Bismark, using the units the Germans would use, taken from Wiki
auto bismark = Ship{.length{m<>(251.)}, .draft{m<>(9.3)}, .beam{m<>(36)}, .speed{km_per_h<>(56)}, .mass{t<>(50'300)}, .mainGuns{mm<>(380)}, .shellMass{kg<>(800)}, .shellSpeed{m_per_s<>(820.)}, .power{kW<>(110.45)}};
// USS Iowa, using units from the foot-pound-second system
auto iowa = Ship{.length{ft<>(860.)}, .draft{ft<>(37.) + in<>(2.)}, .beam{ft<>(108.) + in<>(2.)}, .speed{knot<>(33)}, .mass{lton<>(57'540)}, .mainGuns{in<>(16)}, .shellMass{lb<>(2700)}, .shellSpeed{ft_per_s<>(2690.)}, .power{hp<>(212'000)}};
// HMS King George V, using units from the foot-pound-second system
auto kgv = Ship{.length{ft<>(745.1)}, .draft{ft<>(33.) + in<>(7.5)}, .beam{ft<>(103.2) + in<>(2.5)}, .speed{knot<>(28.3)}, .mass{lton<>(42'245)}, .mainGuns{in<>(14)}, .shellMass{lb<>(1'590)}, .shellSpeed{ft_per_s<>(2483)}, .power{hp<>(110'000)}};
print_details("KMS Bismark, defined in appropriate units from the SI system", bismark);
std::cout << "\n\n";
print_details("USS Iowa, defined in appropriate units foot-pound-second system", iowa);
std::cout << "\n\n";
print_details("HMS King George V, defined in appropriate units foot-pound-second system", kgv);
}
|
//========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file magnoh.cpp
// \brief Magnetized Noh with perturbation in B_phi. Authored by A. Beresnyak
//
// 2D collapse on center, r distance to center
// initial conditions with r in cm:
// rho = rho0*r^alpha [g/cm^3]
// V = V0 [cm/s]
// Bphi = Bphi0*r^beta [gauss] azimuthal
// Bz = Bz0* r^beta [gauss] axial
// pressure = 1.E-6*B^2 actually zero in the exact solution
//
// Can apply sine wave perturbation in a form
// *(1+perturb*cos(mphi*phi)) to the magnetic potential Az
//
// REFERENCES:
// 1) Velikovich, Giuliani, Zalesak, Gardiner, "Exact self-similar solutions for the
// magnetized Noh Z pinch problem", Phys. of Plasmas, vol.19, p.012707 (2012)
//
// 2) Giuliani, Velikovich, Beresnyak, Zalesak, Gianakon, Rousculp, "Self-similar
// solutions for the magnetized Noh problem with axial and azimuthal field", Phys. of
// Plasmas, in prep (2018)
// C++ headers
#include <algorithm>
#include <cmath> // sqrt()
#include <sstream>
#include <stdexcept>
#include <string>
// Athena++ headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../parameter_input.hpp"
#include "../bvals/bvals.hpp"
#include "../coordinates/coordinates.hpp"
#include "../eos/eos.hpp"
#include "../field/field.hpp"
#include "../hydro/hydro.hpp"
#include "../mesh/mesh.hpp"
static Real gm1;
static Real alpha, beta, rho0, P0, pcoeff, vr, perturb, mphi;
static Real bphi0, bz;
// static Real nu_iso, eta_ohm;
#if !MAGNETIC_FIELDS_ENABLED
#error "This problem generator requires magnetic fields"
#endif
//========================================================================================
//! \fn void Mesh::InitUserMeshData(ParameterInput *pin)
// \brief Function to initialize problem-specific data in mesh class. Can also be used
// to initialize variables which are global to (and therefore can be passed to) other
// functions in this file. Called in Mesh constructor.
//========================================================================================
void Mesh::InitUserMeshData(ParameterInput *pin) {
// initialize global variables
// nu_iso = pin->GetOrAddReal("problem", "nu_iso", 0.0);
// eta_ohm = pin->GetOrAddReal("problem", "eta_ohm", 0.0);
alpha = pin->GetReal("problem", "alpha");
beta = pin->GetReal("problem", "beta");
pcoeff= pin->GetReal("problem", "pcoeff");
rho0 = pin->GetReal("problem", "d");
vr = pin->GetReal("problem", "vr");
// convert from CGS to Athena Heaviside units:
bphi0 = pin->GetReal("problem", "bphi")/std::sqrt(4*M_PI);
bz = pin->GetReal("problem", "bz")/std::sqrt(4*M_PI);
P0 = 4*M_PI*pcoeff*(bphi0*bphi0+bz*bz);
perturb = pin->GetOrAddReal("problem","perturb",0.0);
mphi = pin->GetOrAddReal("problem","mphi",1.0);
return;
}
//========================================================================================
//! \fn void MeshBlock::ProblemGenerator(ParameterInput *pin)
// \brief Problem Generator for zpinch problem
//========================================================================================
void MeshBlock::ProblemGenerator(ParameterInput *pin) {
gm1 = peos->GetGamma() - 1.0;
if (COORDINATE_SYSTEM != "cartesian" && COORDINATE_SYSTEM != "cylindrical") {
std::stringstream msg;
msg << "### FATAL ERROR in magnoh.cpp ProblemGenerator" << std::endl
<< "Unrecognized COORDINATE_SYSTEM= " << COORDINATE_SYSTEM << std::endl
<< "Only Cartesian and cylindrical are supported for this problem" << std::endl;
throw std::runtime_error(msg.str().c_str());
}
// initialize vector potential for inflowing B
// (only initializing 2D array for vec potential)
int nx1 = (ie-is)+1 + 2*(NGHOST);
int nx2 = (je-js)+1 + 2*(NGHOST);
AthenaArray<Real> az;
az.NewAthenaArray(nx2,nx1);
for (int j=js; j<=je+1; ++j) {
for (int i=is; i<=ie+1; ++i) {
Real rad,phi;
if (COORDINATE_SYSTEM == "cylindrical") {
rad = pcoord->x1f(i);
phi = pcoord->x2f(j);
} else { // cartesian
Real x1 = pcoord->x1f(i);
Real x2 = pcoord->x2f(j);
rad = std::sqrt(SQR(x1) + SQR(x2));
phi = atan2(x2, x1);
}
// if (rad==0.0) rad=3.0/100000;
az(j,i) = (bphi0/(beta+1))*pow(rad,beta+1)*(1+perturb*cos(mphi*phi));
}
}
// initialize conserved variables
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie; i++) {
// Volume centered coordinates and quantities
Real rad,x1,x2;
if(COORDINATE_SYSTEM == "cylindrical") {
rad = pcoord->x1v(i);
} else { // cartesian
x1=pcoord->x1v(i);
x2=pcoord->x2v(j);
rad = std::sqrt(SQR(x1) + SQR(x2));
}
Real rho = rho0*pow(rad, alpha);
Real P = P0 *pow(rad, 2*beta);
phydro->u(IDN,k,j,i) = rho;
if(COORDINATE_SYSTEM == "cylindrical") {
phydro->u(IM1,k,j,i) = rho*vr;
phydro->u(IM2,k,j,i) = 0.0;
} else { // cartesian
phydro->u(IM1,k,j,i) = rho*vr*x1/rad;
phydro->u(IM2,k,j,i) = rho*vr*x2/rad;
}
phydro->u(IM3,k,j,i) = 0.0;
phydro->u(IEN,k,j,i) = P/gm1 + 0.5*rho*SQR(vr);
}
}
}
// initialize face-averaged magnetic fields
if (MAGNETIC_FIELDS_ENABLED) {
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie+1; i++) {
Real geom_coeff=1.0;
if (COORDINATE_SYSTEM == "cylindrical") geom_coeff=1.0/pcoord->x1f(i);
pfield->b.x1f(k,j,i) = geom_coeff*(az(j+1,i) - az(j,i))/pcoord->dx2f(j);
}
}
}
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je+1; j++) {
for (int i=is; i<=ie; i++) {
Real geom_coeff=1.0;
if (COORDINATE_SYSTEM == "cylindrical") geom_coeff=-1.0; // Left hand system?
pfield->b.x2f(k,j,i) = geom_coeff*(az(j,i) - az(j,i+1))/pcoord->dx1f(i);
}
}
}
for (int k=ks; k<=ke+1; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie; i++) {
Real rad;
if (COORDINATE_SYSTEM == "cylindrical") rad = pcoord->x1v(i);
else rad = std::sqrt(SQR(pcoord->x1v(i)) + SQR(pcoord->x2v(j)));
pfield->b.x3f(k,j,i) = bz*pow(rad,beta);
}
}
}
if (NON_BAROTROPIC_EOS) {
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie; i++) {
phydro->u(IEN,k,j,i) +=
// second-order accurate assumption about volume-averaged field
0.5*0.25*(SQR(pfield->b.x1f(k,j,i)+pfield->b.x1f(k,j,i+1))
+ SQR(pfield->b.x2f(k,j,i)+pfield->b.x2f(k,j+1,i))
+ SQR(pfield->b.x3f(k,j,i)+pfield->b.x3f(k+1,j,i)));
}
}
}
}
}
az.DeleteAthenaArray();
return;
}
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2017-2020 The Qtum Core developers
// Copyright (c) 2020 The BITCOIN2Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/uritests.h>
#include <qt/guiutil.h>
#include <qt/walletmodel.h>
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("bitcoin2:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
|
/*
* Copyright 2011 Aevum Software aevum @ aevumlab.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Victor Vicente de Carvalho victor.carvalho@aevumlab.com
* @author Ozires Bortolon de Faria ozires@aevumlab.com
*/
#ifndef GDX_CPP_UTILS_LOCK_GUARD_HPP
#define GDX_CPP_UTILS_LOCK_GUARD_HPP
//simple template to mimetize boosts's lock_guard template
template <typename mutex>
struct lock_guard {
lock_guard(mutex& m) : ref_mutex(m) {
ref_mutex.lock();
}
~lock_guard() {
ref_mutex.unlock();
}
mutex& getMutex() const {
return ref_mutex;
}
private:
mutex& ref_mutex;
};
#endif
|
/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "istream/DechunkIstream.hxx"
#include "istream/istream.hxx"
#include "istream/Bucket.hxx"
#include <assert.h>
#include <stddef.h>
struct pool;
class EventLoop;
class SocketDescriptor;
/**
* Utilities for reading a HTTP body, either request or response.
*/
class HttpBodyReader : public Istream, DechunkHandler {
/**
* The remaining size is unknown.
*/
static constexpr off_t REST_UNKNOWN = -1;
/**
* EOF chunk has been seen.
*/
static constexpr off_t REST_EOF_CHUNK = -2;
/**
* Chunked response. Will flip to #REST_EOF_CHUNK as soon
* as the EOF chunk is seen.
*/
static constexpr off_t REST_CHUNKED = -3;
/**
* The remaining number of bytes.
*
* @see #REST_UNKNOWN, #REST_EOF_CHUNK,
* #REST_CHUNKED
*/
off_t rest;
FdTypeMask direct_mask = 0;
bool end_seen;
public:
template<typename P>
explicit HttpBodyReader(P &&_pool) noexcept
:Istream(std::forward<P>(_pool)) {}
UnusedIstreamPtr Init(EventLoop &event_loop, off_t content_length,
bool chunked) noexcept;
using Istream::GetPool;
using Istream::Destroy;
IstreamHandler *PrepareEof() noexcept {
/* suppress InvokeEof() if rest==REST_EOF_CHUNK because in
that case, the dechunker has already emitted that event */
return rest == 0
? &Istream::PrepareEof()
: nullptr;
}
void InvokeEof() noexcept {
/* suppress InvokeEof() if rest==REST_EOF_CHUNK because in
that case, the dechunker has already emitted that event */
if (rest == 0)
Istream::InvokeEof();
}
void DestroyEof() noexcept {
InvokeEof();
Destroy();
}
using Istream::InvokeError;
using Istream::DestroyError;
bool IsChunked() const noexcept {
return rest == REST_CHUNKED || rest == REST_EOF_CHUNK;
}
/**
* Do we know the remaining length of the body?
*/
bool KnownLength() const noexcept {
return rest >= 0;
}
bool IsEOF() const noexcept {
return rest == 0 || rest == REST_EOF_CHUNK;
}
bool GotEndChunk() const noexcept {
return rest == REST_EOF_CHUNK;
}
/**
* Do we require more data to finish the body?
*/
bool RequireMore() const noexcept {
return rest > 0 || (rest == REST_CHUNKED && !end_seen);
}
template<typename Socket>
[[gnu::pure]]
off_t GetAvailable(const Socket &s, bool partial) const noexcept {
assert(rest != REST_EOF_CHUNK);
if (KnownLength())
return rest;
return partial
? (off_t)s.GetAvailable()
: -1;
}
template<typename Socket>
void FillBucketList(const Socket &s,
IstreamBucketList &list) noexcept {
auto b = s.ReadBuffer();
if (b.empty()) {
if (!IsEOF())
list.SetMore();
return;
}
size_t max = GetMaxRead(b.size);
if (b.size > max)
b.size = max;
list.Push(ConstBuffer<void>(b.data, b.size));
if ((off_t)b.size != rest)
list.SetMore();
}
template<typename Socket>
size_t ConsumeBucketList(Socket &s, size_t nbytes) noexcept {
auto b = s.ReadBuffer();
if (b.empty())
return 0;
size_t max = GetMaxRead(b.size);
if (nbytes > max)
nbytes = max;
if (nbytes == 0)
return 0;
s.DisposeConsumed(nbytes);
Consumed(nbytes);
return Istream::Consumed(nbytes);
}
size_t FeedBody(const void *data, size_t length) noexcept;
bool CheckDirect(FdType type) const noexcept {
return (direct_mask & FdTypeMask(type)) != 0;
}
ssize_t TryDirect(SocketDescriptor fd, FdType fd_type) noexcept;
/**
* Determines whether the socket can be released now. This is true if
* the body is empty, or if the data in the buffer contains enough for
* the full response.
*/
template<typename Socket>
[[gnu::pure]]
bool IsSocketDone(const Socket &s) const noexcept {
if (IsChunked())
return end_seen;
return KnownLength() && (off_t)s.GetAvailable() >= rest;
}
/**
* The underlying socket has been closed by the remote.
*
* @return true if there is data left in the buffer, false if the body
* has been finished (with or without error)
*/
bool SocketEOF(size_t remaining) noexcept;
/**
* Discard data from the input buffer. This method shall be used
* to discard an unwanted request body.
*
* @return true if the whole body has been removed from the input
* buffer
*/
template<typename Socket>
bool Discard(Socket &s) noexcept {
if (IsChunked() || !KnownLength())
return false;
/* note: using s.ReadBuffer().size instead of s.GetAvailable()
to work around a problem with
ThreadSocketFilter::Consumed() which asserts that
ReadBuffer() has moved decrypted_input into
unprotected_decrypted_input */
size_t available = s.ReadBuffer().size;
if ((off_t)available < rest)
return false;
s.DisposeConsumed(rest);
return true;
}
private:
[[gnu::pure]]
size_t GetMaxRead(size_t length) const noexcept;
void Consumed(size_t nbytes) noexcept;
public:
/* virtual methods from class Istream */
void _SetDirect(FdTypeMask mask) noexcept override {
direct_mask = mask;
}
protected:
/* virtual methods from class DechunkHandler */
void OnDechunkEndSeen() noexcept final;
bool OnDechunkEnd() noexcept final;
};
|
/*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include <cstdio>
#include <bitset>
#include <vector>
using namespace std;
const int maxN = 10000+5;
vector<vector<int> > adjList;
vector<int> disc, low;
bitset<maxN> isAP; // AP means articulation point.
vector<int> used;
int discTime;
int cnt, numberOfComponent, connectedAP;
void dfs_findAP(int u, int parent = -1)
{
low[u] = disc[u] = ++discTime;
int v, sz = adjList[u].size(), childCount = 0;
for(int i = 0; i < sz; ++i) {
v = adjList[u][i];
if(!disc[v]) { // That is, v isn't visited.
++childCount;
dfs_findAP(v, u);
if(parent == -1 && childCount > 1) isAP[u] = true;
if(parent != -1 && low[v] >= disc[u]) isAP[u] = true;
low[u] = min(low[u], low[v]);
}
else if(v != parent)
low[u] = min(low[u], disc[v]);
}
}
void dfs_traverse(int u)
{
++cnt;
used[u] = 1;
int v, sz = adjList[u].size();
for(int i = 0; i < sz; ++i) {
v = adjList[u][i];
if(!used[v] && !isAP[v])
dfs_traverse(v);
if(isAP[v] && used[v] != numberOfComponent) {
++connectedAP;
used[v] = numberOfComponent;
}
}
}
int main()
{
//freopen("in", "r", stdin);
int t;
scanf("%d", &t);
for(int tc = 1; tc <= t; ++tc) {
adjList.clear();
disc.clear();
low.clear();
isAP.reset();
used.clear();
int n, m, u, v;
scanf("%d %d", &n, &m);
adjList.resize(n);
disc.assign(n, 0);
low.resize(n);
used.assign(n, 0);
while(m--) {
scanf("%d %d", &u, &v);
adjList[u].push_back(v);
adjList[v].push_back(u);
}
discTime = 0;
dfs_findAP(0);
numberOfComponent = 0;
int shaft = 0;
unsigned long long numberOfWays = 1;
for(int i = 0; i < n; ++i) {
if(!used[i] && !isAP[i]) {
cnt = connectedAP = 0;
++numberOfComponent;
dfs_traverse(i);
if(connectedAP < 2) {
++shaft;
numberOfWays *= cnt;
}
}
}
if(shaft == 1) {
++shaft;
numberOfWays = (n * (n-1)) / 2;
}
printf("Case %d: %d %llu\n", tc, shaft, numberOfWays);
}
return 0;
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/taucoin-config.h"
#endif
#include "intro.h"
#include "ui_intro.h"
#include "guiutil.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <cmath>
static const uint64_t GB_BYTES = 1000000000LL;
/* Minimum free space (in GB) needed for data directory */
static const uint64_t BLOCK_CHAIN_SIZE = 80;
/* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */
static const uint64_t CHAIN_STATE_SIZE = 2;
/* Total required space (in GB) depending on user choice (prune, not prune) */
static uint64_t requiredSpace;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));
ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));
uint64_t pruneTarget = std::max<int64_t>(0, GetArg("-prune", 0));
requiredSpace = BLOCK_CHAIN_SIZE;
if (pruneTarget)
requiredSpace = CHAIN_STATE_SIZE + std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(tr(PACKAGE_NAME)).arg(requiredSpace));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
Q_EMIT stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void Intro::pickDataDirectory()
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(0, tr(PACKAGE_NAME),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < requiredSpace * GB_BYTES)
{
freeString += " " + tr("(of %n GB needed)", "", requiredSpace);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
|
#include <Arduino.h>
#include "MotorControl.h"
#define RIGHT_FORWARD 0
#define RIGHT_REVERSE 1
#define LEFT_FORWARD 2
#define LEFT_REVERSE 3
MotorControl::MotorControl(MotorPins p)
{
frequency = 50000;
resolution = 8;
config = {
{100, -100, 10, 0, 0}, // right
{100, -100, 10, 0, 0} // left
};
firstLoop = true;
ledcSetup(RIGHT_FORWARD, frequency, resolution);
ledcSetup(RIGHT_REVERSE, frequency, resolution);
ledcSetup(LEFT_FORWARD, frequency, resolution);
ledcSetup(LEFT_REVERSE, frequency, resolution);
setPins(p);
}
void MotorControl::setPins(MotorPins p)
{
ledcDetachPin(pins.right.forward);
ledcDetachPin(pins.right.reverse);
ledcDetachPin(pins.left.forward);
ledcDetachPin(pins.left.reverse);
pins = p;
ledcAttachPin(pins.right.forward, RIGHT_FORWARD);
ledcAttachPin(pins.right.reverse, RIGHT_REVERSE);
ledcAttachPin(pins.left.forward, LEFT_FORWARD);
ledcAttachPin(pins.left.reverse, LEFT_REVERSE);
}
void MotorControl::setRightSpeed(int speed)
{
if (speed < config.right.minSpeed)
{
config.right.targetSpeed = config.right.minSpeed;
}
else if (speed > config.right.maxSpeed)
{
config.right.targetSpeed = config.right.maxSpeed;
}
else
{
config.right.targetSpeed = (float)speed;
}
}
void MotorControl::setLeftSpeed(int speed)
{
if (speed < config.left.minSpeed)
{
config.left.targetSpeed = config.left.minSpeed;
}
else if (speed > config.left.maxSpeed)
{
config.left.targetSpeed = config.left.maxSpeed;
}
else
{
config.left.targetSpeed = (float)speed;
}
}
void threadLoop(void* parameter) {
for (;;)
{
delay(50);
}
}
void MotorControl::loop()
{
if (firstLoop)
{
oldTime = millis() - 10;
firstLoop = false;
}
else
{
oldTime = currentTime;
}
currentTime = millis();
dt = (currentTime - oldTime) / 1000.0;
//
// Right
//
/*
if (config.right.currentSpeed < config.right.targetSpeed)
{
config.right.currentSpeed += dt * config.right.accel;
}
else
{
config.right.currentSpeed -= dt * config.right.accel;
}
*/
config.right.currentSpeed = config.right.targetSpeed;
if (config.right.currentSpeed > 0)
{
ledcWrite(RIGHT_REVERSE, 0);
ledcWrite(RIGHT_FORWARD, config.right.currentSpeed / 100.0 * 255.0);
}
else
{
ledcWrite(RIGHT_FORWARD, 0);
ledcWrite(RIGHT_REVERSE, -config.right.currentSpeed / 100.0 * 255.0);
}
//
// Left
//
/*
if (config.left.currentSpeed < config.left.targetSpeed)
{
config.left.currentSpeed += dt * config.left.accel;
}
else
{
config.left.currentSpeed -= dt * config.left.accel;
}
*/
config.left.currentSpeed = config.left.targetSpeed;
if (config.left.currentSpeed > 0)
{
ledcWrite(LEFT_REVERSE, 0);
ledcWrite(LEFT_FORWARD, config.left.currentSpeed / 100.0 * 255);
}
else
{
ledcWrite(LEFT_FORWARD, 0);
ledcWrite(LEFT_REVERSE, -config.left.currentSpeed / 100.0 * 255);
}
//Serial.print("Left: ");
//Serial.print(ledcRead(LEFT_FORWARD));
//Serial.print(" | Right: ");
//Serial.println(ledcRead(RIGHT_FORWARD));
//delay(15);
}
|
#include "nvparse_errors.h"
#include "nvparse_externs.h"
#include <string.h>
#include <string>
#include <ctype.h>
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
# include <OpenGL/glu.h>
#else
# include <GL/glu.h>
#endif
using namespace std;
namespace
{
void LoadProgram( GLenum target, GLuint id, char *instring );
GLint vpid;
}
bool is_vp10(const char * s)
{
return ! strncmp(s, "!!VP1.0", 7);
}
bool vp10_init(char * s)
{
static bool vpinit = false;
if (vpinit == false )
{
/*
if(! glh_init_extensions("GL_NV_vertex_program"))
{
errors.set("unable to initialize GL_NV_vertex_program");
return false;
}
else
{
*/
vpinit = true;
/*
}
*/
}
errors.reset();
line_number = 1;
myin = s;
glGetIntegerv( GL_VERTEX_PROGRAM_BINDING_NV, &vpid );
if ( vpid == 0 )
{
char str[128];
sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", (int)vpid );
errors.set( str );
return false;
}
return true;
}
int vp10_parse()
{
LoadProgram( GL_VERTEX_PROGRAM_NV, vpid, myin );
return 0;
}
namespace
{
//.----------------------------------------------------------------------------.
//| Function : LoadProgram |
//| Description: Load a program into GL, and report any errors encountered. |
//.----------------------------------------------------------------------------.
void LoadProgram( GLenum target, GLuint id, char *instring )
{
GLint errPos;
GLenum errCode;
int len = strlen(instring);
glLoadProgramNV( target, id, len, (const GLubyte *) instring );
if ( (errCode = glGetError()) != GL_NO_ERROR )
{
glGetIntegerv( GL_PROGRAM_ERROR_POSITION_NV, &errPos );
if (errPos == -1)
return;
int nlines = 1;
int nchar = 1;
int i;
for ( i = 0; i < errPos; i++ )
{
if ( instring[i] == '\n' )
{
nlines++;
nchar = 1;
}
else
{
nchar++;
}
}
int start = 0;
int end = 0;
int flag = ((instring[errPos]==';') | (instring[errPos-1]==';')) ? 1 : 0;
for ( i = errPos; i >= 0; i-- )
{
start = i;
if ( flag && (start >= errPos-1) )
continue;
if ( instring[i] == ';' )
{
if ( !flag )
{
start = i+1;
if ( instring[start] == '\n' )
start++;
}
break;
}
}
for ( i = errPos; i < len; i++ )
{
end = i;
if ( instring[i] == ';' && end > start)
{
break;
}
}
if ( errPos - start > 30 )
{
start = errPos - 30;
}
if ( end - errPos > 30 )
{
end = errPos + 30;
}
char substring[96];
memset( substring, 0, 96 );
strncpy( substring, &(instring[start]), end-start+1 );
char str[256];
//sprintf( str, "error at line %d character %d\n \"%s\"\n", nlines, nchar, substring );
sprintf( str, "error at line %d character %d\n\"%s\"\n", nlines, nchar, substring );
int width = errPos-start;
for ( i = 0; i < width; i++ )
{
strcat( str, " " );
}
strcat( str, "|\n" );
for ( i = 0; i < width; i++ )
{
strcat( str, " " );
}
strcat( str, "^\n" );
errors.set( str );
}
}
}
/* else if(!strncmp(instring, "!!VP1.0", 7))
{
if (vpinit == 0 )
{
if(! glh_init_extensions("GL_NV_vertex_program"))
{
errors.set("unable to initialize GL_NV_vertex_program");
free(instring);
return;
}
else
{
vpinit = 1;
}
}
errors.reset();
line_number = 1;
int vpid;
glGetIntegerv( GL_VERTEX_PROGRAM_BINDING_NV, &vpid );
if ( glGetError() != GL_NO_ERROR )
{
errors.set( "Previous GL_ERROR prior to vertex program parsing.\n" );
}
if ( vpid == 0 )
{
char str[128];
sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", vpid );
errors.set( str );
}
else
{
LoadProgram( GL_VERTEX_PROGRAM_NV, vpid, instring );
}
}
*/
|
#include "dmos.h"
#include "dmutil.h"
#include "dmtypes.h"
#include "dmformat.h"
#include "dmiconv.h"
int main(int argc, char* argv[]) {
{
std::string in = "hello iconv";
std::string out = iconvpp::LatintoUtf8(in);
fmt::fprintf(stdout, "%s\n", out.c_str());
std::string out2 = iconvpp::Utf8toLatin(out);
fmt::fprintf(stdout, "%s\n", out2.c_str());
}
{
std::string in = "今天天气不错";
std::string out = iconvpp::LatintoUtf8(in);
fmt::fprintf(stdout, "%s\n", out.c_str());
std::string out2 = iconvpp::Utf8toLatin(out);
fmt::fprintf(stdout, "%s\n", out2.c_str());
}
{
std::string in = "2018 你好";
std::string out = iconvpp::LatintoUtf8(in);
fmt::fprintf(stdout, "%s\n", out.c_str());
std::string out2 = iconvpp::Utf8toLatin(out);
fmt::fprintf(stdout, "%s\n", out2.c_str());
}
return 0;
}
|
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/core/mir/fusion/quant_dequant_fuse_pass.h"
#include <list>
#include <memory>
#include <vector>
#include "lite/api/paddle_place.h"
#include "lite/core/mir/fusion/quant_dequant_op_fuser.h"
#include "lite/core/mir/pass_registry.h"
namespace paddle {
namespace lite {
namespace mir {
void QuantDequantFusePass::Apply(const std::unique_ptr<SSAGraph>& graph) {
// delete quant node
std::vector<std::string> quant_op_types = {
"fake_quantize_range_abs_max", "fake_quantize_moving_average_abs_max"};
for (auto& op_type : quant_op_types) {
fusion::DeleteQuantOpFuser fuser(op_type);
fuser(graph.get());
}
// fuse quantized node and dequant node
for (auto& op_type : {"conv2d", "mul", "depthwise_conv2d"}) {
fusion::DequantOpFuser fuser(op_type);
fuser(graph.get());
}
for (auto& op_type : {"conv2d", "depthwise_conv2d"}) {
fusion::ChannelWiseDequantOpFuser fuser(op_type);
fuser(graph.get());
}
// delete quant_dequant_node
for (auto op_type : {"pool2d", "elementwise_add"}) {
fusion::DeleteQuantDequantOpFuser fuser(op_type);
fuser(graph.get());
}
}
} // namespace mir
} // namespace lite
} // namespace paddle
REGISTER_MIR_PASS(lite_quant_dequant_fuse_pass,
paddle::lite::mir::QuantDequantFusePass)
.BindTargets({TARGET(kAny)})
.BindKernel("calib");
|
#include <unistd.h>
#include <cassert>
#include <stdlib.h>
#include <QCoreApplication>
#include <QResource>
#include <QLocale>
#include <QFile>
#include <QHostInfo>
#include <QHostAddress>
#include <QString>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <cstdint>
#include <limits>
#include "HyperionConfig.h"
#include <utils/jsonschema/QJsonFactory.h>
#include <utils/Components.h>
#include <hyperion/Hyperion.h>
#include <hyperion/PriorityMuxer.h>
#include <effectengine/EffectEngine.h>
#include <bonjour/bonjourserviceregister.h>
#include <bonjour/bonjourrecord.h>
#include <jsonserver/JsonServer.h>
#include <protoserver/ProtoServer.h>
#include <boblightserver/BoblightServer.h>
#include <udplistener/UDPListener.h>
#include "hyperiond.h"
#include "configMigrator.h"
HyperionDaemon::HyperionDaemon(QString configFile, QObject *parent)
: QObject(parent)
, _log(Logger::getInstance("MAIN"))
, _kodiVideoChecker(nullptr)
, _jsonServer(nullptr)
, _protoServer(nullptr)
, _boblightServer(nullptr)
, _udpListener(nullptr)
, _v4l2Grabbers()
, _dispmanx(nullptr)
#ifdef ENABLE_X11
, _x11Grabber(nullptr)
#endif
, _amlGrabber(nullptr)
, _fbGrabber(nullptr)
, _osxGrabber(nullptr)
, _hyperion(nullptr)
{
loadConfig(configFile, CURRENT_CONFIG_VERSION );
if (Logger::getLogLevel() == Logger::WARNING)
{
if (_qconfig.contains("logger"))
{
const QJsonObject & logConfig = _qconfig["logger"].toObject();
std::string level = logConfig["level"].toString("warn").toStdString(); // silent warn verbose debug
if (level == "silent") Logger::setLogLevel(Logger::OFF);
else if (level == "warn") Logger::setLogLevel(Logger::WARNING);
else if (level == "verbose") Logger::setLogLevel(Logger::INFO);
else if (level == "debug") Logger::setLogLevel(Logger::DEBUG);
else Error(Logger::getInstance("LOGGER"), "log level '%s' used in config is unknown. valid: silent warn verbose debug", level.c_str());
}
}
else
{
WarningIf(_qconfig.contains("logger"), Logger::getInstance("LOGGER"), "Logger settings overridden by command line argument");
}
_hyperion = Hyperion::initInstance(_qconfig, configFile);
Info(_log, "Hyperion initialized");
}
HyperionDaemon::~HyperionDaemon()
{
freeObjects();
delete _hyperion;
}
void HyperionDaemon::freeObjects()
{
Debug(_log, "destroy grabbers and network stuff");
delete _amlGrabber;
delete _dispmanx;
delete _fbGrabber;
delete _osxGrabber;
for(V4L2Wrapper* grabber : _v4l2Grabbers)
{
delete grabber;
}
delete _kodiVideoChecker;
delete _jsonServer;
delete _protoServer;
delete _boblightServer;
delete _udpListener;
_v4l2Grabbers.clear();
_amlGrabber = nullptr;
_dispmanx = nullptr;
_fbGrabber = nullptr;
_osxGrabber = nullptr;
_kodiVideoChecker = nullptr;
_jsonServer = nullptr;
_protoServer = nullptr;
_boblightServer = nullptr;
_udpListener = nullptr;
}
void HyperionDaemon::run()
{
startInitialEffect();
createKODIVideoChecker();
// ---- network services -----
startNetworkServices();
// ---- grabber -----
createGrabberV4L2();
createSystemFrameGrabber();
#if !defined(ENABLE_DISPMANX) && !defined(ENABLE_OSX) && !defined(ENABLE_FB) && !defined(ENABLE_X11) && !defined(ENABLE_AMLOGIC)
WarningIf(_qconfig.contains("framegrabber"), _log, "No grabber can be instantiated, because all grabbers have been left out from the build");
#endif
Info(_log, "Hyperion started");
connect(_hyperion,SIGNAL(closing()),this,SLOT(freeObjects()));
}
int HyperionDaemon::tryLoadConfig(const QString & configFile, const int schemaVersion)
{
// make sure the resources are loaded (they may be left out after static linking)
Q_INIT_RESOURCE(resource);
// read the json schema from the resource
QString schemaFile = ":/hyperion-schema";
if (schemaVersion > 0)
schemaFile += "-" + QString::number(schemaVersion);
QJsonObject schemaJson;
try
{
schemaJson = QJsonFactory::readSchema(schemaFile);
}
catch(const std::runtime_error& error)
{
throw std::runtime_error(error.what());
}
QJsonSchemaChecker schemaChecker;
schemaChecker.setSchema(schemaJson);
_qconfig = QJsonFactory::readConfig(configFile);
if (!schemaChecker.validate(_qconfig))
{
for (std::list<std::string>::const_iterator i = schemaChecker.getMessages().begin(); i != schemaChecker.getMessages().end(); ++i)
{
std::cout << *i << std::endl;
}
throw std::runtime_error("ERROR: Json validation failed");
}
const QJsonObject & generalConfig = _qconfig["general"].toObject();
return generalConfig["configVersion"].toInt(-1);
}
void HyperionDaemon::loadConfig(const QString & configFile, const int neededConfigVersion)
{
Info(_log, "Selected configuration file: %s", configFile.toUtf8().constData());
int configVersionId = tryLoadConfig(configFile,0);
// no config id found, assume legacy hyperion
if (configVersionId < 0)
{
Debug(_log, "config file has no version, assume old hyperion.");
configVersionId = tryLoadConfig(configFile,1);
}
Debug(_log, "config version: %d", configVersionId);
configVersionId = tryLoadConfig(configFile, configVersionId);
if (neededConfigVersion == configVersionId)
{
return;
}
// migrate configVersionId
ConfigMigrator migrator;
migrator.migrate(configFile, configVersionId, neededConfigVersion);
}
void HyperionDaemon::startInitialEffect()
{
#define FGCONFIG_ARRAY fgColorConfig.toArray()
#define BGCONFIG_ARRAY bgColorConfig.toArray()
Hyperion *hyperion = Hyperion::getInstance();
// create boot sequence
const QJsonObject & FGEffectConfig = _qconfig["foregroundEffect"].toObject();
const QJsonObject & BGEffectConfig = _qconfig["backgroundEffect"].toObject();
const int FG_PRIORITY = 0;
const int DURATION_INFINITY = 0;
const int BG_PRIORITY = PriorityMuxer::LOWEST_PRIORITY -1;
// clear the leds
hyperion->setColor(FG_PRIORITY, ColorRgb::BLACK, 100, false);
// initial foreground effect/color
if (FGEffectConfig["enable"].toBool(true))
{
const QString fgTypeConfig = FGEffectConfig["type"].toString("effect");
const QString fgEffectConfig = FGEffectConfig["effect"].toString("Rainbow swirl fast");
const QJsonValue fgColorConfig = FGEffectConfig["color"];
int default_fg_duration_ms = 3000;
int fg_duration_ms = FGEffectConfig["duration_ms"].toInt(default_fg_duration_ms);
if (fg_duration_ms == DURATION_INFINITY)
{
fg_duration_ms = default_fg_duration_ms;
Warning(_log, "foreground effect duration 'infinity' is forbidden, set to default value %d ms",default_fg_duration_ms);
}
if ( fgTypeConfig.contains("color") )
{
ColorRgb fg_color = {
(uint8_t)FGCONFIG_ARRAY.at(0).toInt(0),
(uint8_t)FGCONFIG_ARRAY.at(1).toInt(0),
(uint8_t)FGCONFIG_ARRAY.at(2).toInt(0)
};
hyperion->setColor(FG_PRIORITY, fg_color, fg_duration_ms, false);
Info(_log,"Inital foreground color set (%d %d %d)",fg_color.red,fg_color.green,fg_color.blue);
}
else
{
int result = hyperion->setEffect(fgEffectConfig, FG_PRIORITY, fg_duration_ms);
Info(_log,"Inital foreground effect '%s' %s", fgEffectConfig.toUtf8().constData(), ((result == 0) ? "started" : "failed"));
}
}
// initial background effect/color
if (BGEffectConfig["enable"].toBool(true))
{
const QString bgTypeConfig = BGEffectConfig["type"].toString("effect");
const QString bgEffectConfig = BGEffectConfig["effect"].toString("Warm mood blobs");
const QJsonValue bgColorConfig = BGEffectConfig["color"];
if (bgTypeConfig.contains("color"))
{
ColorRgb bg_color = {
(uint8_t)BGCONFIG_ARRAY.at(0).toInt(0),
(uint8_t)BGCONFIG_ARRAY.at(1).toInt(0),
(uint8_t)BGCONFIG_ARRAY.at(2).toInt(0)
};
hyperion->setColor(BG_PRIORITY, bg_color, DURATION_INFINITY, false);
Info(_log,"Inital background color set (%d %d %d)",bg_color.red,bg_color.green,bg_color.blue);
}
else
{
int result = hyperion->setEffect(bgEffectConfig, BG_PRIORITY, DURATION_INFINITY);
Info(_log,"Inital background effect '%s' %s", bgEffectConfig.toUtf8().constData(), ((result == 0) ? "started" : "failed"));
}
}
#undef FGCONFIG_ARRAY
#undef BGCONFIG_ARRAY
}
// create KODI video checker if the _configuration is present
void HyperionDaemon::createKODIVideoChecker()
{
bool kodiCheckerConfigured = _qconfig.contains("kodiVideoChecker");
const QJsonObject & videoCheckerConfig = _qconfig["kodiVideoChecker"].toObject();
_kodiVideoChecker = KODIVideoChecker::initInstance(
videoCheckerConfig["kodiAddress"].toString("127.0.0.1"),
videoCheckerConfig["kodiTcpPort"].toInt(9090),
videoCheckerConfig["grabVideo"].toBool(true),
videoCheckerConfig["grabPictures"].toBool(true),
videoCheckerConfig["grabAudio"].toBool(true),
videoCheckerConfig["grabMenu"].toBool(false),
videoCheckerConfig["grabPause"].toBool(true),
videoCheckerConfig["grabScreensaver"].toBool(false),
videoCheckerConfig["enable3DDetection"].toBool(true));
Debug(_log, "KODI checker created ");
if( kodiCheckerConfigured && videoCheckerConfig["enable"].toBool(true))
{
_kodiVideoChecker->start();
}
_hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_KODICHECKER, _kodiVideoChecker->componentState());
connect( Hyperion::getInstance(), SIGNAL(componentStateChanged(hyperion::Components,bool)), _kodiVideoChecker, SLOT(componentStateChanged(hyperion::Components,bool)));
}
void HyperionDaemon::startNetworkServices()
{
KODIVideoChecker* kodiVideoChecker = KODIVideoChecker::getInstance();
// Create Json server if configuration is present
unsigned int jsonPort = 19444;
if (_qconfig.contains("jsonServer"))
{
const QJsonObject & jsonServerConfig = _qconfig["jsonServer"].toObject();
//jsonEnable = jsonServerConfig.get("enable", true).asBool();
jsonPort = jsonServerConfig["port"].toInt(jsonPort);
}
_jsonServer = new JsonServer(jsonPort);
Info(_log, "Json server created and started on port %d", _jsonServer->getPort());
// Create Proto server if configuration is present
unsigned int protoPort = 19445;
if (_qconfig.contains("protoServer"))
{
const QJsonObject & protoServerConfig = _qconfig["protoServer"].toObject();
//protoEnable = protoServerConfig.get("enable", true).asBool();
protoPort = protoServerConfig["port"].toInt(protoPort);
}
_protoServer = new ProtoServer(protoPort);
if (kodiVideoChecker != nullptr)
{
QObject::connect(kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), _protoServer, SIGNAL(grabbingMode(GrabbingMode)));
QObject::connect(kodiVideoChecker, SIGNAL(videoMode(VideoMode)), _protoServer, SIGNAL(videoMode(VideoMode)));
}
Info(_log, "Proto server created and started on port %d", _protoServer->getPort());
// Create Boblight server if configuration is present
bool boblightConfigured = _qconfig.contains("boblightServer");
const QJsonObject & boblightServerConfig = _qconfig["boblightServer"].toObject();
_boblightServer = new BoblightServer(
boblightServerConfig["priority"].toInt(710),
boblightServerConfig["port"].toInt(19333) );
Debug(_log, "Boblight server created");
if ( boblightConfigured && boblightServerConfig["enable"].toBool(true))
{
_boblightServer->start();
}
_hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_BOBLIGHTSERVER, _boblightServer->componentState());
connect( Hyperion::getInstance(), SIGNAL(componentStateChanged(hyperion::Components,bool)), _boblightServer, SLOT(componentStateChanged(hyperion::Components,bool)));
// Create UDP listener if configuration is present
bool udpListenerConfigured = _qconfig.contains("udpListener");
const QJsonObject & udpListenerConfig = _qconfig["udpListener"].toObject();
_udpListener = new UDPListener(
udpListenerConfig["priority"].toInt(700),
udpListenerConfig["timeout"].toInt(10000),
udpListenerConfig["address"].toString(""),
udpListenerConfig["port"].toInt(2801),
udpListenerConfig["shared"].toBool(false));
Debug(_log, "UDP listener created");
if ( udpListenerConfigured && udpListenerConfig["enable"].toBool(true))
{
_udpListener->start();
}
_hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_UDPLISTENER, _udpListener->componentState());
connect( Hyperion::getInstance(), SIGNAL(componentStateChanged(hyperion::Components,bool)), _udpListener, SLOT(componentStateChanged(hyperion::Components,bool)));
// zeroconf description - $leddevicename@$hostname
const QJsonObject & generalConfig = _qconfig["general"].toObject();
const std::string mDNSDescr = ( generalConfig["name"].toString("").toStdString()
+ "@" +
QHostInfo::localHostName().toStdString()
);
// zeroconf udp listener
if (_udpListener != nullptr) {
BonjourServiceRegister *bonjourRegister_udp = new BonjourServiceRegister();
bonjourRegister_udp->registerService(
BonjourRecord(mDNSDescr.c_str(), "_hyperiond-rgbled._udp", QString()),
_udpListener->getPort()
);
Debug(_log, "UDP LIstener mDNS responder started");
}
// zeroconf json
BonjourServiceRegister *bonjourRegister_json = new BonjourServiceRegister();
bonjourRegister_json->registerService(
BonjourRecord(mDNSDescr.c_str(), "_hyperiond-json._tcp", QString()),
_jsonServer->getPort()
);
Debug(_log, "Json mDNS responder started");
// zeroconf proto
BonjourServiceRegister *bonjourRegister_proto = new BonjourServiceRegister();
bonjourRegister_proto->registerService(
BonjourRecord(mDNSDescr.c_str(), "_hyperiond-proto._tcp", QString()),
_protoServer->getPort()
);
Debug(_log, "Proto mDNS responder started");
}
void HyperionDaemon::createSystemFrameGrabber()
{
if (_qconfig.contains("framegrabber"))
{
const QJsonObject & grabberConfig = _qconfig["framegrabber"].toObject();
// if (grabberConfig["enable"].toBool(true))
{
_grabber_width = grabberConfig["width"].toInt(96);
_grabber_height = grabberConfig["height"].toInt(96);
_grabber_frequency = grabberConfig["frequency_Hz"].toInt(10);
_grabber_priority = grabberConfig["priority"].toInt(900);
_grabber_cropLeft = grabberConfig["cropLeft"].toInt(0);
_grabber_cropRight = grabberConfig["cropRight"].toInt(0);
_grabber_cropTop = grabberConfig["cropTop"].toInt(0);
_grabber_cropBottom = grabberConfig["cropBottom"].toInt(0);
#ifdef ENABLE_OSX
QString type = "osx";
#else
QString type = grabberConfig["type"].toString("auto");
#endif
QFile amvideo("/dev/amvideo");
// auto eval of type
if ( type == "auto" )
{
// dispmanx -> on raspi
// TODO currently a compile option
#ifdef ENABLE_DISPMANX
if (true)
#else
if (false)
#endif
{
type = "dispmanx";
}
// amlogic -> /dev/amvideo exists
else if ( amvideo.exists() )
{
type = "amlogic";
}
// x11 -> if DISPLAY is set
else if (getenv("DISPLAY") != NULL )
{
type = "x11";
}
// framebuffer -> if nothing other applies
else
{
type = "framebuffer";
}
Info( _log, "set screen capture device to '%s'", type.toUtf8().constData());
}
bool grabberCompState = grabberConfig["enable"].toBool(true);
if (type == "") { Info( _log, "screen capture device disabled"); grabberCompState = false; }
else if (type == "framebuffer") createGrabberFramebuffer(grabberConfig);
else if (type == "dispmanx") createGrabberDispmanx();
else if (type == "amlogic") { createGrabberAmlogic(); createGrabberFramebuffer(grabberConfig); }
else if (type == "osx") createGrabberOsx(grabberConfig);
else if (type == "x11") createGrabberX11(grabberConfig);
else { Warning( _log, "unknown framegrabber type '%s'", type.toUtf8().constData()); grabberCompState = false; }
// _hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_GRABBER, grabberCompState);
_hyperion->setComponentState(hyperion::COMP_GRABBER, grabberCompState );
}
}
}
void HyperionDaemon::createGrabberDispmanx()
{
#ifdef ENABLE_DISPMANX
_dispmanx = new DispmanxWrapper(_grabber_width, _grabber_height, _grabber_frequency, _grabber_priority);
_dispmanx->setCropping(_grabber_cropLeft, _grabber_cropRight, _grabber_cropTop, _grabber_cropBottom);
QObject::connect(_kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), _dispmanx, SLOT(setGrabbingMode(GrabbingMode)));
QObject::connect(_kodiVideoChecker, SIGNAL(videoMode(VideoMode)), _dispmanx, SLOT(setVideoMode(VideoMode)));
QObject::connect(_dispmanx, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _protoServer, SLOT(sendImageToProtoSlaves(int, const Image<ColorRgb>&, const int)) );
QObject::connect(_dispmanx, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _hyperion, SLOT(setImage(int, const Image<ColorRgb>&, const int)) );
_dispmanx->start();
Info(_log, "DISPMANX frame grabber created and started");
#else
ErrorIf(_qconfig.contains("framegrabber"), _log, "The dispmanx framegrabber can not be instantiated, because it has been left out from the build");
#endif
}
void HyperionDaemon::createGrabberAmlogic()
{
#ifdef ENABLE_AMLOGIC
_amlGrabber = new AmlogicWrapper(_grabber_width, _grabber_height, _grabber_frequency, _grabber_priority-1);
QObject::connect(_kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), _amlGrabber, SLOT(setGrabbingMode(GrabbingMode)));
QObject::connect(_kodiVideoChecker, SIGNAL(videoMode(VideoMode)), _amlGrabber, SLOT(setVideoMode(VideoMode)));
QObject::connect(_amlGrabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _protoServer, SLOT(sendImageToProtoSlaves(int, const Image<ColorRgb>&, const int)) );
QObject::connect(_amlGrabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _hyperion, SLOT(setImage(int, const Image<ColorRgb>&, const int)) );
_amlGrabber->start();
Info(_log, "AMLOGIC grabber created and started");
#else
Error( _log, "The AMLOGIC grabber can not be instantiated, because it has been left out from the build");
#endif
}
void HyperionDaemon::createGrabberX11(const QJsonObject & grabberConfig)
{
#ifdef ENABLE_X11
_x11Grabber = new X11Wrapper(
grabberConfig["useXGetImage"].toBool(false),
_grabber_cropLeft, _grabber_cropRight, _grabber_cropTop, _grabber_cropBottom,
grabberConfig["horizontalPixelDecimation"].toInt(8),
grabberConfig["verticalPixelDecimation"].toInt(8),
_grabber_frequency, _grabber_priority );
QObject::connect(_kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), _x11Grabber, SLOT(setGrabbingMode(GrabbingMode)));
QObject::connect(_kodiVideoChecker, SIGNAL(videoMode(VideoMode)), _x11Grabber, SLOT(setVideoMode(VideoMode)));
QObject::connect(_x11Grabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _protoServer, SLOT(sendImageToProtoSlaves(int, const Image<ColorRgb>&, const int)) );
QObject::connect(_x11Grabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _hyperion, SLOT(setImage(int, const Image<ColorRgb>&, const int)) );
_x11Grabber->start();
Info(_log, "X11 grabber created and started");
#else
Error(_log, "The X11 grabber can not be instantiated, because it has been left out from the build");
#endif
}
void HyperionDaemon::createGrabberFramebuffer(const QJsonObject & grabberConfig)
{
#ifdef ENABLE_FB
// Construct and start the framebuffer grabber if the configuration is present
_fbGrabber = new FramebufferWrapper(
grabberConfig["device"].toString("/dev/fb0").toStdString(),
_grabber_width, _grabber_height, _grabber_frequency, _grabber_priority);
QObject::connect(_kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), _fbGrabber, SLOT(setGrabbingMode(GrabbingMode)));
QObject::connect(_kodiVideoChecker, SIGNAL(videoMode(VideoMode)), _fbGrabber, SLOT(setVideoMode(VideoMode)));
QObject::connect(_fbGrabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _protoServer, SLOT(sendImageToProtoSlaves(int, const Image<ColorRgb>&, const int)) );
QObject::connect(_fbGrabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _hyperion, SLOT(setImage(int, const Image<ColorRgb>&, const int)) );
_fbGrabber->start();
Info(_log, "Framebuffer grabber created and started");
#else
Error(_log, "The framebuffer grabber can not be instantiated, because it has been left out from the build");
#endif
}
void HyperionDaemon::createGrabberOsx(const QJsonObject & grabberConfig)
{
#ifdef ENABLE_OSX
// Construct and start the osx grabber if the configuration is present
_osxGrabber = new OsxWrapper(
grabberConfig["display"].toInt(0),
_grabber_width, _grabber_height, _grabber_frequency, _grabber_priority);
QObject::connect(_kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), _osxGrabber, SLOT(setGrabbingMode(GrabbingMode)));
QObject::connect(_kodiVideoChecker, SIGNAL(videoMode(VideoMode)), _osxGrabber, SLOT(setVideoMode(VideoMode)));
QObject::connect(_osxGrabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _protoServer, SLOT(sendImageToProtoSlaves(int, const Image<ColorRgb>&, const int)) );
QObject::connect(_osxGrabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _hyperion, SLOT(setImage(int, const Image<ColorRgb>&, const int)) );
_osxGrabber->start();
Info(_log, "OSX grabber created and started");
#else
Error(_log, "The osx grabber can not be instantiated, because it has been left out from the build");
#endif
}
void HyperionDaemon::createGrabberV4L2()
{
// construct and start the v4l2 grabber if the configuration is present
bool v4lConfigured = _qconfig.contains("grabberV4L2");
bool v4lStarted = false;
unsigned v4lEnableCount = 0;
if (_qconfig["grabberV4L2"].isArray())
{
const QJsonArray & v4lArray = _qconfig["grabberV4L2"].toArray();
for ( signed idx=0; idx<v4lArray.size(); idx++)
{
const QJsonObject & grabberConfig = v4lArray.at(idx).toObject();
bool enableV4l = v4lConfigured && grabberConfig["enable"].toBool(true);
if (enableV4l)
{
v4lEnableCount++;
}
#ifdef ENABLE_V4L2
V4L2Wrapper* grabber = new V4L2Wrapper(
grabberConfig["device"].toString("auto").toStdString(),
grabberConfig["input"].toInt(0),
parseVideoStandard(grabberConfig["standard"].toString("no-change").toStdString()),
parsePixelFormat(grabberConfig["pixelFormat"].toString("no-change").toStdString()),
grabberConfig["width"].toInt(-1),
grabberConfig["height"].toInt(-1),
grabberConfig["frameDecimation"].toInt(2),
grabberConfig["sizeDecimation"].toInt(8),
grabberConfig["redSignalThreshold"].toDouble(0.0),
grabberConfig["greenSignalThreshold"].toDouble(0.0),
grabberConfig["blueSignalThreshold"].toDouble(0.0),
grabberConfig["priority"].toInt(890));
grabber->set3D(parse3DMode(grabberConfig["mode"].toString("2D").toStdString()));
grabber->setCropping(
grabberConfig["cropLeft"].toInt(0),
grabberConfig["cropRight"].toInt(0),
grabberConfig["cropTop"].toInt(0),
grabberConfig["cropBottom"].toInt(0));
grabber->setSignalDetectionOffset(
grabberConfig["signalDetectionHorizontalOffsetMin"].toDouble(0.25),
grabberConfig["signalDetectionVerticalOffsetMin"].toDouble(0.25),
grabberConfig["signalDetectionHorizontalOffsetMax"].toDouble(0.75),
grabberConfig["signalDetectionVerticalOffsetMax"].toDouble(0.75));
Debug(_log, "V4L2 grabber created");
QObject::connect(grabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _protoServer, SLOT(sendImageToProtoSlaves(int, const Image<ColorRgb>&, const int)));
QObject::connect(grabber, SIGNAL(emitImage(int, const Image<ColorRgb>&, const int)), _hyperion, SLOT(setImage(int, const Image<ColorRgb>&, const int)));
if (grabberConfig["useKodiChecker"].toBool(false))
{
QObject::connect(_kodiVideoChecker, SIGNAL(grabbingMode(GrabbingMode)), grabber, SLOT(setGrabbingMode(GrabbingMode)));
}
if (enableV4l && grabber->start())
{
v4lStarted = true;
Info(_log, "V4L2 grabber started");
}
_v4l2Grabbers.push_back(grabber);
#endif
}
}
ErrorIf( (v4lEnableCount>0 && _v4l2Grabbers.size()==0), _log, "The v4l2 grabber can not be instantiated, because it has been left out from the build");
_hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_V4L, (_v4l2Grabbers.size()>0 && v4lEnableCount>0 && v4lStarted) );
}
|
/*
* Copyright (c) 2020, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "GameSizeDialog.h"
#include "Game.h"
#include <AK/IntegralMath.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/CheckBox.h>
#include <LibGUI/Label.h>
#include <LibGUI/SpinBox.h>
GameSizeDialog::GameSizeDialog(GUI::Window* parent, size_t board_size, size_t target, bool evil_ai)
: GUI::Dialog(parent)
, m_board_size(board_size)
, m_target_tile_power(AK::log2(target))
, m_evil_ai(evil_ai)
{
set_rect({ 0, 0, 250, 150 });
set_title("New Game");
set_icon(parent->icon());
set_resizable(false);
auto& main_widget = set_main_widget<GUI::Widget>();
main_widget.set_fill_with_background_color(true);
auto& layout = main_widget.set_layout<GUI::VerticalBoxLayout>();
layout.set_margins(4);
auto& board_size_box = main_widget.add<GUI::Widget>();
auto& input_layout = board_size_box.set_layout<GUI::HorizontalBoxLayout>();
input_layout.set_spacing(4);
board_size_box.add<GUI::Label>("Board size").set_text_alignment(Gfx::TextAlignment::CenterLeft);
auto& spinbox = board_size_box.add<GUI::SpinBox>();
auto& target_box = main_widget.add<GUI::Widget>();
auto& target_layout = target_box.set_layout<GUI::HorizontalBoxLayout>();
target_layout.set_spacing(4);
spinbox.set_min(2);
spinbox.set_value(m_board_size);
target_box.add<GUI::Label>("Target tile").set_text_alignment(Gfx::TextAlignment::CenterLeft);
auto& tile_value_label = target_box.add<GUI::Label>(String::number(target_tile()));
tile_value_label.set_text_alignment(Gfx::TextAlignment::CenterRight);
auto& target_spinbox = target_box.add<GUI::SpinBox>();
target_spinbox.set_max(Game::max_power_for_board(m_board_size));
target_spinbox.set_min(3);
target_spinbox.set_value(m_target_tile_power);
spinbox.on_change = [&](auto value) {
m_board_size = value;
target_spinbox.set_max(Game::max_power_for_board(m_board_size));
};
target_spinbox.on_change = [&](auto value) {
m_target_tile_power = value;
tile_value_label.set_text(String::number(target_tile()));
};
auto& evil_ai_checkbox = main_widget.add<GUI::CheckBox>("Evil AI");
evil_ai_checkbox.set_checked(m_evil_ai);
evil_ai_checkbox.on_checked = [this](auto checked) { m_evil_ai = checked; };
auto& temp_checkbox = main_widget.add<GUI::CheckBox>("Temporarily apply changes");
temp_checkbox.set_checked(m_temporary);
temp_checkbox.on_checked = [this](auto checked) { m_temporary = checked; };
auto& buttonbox = main_widget.add<GUI::Widget>();
auto& button_layout = buttonbox.set_layout<GUI::HorizontalBoxLayout>();
button_layout.set_spacing(10);
buttonbox.add<GUI::Button>("Cancel").on_click = [this](auto) {
done(Dialog::ExecCancel);
};
buttonbox.add<GUI::Button>("OK").on_click = [this](auto) {
done(Dialog::ExecOK);
};
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura/mus/mojo_gpu_memory_buffer_manager.h"
#include "base/logging.h"
#include "ui/aura/mus/mojo_gpu_memory_buffer.h"
namespace aura {
MojoGpuMemoryBufferManager::MojoGpuMemoryBufferManager() {}
MojoGpuMemoryBufferManager::~MojoGpuMemoryBufferManager() {}
std::unique_ptr<gfx::GpuMemoryBuffer>
MojoGpuMemoryBufferManager::AllocateGpuMemoryBuffer(
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
gpu::SurfaceHandle surface_handle) {
return MojoGpuMemoryBufferImpl::Create(size, format, usage);
}
std::unique_ptr<gfx::GpuMemoryBuffer>
MojoGpuMemoryBufferManager::CreateGpuMemoryBufferFromHandle(
const gfx::GpuMemoryBufferHandle& handle,
const gfx::Size& size,
gfx::BufferFormat format) {
const gfx::BufferUsage usage = gfx::BufferUsage::GPU_READ;
return MojoGpuMemoryBufferImpl::CreateFromHandle(handle, size, format, usage);
}
void MojoGpuMemoryBufferManager::SetDestructionSyncToken(
gfx::GpuMemoryBuffer* buffer,
const gpu::SyncToken& sync_token) {
NOTIMPLEMENTED();
}
} // namespace aura
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2013-2015 Adam Wulkiewicz, Lodz, Poland.
// This file was modified by Oracle on 2013, 2015.
// Modifications copyright (c) 2013-2015, Oracle and/or its affiliates.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "test_intersects.hpp"
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/util/rational.hpp>
template <typename P>
void test_intersects_polygon_polygon()
{
typedef bg::model::polygon<P, false, false> poly_ccw_o;
test_geometry<poly_ccw_o, poly_ccw_o>("POLYGON((1 1, 3 3, 2 5))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", true);
test_geometry<poly_ccw_o, poly_ccw_o>("POLYGON((6 6, 7 6, 7 7, 6 7))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", false);
test_geometry<poly_ccw_o, poly_ccw_o>("POLYGON((7 7, 9 7, 9 9, 7 9))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", true);
}
template <typename P>
void test_intersects_linestring_segment()
{
typedef bg::model::linestring<P> ls;
typedef bg::model::segment<P> seg;
test_geometry<ls, seg>("LINESTRING(1 1, 3 3, 2 5)", "SEGMENT(2 0, 2 6)", true);
test_geometry<ls, seg>("LINESTRING(1 1, 3 3)", "SEGMENT(1 0, 1 1)", true);
test_geometry<ls, seg>("LINESTRING(1 1, 3 3)", "SEGMENT(2 0, 2 2)", true);
test_geometry<ls, seg>("LINESTRING(1 1, 3 3)", "SEGMENT(3 0, 4 1)", false);
}
template <typename P>
void test_intersects_linestring_linestring()
{
typedef bg::model::linestring<P> ls;
test_geometry<ls, ls>("LINESTRING(0 0,2 0,3 0)", "LINESTRING(0 0,1 1,2 2)", true);
test_geometry<ls, ls>("LINESTRING(0 0,2 0,3 0)", "LINESTRING(2 2,1 1,0 0)", true);
test_geometry<ls, ls>("LINESTRING(3 0,2 0,0 0)", "LINESTRING(0 0,1 1,2 2)", true);
test_geometry<ls, ls>("LINESTRING(3 0,2 0,0 0)", "LINESTRING(2 2,1 1,0 0)", true);
test_geometry<ls, ls>("LINESTRING(0 0,2 0,3 0)", "LINESTRING(1 0,4 0,5 0)", true);
test_geometry<ls, ls>("LINESTRING(1 0,2 0)", "LINESTRING(1 0,0 0)", true);
}
template <typename P>
void test_intersects_linestring_polygon()
{
typedef bg::model::linestring<P> ls;
typedef bg::model::multi_linestring<ls> mls;
typedef bg::model::polygon<P> poly_cw_c;
typedef bg::model::polygon<P, false> poly_ccw_c;
typedef bg::model::polygon<P, false, false> poly_ccw_o;
typedef bg::model::multi_polygon<poly_ccw_c> mpoly_ccw_c;
test_geometry<ls, poly_ccw_c>("LINESTRING(1 1,2 2)", "POLYGON((0 0,10 0,10 10,0 10,0 0))", true);
test_geometry<ls, poly_ccw_c>("LINESTRING(1 0,2 2)", "POLYGON((0 0,10 0,10 10,0 10,0 0))", true);
test_geometry<ls, poly_ccw_c>("LINESTRING(11 0,12 12)", "POLYGON((0 0,10 0,10 10,0 10,0 0))", false);
test_geometry<ls, poly_ccw_o>("LINESTRING(1 1, 3 3, 2 5)", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", true);
test_geometry<ls, poly_ccw_o>("LINESTRING(6 6, 7 6, 7 7, 6 7)", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", false);
test_geometry<ls, poly_ccw_o>("LINESTRING(7 7, 9 7, 9 9, 7 9)", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", true);
test_geometry<poly_cw_c, ls>("POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))", "LINESTRING(-2 -2, 12 7)", true);
test_geometry<poly_cw_c, ls>("POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))", "LINESTRING(5 5, 15 4)", true);
test_geometry<poly_cw_c, ls>("POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))", "LINESTRING(7 6, 15 4)", true);
test_geometry<poly_cw_c, ls>("POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))", "LINESTRING(6 2, 12 1)", true);
// MULTI
test_geometry<ls, mpoly_ccw_c>("LINESTRING(1 1,2 2)", "MULTIPOLYGON(((0 0,10 0,10 10,0 10,0 0)))", true);
test_geometry<mls, mpoly_ccw_c>("MULTILINESTRING((1 1,2 2))", "MULTIPOLYGON(((0 0,10 0,10 10,0 10,0 0)))", true);
}
template <typename P>
void test_intersects_linestring_ring()
{
typedef bg::model::linestring<P> ls;
typedef bg::model::multi_linestring<ls> mls;
typedef bg::model::ring<P, false> ring_ccw_c;
test_geometry<ls, ring_ccw_c>("LINESTRING(1 1,2 2)", "POLYGON((0 0,10 0,10 10,0 10,0 0))", true);
test_geometry<ls, ring_ccw_c>("LINESTRING(1 0,2 2)", "POLYGON((0 0,10 0,10 10,0 10,0 0))", true);
test_geometry<ls, ring_ccw_c>("LINESTRING(11 0,12 12)", "POLYGON((0 0,10 0,10 10,0 10,0 0))", false);
// MULTI
test_geometry<mls, ring_ccw_c>("MULTILINESTRING((1 1,2 2))", "POLYGON((0 0,10 0,10 10,0 10,0 0))", true);
}
template <typename P>
void test_intersects_ring_polygon()
{
typedef bg::model::ring<P, false, false> ring_ccw_o;
typedef bg::model::polygon<P, false, false> poly_ccw_o;
test_geometry<ring_ccw_o, poly_ccw_o>("POLYGON((1 1, 3 3, 2 5))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", true);
test_geometry<ring_ccw_o, poly_ccw_o>("POLYGON((6 6, 7 6, 7 7, 6 7))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", false);
test_geometry<ring_ccw_o, poly_ccw_o>("POLYGON((7 7, 9 7, 9 9, 7 9))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", true);
test_geometry<ring_ccw_o, poly_ccw_o>("POLYGON((6 6,7 6,7 7,6 7))", "POLYGON((0 0, 9 0, 9 9, 0 9),(5 5,5 8,8 8,8 5))", false);
}
template <typename P>
void test_intersects_point_linestring()
{
typedef bg::model::linestring<P> ls;
typedef bg::model::multi_linestring<ls> mls;
test_geometry<P, ls>("POINT(0 0)", "LINESTRING(0 0,2 2,4 0)", true);
test_geometry<P, ls>("POINT(1 1)", "LINESTRING(0 0,2 2,4 0)", true);
test_geometry<P, ls>("POINT(1 0)", "LINESTRING(0 0,2 2,4 0)", false);
// MULTI
test_geometry<P, mls>("POINT(0 0)", "MULTILINESTRING((0 0,2 2,4 0))", true);
}
template <typename P>
void test_intersects_point_segment()
{
typedef bg::model::segment<P> seg;
test_geometry<P, seg>("POINT(0 0)", "LINESTRING(0 0,2 2)", true);
test_geometry<P, seg>("POINT(1 1)", "LINESTRING(0 0,2 2)", true);
test_geometry<P, seg>("POINT(1 0)", "LINESTRING(0 0,2 2)", false);
}
template <typename P>
void test_multi_linestring_polygon()
{
typedef bg::model::linestring<P> ls;
typedef bg::model::multi_linestring<ls> mls;
typedef bg::model::polygon<P> poly;
test_geometry<mls, poly>("MULTILINESTRING((11 11, 20 20),(5 7, 4 1))",
"POLYGON((0 0,0 10,10 10,10 0,0 0),(2 2,4 2,4 4,2 4,2 2))",
true);
test_geometry<mls, poly>("MULTILINESTRING((10 0, 18 12),(2 2,2 1))",
"POLYGON((5 0,0 -5,-5 0,0 5,5 0))",
true);
}
template <typename P>
void test_multi_polygon_polygon()
{
typedef bg::model::polygon<P> poly;
typedef bg::model::multi_polygon<poly> mpoly;
test_geometry<mpoly, poly>("MULTIPOLYGON(((11 11,11 20,20 20,20 11,11 11)),((5 5,5 6,6 6,6 5,5 5)))",
"POLYGON((0 0,0 10,10 10,10 0,0 0),(2 2,4 2,4 4,2 4,2 2))",
true);
}
template <typename P>
void test_all()
{
typedef bg::model::polygon<P> polygon;
typedef bg::model::ring<P> ring;
test_intersects_point_segment<P>();
test_intersects_point_linestring<P>();
test_intersects_polygon_polygon<P>();
test_intersects_linestring_polygon<P>();
test_intersects_linestring_ring<P>();
test_intersects_linestring_segment<P>();
test_intersects_linestring_linestring<P>();
test_intersects_ring_polygon<P>();
test_multi_linestring_polygon<P>();
test_multi_polygon_polygon<P>();
test_geometry<P, ring>(
"POINT(0 0)",
"POLYGON((0 0,3 3,3 3,4 1))",
true);
test_geometry<P, polygon>(
"POINT(0 0)",
"POLYGON((0 0,3 3,3 3,4 1))",
true);
test_geometry<ring, P>(
"POLYGON((0 0,3 3,3 3,4 1))",
"POINT(0 0)",
true);
test_geometry<polygon, P>(
"POLYGON((0 0,3 3,3 3,4 1))",
"POINT(0 0)",
true);
}
int test_main( int , char* [] )
{
test_all<bg::model::d2::point_xy<double> >();
#if ! defined(BOOST_GEOMETRY_RESCALE_TO_ROBUST)
test_all<bg::model::d2::point_xy<boost::rational<int> > >();
#endif
#if defined(HAVE_TTMATH)
test_all<bg::model::d2::point_xy<ttmath_big> >();
#endif
return 0;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/tabs/windows_event_router.h"
#include <utility>
#include "base/bind.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/extensions/api/tabs/app_base_window.h"
#include "chrome/browser/extensions/api/tabs/app_window_controller.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/api/tabs/windows_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/window_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/windows.h"
#include "chrome/common/extensions/extension_constants.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_util.h"
#include "extensions/common/constants.h"
#include "extensions/common/mojom/event_dispatcher.mojom.h"
using content::BrowserContext;
namespace extensions {
namespace windows = extensions::api::windows;
namespace {
bool ControllerVisibleToListener(WindowController* window_controller,
const Extension* extension,
const base::DictionaryValue* listener_filter) {
if (!window_controller)
return false;
// If there is no filter the visibility is based on the extension.
const base::ListValue* filter_value = nullptr;
if (listener_filter)
listener_filter->GetList(extensions::tabs_constants::kWindowTypesKey,
&filter_value);
// TODO(https://crbug.com/807313): Remove this.
bool allow_dev_tools_windows = !!filter_value;
if (!window_controller->IsVisibleToTabsAPIForExtension(
extension, allow_dev_tools_windows)) {
return false;
}
return !filter_value ||
window_controller->MatchesFilter(
WindowController::GetFilterFromWindowTypesValues(filter_value));
}
bool WillDispatchWindowEvent(WindowController* window_controller,
BrowserContext* browser_context,
Feature::Context target_context,
const Extension* extension,
Event* event,
const base::DictionaryValue* listener_filter) {
bool has_filter =
listener_filter &&
listener_filter->HasKey(extensions::tabs_constants::kWindowTypesKey);
// TODO(https://crbug.com/807313): Remove this.
bool allow_dev_tools_windows = has_filter;
if (!window_controller->IsVisibleToTabsAPIForExtension(
extension, allow_dev_tools_windows)) {
return false;
}
// Cleanup previous values.
event->filter_info = mojom::EventFilteringInfo::New();
// Only set the window type if the listener has set a filter.
// Otherwise we set the window visibility relative to the extension.
if (has_filter) {
event->filter_info->window_type = window_controller->GetWindowTypeText();
} else {
event->filter_info->has_window_exposed_by_default = true;
event->filter_info->window_exposed_by_default = true;
}
return true;
}
bool WillDispatchWindowFocusedEvent(
WindowController* window_controller,
BrowserContext* browser_context,
Feature::Context target_context,
const Extension* extension,
Event* event,
const base::DictionaryValue* listener_filter) {
int window_id = extension_misc::kUnknownWindowId;
Profile* new_active_context = nullptr;
bool has_filter =
listener_filter &&
listener_filter->HasKey(extensions::tabs_constants::kWindowTypesKey);
// We might not have a window controller if the focus moves away
// from chromium's windows.
if (window_controller) {
window_id = window_controller->GetWindowId();
new_active_context = window_controller->profile();
}
// Cleanup previous values.
event->filter_info = mojom::EventFilteringInfo::New();
// Only set the window type if the listener has set a filter,
// otherwise set the visibility to true (if the window is not
// supposed to be visible by the extension, we will clear out the
// window id later).
if (has_filter) {
event->filter_info->window_type =
window_controller ? window_controller->GetWindowTypeText()
: extensions::tabs_constants::kWindowTypeValueNormal;
} else {
event->filter_info->has_window_exposed_by_default = true;
event->filter_info->window_exposed_by_default = true;
}
// When switching between windows in the default and incognito profiles,
// dispatch WINDOW_ID_NONE to extensions whose profile lost focus that
// can't see the new focused window across the incognito boundary.
// See crbug.com/46610.
bool cant_cross_incognito =
new_active_context && new_active_context != browser_context &&
!util::CanCrossIncognito(extension, browser_context);
// If the window is not visible by the listener, we also need to
// clear out the window id from the event.
bool visible_to_listener = ControllerVisibleToListener(
window_controller, extension, listener_filter);
if (cant_cross_incognito || !visible_to_listener) {
event->event_args->ClearList();
event->event_args->Append(extension_misc::kUnknownWindowId);
} else {
event->event_args->ClearList();
event->event_args->Append(window_id);
}
return true;
}
} // namespace
WindowsEventRouter::WindowsEventRouter(Profile* profile)
: profile_(profile),
focused_profile_(nullptr),
focused_window_id_(extension_misc::kUnknownWindowId) {
DCHECK(!profile->IsOffTheRecord());
observed_app_registry_.Observe(AppWindowRegistry::Get(profile_));
observed_controller_list_.Observe(WindowControllerList::GetInstance());
// Needed for when no suitable window can be passed to an extension as the
// currently focused window. On Mac (even in a toolkit-views build) always
// rely on the notification sent by AppControllerMac after AppKit sends
// NSWindowDidBecomeKeyNotification and there is no [NSApp keyWindo7w]. This
// allows windows not created by toolkit-views to be tracked.
#if defined(OS_MAC)
observed_key_window_notifier_.Observe(
&g_browser_process->platform_part()->key_window_notifier());
#elif defined(TOOLKIT_VIEWS)
views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);
#else
#error Unsupported
#endif
AppWindowRegistry* registry = AppWindowRegistry::Get(profile_);
for (AppWindow* app_window : registry->app_windows())
AddAppWindow(app_window);
}
WindowsEventRouter::~WindowsEventRouter() {
#if defined(TOOLKIT_VIEWS) && !defined(OS_MAC)
views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);
#endif
}
void WindowsEventRouter::OnAppWindowAdded(extensions::AppWindow* app_window) {
if (!profile_->IsSameOrParent(
Profile::FromBrowserContext(app_window->browser_context())))
return;
AddAppWindow(app_window);
}
void WindowsEventRouter::OnAppWindowRemoved(extensions::AppWindow* app_window) {
if (!profile_->IsSameOrParent(
Profile::FromBrowserContext(app_window->browser_context())))
return;
app_windows_.erase(app_window->session_id().id());
}
void WindowsEventRouter::OnAppWindowActivated(
extensions::AppWindow* app_window) {
AppWindowMap::const_iterator iter =
app_windows_.find(app_window->session_id().id());
OnActiveWindowChanged(iter != app_windows_.end() ? iter->second.get()
: nullptr);
}
void WindowsEventRouter::OnWindowControllerAdded(
WindowController* window_controller) {
if (!HasEventListener(windows::OnCreated::kEventName))
return;
if (!profile_->IsSameOrParent(window_controller->profile()))
return;
// Ignore any windows without an associated browser (e.g., AppWindows).
if (!window_controller->GetBrowser())
return;
std::unique_ptr<base::ListValue> args(new base::ListValue());
// Since we don't populate tab info here, the context type doesn't matter.
constexpr ExtensionTabUtil::PopulateTabBehavior populate_behavior =
ExtensionTabUtil::kDontPopulateTabs;
constexpr Feature::Context context_type = Feature::UNSPECIFIED_CONTEXT;
args->Append(ExtensionTabUtil::CreateWindowValueForExtension(
*window_controller->GetBrowser(), nullptr, populate_behavior,
context_type));
DispatchEvent(events::WINDOWS_ON_CREATED, windows::OnCreated::kEventName,
window_controller, std::move(args));
}
void WindowsEventRouter::OnWindowControllerRemoved(
WindowController* window_controller) {
if (!HasEventListener(windows::OnRemoved::kEventName))
return;
if (!profile_->IsSameOrParent(window_controller->profile()))
return;
// Ignore any windows without an associated browser (e.g., AppWindows).
if (!window_controller->GetBrowser())
return;
int window_id = window_controller->GetWindowId();
std::unique_ptr<base::ListValue> args(new base::ListValue());
args->Append(window_id);
DispatchEvent(events::WINDOWS_ON_REMOVED, windows::OnRemoved::kEventName,
window_controller, std::move(args));
}
void WindowsEventRouter::OnWindowBoundsChanged(
WindowController* window_controller) {
if (!HasEventListener(windows::OnBoundsChanged::kEventName))
return;
if (!profile_->IsSameOrParent(window_controller->profile()))
return;
// Ignore any windows without an associated browser (e.g., AppWindows).
if (!window_controller->GetBrowser())
return;
auto args = std::make_unique<base::ListValue>();
// Since we don't populate tab info here, the context type doesn't matter.
constexpr ExtensionTabUtil::PopulateTabBehavior populate_behavior =
ExtensionTabUtil::kDontPopulateTabs;
constexpr Feature::Context context_type = Feature::UNSPECIFIED_CONTEXT;
args->Append(ExtensionTabUtil::CreateWindowValueForExtension(
*window_controller->GetBrowser(), nullptr, populate_behavior,
context_type));
DispatchEvent(events::WINDOWS_ON_BOUNDS_CHANGED,
windows::OnBoundsChanged::kEventName, window_controller,
std::move(args));
}
#if defined(TOOLKIT_VIEWS) && !defined(OS_MAC)
void WindowsEventRouter::OnNativeFocusChanged(gfx::NativeView focused_now) {
if (!focused_now)
OnActiveWindowChanged(nullptr);
}
#endif
#if defined(OS_MAC)
void WindowsEventRouter::OnNoKeyWindow() {
OnActiveWindowChanged(nullptr);
}
#endif
void WindowsEventRouter::OnActiveWindowChanged(
WindowController* window_controller) {
Profile* window_profile = nullptr;
int window_id = extension_misc::kUnknownWindowId;
if (window_controller &&
profile_->IsSameOrParent(window_controller->profile())) {
window_profile = window_controller->profile();
window_id = window_controller->GetWindowId();
}
if (focused_window_id_ == window_id)
return;
// window_profile is either the default profile for the active window, its
// incognito profile, or nullptr if the previous profile is losing focus.
focused_profile_ = window_profile;
focused_window_id_ = window_id;
if (!HasEventListener(windows::OnFocusChanged::kEventName))
return;
std::unique_ptr<Event> event = std::make_unique<Event>(
events::WINDOWS_ON_FOCUS_CHANGED, windows::OnFocusChanged::kEventName,
std::vector<base::Value>());
event->will_dispatch_callback =
base::BindRepeating(&WillDispatchWindowFocusedEvent, window_controller);
EventRouter::Get(profile_)->BroadcastEvent(std::move(event));
}
void WindowsEventRouter::DispatchEvent(events::HistogramValue histogram_value,
const std::string& event_name,
WindowController* window_controller,
std::unique_ptr<base::ListValue> args) {
auto event = std::make_unique<Event>(histogram_value, event_name,
std::move(*args).TakeList(),
window_controller->profile());
event->will_dispatch_callback =
base::BindRepeating(&WillDispatchWindowEvent, window_controller);
EventRouter::Get(profile_)->BroadcastEvent(std::move(event));
}
bool WindowsEventRouter::HasEventListener(const std::string& event_name) {
return EventRouter::Get(profile_)->HasEventListener(event_name);
}
void WindowsEventRouter::AddAppWindow(extensions::AppWindow* app_window) {
std::unique_ptr<AppWindowController> controller(new AppWindowController(
app_window, std::make_unique<AppBaseWindow>(app_window), profile_));
app_windows_[app_window->session_id().id()] = std::move(controller);
}
} // namespace extensions
|
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Created by İhsan Demir on 21/12/15.
//
#include <hazelcast/client/HazelcastClient.h>
#include <hazelcast/client/adaptor/RawPointerMap.h>
using namespace hazelcast::client;
class BaseDataSerializable : public serialization::IdentifiedDataSerializable {
public:
virtual ~BaseDataSerializable() {}
virtual int getFactoryId() const {
return 666;
}
virtual int getClassId() const {
return 10;
}
virtual void writeData(serialization::ObjectDataOutput &writer) const {
}
virtual void readData(serialization::ObjectDataInput &reader) {
}
virtual bool operator<(const BaseDataSerializable &rhs) const {
return getClassId() < rhs.getClassId();
}
};
class Derived1DataSerializable : public BaseDataSerializable {
public:
virtual int getClassId() const {
return 11;
}
};
class Derived2DataSerializable : public Derived1DataSerializable {
public:
virtual int getClassId() const {
return 12;
}
};
class PolymorphicDataSerializableFactory : public serialization::DataSerializableFactory {
public:
virtual std::auto_ptr<serialization::IdentifiedDataSerializable> create(int32_t typeId) {
switch (typeId) {
case 10:
return std::auto_ptr<serialization::IdentifiedDataSerializable>(new BaseDataSerializable);
case 11:
return std::auto_ptr<serialization::IdentifiedDataSerializable>(new Derived1DataSerializable);
case 12:
return std::auto_ptr<serialization::IdentifiedDataSerializable>(new Derived2DataSerializable);
default:
return std::auto_ptr<serialization::IdentifiedDataSerializable>();
}
}
};
int main() {
ClientConfig config;
SerializationConfig &serializationConfig = config.getSerializationConfig();
serializationConfig.addDataSerializableFactory(666,
boost::shared_ptr<serialization::DataSerializableFactory>(
new PolymorphicDataSerializableFactory()));
HazelcastClient client(config);
IMap<int, BaseDataSerializable> imapCustom(client.getMap<int, BaseDataSerializable>("MyMap"));
adaptor::RawPointerMap<int, BaseDataSerializable> rawPointerMap(imapCustom);
BaseDataSerializable base;
Derived1DataSerializable derived1;
Derived2DataSerializable derived2;
rawPointerMap.put(1, base);
rawPointerMap.put(2, derived1);
rawPointerMap.put(3, derived2);
std::auto_ptr<BaseDataSerializable> value = rawPointerMap.get(3);
std::cout << "Got the value for key 3. The value class id is:" << value->getClassId() << std::endl;
std::set<int> keys;
keys.insert(1);
keys.insert(2);
keys.insert(3);
std::auto_ptr<EntryArray<int, BaseDataSerializable> > entries = rawPointerMap.getAll(keys);
size_t numberOfEntries = entries->size();
std::cout << "Got " << numberOfEntries << " entries from the map." << std::endl;
for (size_t i = 0; i < numberOfEntries; ++i) {
std::pair<const int *, const BaseDataSerializable *> entry = (*entries)[i];
std::cout << "Entry " << i << ": (" << *entry.first << ", " << entry.second->getClassId() << ")" << std::endl;
}
std::cout << "Finished" << std::endl;
return 0;
}
|
#include <iostream>
#include <vector>
template <typename T, typename U>
std::istream& operator >>(std::istream& input, std::pair<T, U>& v)
{
return input >> v.first >> v.second;
}
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(unsigned long long v)
{
std::cout << v << '\n';
}
void solve(unsigned n, unsigned m, unsigned r, unsigned c, const std::vector<std::pair<int, int>>& d)
{
unsigned long long k = 0;
for (const auto [dr, dc] : d) {
unsigned dk = ~0u;
if (dr > 0)
dk = std::min(dk, (n - r) / dr);
if (dr < 0)
dk = std::min(dk, (r - 1) / -dr);
if (dc > 0)
dk = std::min(dk, (m - c) / dc);
if (dc < 0)
dk = std::min(dk, (c - 1) / -dc);
r += dk * dr;
c += dk * dc;
k += dk;
}
answer(k);
}
int main()
{
unsigned n, m;
std::cin >> n >> m;
unsigned r, c;
std::cin >> r >> c;
size_t k;
std::cin >> k;
std::vector<std::pair<int, int>> d(k);
std::cin >> d;
solve(n, m, r, c, d);
return 0;
}
|
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2021, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include "core/matrix/sellp_kernels.hpp"
#include <hip/hip_runtime.h>
#include <ginkgo/core/base/exception_helpers.hpp>
#include <ginkgo/core/base/math.hpp>
#include <ginkgo/core/base/types.hpp>
#include <ginkgo/core/matrix/csr.hpp>
#include <ginkgo/core/matrix/dense.hpp>
#include "core/components/prefix_sum.hpp"
#include "hip/base/config.hip.hpp"
#include "hip/base/hipsparse_bindings.hip.hpp"
#include "hip/base/types.hip.hpp"
#include "hip/components/reduction.hip.hpp"
#include "hip/components/thread_ids.hip.hpp"
namespace gko {
namespace kernels {
namespace hip {
/**
* @brief The SELL-P matrix format namespace.
*
* @ingroup sellp
*/
namespace sellp {
constexpr int default_block_size = 512;
#include "common/cuda_hip/matrix/sellp_kernels.hpp.inc"
template <typename ValueType, typename IndexType>
void spmv(std::shared_ptr<const HipExecutor> exec,
const matrix::Sellp<ValueType, IndexType>* a,
const matrix::Dense<ValueType>* b, matrix::Dense<ValueType>* c)
{
const dim3 blockSize(matrix::default_slice_size);
const dim3 gridSize(ceildiv(a->get_size()[0], matrix::default_slice_size),
b->get_size()[1]);
hipLaunchKernelGGL(
spmv_kernel, dim3(gridSize), dim3(blockSize), 0, 0, a->get_size()[0],
b->get_size()[1], b->get_stride(), c->get_stride(),
a->get_const_slice_lengths(), a->get_const_slice_sets(),
as_hip_type(a->get_const_values()), a->get_const_col_idxs(),
as_hip_type(b->get_const_values()), as_hip_type(c->get_values()));
}
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(GKO_DECLARE_SELLP_SPMV_KERNEL);
template <typename ValueType, typename IndexType>
void advanced_spmv(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType>* alpha,
const matrix::Sellp<ValueType, IndexType>* a,
const matrix::Dense<ValueType>* b,
const matrix::Dense<ValueType>* beta,
matrix::Dense<ValueType>* c)
{
const dim3 blockSize(matrix::default_slice_size);
const dim3 gridSize(ceildiv(a->get_size()[0], matrix::default_slice_size),
b->get_size()[1]);
hipLaunchKernelGGL(
advanced_spmv_kernel, dim3(gridSize), dim3(blockSize), 0, 0,
a->get_size()[0], b->get_size()[1], b->get_stride(), c->get_stride(),
a->get_const_slice_lengths(), a->get_const_slice_sets(),
as_hip_type(alpha->get_const_values()),
as_hip_type(a->get_const_values()), a->get_const_col_idxs(),
as_hip_type(b->get_const_values()),
as_hip_type(beta->get_const_values()), as_hip_type(c->get_values()));
}
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_SELLP_ADVANCED_SPMV_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_dense(std::shared_ptr<const HipExecutor> exec,
const matrix::Sellp<ValueType, IndexType>* source,
matrix::Dense<ValueType>* result)
{
const auto num_rows = source->get_size()[0];
const auto num_cols = source->get_size()[1];
const auto vals = source->get_const_values();
const auto col_idxs = source->get_const_col_idxs();
const auto slice_lengths = source->get_const_slice_lengths();
const auto slice_sets = source->get_const_slice_sets();
const auto slice_size = source->get_slice_size();
const auto slice_num = ceildiv(num_rows, slice_size);
const dim3 block_size(config::warp_size,
config::max_block_size / config::warp_size, 1);
const dim3 init_grid_dim(ceildiv(num_cols, block_size.x),
ceildiv(num_rows, block_size.y), 1);
if (num_rows > 0 && result->get_stride() > 0) {
hipLaunchKernelGGL(kernel::initialize_zero_dense, dim3(init_grid_dim),
dim3(block_size), 0, 0, num_rows, num_cols,
result->get_stride(),
as_hip_type(result->get_values()));
}
constexpr auto threads_per_row = config::warp_size;
const auto grid_dim =
ceildiv(slice_size * slice_num * threads_per_row, default_block_size);
if (grid_dim > 0) {
hipLaunchKernelGGL(
HIP_KERNEL_NAME(kernel::fill_in_dense<threads_per_row>),
dim3(grid_dim), dim3(default_block_size), 0, 0, num_rows, num_cols,
result->get_stride(), slice_size, as_hip_type(slice_lengths),
as_hip_type(slice_sets), as_hip_type(col_idxs), as_hip_type(vals),
as_hip_type(result->get_values()));
}
}
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_SELLP_CONVERT_TO_DENSE_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_csr(std::shared_ptr<const HipExecutor> exec,
const matrix::Sellp<ValueType, IndexType>* source,
matrix::Csr<ValueType, IndexType>* result)
{
const auto num_rows = source->get_size()[0];
const auto slice_size = source->get_slice_size();
const auto slice_num = ceildiv(num_rows, slice_size);
const auto source_values = source->get_const_values();
const auto source_slice_lengths = source->get_const_slice_lengths();
const auto source_slice_sets = source->get_const_slice_sets();
const auto source_col_idxs = source->get_const_col_idxs();
auto result_values = result->get_values();
auto result_col_idxs = result->get_col_idxs();
auto result_row_ptrs = result->get_row_ptrs();
auto grid_dim = ceildiv(num_rows * config::warp_size, default_block_size);
if (grid_dim > 0) {
hipLaunchKernelGGL(
kernel::count_nnz_per_row, dim3(grid_dim), dim3(default_block_size),
0, 0, num_rows, slice_size, as_hip_type(source_slice_sets),
as_hip_type(source_values), as_hip_type(result_row_ptrs));
}
components::prefix_sum(exec, result_row_ptrs, num_rows + 1);
grid_dim = ceildiv(num_rows, default_block_size);
if (grid_dim > 0) {
hipLaunchKernelGGL(
kernel::fill_in_csr, dim3(grid_dim), dim3(default_block_size), 0, 0,
num_rows, slice_size, as_hip_type(source_slice_sets),
as_hip_type(source_col_idxs), as_hip_type(source_values),
as_hip_type(result_row_ptrs), as_hip_type(result_col_idxs),
as_hip_type(result_values));
}
}
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_SELLP_CONVERT_TO_CSR_KERNEL);
template <typename ValueType, typename IndexType>
void count_nonzeros(std::shared_ptr<const HipExecutor> exec,
const matrix::Sellp<ValueType, IndexType>* source,
size_type* result)
{
const auto num_rows = source->get_size()[0];
if (num_rows <= 0) {
*result = 0;
return;
}
const auto slice_size = source->get_slice_size();
const auto slice_sets = source->get_const_slice_sets();
const auto values = source->get_const_values();
auto nnz_per_row = Array<size_type>(exec, num_rows);
auto grid_dim = ceildiv(num_rows * config::warp_size, default_block_size);
hipLaunchKernelGGL(kernel::count_nnz_per_row, dim3(grid_dim),
dim3(default_block_size), 0, 0, num_rows, slice_size,
as_hip_type(slice_sets), as_hip_type(values),
as_hip_type(nnz_per_row.get_data()));
*result = reduce_add_array(exec, num_rows, nnz_per_row.get_const_data());
}
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_SELLP_COUNT_NONZEROS_KERNEL);
template <typename ValueType, typename IndexType>
void extract_diagonal(std::shared_ptr<const HipExecutor> exec,
const matrix::Sellp<ValueType, IndexType>* orig,
matrix::Diagonal<ValueType>* diag)
{
const auto diag_size = diag->get_size()[0];
const auto slice_size = orig->get_slice_size();
const auto slice_num = ceildiv(diag_size, slice_size);
const auto num_blocks =
ceildiv(slice_num * config::warp_size, default_block_size);
const auto orig_slice_sets = orig->get_const_slice_sets();
const auto orig_values = orig->get_const_values();
const auto orig_col_idxs = orig->get_const_col_idxs();
auto diag_values = diag->get_values();
hipLaunchKernelGGL(kernel::extract_diagonal, dim3(num_blocks),
dim3(default_block_size), 0, 0, diag_size, slice_size,
as_hip_type(orig_slice_sets), as_hip_type(orig_values),
as_hip_type(orig_col_idxs), as_hip_type(diag_values));
}
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_SELLP_EXTRACT_DIAGONAL_KERNEL);
} // namespace sellp
} // namespace hip
} // namespace kernels
} // namespace gko
|
/* ************************************************************************************** */
/* This is a Helix API Test file. This file is included directly into the HelixTestApi */
/* application at compile time. No extra headers, etc. should be necessary here. Refer */
/* to HelixTestApi for the global variables and structures that you have access to. */
/* */
/* Note that this file is auto-generated if missing, but then editable and maintained by */
/* the developers. If you want to get a fresh/updated version of this file, simply */
/* delete it and it will be re-generated. */
/* */
/* ************************************************************************************** */
/* ************************************************************************************** */
/* Define all Local test methods here. */
/* ************************************************************************************** */
void ApiTest_logic_admin_GetWorkFileList_NoAuthorization_ShouldFail();
void ApiTest_logic_admin_GetWorkFileList_CallWithEmptyPayload();
void ApiTest_logic_admin_GetWorkFileList_CallWithValidPayload();
void ApiTest_logic_admin_GetWorkFileList_CallWithInvalidPayload();
// Define more of your own tests and methods for testing /logic/admin/GetWorkFileList here
/** This is the main method that executes the tests for the /logic/admin/GetWorkFileList api. All tests
* that should be executed against this api should be invoked directly here.
*/
void ApiTest_logic_admin_GetWorkFileList()
{
// Ensure that we should be testing this API
if(runTestsForApi("/logic/admin/GetWorkFileList") == false){
return; // Tests for this api are not included in this run.
}
// Test the Api without authorization:
ApiTest_logic_admin_GetWorkFileList_NoAuthorization_ShouldFail();
// Test the Api with an empty payload
ApiTest_logic_admin_GetWorkFileList_CallWithEmptyPayload();
// Test the Api with a valid payload
ApiTest_logic_admin_GetWorkFileList_CallWithValidPayload();
// Test the Api with an invalid payload
ApiTest_logic_admin_GetWorkFileList_CallWithInvalidPayload();
// Call any other tests that you have defined here:
}
/** This will call the /logic/admin/GetWorkFileList without any authorization information. This should
* be rejected by the server, and we should receive the error message.
*/
void ApiTest_logic_admin_GetWorkFileList_NoAuthorization_ShouldFail()
{
BEGIN_TEST_METHOD( "ApiTest_logic_admin_GetWorkFileList_NoAuthorization_ShouldFail" )
// Remove this out when you've updated these tests to be real
ASSERT_TRUE(false, "Test not implemented yet.");
// Api /logic/admin/GetWorkFileList requires an object of type IAFolder as input.
IAFolder inputObj;
// Fill out the details for inputObj here:
//inputObj.memberName1 = 1;
//inputObj.memberName2 = 2;
// etc...
xmlDocPtr resp;
resp = m_api->GetWorkFileList(inputObj);
if(m_log_steps){
printf("++ Received XML Response:\n%s\n", XmlHelpers::docToStringPretty( resp )() );
}
// Check to see if the return indicates that user hasn't logged in:
ASSERT_TRUE(m_api->returnRequiresDB(), "Should have received a response indicating the user must log in.")
// Useful macros:
// ASSERT_EQUALS(a, b, "a is not equal to b, but it should be.")
// ASSERT_NOTEQUALS(a, b, "a is equal to b, but it shouldn't be.")
// ASSERT_NULL(a, "a should be null, but it isn't.")
// ASSERT_NOTNULL(a, "a should not be null, but it is.")
// ASSERT_TRUE(a, "a should be true, but it isn't.")
// ASSERT_FALSE(a, "a should be false, but it isn't.")
// QUIT_TEST_METHOD - Allows you to bail out of test early, with a successful result.
END_TEST_METHOD
}
/** This test will call the /logic/admin/GetWorkFileList with an empty payload and check the response
* that is received.
*/
void ApiTest_logic_admin_GetWorkFileList_CallWithEmptyPayload()
{
BEGIN_TEST_METHOD( "ApiTest_logic_admin_GetWorkFileList_CallWithEmptyPayload" )
// Remove this out when you've updated these tests to be real
ASSERT_TRUE(false, "Test not implemented yet.");
// Api /logic/admin/GetWorkFileList requires an object of type IAFolder as input.
IAFolder inputObj;
// Fill out the details for inputObj here:
//inputObj.memberName1 = 1;
//inputObj.memberName2 = 2;
// etc...
xmlDocPtr resp;
resp = m_api->GetWorkFileList(inputObj);
if(m_log_steps){
printf("++ Received XML Response:\n%s\n", XmlHelpers::docToStringPretty( resp )() );
}
// Useful macros:
// ASSERT_EQUALS(a, b, "a is not equal to b, but it should be.")
// ASSERT_NOTEQUALS(a, b, "a is equal to b, but it shouldn't be.")
// ASSERT_NULL(a, "a should be null, but it isn't.")
// ASSERT_NOTNULL(a, "a should not be null, but it is.")
// ASSERT_TRUE(a, "a should be true, but it isn't.")
// ASSERT_FALSE(a, "a should be false, but it isn't.")
// QUIT_TEST_METHOD - Allows you to bail out of test early, with a successful result.
END_TEST_METHOD
}
/** This test will call the /logic/admin/GetWorkFileList with a valid payload and check the response
* that is received.
*/
void ApiTest_logic_admin_GetWorkFileList_CallWithValidPayload()
{
BEGIN_TEST_METHOD( "ApiTest_logic_admin_GetWorkFileList_CallWithValidPayload" )
// Remove this out when you've updated these tests to be real
ASSERT_TRUE(false, "Test not implemented yet.");
// Api /logic/admin/GetWorkFileList requires an object of type IAFolder as input.
IAFolder inputObj;
// Fill out the details for inputObj here:
//inputObj.memberName1 = 1;
//inputObj.memberName2 = 2;
// etc...
xmlDocPtr resp;
resp = m_api->GetWorkFileList(inputObj);
if(m_log_steps){
printf("++ Received XML Response:\n%s\n", XmlHelpers::docToStringPretty( resp )() );
}
// Useful macros:
// ASSERT_EQUALS(a, b, "a is not equal to b, but it should be.")
// ASSERT_NOTEQUALS(a, b, "a is equal to b, but it shouldn't be.")
// ASSERT_NULL(a, "a should be null, but it isn't.")
// ASSERT_NOTNULL(a, "a should not be null, but it is.")
// ASSERT_TRUE(a, "a should be true, but it isn't.")
// ASSERT_FALSE(a, "a should be false, but it isn't.")
// QUIT_TEST_METHOD - Allows you to bail out of test early, with a successful result.
END_TEST_METHOD
}
/** This test will call the /logic/admin/GetWorkFileList with an invalid payload and check the response
* that is received.
*/
void ApiTest_logic_admin_GetWorkFileList_CallWithInvalidPayload()
{
BEGIN_TEST_METHOD( "ApiTest_logic_admin_GetWorkFileList_CallWithInvalidPayload" )
// Remove this out when you've updated these tests to be real
ASSERT_TRUE(false, "Test not implemented yet.");
// Api /logic/admin/GetWorkFileList requires an object of type IAFolder as input.
IAFolder inputObj;
// Fill out the details for inputObj here:
//inputObj.memberName1 = 1;
//inputObj.memberName2 = 2;
// etc...
xmlDocPtr resp;
resp = m_api->GetWorkFileList(inputObj);
if(m_log_steps){
printf("++ Received XML Response:\n%s\n", XmlHelpers::docToStringPretty( resp )() );
}
// Useful macros:
// ASSERT_EQUALS(a, b, "a is not equal to b, but it should be.")
// ASSERT_NOTEQUALS(a, b, "a is equal to b, but it shouldn't be.")
// ASSERT_NULL(a, "a should be null, but it isn't.")
// ASSERT_NOTNULL(a, "a should not be null, but it is.")
// ASSERT_TRUE(a, "a should be true, but it isn't.")
// ASSERT_FALSE(a, "a should be false, but it isn't.")
// QUIT_TEST_METHOD - Allows you to bail out of test early, with a successful result.
END_TEST_METHOD
}
|
VectorXf v;
v.setConstant(3, 5);
cout << v << endl;
|
#include "os.h"
// Most of this code is a heavily modified version of some of the subsystem in Remotery
#ifdef PLATFORM_LINUX
#include <time.h>
#ifdef __FreeBSD__
#include <pthread_np.h>
#else
#include <sys/prctl.h>
#endif
#endif
#if defined(PLATFORM_POSIX)
#include <sys/types.h>
#include <sys/syscall.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <dlfcn.h>
#endif
#if defined(PLATFORM_WINDOWS)
#include <windows.h>
#include <intrin.h>
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "Hash.h"
void* osLoadLibrary(const char* path)
{
#if defined(PLATFORM_WINDOWS)
return (void*)LoadLibraryA(path);
#elif defined(PLATFORM_POSIX)
return dlopen(path, RTLD_LOCAL | RTLD_LAZY);
#else
return nullptr;
#endif
}
void osFreeLibrary(void* handle)
{
#if defined(PLATFORM_WINDOWS)
FreeLibrary((HMODULE)handle);
#elif defined(PLATFORM_POSIX)
dlclose(handle);
#endif
}
void* osGetProcAddress(void* handle, const char* symbol)
{
#if defined(PLATFORM_WINDOWS)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4152) // C4152: nonstandard extension, function/data pointer conversion in expression
#endif
return GetProcAddress((HMODULE)handle, (LPCSTR)symbol);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#elif defined(PLATFORM_POSIX)
return dlsym(handle, symbol);
#else
return nullptr;
#endif
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@TIMERS: Platform-specific timers
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
//
// Get millisecond timer value that has only one guarantee: multiple calls are consistently comparable.
// On some platforms, even though this returns milliseconds, the timer may be far less accurate.
//
u32 msTimer_Get()
{
#ifdef PLATFORM_WINDOWS
return (u32)GetTickCount();
#else
clock_t time = clock();
// CLOCKS_PER_SEC is 128 on FreeBSD, causing div/0
#ifdef __FreeBSD__
u32 msTime = (u32)(time * 1000 / CLOCKS_PER_SEC);
#else
u32 msTime = (u32)(time / (CLOCKS_PER_SEC / 1000));
#endif
return msTime;
#endif
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@TLS: Thread-Local Storage
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
#define TLS_INVALID_HANDLE 0xFFFFFFFF
osError tlsAlloc(osTLS* handle)
{
assert(handle != NULL);
#if defined(PLATFORM_WINDOWS)
*handle = (osTLS)TlsAlloc();
if (*handle == TLS_OUT_OF_INDEXES)
{
*handle = TLS_INVALID_HANDLE;
return OS_ERROR_TLS_ALLOC_FAIL;
}
#elif defined(PLATFORM_POSIX)
if (pthread_key_create((pthread_key_t *)handle, NULL) != 0)
{
*handle = TLS_INVALID_HANDLE;
return OS_ERROR_TLS_ALLOC_FAIL;
}
#endif
return OS_ERROR_NONE;
}
void tlsFree(osTLS handle)
{
assert(handle != TLS_INVALID_HANDLE);
#if defined(PLATFORM_WINDOWS)
TlsFree(handle);
#elif defined(PLATFORM_POSIX)
pthread_key_delete((pthread_key_t)handle);
#endif
}
void tlsSet(osTLS handle, void* value)
{
assert(handle != TLS_INVALID_HANDLE);
#if defined(PLATFORM_WINDOWS)
TlsSetValue(handle, value);
#elif defined(PLATFORM_POSIX)
pthread_setspecific((pthread_key_t)handle, value);
#endif
}
void* tlsGet(osTLS handle)
{
assert(handle != TLS_INVALID_HANDLE);
#if defined(PLATFORM_WINDOWS)
return TlsGetValue(handle);
#elif defined(PLATFORM_POSIX)
return pthread_getspecific((pthread_key_t)handle);
#endif
}
/*
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
@ATOMIC: Atomic Operations
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
*/
bool AtomicCompareAndSwap(u32 volatile* val, long old_val, long new_val)
{
#if defined(PLATFORM_WINDOWS) && !defined(__MINGW32__)
return _InterlockedCompareExchange((long volatile*)val, new_val, old_val) == old_val ? true : false;
#elif defined(PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_bool_compare_and_swap(val, old_val, new_val) ? true : false;
#endif
}
bool AtomicCompareAndSwapPointer(long* volatile* ptr, long* old_ptr, long* new_ptr)
{
#if defined(PLATFORM_WINDOWS) && !defined(__MINGW32__)
#ifdef _WIN64
return _InterlockedCompareExchange64((__int64 volatile*)ptr, (__int64)new_ptr, (__int64)old_ptr) == (__int64)old_ptr ? true : false;
#else
return _InterlockedCompareExchange((long volatile*)ptr, (long)new_ptr, (long)old_ptr) == (long)old_ptr ? true : false;
#endif
#elif defined(PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_bool_compare_and_swap(ptr, old_ptr, new_ptr) ? false : true;
#endif
}
//
// NOTE: Does not guarantee a memory barrier
// TODO: Make sure all platforms don't insert a memory barrier as this is only for stats
// Alternatively, add strong/weak memory order equivalents
//
s32 AtomicAdd(s32 volatile* value, s32 add)
{
#if defined(PLATFORM_WINDOWS) && !defined(__MINGW32__)
return _InterlockedExchangeAdd((long volatile*)value, (long)add);
#elif defined(PLATFORM_POSIX) || defined(__MINGW32__)
return __sync_fetch_and_add(value, add);
#endif
}
void AtomicSub(s32 volatile* value, s32 sub)
{
// Not all platforms have an implementation so just negate and add
AtomicAdd(value, -sub);
}
// Compiler write fences (windows implementation)
void WriteFence()
{
#if defined(PLATFORM_WINDOWS) && !defined(__MINGW32__)
_WriteBarrier();
#elif defined (__clang__)
__asm__ volatile("" : : : "memory");
#else
asm volatile ("" : : : "memory");
#endif
}
u64 osGetCurrentProcessId()
{
#if defined(PLATFORM_WINDOWS)
return GetCurrentProcessId();
#elif defined(PLATFORM_POSIX)
return getpid();
#endif
}
u64 osGetCurrentThreadId()
{
#if defined(PLATFORM_WINDOWS)
return GetCurrentThreadId();
#elif defined(PLATFORM_LINUX)
return syscall(__NR_gettid);
#elif defined(PLATFORM_MACOS)
uint64_t tid;
pthread_threadid_np(NULL, &tid);
return tid;
#endif
}
// @TODO: We need to pass a list of the libraries (externs) that
// the program has to link against
int compile_c_into_binary(FileObject &filename, ImportsHash &imports)
{
#if defined(PLATFORM_WINDOWS)
STARTUPINFOA si;
PROCESS_INFORMATION pi;
char cmd_line[512] = {};
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
u32 chars_written = sprintf_s(cmd_line, "cl.exe /nologo %s", filename.getFilename());
auto it = imports.begin();
char *line_ptr = cmd_line + chars_written;
while (!imports.isEnd(it)) {
if (it.entry) {
chars_written = sprintf(line_ptr, " modules\\%s.lib", it.entry->key());
line_ptr = line_ptr + chars_written;
}
it = imports.next(it);
}
if (!CreateProcessA(NULL, cmd_line, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
printf("Process creation [%s] failed (%d)\n", cmd_line, GetLastError());
return -1;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exit_code;
GetExitCodeProcess(pi.hProcess, &exit_code);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return exit_code;
#elif defined(PLATFORM_POSIX)
char cmd_line[512] = {};
char outfile[64];
strncpy(outfile, filename.getFilename(), sizeof(outfile));
char *ext = strrchr(outfile, '.');
*ext = 0;
sprintf(cmd_line, "clang %s -g -o %s -lstdc++", filename.getFilename(), outfile);
int exit_code = system(cmd_line);
return exit_code;
#endif
}
|
////////////////////////////////////////////////////////////////////////////////
/// @brief Write-ahead log storage allocator thread
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "AllocatorThread.h"
#include "BasicsC/logging.h"
#include "Basics/ConditionLocker.h"
#include "Utils/Exception.h"
#include "Wal/LogfileManager.h"
using namespace triagens::wal;
// -----------------------------------------------------------------------------
// --SECTION-- class AllocatorThread
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief wait interval for the allocator thread when idle
////////////////////////////////////////////////////////////////////////////////
const uint64_t AllocatorThread::Interval = 500 * 1000;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief create the allocator thread
////////////////////////////////////////////////////////////////////////////////
AllocatorThread::AllocatorThread (LogfileManager* logfileManager)
: Thread("WalAllocator"),
_logfileManager(logfileManager),
_condition(),
_requestedSize(0),
_stop(0),
_inRecovery(true) {
allowAsynchronousCancelation();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroy the allocator thread
////////////////////////////////////////////////////////////////////////////////
AllocatorThread::~AllocatorThread () {
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief stops the allocator thread
////////////////////////////////////////////////////////////////////////////////
void AllocatorThread::stop () {
if (_stop > 0) {
return;
}
_stop = 1;
_condition.signal();
while (_stop != 2) {
usleep(10000);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief signal the creation of a new logfile
////////////////////////////////////////////////////////////////////////////////
void AllocatorThread::signal (uint32_t markerSize) {
CONDITION_LOCKER(guard, _condition);
if (_requestedSize == 0 ||
markerSize > _requestedSize) {
// logfile must be as big as the requested marker
_requestedSize = markerSize;
}
guard.signal();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new reserve logfile
////////////////////////////////////////////////////////////////////////////////
bool AllocatorThread::createReserveLogfile (uint32_t size) {
int res = _logfileManager->createReserveLogfile(size);
return (res == TRI_ERROR_NO_ERROR);
}
// -----------------------------------------------------------------------------
// --SECTION-- Thread methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief main loop
////////////////////////////////////////////////////////////////////////////////
void AllocatorThread::run () {
while (_stop == 0) {
uint32_t requestedSize = 0;
{
CONDITION_LOCKER(guard, _condition);
requestedSize = _requestedSize;
_requestedSize = 0;
}
try {
if (requestedSize == 0 &&
! _inRecovery &&
! _logfileManager->hasReserveLogfiles()) {
// only create reserve files if we are not in the recovery mode
if (createReserveLogfile(0)) {
continue;
}
LOG_ERROR("unable to create new WAL reserve logfile");
}
else if (requestedSize > 0 &&
_logfileManager->logfileCreationAllowed(requestedSize)) {
if (createReserveLogfile(requestedSize)) {
continue;
}
LOG_ERROR("unable to create new WAL reserve logfile");
}
}
catch (triagens::arango::Exception const& ex) {
int res = ex.code();
LOG_ERROR("got unexpected error in allocatorThread: %s", TRI_errno_string(res));
}
catch (...) {
LOG_ERROR("got unspecific error in allocatorThread");
}
{
CONDITION_LOCKER(guard, _condition);
guard.wait(Interval);
}
}
_stop = 2;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
|
/*************************************************************************/
/* pin_joint_bullet.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "pin_joint_bullet.h"
#include "bullet_types_converter.h"
#include "rigid_body_bullet.h"
#include "core/string.h"
#include "core/string_utils.h"
#include <BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h>
/**
@author AndreaCatania
*/
PinJointBullet::PinJointBullet(RigidBodyBullet *p_body_a, const Vector3 &p_pos_a, RigidBodyBullet *p_body_b, const Vector3 &p_pos_b) :
JointBullet() {
if (p_body_b) {
btVector3 btPivotA;
btVector3 btPivotB;
G_TO_B(p_pos_a * p_body_a->get_body_scale(), btPivotA);
G_TO_B(p_pos_b * p_body_b->get_body_scale(), btPivotB);
p2pConstraint = bulletnew(btPoint2PointConstraint(*p_body_a->get_bt_rigid_body(),
*p_body_b->get_bt_rigid_body(),
btPivotA,
btPivotB));
} else {
btVector3 btPivotA;
G_TO_B(p_pos_a, btPivotA);
p2pConstraint = bulletnew(btPoint2PointConstraint(*p_body_a->get_bt_rigid_body(), btPivotA));
}
setup(p2pConstraint);
}
PinJointBullet::~PinJointBullet() {}
void PinJointBullet::set_param(PhysicsServer3D::PinJointParam p_param, real_t p_value) {
switch (p_param) {
case PhysicsServer3D::PIN_JOINT_BIAS:
p2pConstraint->m_setting.m_tau = p_value;
break;
case PhysicsServer3D::PIN_JOINT_DAMPING:
p2pConstraint->m_setting.m_damping = p_value;
break;
case PhysicsServer3D::PIN_JOINT_IMPULSE_CLAMP:
p2pConstraint->m_setting.m_impulseClamp = p_value;
break;
}
}
real_t PinJointBullet::get_param(PhysicsServer3D::PinJointParam p_param) const {
switch (p_param) {
case PhysicsServer3D::PIN_JOINT_BIAS:
return p2pConstraint->m_setting.m_tau;
case PhysicsServer3D::PIN_JOINT_DAMPING:
return p2pConstraint->m_setting.m_damping;
case PhysicsServer3D::PIN_JOINT_IMPULSE_CLAMP:
return p2pConstraint->m_setting.m_impulseClamp;
default:
WARN_DEPRECATED_MSG("The parameter " + itos(p_param) + " is deprecated.");
return 0;
}
}
void PinJointBullet::setPivotInA(const Vector3 &p_pos) {
btVector3 btVec;
G_TO_B(p_pos, btVec);
p2pConstraint->setPivotA(btVec);
}
void PinJointBullet::setPivotInB(const Vector3 &p_pos) {
btVector3 btVec;
G_TO_B(p_pos, btVec);
p2pConstraint->setPivotB(btVec);
}
Vector3 PinJointBullet::getPivotInA() {
btVector3 vec = p2pConstraint->getPivotInA();
Vector3 gVec;
B_TO_G(vec, gVec);
return gVec;
}
Vector3 PinJointBullet::getPivotInB() {
btVector3 vec = p2pConstraint->getPivotInB();
Vector3 gVec;
B_TO_G(vec, gVec);
return gVec;
}
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/animation/animatable/AnimatableClipPathOperation.h"
namespace blink {
bool AnimatableClipPathOperation::usesDefaultInterpolationWith(const AnimatableValue* value) const
{
const AnimatableClipPathOperation* toOperation = toAnimatableClipPathOperation(value);
if (m_operation->type() != ClipPathOperation::SHAPE || toOperation->m_operation->type() != ClipPathOperation::SHAPE)
return true;
const BasicShape* fromShape = toShapeClipPathOperation(clipPathOperation())->basicShape();
const BasicShape* toShape = toShapeClipPathOperation(toOperation->clipPathOperation())->basicShape();
return !fromShape->canBlend(toShape);
}
PassRefPtrWillBeRawPtr<AnimatableValue> AnimatableClipPathOperation::interpolateTo(const AnimatableValue* value, double fraction) const
{
if (usesDefaultInterpolationWith(value))
return defaultInterpolateTo(this, value, fraction);
const AnimatableClipPathOperation* toOperation = toAnimatableClipPathOperation(value);
const BasicShape* fromShape = toShapeClipPathOperation(clipPathOperation())->basicShape();
const BasicShape* toShape = toShapeClipPathOperation(toOperation->clipPathOperation())->basicShape();
return AnimatableClipPathOperation::create(ShapeClipPathOperation::create(toShape->blend(fromShape, fraction)).get());
}
bool AnimatableClipPathOperation::equalTo(const AnimatableValue* value) const
{
const ClipPathOperation* operation = toAnimatableClipPathOperation(value)->m_operation.get();
return m_operation == operation || (m_operation && operation && *m_operation == *operation);
}
}
|
/*
* kd_tree.hpp
*
* Created on: Dec 31, 2018 10:27
* Description:
*
* Copyright (c) 2018 Ruixiang Du (rdu)
*/
#ifndef KD_TREE_HPP
#define KD_TREE_HPP
#include <limits>
#include <algorithm>
#include "spatial/spatial.hpp"
#include "spatial/point_multiset.hpp"
#include "spatial/neighbor_iterator.hpp"
#include "graph/tree.hpp"
#include "sampling/base/tree_adapter.hpp"
namespace robotnav
{
template <typename Space>
class KdTree : public Tree<typename Space::StateType *, double>, public TreeAdapter<Space>
{
public:
using TreeType = Tree<typename Space::StateType *, double>;
using AdapterType = TreeAdapter<Space>;
using StateType = typename TreeAdapter<Space>::StateType;
using PathType = typename TreeAdapter<Space>::PathType;
// inherit constructors
using Tree<typename Space::StateType *, double>::Tree;
using TreeAdapter<Space>::TreeAdapter;
// setup Kd-tree types
struct StateAccessor
{
double operator()(spatial::dimension_type dim, StateType *state) const
{
return (*state)[dim];
}
};
using KdTreeType = spatial::point_multiset<Space::DimensionSize,
StateType *,
spatial::accessor_less<StateAccessor, StateType *>>;
public:
void AddTreeRootNode(StateType *sstate) final
{
TreeType::AddVertex(sstate);
kdtree_.insert(sstate);
}
void ConnectTreeNodes(StateType *sstate, StateType *dstate, double dist) final
{
TreeType::AddEdge(sstate, dstate, dist);
kdtree_.insert(sstate);
kdtree_.insert(dstate);
}
void DisconnectTreeNodes(StateType *sstate, StateType *dstate) final
{
TreeType::RemoveEdge(sstate, dstate);
}
std::size_t GetTotalTreeNodeNumber() final
{
return TreeType::GetTotalVertexNumber();
}
PathType TraceBackToRoot(StateType *state) final
{
PathType path;
path.push_back(state);
auto parent = TreeType::GetParentVertex(state);
while (parent != TreeType::vertex_end())
{
path.push_back(parent->state_);
parent = TreeType::GetParentVertex(parent->vertex_id_);
}
std::reverse(path.begin(), path.end());
return path;
}
StateType *FindNearest(StateType *state) final
{
spatial::neighbor_iterator<KdTreeType> iter = spatial::neighbor_begin(kdtree_, state);
return (*iter);
}
std::vector<StateType *> FindNear(StateType *state, double radius) final
{
std::vector<StateType *> near_states;
spatial::neighbor_iterator<KdTreeType> iter = spatial::neighbor_begin(kdtree_, state);
for (auto it = iter; it != kdtree_.end(); ++it)
{
if (distance(it) <= radius)
near_states.push_back(*it);
else
break;
}
return near_states;
}
private:
KdTreeType kdtree_;
};
} // namespace robotnav
#endif /* KD_TREE_HPP */
|
#pragma once
#include <typed-geometry/tg-lean.hh>
// TODO
|
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "uitemplatecontroller.h"
#if VSTGUI_LIVE_EDITING
#include "../uiviewfactory.h"
#include "../uiattributes.h"
#include "../../lib/controls/ctextedit.h"
#include "../../lib/controls/coptionmenu.h"
#include "../../lib/controls/cscrollbar.h"
#include "uieditcontroller.h"
#include "uiselection.h"
#include "uiundomanager.h"
#include "uiactions.h"
#include "uieditmenucontroller.h"
#include <cassert>
#ifdef verify
#undef verify
#endif
namespace VSTGUI {
//----------------------------------------------------------------------------------------------------
class UINavigationDataSource : public GenericStringListDataBrowserSource
{
public:
UINavigationDataSource (IGenericStringListDataBrowserSourceSelectionChanged* delegate)
: GenericStringListDataBrowserSource (nullptr, delegate) { textInset.x = 4.; headerBackgroundColor = kTransparentCColor; }
int32_t dbOnKeyDown (const VstKeyCode& key, CDataBrowser* browser) override
{
if (dynamic_cast<CTextEdit*> (browser->getFrame ()->getFocusView ()))
return -1;
if (key.virt == VKEY_LEFT)
{
if (auto parent = browser->getParentView ()->asViewContainer ())
{
if (parent->advanceNextFocusView (browser, true))
{
return 1;
}
}
}
else if (key.virt == VKEY_RIGHT)
{
if (auto parent = browser->getParentView ()->asViewContainer ())
{
if (parent->advanceNextFocusView (browser, false))
{
CView* focusView = dynamic_cast<CView*> (browser->getFrame()->getFocusView ());
if (focusView)
{
CViewContainer* parent = focusView->getParentView ()->asViewContainer ();
while (parent != browser->getFrame ())
{
parent = parent->getParentView ()->asViewContainer ();
CDataBrowser* focusBrowser = dynamic_cast<CDataBrowser*>(parent);
if (focusBrowser)
{
if (focusBrowser->getSelectedRow() == CDataBrowser::kNoSelection)
focusBrowser->setSelectedRow (0);
break;
}
}
}
return 1;
}
}
}
return GenericStringListDataBrowserSource::dbOnKeyDown (key, browser);
}
virtual const UTF8String& getHeaderTitle () const { return headerTitle; }
void dbDrawHeader (CDrawContext* context, const CRect& size, int32_t column, int32_t flags, CDataBrowser* browser) override
{
context->setDrawMode (kAliasing);
context->setLineWidth (1);
if (headerBackgroundColor == kTransparentCColor)
{
double h,s,l;
rowAlternateBackColor.toHSL (h, s, l);
l /= 2.;
headerBackgroundColor.fromHSL (h, s, l);
headerBackgroundColor.alpha = rowAlternateBackColor.alpha;
}
context->setFillColor (headerBackgroundColor);
context->drawRect (size, kDrawFilled);
context->setFrameColor (rowlineColor);
context->drawLine (CPoint (size.left, size.bottom-1), CPoint (size.right, size.bottom-1));
if (!getHeaderTitle ().empty ())
{
if (headerFont == nullptr)
{
headerFont = makeOwned<CFontDesc> (*drawFont);
headerFont->setStyle (kBoldFace);
headerFont->setSize (headerFont->getSize ()-1);
}
context->setFont (headerFont);
context->setFontColor (fontColor);
context->drawString (getHeaderTitle ().getPlatformString (), size, kCenterText);
}
}
protected:
mutable UTF8String headerTitle;
CColor headerBackgroundColor;
SharedPointer<CFontDesc> headerFont;
};
//----------------------------------------------------------------------------------------------------
class UITemplatesDataSource : public UINavigationDataSource
{
public:
UITemplatesDataSource (IGenericStringListDataBrowserSourceSelectionChanged* delegate, UIDescription* description, IActionPerformer* actionPerformer, const std::string* templateName);
CMouseEventResult dbOnMouseDown (const CPoint& where, const CButtonState& buttons, int32_t row, int32_t column, CDataBrowser* browser) override;
void dbCellTextChanged (int32_t row, int32_t column, UTF8StringPtr newText, CDataBrowser* browser) override;
void dbCellSetupTextEdit (int32_t row, int32_t column, CTextEdit* textEditControl, CDataBrowser* browser) override;
void dbAttached (CDataBrowser* browser) override;
protected:
SharedPointer<UIDescription> description;
IActionPerformer* actionPerformer;
std::string firstSelectedTemplateName;
};
//----------------------------------------------------------------------------------------------------
class UIViewListDataSource : public UINavigationDataSource
{
public:
UIViewListDataSource (CViewContainer* view, const IViewFactory* viewFactory, UISelection* selection, UIUndoManager* undoManager ,IGenericStringListDataBrowserSourceSelectionChanged* delegate);
~UIViewListDataSource () override;
CViewContainer* getView () const { return view; }
CView* getSubview (int32_t index);
bool update (CViewContainer* vc);
void remove ();
protected:
const UTF8String& getHeaderTitle () const override
{
headerTitle = "";
if (view)
{
headerTitle = viewFactory->getViewName (view);
if (headerTitle.empty () && view->getParentView ())
headerTitle = viewFactory->getViewName (view->getParentView ());
}
return headerTitle;
}
void verify ();
CMessageResult notify (CBaseObject* sender, IdStringPtr message) override;
CCoord calculateSubViewWidth (CViewContainer* view);
void dbSelectionChanged (CDataBrowser* browser) override;
CMouseEventResult dbOnMouseDown (const CPoint& where, const CButtonState& buttons, int32_t row, int32_t column, CDataBrowser* browser) override;
int32_t dbOnKeyDown (const VstKeyCode& key, CDataBrowser* browser) override;
CViewContainer* view;
const IViewFactory* viewFactory;
UIViewListDataSource* next;
SharedPointer<UISelection> selection;
SharedPointer<UIUndoManager> undoManager;
CView* selectedView;
StringVector names;
std::vector<CView*> subviews;
bool inUpdate;
};
//----------------------------------------------------------------------------------------------------
IdStringPtr UITemplateController::kMsgTemplateChanged = "UITemplateController::kMsgTemplateChanged";
IdStringPtr UITemplateController::kMsgTemplateNameChanged = "UITemplateController::kMsgTemplateNameChanged";
//----------------------------------------------------------------------------------------------------
UITemplateController::UITemplateController (IController* baseController, UIDescription* description, UISelection* selection, UIUndoManager* undoManager, IActionPerformer* actionPerformer)
: DelegationController (baseController)
, editDescription (description)
, selection (selection)
, undoManager (undoManager)
, actionPerformer (actionPerformer)
, templateView (nullptr)
, templateDataBrowser (nullptr)
, mainViewDataSource (nullptr)
, selectedTemplateName (nullptr)
{
editDescription->addDependency (this);
}
//----------------------------------------------------------------------------------------------------
UITemplateController::~UITemplateController ()
{
if (mainViewDataSource)
mainViewDataSource->forget ();
editDescription->removeDependency (this);
}
//----------------------------------------------------------------------------------------------------
void UITemplateController::setupDataBrowser (CDataBrowser* orignalBrowser, CDataBrowser* dataBrowser)
{
if (orignalBrowser)
{
dataBrowser->setTransparency (orignalBrowser->getTransparency ());
dataBrowser->setBackgroundColor (orignalBrowser->getBackgroundColor ());
dataBrowser->setAutosizeFlags (orignalBrowser->getAutosizeFlags ());
dataBrowser->setStyle (orignalBrowser->getStyle ());
dataBrowser->setScrollbarWidth (orignalBrowser->getScrollbarWidth ());
CScrollbar* sb1 = orignalBrowser->getHorizontalScrollbar ();
CScrollbar* sb2 = dataBrowser->getHorizontalScrollbar ();
if (sb1 && sb2)
{
sb2->setScrollerColor (sb1->getScrollerColor ());
sb2->setBackgroundColor (sb1->getBackgroundColor ());
sb2->setFrameColor (sb1->getFrameColor ());
}
sb1 = orignalBrowser->getVerticalScrollbar ();
sb2 = dataBrowser->getVerticalScrollbar ();
if (sb1 && sb2)
{
sb2->setScrollerColor (sb1->getScrollerColor ());
sb2->setBackgroundColor (sb1->getBackgroundColor ());
sb2->setFrameColor (sb1->getFrameColor ());
}
}
}
//----------------------------------------------------------------------------------------------------
void UITemplateController::selectTemplate (UTF8StringPtr name)
{
if (templateDataBrowser)
{
int32_t index = 0;
for (auto& templName : templateNames)
{
if (templName == name)
{
templateDataBrowser->setSelectedRow (index, true);
break;
}
index++;
}
}
}
//----------------------------------------------------------------------------------------------------
void UITemplateController::dbSelectionChanged (int32_t selectedRow, GenericStringListDataBrowserSource* source)
{
if (source->getStringList () == &templateNames)
{
UTF8String* newName = nullptr;
if (selectedRow == CDataBrowser::kNoSelection)
newName = nullptr;
else
newName = &templateNames[static_cast<uint32_t> (selectedRow)];
if ((newName == nullptr && selectedTemplateName != nullptr)
|| (newName != nullptr && selectedTemplateName == nullptr)
|| (newName != selectedTemplateName && *newName != *selectedTemplateName))
{
selectedTemplateName = newName;
UIAttributes* attr = editDescription->getCustomAttributes ("UITemplateController", true);
if (attr)
{
attr->setAttribute ("SelectedTemplate", selectedTemplateName ? selectedTemplateName->getString () : "");
}
changed (kMsgTemplateChanged);
}
else if (templateView)
{
selection->setExclusive (templateView);
}
else
selection->empty ();
return;
}
}
//----------------------------------------------------------------------------------------------------
CMessageResult UITemplateController::notify (CBaseObject* sender, IdStringPtr message)
{
if (templateDataBrowser && message == UIDescription::kMessageTemplateChanged)
{
GenericStringListDataBrowserSource* dataSource = dynamic_cast<GenericStringListDataBrowserSource*>(templateDataBrowser->getDelegate ());
if (dataSource)
{
DeferChanges dc (this);
int32_t rowToSelect = templateDataBrowser->getSelectedRow ();
int32_t index = 0;
auto selectedTemplateStr = selectedTemplateName ? *selectedTemplateName : "";
templateNames.clear ();
dataSource->setStringList (&templateNames);
std::list<const std::string*> tmp;
editDescription->collectTemplateViewNames (tmp);
tmp.sort (UIEditController::std__stringCompare);
for (auto& name : tmp)
{
templateNames.emplace_back (*name);
if (*name == selectedTemplateStr)
rowToSelect = index;
++index;
}
if (rowToSelect < 0)
rowToSelect = 0;
dataSource->setStringList (&templateNames);
templateDataBrowser->setSelectedRow (rowToSelect, true);
}
return kMessageNotified;
}
return kMessageUnknown;
}
//----------------------------------------------------------------------------------------------------
void UITemplateController::setTemplateView (CViewContainer* view)
{
if (view != templateView && templateDataBrowser && templateDataBrowser->getParentView ())
{
templateView = view;
if (mainViewDataSource)
{
mainViewDataSource->remove ();
mainViewDataSource->forget ();
mainViewDataSource = nullptr;
}
if (templateView && templateDataBrowser)
{
CViewContainer* parentView = static_cast<CViewContainer*>(templateDataBrowser->getParentView ());
if (parentView)
{
const IViewFactory* viewFactory = editDescription->getViewFactory ();
mainViewDataSource = new UIViewListDataSource (templateView, viewFactory, selection, undoManager, this);
UIEditController::setupDataSource (mainViewDataSource);
CRect r (templateDataBrowser->getViewSize ());
r.offset (r.getWidth (), 0);
CDataBrowser* browser = new CDataBrowser (r, mainViewDataSource);
setupDataBrowser (templateDataBrowser, browser);
parentView->addView (browser);
}
}
}
}
//----------------------------------------------------------------------------------------------------
CView* UITemplateController::createView (const UIAttributes& attributes, const IUIDescription* description)
{
const std::string* name = attributes.getAttributeValue (IUIDescription::kCustomViewName);
if (name)
{
if (*name == "TemplateBrowser")
{
vstgui_assert (templateDataBrowser == nullptr);
std::list<const std::string*> tmp;
editDescription->collectTemplateViewNames (tmp);
tmp.sort (UIEditController::std__stringCompare);
for (auto& name : tmp)
templateNames.emplace_back (*name);
UIAttributes* attr = editDescription->getCustomAttributes ("UITemplateController", true);
const std::string* templateName = attr ? attr->getAttributeValue ("SelectedTemplate") : nullptr;
UITemplatesDataSource* dataSource = new UITemplatesDataSource (this, editDescription, actionPerformer, templateName);
dataSource->setStringList (&templateNames);
UIEditController::setupDataSource (dataSource);
templateDataBrowser = new CDataBrowser (CRect (0, 0, 0, 0), dataSource, CDataBrowser::kDrawRowLines|CScrollView::kAutoHideScrollbars|CScrollView::kHorizontalScrollbar|CScrollView::kVerticalScrollbar|CDataBrowser::kDrawHeader);
dataSource->forget ();
return templateDataBrowser;
}
}
return DelegationController::createView (attributes, description);
}
//----------------------------------------------------------------------------------------------------
CView* UITemplateController::verifyView (CView* view, const UIAttributes& attributes, const IUIDescription* description)
{
return DelegationController::verifyView (view, attributes, description);
}
//----------------------------------------------------------------------------------------------------
IController* UITemplateController::createSubController (UTF8StringPtr name, const IUIDescription* description)
{
return DelegationController::createSubController (name, description);
}
//----------------------------------------------------------------------------------------------------
void UITemplateController::appendContextMenuItems (COptionMenu& contextMenu, CView* view, const CPoint& where)
{
CPoint w (where);
view->localToFrame (w);
templateDataBrowser->frameToLocal (w);
if (!templateDataBrowser->hitTest (w))
return;
auto cell = templateDataBrowser->getCellAt (w);
if (!cell.isValid ())
return;
auto dataSource = dynamic_cast<UITemplatesDataSource*> (templateDataBrowser->getDelegate ());
auto templateName = dataSource->getStringList()->at (static_cast<uint32_t> (cell.row));
vstgui_assert (dataSource);
auto item = new CCommandMenuItem ("Duplicate Template '" + templateName + "'");
item->setActions ([this, cell, dataSource] (CCommandMenuItem*) {
std::list<const std::string*> tmp;
editDescription->collectTemplateViewNames (tmp);
std::string newName (dataSource->getStringList ()->at (static_cast<uint32_t> (cell.row)).data ());
UIEditMenuController::createUniqueTemplateName (tmp, newName);
actionPerformer->performDuplicateTemplate (dataSource->getStringList ()->at (static_cast<uint32_t> (cell.row)).data (), newName.data ());
});
contextMenu.addEntry (item);
item = new CCommandMenuItem ("Delete Template '" + templateName + "'");
item->setActions ([this, cell, dataSource] (CCommandMenuItem*) {
actionPerformer->performDeleteTemplate (dataSource->getStringList ()->at (static_cast<uint32_t> (cell.row)).data ());
});
contextMenu.addEntry (item);
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
UIViewListDataSource::UIViewListDataSource (CViewContainer* view, const IViewFactory* viewFactory, UISelection* selection, UIUndoManager* undoManager, IGenericStringListDataBrowserSourceSelectionChanged* delegate)
: UINavigationDataSource (delegate)
, view (view)
, viewFactory (viewFactory)
, next (nullptr)
, selection (selection)
, undoManager (undoManager)
, selectedView (nullptr)
, inUpdate (false)
{
update (view);
undoManager->addDependency (this);
}
//----------------------------------------------------------------------------------------------------
UIViewListDataSource::~UIViewListDataSource ()
{
undoManager->removeDependency (this);
}
//----------------------------------------------------------------------------------------------------
CView* UIViewListDataSource::getSubview (int32_t index)
{
if (index >= 0 && index < (int32_t)subviews.size ())
return subviews[static_cast<uint32_t> (index)];
return nullptr;
}
//----------------------------------------------------------------------------------------------------
bool UIViewListDataSource::update (CViewContainer* vc)
{
inUpdate = true;
names.clear ();
subviews.clear ();
ViewIterator it (vc);
while (*it)
{
CView* subview = *it;
IdStringPtr viewName = viewFactory->getViewName (subview);
if (viewName)
{
names.emplace_back (viewName);
subviews.emplace_back (subview);
}
it++;
}
if (names.empty () && vc->getNbViews () > 0)
{
ViewIterator it (vc);
while (*it)
{
if (auto subview = (*it)->asViewContainer ())
{
if (update (subview))
{
view = subview;
inUpdate = false;
return true;
}
}
it++;
}
inUpdate = false;
return false;
}
setStringList (&names);
inUpdate = false;
return true;
}
//----------------------------------------------------------------------------------------------------
CCoord UIViewListDataSource::calculateSubViewWidth (CViewContainer* view)
{
CCoord result = 0;
ViewIterator it (view);
while (*it)
{
result += (*it)->getViewSize ().getWidth ();
it++;
}
return result;
}
//----------------------------------------------------------------------------------------------------
void UIViewListDataSource::dbSelectionChanged (CDataBrowser* browser)
{
CView* subview = getSubview (browser->getSelectedRow ());
if (subview == selectedView || inUpdate)
return;
selectedView = subview;
if (next)
{
next->remove ();
next = nullptr;
}
GenericStringListDataBrowserSource::dbSelectionChanged (browser);
if (auto container = subview ? subview->asViewContainer () : nullptr)
{
UIViewListDataSource* dataSource = new UIViewListDataSource (container, viewFactory, selection, undoManager, delegate);
UIEditController::setupDataSource (dataSource);
CRect r (browser->getViewSize ());
r.offset (r.getWidth (), 0);
CDataBrowser* newDataBrowser = new CDataBrowser (r, dataSource);
UITemplateController::setupDataBrowser (browser, newDataBrowser);
CViewContainer* parentView = static_cast<CViewContainer*>(browser->getParentView ());
parentView->addView (newDataBrowser);
next = dataSource;
dataSource->forget ();
CScrollView* scrollView = dynamic_cast<CScrollView*>(parentView->getParentView ());
if (scrollView)
{
CRect containerSize (scrollView->getContainerSize ());
containerSize.right = calculateSubViewWidth (parentView);
scrollView->setContainerSize (containerSize, true);
}
}
}
//----------------------------------------------------------------------------------------------------
void UIViewListDataSource::remove ()
{
if (next)
{
next->remove ();
next = nullptr;
}
if (dataBrowser)
{
CViewContainer* parentView = static_cast<CViewContainer*>(dataBrowser->getParentView ());
CScrollView* scrollView = dynamic_cast<CScrollView*>(parentView->getParentView ());
parentView->removeView (dataBrowser);
if (scrollView)
{
CRect containerSize (scrollView->getContainerSize ());
containerSize.right = calculateSubViewWidth (parentView);
scrollView->setContainerSize (containerSize, true);
}
}
}
//----------------------------------------------------------------------------------------------------
CMouseEventResult UIViewListDataSource::dbOnMouseDown (const CPoint& where, const CButtonState& buttons, int32_t row, int32_t column, CDataBrowser* browser)
{
if (buttons.isLeftButton() && buttons.isDoubleClick ())
{
CView* subview = getSubview (row);
if (subview)
{
if (buttons.getModifierState () & kControl)
{
if (selection->contains (subview))
selection->remove (subview);
else
selection->add (subview);
}
else
selection->setExclusive (subview);
}
}
return kMouseDownEventHandledButDontNeedMovedOrUpEvents;
}
//----------------------------------------------------------------------------------------------------
CMessageResult UIViewListDataSource::notify (CBaseObject* sender, IdStringPtr message)
{
if (message == UIUndoManager::kMsgChanged)
{
update (view);
if (selectedView)
{
if (dataBrowser)
{
int32_t index = 0;
for (std::vector<CView*>::const_iterator it = subviews.begin (); it != subviews.end (); ++it, index++)
{
if (*it == selectedView)
{
dataBrowser->setSelectedRow (index, true);
return kMessageNotified;
}
}
}
selectedView = nullptr;
if (next)
{
next->remove ();
next = nullptr;
}
}
return kMessageNotified;
}
return GenericStringListDataBrowserSource::notify (sender, message);
}
//----------------------------------------------------------------------------------------------------
int32_t UIViewListDataSource::dbOnKeyDown (const VstKeyCode& key, CDataBrowser* browser)
{
if (key.virt != 0)
{
int32_t row = browser->getSelectedRow ();
CView* subview = getSubview (row);
if (subview)
{
switch (key.virt)
{
case VKEY_RETURN:
{
selection->setExclusive (subview);
return 1;
}
}
}
}
return UINavigationDataSource::dbOnKeyDown (key, browser);
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
UITemplatesDataSource::UITemplatesDataSource (IGenericStringListDataBrowserSourceSelectionChanged* delegate, UIDescription* description, IActionPerformer* actionPerformer, const std::string* templateName)
: UINavigationDataSource (delegate)
, description (description)
, actionPerformer (actionPerformer)
{
headerTitle = "Templates";
if (templateName)
firstSelectedTemplateName = *templateName;
}
//----------------------------------------------------------------------------------------------------
CMouseEventResult UITemplatesDataSource::dbOnMouseDown (const CPoint& where, const CButtonState& buttons, int32_t row, int32_t column, CDataBrowser* browser)
{
if (buttons.isLeftButton ())
{
if (buttons.isDoubleClick ())
{
browser->beginTextEdit (CDataBrowser::Cell (row, column), getStringList ()->at (static_cast<uint32_t> (row)).data ());
return kMouseDownEventHandledButDontNeedMovedOrUpEvents;
}
delegate->dbSelectionChanged (row, this);
return kMouseDownEventHandledButDontNeedMovedOrUpEvents;
}
else if (buttons.isRightButton ())
{
COptionMenu menu;
menu.addEntry ("Duplicate");
menu.addEntry ("Delete");
CPoint p (where);
browser->CView::localToFrame (p);
if (menu.popup (browser->getFrame(), p))
{
switch (menu.getLastResult ())
{
case 0:
{
std::list<const std::string*> tmp;
description->collectTemplateViewNames (tmp);
std::string newName (getStringList ()->at (static_cast<uint32_t> (row)).data ());
UIEditMenuController::createUniqueTemplateName (tmp, newName);
actionPerformer->performDuplicateTemplate (getStringList ()->at (static_cast<uint32_t> (row)).data (), newName.data ());
break;
}
case 1:
{
actionPerformer->performDeleteTemplate (getStringList ()->at (static_cast<uint32_t> (row)).data ());
break;
}
}
}
}
return UINavigationDataSource::dbOnMouseDown (where, buttons, row, column, browser);
}
//----------------------------------------------------------------------------------------------------
void UITemplatesDataSource::dbCellTextChanged (int32_t row, int32_t column, UTF8StringPtr newText, CDataBrowser* browser)
{
auto oldName = getStringList ()->at (static_cast<uint32_t> (row));
if (oldName != newText)
{
for (auto& name : *getStringList ())
{
if (name == newText)
return;
}
actionPerformer->performTemplateNameChange (oldName.data (), newText);
}
}
//----------------------------------------------------------------------------------------------------
void UITemplatesDataSource::dbCellSetupTextEdit (int32_t row, int32_t column, CTextEdit* textEditControl, CDataBrowser* browser)
{
textEditControl->setBackColor (kWhiteCColor);
textEditControl->setFontColor (fontColor);
textEditControl->setFont (drawFont);
textEditControl->setHoriAlign (kLeftText);
textEditControl->setTextInset (textInset);
}
//----------------------------------------------------------------------------------------------------
void UITemplatesDataSource::dbAttached (CDataBrowser* browser)
{
UINavigationDataSource::dbAttached (browser);
if (getStringList ())
{
if (firstSelectedTemplateName.empty ())
{
browser->setSelectedRow (0, true);
}
else
{
uint32_t index = 0;
for (auto& name : *getStringList ())
{
if (name == firstSelectedTemplateName)
{
browser->setSelectedRow (static_cast<int32_t> (index), true);
break;
}
index++;
}
}
}
}
} // namespace
#endif // VSTGUI_LIVE_EDITING
|
#pragma once
#include <typed-geometry/types/mat.hh>
namespace tg
{
template <int D, class ScalarT>
[[nodiscard]] constexpr ScalarT trace(mat<D, D, ScalarT> const& A)
{
if constexpr (D == 1)
return A[0][0];
else if constexpr (D == 2)
return A[0][0] + A[1][1];
else if constexpr (D == 3)
return A[0][0] + A[1][1] + A[2][2];
else if constexpr (D == 4)
return A[0][0] + A[1][1] + A[2][2] + A[3][3];
else
static_assert(D <= 4, "only up to 3D supported");
}
// trace(A * B)
template <int N, int M, class ScalarT>
[[nodiscard]] constexpr ScalarT trace_of_product(mat<N, M, ScalarT> const& A, mat<M, N, ScalarT> const& B)
{
auto r = ScalarT(0);
for (auto i = 0; i < N; ++i)
for (auto j = 0; j < N; ++j)
r += A[i][j] * B[j][i];
return r;
}
}
|
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main(){
char* str;
short len;
cout<<"len:";
cin>>len;
str=new char[len+1];
fstream file;
file.open("strings.txt",ios::app);
cout<<"Enter string:";
cin.ignore();
cin.getline(str,len);
cout<<str<<endl;
file<<str<<";";
file.close();
file.open("strings.txt",ios::in);
while(!file.eof()){
file.getline(str,len,';');
cout<<str<<endl;
}
file.close();
delete[] str;
return 0;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2019 The KZCash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "chain.h"
#include "core_io.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "policy/rbf.h"
#include "rpcserver.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include "walletdb.h"
#include "keepass.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nRequires wallet passphrase to be set with walletpassphrase call."
: "";
}
bool EnsureWalletIsAvailable(bool avoidException)
{
if (!pwalletMain)
{
if (!avoidException)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
else
return false;
}
return true;
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain(false);
int confirmsTotal = GetIXConfirmations(wtx.GetHash()) + confirms;
entry.push_back(Pair("confirmations", confirmsTotal));
entry.push_back(Pair("bcconfirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
} else {
entry.push_back(Pair("trusted", wtx.IsTrusted()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
// Add opt-in RBF status
std::string rbfStatus = "no";
if (confirms <= 0) {
LOCK(mempool.cs);
if (!mempool.exists(hash)) {
if (SignalsOptInRBF(wtx)) {
rbfStatus = "yes";
} else {
rbfStatus = "unknown";
}
} else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) {
rbfStatus = "yes";
}
}
entry.push_back(Pair("bip125-replaceable", rbfStatus));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const UniValue& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
UniValue getnewaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new KZCash address for receiving payments.\n"
"If 'account' is specified (DEPRECATED), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"kzcashaddress\" (string) The new kzcash address\n"
"\nExamples:\n"
+ HelpExampleCli("getnewaddress", "")
+ HelpExampleRpc("getnewaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked(true))
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
UniValue getaccountaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress \"account\"\n"
"\nDEPRECATED. Returns the current KZCash address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"kzcashaddress\" (string) The account kzcash address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccountaddress", "")
+ HelpExampleCli("getaccountaddress", "\"\"")
+ HelpExampleCli("getaccountaddress", "\"myaccount\"")
+ HelpExampleRpc("getaccountaddress", "\"myaccount\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
UniValue ret(UniValue::VSTR);
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"\nReturns a new KZCash address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n"
+ HelpExampleCli("getrawchangeaddress", "")
+ HelpExampleRpc("getrawchangeaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!pwalletMain->IsLocked(true))
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CBitcoinAddress(keyID).ToString();
}
UniValue setaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount \"kzcashaddress\" \"account\"\n"
"\nDEPRECATED. Sets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"kzcashaddress\" (string, required) The kzcash address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n"
+ HelpExampleCli("setaccount", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" \"tabby\"")
+ HelpExampleRpc("setaccount", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\", \"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid KZCash address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get()))
{
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
}
else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return NullUniValue;
}
UniValue getaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount \"kzcashaddress\"\n"
"\nDEPRECATED. Returns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"kzcashaddress\" (string, required) The kzcash address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccount", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\"")
+ HelpExampleRpc("getaccount", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid KZCash address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nDEPRECATED. Returns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"kzcashaddress\" (string) a kzcash address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
+ HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, bool fUseInstantSend=false, bool fUsePrivateSend=false)
{
CAmount curBalance = pwalletMain->GetBalance();
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
// Parse KZCash address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
std::string strError;
vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet,
strError, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey, fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue sendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 7)
throw runtime_error(
"sendtoaddress \"kzcashaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount use_is use_ps )\n"
"\nSend an amount to a given address.\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"kzcashaddress\" (string, required) The kzcash address to send to.\n"
"2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less amount of KZCash than you enter in the amount field.\n"
"6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n"
"7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("sendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.1")
+ HelpExampleCli("sendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("sendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("sendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid KZCash address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
if (params.size() > 5)
fUseInstantSend = params[5].get_bool();
if (params.size() > 6)
fUsePrivateSend = params[6].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, fUseInstantSend, fUsePrivateSend);
return wtx.GetHash().GetHex();
}
UniValue instantsendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 5)
throw runtime_error(
"instantsendtoaddress \"kzcashaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"kzcashaddress\" (string, required) The kzcash address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less amount of KZCash than you enter in the amount field.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("instantsendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.1")
+ HelpExampleCli("instantsendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("instantsendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("instantsendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid KZCash address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, true);
return wtx.GetHash().GetHex();
}
UniValue listaddressgroupings(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"kzcashaddress\", (string) The kzcash address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"account\" (string, optional) The account (DEPRECATED)\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listaddressgroupings", "")
+ HelpExampleRpc("listaddressgroupings", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH(CTxDestination address, grouping)
{
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
UniValue signmessage(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage \"kzcashaddress\" \"message\"\n"
"\nSign a message with the private key of an address"
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"kzcashaddress\" (string, required) The kzcash address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessage", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\", \"my message\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress \"kzcashaddress\" ( minconf )\n"
"\nReturns the total amount received by the given kzcashaddress in transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"kzcashaddress\" (string, required) The kzcash address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n"
+ HelpExampleCli("getreceivedbyaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// KZCash address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid KZCash address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n"
"\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CAmount nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
}
UniValue getbalance(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"getbalance ( \"account\" minconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance.\n"
"If account is specified (DEPRECATED), returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the wallet\n"
+ HelpExampleCli("getbalance", "") +
"\nThe total amount in the wallet at least 5 blocks confirmed\n"
+ HelpExampleCli("getbalance", "\"*\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getbalance", "\"*\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH(const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter);
return ValueFromAmount(nBalance);
}
UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
LOCK2(cs_main, pwalletMain->cs_wallet);
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
UniValue movecmd(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n"
"\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n"
+ HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n"
+ HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
pwalletMain->AddAccountingEntry(debit, walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
pwalletMain->AddAccountingEntry(credit, walletdb);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
UniValue sendfrom(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom \"fromaccount\" \"tokzcashaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
"\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a kzcash address."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"tokzcashaddress\" (string, required) The kzcash address to send funds to.\n"
"3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n"
+ HelpExampleCli("sendfrom", "\"\" \"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n"
+ HelpExampleCli("sendfrom", "\"tabby\" \"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 0.01 6 \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendfrom", "\"tabby\", \"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\", 0.01, 6, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid KZCash address");
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, false, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendmany(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 7)
throw runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric or string) The kzcash address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. \"comment\" (string, optional) A comment\n"
"5. subtractfeefromamount (string, optional) A json array with addresses.\n"
" The fee will be equally deducted from the amount of each selected address.\n"
" Those recipients will receive less kzcashs than you enter in their corresponding amount field.\n"
" If no addresses are specified here, the sender pays the fee.\n"
" [\n"
" \"address\" (string) Subtract fee from this address\n"
" ,...\n"
" ]\n"
"6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n"
"7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n"
+ HelpExampleCli("sendmany", "\"tabby\" \"{\\\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n"
+ HelpExampleCli("sendmany", "\"tabby\" \"{\\\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\" 6 \"testing\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\", 6, \"testing\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
UniValue sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (params.size() > 4)
subtractFeeFromAmount = params[4].get_array();
set<CBitcoinAddress> setAddress;
vector<CRecipient> vecSend;
CAmount totalAmount = 0;
vector<string> keys = sendTo.getKeys();
BOOST_FOREACH(const string& name_, keys)
{
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid KZCash address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
const UniValue& addr = subtractFeeFromAmount[idx];
if (addr.get_str() == name_)
fSubtractFeeFromAmount = true;
}
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
string strFailReason;
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
if (params.size() > 5)
fUseInstantSend = params[5].get_bool();
if (params.size() > 6)
fUsePrivateSend = params[6].get_bool();
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason,
NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange, fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpcmisc.cpp
extern CScript _createmultisig_redeemScript(const UniValue& params);
UniValue addmultisigaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a KZCash address or hex-encoded public key.\n"
"If 'account' is specified (DEPRECATED), assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of kzcash addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) kzcash address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n"
"\nResult:\n"
"\"kzcashaddress\" (string) A kzcash address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n"
+ HelpExampleCli("addmultisigaddress", "2 \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") +
"\nAs json rpc call\n"
+ HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"")
;
throw runtime_error(msg);
}
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
CAmount nAmount;
int nConf;
int nBCConf;
vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
nBCConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
UniValue ListReceived(const UniValue& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
int nBCDepth = wtx.GetDepthInMainChain(false);
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if(!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.nBCConf = min(item.nBCConf, nBCDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
int nBCConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
nBCConf = (*it).second.nBCConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
item.nBCConf = min(item.nBCConf, nBCConf);
item.fIsWatchonly = fIsWatchonly;
}
else
{
UniValue obj(UniValue::VOBJ);
if(fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
if (!fByAccounts)
obj.push_back(Pair("label", strAccount));
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
int nBCConf = (*it).second.nBCConf;
UniValue obj(UniValue::VOBJ);
if((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
ret.push_back(obj);
}
}
return ret;
}
UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaddress", "")
+ HelpExampleCli("listreceivedbyaddress", "6 true")
+ HelpExampleRpc("listreceivedbyaddress", "6, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, false);
}
UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
"\nDEPRECATED. List balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaccount", "")
+ HelpExampleCli("listreceivedbyaccount", "6 true")
+ HelpExampleRpc("listreceivedbyaccount", "6, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const COutputEntry& s, listSent)
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS");
entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "privatesend" : "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
if (pwalletMain->mapAddressBook.count(s.destination))
entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
entry.push_back(Pair("abandoned", wtx.isAbandoned()));
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount))
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
if (pwalletMain->mapAddressBook.count(r.destination))
entry.push_back(Pair("label", account));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
UniValue listtransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"kzcashaddress\", (string) The kzcash address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\": n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions. Negative confirmations indicate the\n"
" transation conflicts with the block chain\n"
" \"bcconfirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions. Negative confirmations indicate the\n"
" transation conflicts with the block chain\n"
" \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\": \"label\" (string) A comment for the address/transaction, if any\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n"
+ HelpExampleCli("listtransactions", "") +
"\nList transactions 100 to 120\n"
+ HelpExampleCli("listtransactions", "\"*\" 20 100") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listtransactions", "\"*\", 20, 100")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 3)
if(params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered;
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
vector<UniValue> arrTmp = ret.getValues();
vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
UniValue listaccounts(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 2)
throw runtime_error(
"listaccounts ( minconf includeWatchonly)\n"
"\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n"
+ HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n"
+ HelpExampleCli("listaccounts", "0") +
"\nList account balances for 6 or more confirmations\n"
+ HelpExampleCli("listaccounts", "6") +
"\nAs json rpc call\n"
+ HelpExampleRpc("listaccounts", "6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
const list<CAccountingEntry> & acentries = pwalletMain->laccentries;
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
UniValue listsinceblock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"kzcashaddress\", (string) The kzcash address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("listsinceblock", "")
+ HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
+ HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBlockIndex *pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0)
{
uint256 blockId;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid blockhash");
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
UniValue transactions(UniValue::VARR);
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain(false) < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
UniValue gettransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"kzcashaddress\", (string) The kzcash address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
+ HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
UniValue abandontransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"abandontransaction \"txid\"\n"
"\nMark in-wallet transaction <txid> as abandoned\n"
"This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
"for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
"It only works on transactions which are not included in a block and are not currently in the mempool.\n"
"It has no effect on transactions which are already conflicted or abandoned.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
if (!pwalletMain->AbandonTransaction(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
return NullUniValue;
}
UniValue backupwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n"
+ HelpExampleCli("backupwallet", "\"backup.dat\"")
+ HelpExampleRpc("backupwallet", "\"backup.dat\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return NullUniValue;
}
UniValue keypoolrefill(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool."
+ HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=" + itostr(DEFAULT_KEYPOOL_SIZE) + ") The new keypool size\n"
"\nExamples:\n"
+ HelpExampleCli("keypoolrefill", "")
+ HelpExampleRpc("keypoolrefill", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < kpSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return NullUniValue;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
UniValue walletpassphrase(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase \"passphrase\" timeout ( mixingonly )\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending kzcashs\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"3. mixingonly (boolean, optional, default=false) If is true sending functions are disabled."
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one.\n"
"\nExamples:\n"
"\nUnlock the wallet for 60 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nUnlock the wallet for 60 seconds but allow PrivateSend mixing only\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") +
"\nLock the wallet again (before 60 seconds)\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
int64_t nSleepTime = params[1].get_int64();
bool fForMixingOnly = false;
if (params.size() >= 3)
fForMixingOnly = params[2].get_bool();
if (fForMixingOnly && !pwalletMain->IsLocked(true) && pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked for mixing only.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already fully unlocked.");
if (!pwalletMain->Unlock(strWalletPass, fForMixingOnly))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
pwalletMain->TopUpKeyPool();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
return NullUniValue;
}
UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n"
+ HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
+ HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return NullUniValue;
}
UniValue walletlock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n"
+ HelpExampleCli("sendtoaddress", "\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletlock", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return NullUniValue;
}
UniValue encryptwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n"
+ HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending kzcash\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n"
+ HelpExampleCli("signmessage", "\"kzcashaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n"
+ HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "Wallet encrypted; KZCash Core server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
UniValue lockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending kzcashs.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 1)
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256S(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
UniValue listlockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listlockunspent", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
UniValue settxfee(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n"
"\nArguments:\n"
"1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n"
+ HelpExampleCli("settxfee", "0.00001")
+ HelpExampleRpc("settxfee", "0.00001")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Amount
CAmount nAmount = AmountFromValue(params[0]);
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
UniValue getwalletinfo(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"keys_left\": xxxx, (numeric) how many new keys are left since last automatic backup\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getwalletinfo", "")
+ HelpExampleRpc("getwalletinfo", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance())));
obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
return obj;
}
UniValue keepass(const UniValue& params, bool fHelp) {
string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "genkey" && strCommand != "init" && strCommand != "setpassphrase"))
throw runtime_error(
"keepass <genkey|init|setpassphrase>\n");
if (strCommand == "genkey")
{
SecureString sResult;
// Generate RSA key
SecureString sKey = CKeePassIntegrator::generateKeePassKey();
sResult = "Generated Key: ";
sResult += sKey;
return sResult.c_str();
}
else if(strCommand == "init")
{
// Generate base64 encoded 256 bit RSA key and associate with KeePassHttp
SecureString sResult;
SecureString sKey;
std::string strId;
keePassInt.rpcAssociate(strId, sKey);
sResult = "Association successful. Id: ";
sResult += strId.c_str();
sResult += " - Key: ";
sResult += sKey.c_str();
return sResult.c_str();
}
else if(strCommand == "setpassphrase")
{
if(params.size() != 2) {
return "setlogin: invalid number of parameters. Requires a passphrase";
}
SecureString sPassphrase = SecureString(params[1].get_str().c_str());
keePassInt.updatePassphrase(sPassphrase);
return "setlogin: Updated credentials.";
}
return "Invalid command";
}
UniValue resendwallettransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw runtime_error(
"resendwallettransactions\n"
"Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
"Intended only for testing; the wallet code periodically re-broadcasts\n"
"automatically.\n"
"Returns array of transaction ids that were re-broadcast.\n"
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime());
UniValue result(UniValue::VARR);
BOOST_FOREACH(const uint256& txid, txids)
{
result.push_back(txid.ToString());
}
return result;
}
UniValue listunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of kzcash addresses to filter\n"
" [\n"
" \"address\" (string) kzcash address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the kzcash address\n"
" \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" \"ps_rounds\" : n (numeric) The number of PS round\n"
" \"spendable\" : true|false (boolean) True if spendable\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"KinyzZcdoTzAj8QEn2ZBBu3w8TR4GMD96W\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
UniValue inputs = params[2].get_array();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid KZCash address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
UniValue results(UniValue::VARR);
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
BOOST_FOREACH(const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
entry.push_back(Pair("ps_rounds", pwalletMain->GetInputPrivateSendRounds(CTxIn(out.tx->GetHash(), out.i))));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
UniValue fundrawtransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"fundrawtransaction \"hexstring\" includeWatching\n"
"\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
"This will not modify existing inputs, and will add one change output to the outputs.\n"
"Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
"The inputs added will not be signed, use signrawtransaction for that.\n"
"Note that all existing inputs must have their previous output transaction be in the wallet.\n"
"Note that all inputs selected must be of standard form and P2SH scripts must be"
"in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
"Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction\n"
"2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
" \"fee\": n, (numeric) Fee the resulting transaction pays\n"
" \"changepos\": n (numeric) The position of the added change output, or -1\n"
"}\n"
"\"hex\" \n"
"\nExamples:\n"
"\nCreate a transaction with no inputs\n"
+ HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
"\nAdd sufficient unsigned inputs to meet the output value\n"
+ HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
"\nSign the transaction\n"
+ HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
"\nSend the transaction\n"
+ HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction origTx;
if (!DecodeHexTx(origTx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
if (origTx.vout.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
bool includeWatching = false;
if (params.size() > 1)
includeWatching = params[1].get_bool();
CMutableTransaction tx(origTx);
CAmount nFee;
string strFailReason;
int nChangePos = -1;
if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching))
throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(tx)));
result.push_back(Pair("changepos", nChangePos));
result.push_back(Pair("fee", ValueFromAmount(nFee)));
return result;
}
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _FMTANCHR_HXX
#define _FMTANCHR_HXX
#include "swdllapi.h"
#include <hintids.hxx>
#include <swtypes.hxx>
#include <format.hxx>
#include <svl/poolitem.hxx>
struct SwPosition;
class IntlWrapper;
#define IVER_FMTANCHOR_LONGIDX ((sal_uInt16)1)
//FlyAnchor, Anker des Freifliegenden Rahmen ----
class SW_DLLPUBLIC SwFmtAnchor: public SfxPoolItem
{
SwPosition *pCntntAnchor; //0 Fuer Seitengebundene Rahmen.
//Index fuer Absatzgebundene Rahmen.
//Position fuer Zeichengebundene Rahmen
RndStdIds nAnchorId;
sal_uInt16 nPageNum; //Seitennummer bei Seitengeb. Rahmen.
// OD 2004-05-05 #i28701# - getting anchor positions ordered
sal_uInt32 mnOrder;
static sal_uInt32 mnOrderCounter;
public:
SwFmtAnchor( RndStdIds eRnd = FLY_AT_PAGE, sal_uInt16 nPageNum = 0 );
SwFmtAnchor( const SwFmtAnchor &rCpy );
~SwFmtAnchor();
// Zuweisungsoperator
SwFmtAnchor &operator=( const SwFmtAnchor& );
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 );
RndStdIds GetAnchorId() const { return nAnchorId; }
sal_uInt16 GetPageNum() const { return nPageNum; }
const SwPosition *GetCntntAnchor() const { return pCntntAnchor; }
// OD 2004-05-05 #i28701#
sal_uInt32 GetOrder() const;
void SetType( RndStdIds nRndId ) { nAnchorId = nRndId; }
void SetPageNum( sal_uInt16 nNew ) { nPageNum = nNew; }
void SetAnchor( const SwPosition *pPos );
};
inline const SwFmtAnchor &SwAttrSet::GetAnchor(sal_Bool bInP) const
{ return static_cast<const SwFmtAnchor&>(Get(RES_ANCHOR, bInP)); }
inline const SwFmtAnchor &SwFmt::GetAnchor(sal_Bool bInP) const
{ return aSet.GetAnchor(bInP); }
#endif
|
#include <stdexcept>
/**
LinkedElement é uma struct utilizada pela classe LinkedStack, no qual
possuirá o seu próprio conteúdo e o endereço dos elementos vinculados ao mesmo.
*/
template <typename Type> struct LinkedElement {
Type content;
LinkedElement<Type> *previous;
LinkedElement<Type> *next;
};
/**
LinkedStack é uma classe para criar pilhas dinâmicas, onde cada
elemento estará vinculado com o próximo elemento da pilha.
*/
template <typename ElementType> class LinkedStack {
private:
int length = 0;
LinkedElement<ElementType> *firstElement = NULL;
LinkedElement<ElementType> *lastElement = NULL;
/**
Método para criar um novo objeto de LinkedElement, retornando o seu ponteiro.
*/
struct LinkedElement<ElementType> *createLinkedElement(ElementType element) {
struct LinkedElement<ElementType> *newElement = new LinkedElement<ElementType>;
newElement->content = element;
newElement->previous = NULL;
newElement->next = NULL;
return newElement;
}
/**
Método para retornar um elemento, ponteiro de LinkedElement, através do índice.
*/
struct LinkedElement<ElementType> *getLinkedElement(int index) {
struct LinkedElement<ElementType> *targetElement;
bool searchFromBegin = (index < length / 2);
// Se o índice for maior que a metade da pilha, é mais eficiente começar
// a busca a partir do final da pilha.
if (searchFromBegin) {
targetElement = firstElement;
}
else {
targetElement = lastElement;
index = length - index - 1;
}
// Percorre os elementos, começando da direita para esquerda ou da esquerda para direita.
for (int i = 0; i < index; i++) {
targetElement = searchFromBegin ? targetElement->next : targetElement->previous;
}
// Retorna o elemento encontrado.
return targetElement;
}
/**
Método para comparar uma pilha com outra.
*/
bool equals(LinkedStack &stack) {
// Verifica se o tamanho das pilhas é diferente.
if (stack.getLength() != length) {
return false;
}
struct LinkedElement<ElementType> *element1 = stack.lastElement;
struct LinkedElement<ElementType> *element2 = lastElement;
// Percorre os elementos de ambas as pilhas, verificando se são diferentes.
for (int i = 0; i < length; i++) {
element1 = element1->next;
element2 = element2->next;
if (element1->content != element2->content) {
return false;
}
}
return true;
}
/**
Método para validar um índice, verificando se ele é menor que o tamanho da pilha.
*/
bool validateIndex(int index, bool throwError = false) {
if (index < length) {
return true;
}
if (throwError) {
throw std::out_of_range("stack index out of range");
}
return false;
}
public:
/**
Destrutor da classe.
*/
~LinkedStack() {
clear();
}
/**
Método para retornar um elemento, a partir de um índice,
utilizando a sintaxe dos colchetes.
*/
ElementType operator [](int index) {
return get(index);
}
/**
Método para adicionar um elemento na pilha, utilizando a atribuição com soma.
*/
void operator +=(ElementType element) {
return add(element);
}
/**
Método para verificar se a pilha é igual à outra,
utilizando o operador de comparação.
*/
bool operator ==(LinkedStack &stack) {
return equals(stack);
}
/**
Método para verificar se a pilha é diferente de outra,
utilizando o operador de comparação.
*/
bool operator !=(LinkedStack &stack) {
return !equals(stack);
}
/**
Método para retornar o tamanho da pilha.
*/
int getLength() {
return length;
}
/**
Método para limpar a pilha.
*/
void clear() {
while (length != 0) {
remove();
}
}
/**
Método para verificar se a pilha possui um determinado elemento.
*/
bool contains(ElementType element) {
struct LinkedElement<ElementType> *targetElement = lastElement;
// Percorre os elementos da pilha, verificando
// se um deles é igual ao elemento recebido.
for (int i = 0; i < length; i++) {
targetElement = targetElement->next;
if (targetElement->content == element) {
return true;
}
}
return false;
}
/**
Método para contar quantos elementos X existem na pilha.
*/
int count(ElementType element) {
struct LinkedElement<ElementType> *targetElement = lastElement;
int elementCount = 0;
// Percorre os elementos da pilha, verificando
// se são iguais ao elemento recebido.
for (int i = 0; i < length; i++) {
targetElement = targetElement->next;
if (targetElement->content == element) {
elementCount++;
}
}
return elementCount;
}
/**
Método para retornar o índice de um dado elemento.
*/
int indexOf(ElementType element) {
struct LinkedElement<ElementType> *targetElement = lastElement;
// Percorre os elementos da pilha, verificando
// se são iguais ao elemento recebido.
for (int index = 0; index < length; index++) {
targetElement = targetElement->next;
if (targetElement->content == element) {
return index;
}
}
return -1;
}
/**
Método para adicionar um elemento na pilha.
*/
void add(ElementType element) {
// Cria um LinkedElement para o elemento a ser inserido.
struct LinkedElement<ElementType> *newElement = createLinkedElement(element);
// Se não houver elemento na pilha, o elemento será adicionado como
// o primeiro e último da pilha.
if (length == 0) {
firstElement = newElement;
firstElement->previous = newElement;
firstElement->next = newElement;
lastElement = firstElement;
}
// Insere o elemento no final da pilha, vinculando o último elemento com o elemento
// da inserção e o elemento da inserção com o primeiro elemento. Após isso, o último
// elemento passará a ser o elemento da inserção.
else {
newElement->next = firstElement;
newElement->previous = lastElement;
lastElement->next = newElement;
firstElement->previous = newElement;
lastElement = newElement;
}
// Computa a inserção do elemento na pilha.
length++;
}
/**
Método para adicionar todos os elementos de uma dada pilha.
*/
void expand(LinkedStack<ElementType> &stack) {
struct LinkedElement<ElementType> *element = stack.lastElement;
for (int index = 0; index < stack.getLength(); index++) {
element = element->next;
add(element->content);
}
}
/**
Método para retornar um elemento, a partir de um índice.
*/
ElementType get(int index) {
// Valida o índice recebido.
validateIndex(index, true);
// Obtém o elemento alvo, através do índice especificado.
struct LinkedElement<ElementType> *targetElement = getLinkedElement(index);
// Retorna o seu conteúdo.
return targetElement->content;
}
/**
Método para remover o próximo elemento da pilha.
*/
ElementType remove() {
// Remove o último elemento (último a entrar) da pilha, vinculando o
// penúltimo elemento com o primeiro elemento. Após isso, o penúltimo
// elemento da pilha será o último elemento.
struct LinkedElement<ElementType> *targetElement = lastElement;
targetElement->previous->next = firstElement;
firstElement->previous = targetElement->previous;
lastElement = targetElement->previous;
// Salva o conteúdo e apaga o elemento da memória.
ElementType content = targetElement->content;
delete targetElement;
// Computa a remoção do elemento.
length--;
return content;
}
/**
Método para retornar uma cópia da pilha, copiando todos os seus elementos.
*/
LinkedStack<ElementType> ©() {
// Cria na memória um novo objeto da pilha.
LinkedStack<ElementType> * newStack = new LinkedStack<ElementType>;
// Adiciona todos os elementos no novo objeto.
newStack->expand(*this);
return *newStack;
}
};
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "core/assert.hpp"
#include "storage/random_access_stack.hpp"
#include <algorithm>
#include <array>
#include <fstream>
#include <map>
#include <string>
#include <unordered_map>
namespace fetch {
namespace storage {
/**
* The CacheLineRandomAccessStack owns a stack of type T (RandomAccessStack), and provides
* caching in an invisible manner.
*
* It does this by maintaining a quick access structure (data_ map) that can be used without disk
* access. The map resembles a CPU cache line.
*
* The stack is responsible for flushing this to disk at regular intervals to keep the map size
* small and guard against loss of data in the event of system failure. Sets and gets will fill
* this map.
*
*/
template <typename T, typename D = uint64_t>
class CacheLineRandomAccessStack
{
public:
using EventHandlerType = std::function<void()>;
using StackType = RandomAccessStack<T, D>;
using HeaderExtraType = D;
using type = T;
CacheLineRandomAccessStack() = default;
~CacheLineRandomAccessStack()
{
Flush(false);
}
/**
* Indicate whether the stack is writing directly to disk or caching writes. Since
* This class intends to invisibly provide caching it returns that it's a
* direct write class.
*
* @return: Whether the stack is written straight to disk.
*/
static constexpr bool DirectWrite()
{
return true;
}
void Load(std::string const &filename, bool const &create_if_not_exists = true)
{
stack_.Load(filename, create_if_not_exists);
this->objects_ = stack_.size();
this->SignalFileLoaded();
}
void New(std::string const &filename)
{
stack_.New(filename);
this->objects_ = 0;
this->SignalFileLoaded();
}
void ClearEventHandlers()
{
on_file_loaded_ = nullptr;
on_before_flush_ = nullptr;
}
void OnFileLoaded(EventHandlerType const &f)
{
on_file_loaded_ = f;
}
void OnBeforeFlush(EventHandlerType const &f)
{
on_before_flush_ = f;
}
void Get(uint64_t i, type &object) const
{
assert(i < objects_);
uint64_t cache_lookup = i >> cache_line_ln2; // Upper N bits
uint64_t cache_subindex = i & ((1 << cache_line_ln2) - 1); // Lower total - N bits
auto iter = data_.find(cache_lookup);
// Found the item via local map
if (iter != data_.end())
{
++((*iter).second.reads);
object = iter->second.elements[cache_subindex];
}
else
{
// Case where item isn't found, load it into the cache, then access
LoadCacheLine(i);
data_[cache_lookup].reads++;
object = data_[cache_lookup].elements[cache_subindex];
}
}
/**
* Set index i to object. Undefined behaviour if i >= stack size.
*
* @param: i The index
* @param: object The object to write
*/
void Set(uint64_t i, type const &object)
{
assert(i < objects_);
uint64_t cache_lookup = i >> cache_line_ln2; // Upper N bits
uint64_t cache_subindex = i & ((1 << cache_line_ln2) - 1); // Lower total - N bits
auto iter = data_.find(cache_lookup);
// Found the item via local map
if (iter != data_.end())
{
++iter->second.writes;
iter->second.elements[cache_subindex] = object;
}
else
{
// Case where item isn't found, load it into the cache, then access
LoadCacheLine(i);
data_[cache_lookup].writes++;
data_[cache_lookup].elements[cache_subindex] = object;
}
}
void Close()
{
Flush(false);
stack_.Close(false);
}
void SetExtraHeader(HeaderExtraType const &he)
{
stack_.SetExtraHeader(he);
}
HeaderExtraType const &header_extra() const
{
return stack_.header_extra();
}
uint64_t Push(type const &object)
{
uint64_t ret = objects_;
++objects_;
// Guaranteed to be safe - sets make sure the underlying stack has the memory
Set(objects_ - 1, object);
return ret;
}
/**
* Since we're caching, we decrement our internal counter and fix it on the next hard
* flush.
*/
void Pop()
{
--objects_;
}
type Top()
{
type ret;
Get(objects_ - 1, ret);
return ret;
}
void Swap(uint64_t i, uint64_t j)
{
if (i == j)
{
return;
}
uint64_t cache_lookup_i = i >> cache_line_ln2;
uint64_t cache_lookup_j = j >> cache_line_ln2;
uint64_t cache_subindex_i = i & ((1 << cache_line_ln2) - 1);
uint64_t cache_subindex_j = j & ((1 << cache_line_ln2) - 1);
// make sure both items are in the cache
if (data_.find(cache_lookup_i) == data_.end())
{
LoadCacheLine(cache_lookup_i);
}
if (data_.find(cache_lookup_j) == data_.end())
{
LoadCacheLine(cache_lookup_j);
}
// If this assertion fails, there might not be enough memory for two cache lines
assert(data_.find(cache_lookup_i) != data_.end());
assert(data_.find(cache_lookup_j) != data_.end());
data_[cache_lookup_i].reads++;
data_[cache_lookup_j].reads++;
std::swap(data_[cache_lookup_i].elements[cache_subindex_i],
data_[cache_lookup_j].elements[cache_subindex_j]);
}
std::size_t size() const
{
return objects_;
}
std::size_t empty() const
{
return objects_ == 0;
}
void Clear()
{
stack_.Clear();
objects_ = 0;
data_.clear();
}
/**
* Flush all of the cached elements to file if they have been updated
*/
void Flush(bool lazy = true) const
{
if (!lazy)
{
for (auto const &i : data_)
{
FlushLine(i.first << cache_line_ln2, i.second);
}
// Trim stack size down
while (stack_.size() > objects_ && stack_.is_open())
{
stack_.Pop();
}
if (stack_.is_open())
{
stack_.Flush(false);
}
}
}
bool is_open() const
{
return stack_.is_open();
}
/**
* Set the limit for the amount of RAM this structure will use to amortize the cost of disk
* writes.
*
* @param: bytes The number of bytes allowed as an upper bound
*/
void SetMemoryLimit(std::size_t bytes)
{
memory_limit_bytes_ = bytes;
}
private:
// Cached items
static constexpr std::size_t cache_line_ln2 = 13; // Default cache lines 8192 * sizeof(T)
std::size_t memory_limit_bytes_ = std::size_t(1ULL << 29); // Default 500K memory
T dummy_{};
EventHandlerType on_file_loaded_;
EventHandlerType on_before_flush_;
// Underlying stack
mutable StackType stack_;
struct CachedDataItem
{
uint64_t reads = 0;
uint64_t writes = 0;
std::array<type, 1 << cache_line_ln2> elements{};
};
mutable std::map<uint64_t, CachedDataItem> data_;
mutable uint64_t last_removed_index_ = 0;
uint64_t objects_ = 0;
void FlushLine(uint64_t line, CachedDataItem const &items) const
{
if (items.writes == 0)
{
return;
}
if (!stack_.is_open())
{
return;
}
stack_.SetBulk(line, 1ull << cache_line_ln2, items.elements.data());
}
void GetLine(uint64_t line, CachedDataItem &items) const
{
if (!stack_.is_open())
{
return;
}
stack_.GetBulk(line, 1 << cache_line_ln2, items.elements.data());
}
bool ManageMemory() const
{
// Lazy policy: remove items FILO style
using MapElement = typename decltype(data_)::value_type;
if (!(data_.size() * sizeof(MapElement) > memory_limit_bytes_))
{
return false;
}
// Find and remove next index up from the last one we removed
auto next_to_remove = data_.upper_bound(last_removed_index_);
if (next_to_remove->first > last_removed_index_ && next_to_remove != data_.end())
{
last_removed_index_ = next_to_remove->first;
FlushLine(next_to_remove->first << cache_line_ln2, next_to_remove->second);
data_.erase(next_to_remove);
}
else
{
next_to_remove = data_.begin(); // Get min element
FlushLine(next_to_remove->first << cache_line_ln2, next_to_remove->second);
last_removed_index_ = next_to_remove->first;
data_.erase(next_to_remove);
}
return true;
}
void LoadCacheLine(uint64_t line) const
{
// Cull memory usage to max allowed
for (;;)
{
if (!ManageMemory())
{
break;
}
}
// Load in the cache line (memory usage now slightly over)
uint64_t cache_index = (line >> cache_line_ln2) << cache_line_ln2;
GetLine(cache_index, data_[cache_index >> cache_line_ln2]);
}
void SignalFileLoaded()
{
if (on_file_loaded_)
{
on_file_loaded_();
}
}
};
} // namespace storage
} // namespace fetch
|
#pragma once
#include <iostream>
#include "../LAYER_RNN/Layer_LSTM.hpp"
#include "../LOAD/MnistData.hpp"
namespace RNN
{
namespace MnistLSTM
{
// g++ Source.cpp -O3
void MnistLSTM()
{
MNistData::loadMnist();
std::vector<std::vector<MidData *>> bottom_x_vec;
for (int i = 0; i < 55000; i++)
{
mat s = ORIGDATA::mat_L_Tr_2D->data_f.row(i);
std::vector<MidData *> vec_in;
for (int j = 0; j < 28; j++)
{
MidData *mid = new MidData;
mid->data_f = s.block(0, j * 28, 1, 28);
vec_in.push_back(mid);
}
bottom_x_vec.push_back(vec_in);
}
std::vector<std::vector<MidData *>> bottom_x_vec_T;
for (int i = 0; i < 10000; i++)
{
mat s = ORIGDATA::mat_L_Te_2D->data_f.row(i);
std::vector<MidData *> vec_in;
for (int j = 0; j < 28; j++)
{
MidData *mid = new MidData;
mid->data_f = s.block(0, j * 28, 1, 28);
vec_in.push_back(mid);
}
bottom_x_vec_T.push_back(vec_in);
}
// ================================================================================================
Net_LSTM net_LSTM_T(28, 28, 128);
mat classify(128, 10);
classify.setRandom();
MidData out;
for (int p = 0; p < 2; p++)
{
for (int i = 0; i < 55000; i++)
{
net_LSTM_T.setInitial(i, bottom_x_vec);
net_LSTM_T.calForward();
out.data_f = (net_LSTM_T.cell_LSTM_Vec.back().h_L4->out->data_f * classify).array().exp().matrix() / (net_LSTM_T.cell_LSTM_Vec.back().h_L4->out->data_f * classify).array().exp().sum();
out.data_b = out.data_f - ORIGDATA::mat_R_Tr_2D->data_b.row(i);
net_LSTM_T.cell_LSTM_Vec.back().h_L4->out->data_b = out.data_b * classify.transpose();
net_LSTM_T.calBackward();
net_LSTM_T.upW();
classify = classify - 0.05 * net_LSTM_T.cell_LSTM_Vec.back().h_L4->out->data_f.transpose() * out.data_b;
//std::cout << i << ":::" << out.data_f << std::endl;
}
}
int totalNum = 0;
for( int i = 0; i < 10000; i++ )
{
net_LSTM_T.setInitial(i, bottom_x_vec_T);
net_LSTM_T.calForward();
out.data_f = (net_LSTM_T.cell_LSTM_Vec.back().h_L4->out->data_f * classify).array().exp().matrix() / (net_LSTM_T.cell_LSTM_Vec.back().h_L4->out->data_f * classify).array().exp().sum();
if( colMax(out.data_f) == colMax( ORIGDATA::mat_R_Te_2D->data_b.row(i) ) )
{
totalNum++;
}
}
std::cout << totalNum << std::endl;
}
} // namespace MnistLSTM
} // namespace RNN
|
/*
Copyright (C) 2016 Vladimir "allejo" Jimenez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iterator>
#include <map>
#include <random>
#include <sstream>
#include <vector>
#include "bzfsAPI.h"
// Define plugin name
const std::string PLUGIN_NAME = "Spawn at Custom Base";
// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 0;
const int REV = 0;
const int BUILD = 6;
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0, (int)(std::distance(start, end) - 1));
std::advance(start, dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start, end, gen);
}
class BaseSpawnZone : public bz_CustomZoneObject
{
public:
BaseSpawnZone() : bz_CustomZoneObject(),
team(eNoTeam) {}
bz_eTeamType team;
};
class SpawnAtBase : public bz_Plugin, bz_CustomMapObjectHandler
{
public:
virtual const char* Name ();
virtual void Init (const char* config);
virtual void Event (bz_EventData *eventData);
virtual void Cleanup (void);
virtual bool MapObject (bz_ApiString object, bz_CustomMapObjectInfo *data);
typedef std::vector<BaseSpawnZone> ZoneVector;
std::map<bz_eTeamType, ZoneVector> TeamZones;
};
BZ_PLUGIN(SpawnAtBase)
const char* SpawnAtBase::Name (void)
{
static std::string pluginBuild = "";
if (!pluginBuild.size())
{
std::ostringstream pluginBuildStream;
pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")";
pluginBuild = pluginBuildStream.str();
}
return pluginBuild.c_str();
}
void SpawnAtBase::Init (const char* /*commandLine*/)
{
bz_registerCustomMapObject("BASESPAWNZONE", this);
// Register our events with Register()
Register(bz_eGetPlayerSpawnPosEvent);
}
void SpawnAtBase::Cleanup (void)
{
Flush(); // Clean up all the events
}
bool SpawnAtBase::MapObject (bz_ApiString object, bz_CustomMapObjectInfo *data)
{
if (object != "BASESPAWNZONE" || !data)
{
return false;
}
BaseSpawnZone newZone;
newZone.handleDefaultOptions(data);
for (unsigned int i = 0; i < data->data.size(); i++)
{
std::string line = data->data.get(i).c_str();
bz_APIStringList *nubs = bz_newStringList();
nubs->tokenize(line.c_str(), " ", 0, true);
if (nubs->size() > 0)
{
std::string key = bz_toupper(nubs->get(0).c_str());
if (key == "COLOR" && nubs->size() == 2)
{
newZone.team = (bz_eTeamType)atoi(nubs->get(1).c_str());
}
}
bz_deleteStringList(nubs);
}
TeamZones[newZone.team].push_back(newZone);
return true;
}
void SpawnAtBase::Event (bz_EventData *eventData)
{
switch (eventData->eventType)
{
case bz_eGetPlayerSpawnPosEvent: // This event is called each time the server needs a new spawn postion
{
bz_GetPlayerSpawnPosEventData_V1* spawnData = (bz_GetPlayerSpawnPosEventData_V1*)eventData;
if (bz_getPlayerSpawnAtBase(spawnData->playerID) && !TeamZones[spawnData->team].empty())
{
spawnData->handled = true;
float spawnLocation[3];
BaseSpawnZone zone = *select_randomly(TeamZones[spawnData->team].begin(), TeamZones[spawnData->team].end());
bz_getRandomPoint((bz_CustomZoneObject*)&zone, spawnLocation);
spawnData->pos[0] = spawnLocation[0];
spawnData->pos[1] = spawnLocation[1];
spawnData->pos[2] = spawnLocation[2];
}
}
break;
default: break;
}
}
|
#include "qrcodedialog.h"
#include "ui_qrcodedialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include <QPixmap>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#include <qrencode.h>
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
QDialog(parent),
ui(new Ui::QRCodeDialog),
model(0),
address(addr)
{
ui->setupUi(this);
setWindowTitle(QString("%1").arg(address));
ui->chkReqPayment->setVisible(enableReq);
ui->lblAmount->setVisible(enableReq);
ui->lnReqAmount->setVisible(enableReq);
ui->lnLabel->setText(label);
ui->btnSaveAs->setEnabled(false);
genCode();
}
QRCodeDialog::~QRCodeDialog()
{
delete ui;
}
void QRCodeDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void QRCodeDialog::genCode()
{
QString uri = getURI();
if (uri != "")
{
ui->lblQRCode->setText("");
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->outUri->setPlainText(uri);
}
}
QString QRCodeDialog::getURI()
{
QString ret = QString("venuscoin:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();
if (ui->chkReqPayment->isChecked())
{
if (ui->lnReqAmount->validate())
{
// even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21)
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value()));
paramCount++;
}
else
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("The entered amount is invalid, please check."));
return QString("");
}
}
if (!ui->lnLabel->text().isEmpty())
{
QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!ui->lnMessage->text().isEmpty())
{
QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
// limit URI length to prevent a DoS against the QR-Code dialog
if (ret.length() > MAX_URI_LENGTH)
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
return QString("");
}
ui->btnSaveAs->setEnabled(true);
return ret;
}
void QRCodeDialog::on_lnReqAmount_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnLabel_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnMessage_textChanged()
{
genCode();
}
void QRCodeDialog::on_btnSaveAs_clicked()
{
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)"));
if (!fn.isEmpty())
myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);
}
void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)
{
if (!fChecked)
// if chkReqPayment is not active, don't display lnReqAmount as invalid
ui->lnReqAmount->setValid(true);
genCode();
}
void QRCodeDialog::updateDisplayUnit()
{
if (model)
{
// Update lnReqAmount with the current unit
ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define watch(x) cerr << #x << " = " << x << "\n"
typedef pair<int, int> pii;
typedef long long int64;
const double eps = 1e-9;
const int inf = 0x3f3f3f3f;
int main()
{
#ifndef ONLINE_JUDGE
freopen("../io/in.txt", "r", stdin);
//freopen("../io/out.txt", "w", stdout);
#endif // ONLINE_JUDGE
int x, y, n;
cin >> n >> x >> y;
int a[n+2];
int cnt = 0;
for(int i=0; i<n; i++) {
cin >> a[i];
if(a[i] <= x) cnt++;
}
int res = 0;
if(x > y) res = n;
else {
res = (cnt/2) + (cnt&1);
}
cout << res << "\n";
return 0;
}
|
// Напишете функция, която по въведени цели положителни числа a, b(b > a)
// да върне сумата на всички прости числа в интервала[a;b].
//
// Пример:
//
// Вход: 2 10
// Изход : 17 // 2+3+5+7
#include <iostream>
bool IsPrime(int x);
int GetPrimesSum(int n, int k);
int main()
{
int k, n;
std::cout << "enter two numbers" << std::endl;
std::cin >> n >> k;
std::cout << "sum = " << GetPrimesSum( n,k);
}
int GetPrimesSum(int n, int k) {
int sum = 0;
for (size_t i = n; i < k; i++)
{
if (IsPrime(i))
{
sum += i;
}
}
return sum;
}
bool IsPrime(int x) {
bool isPrime = true;
for (size_t i = 2; i < sqrt(x + 1); i++)
{
if (x % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2015 by Contributors
* \file resource.cc
* \brief Implementation of resource manager.
*/
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <dmlc/thread_local.h>
#include <mxnet/base.h>
#include <mxnet/engine.h>
#include <mxnet/random_generator.h>
#include <mxnet/resource.h>
#include <limits>
#include <atomic>
#include <memory>
#include "./common/lazy_alloc_array.h"
#include "./common/utils.h"
#include "./common/cuda/utils.h"
#include "./profiler/storage_profiler.h"
namespace mxnet {
namespace resource {
// internal structure for space allocator
struct SpaceAllocator {
// internal context
Context ctx;
// internal handle
Storage::Handle handle;
// internal CPU handle
Storage::Handle host_handle;
SpaceAllocator() {
handle.dptr = nullptr;
handle.size = 0;
host_handle.dptr = nullptr;
host_handle.size = 0;
}
inline void ReleaseAll() {
Storage::Get()->DirectFree(handle);
handle.dptr = nullptr;
handle.size = 0;
Storage::Get()->DirectFree(host_handle);
host_handle.dptr = nullptr;
host_handle.size = 0;
}
inline void* GetSpace(size_t size, const std::string &name) {
if (handle.size >= size) return handle.dptr;
Storage::Get()->DirectFree(handle);
handle = Storage::Get()->Alloc(size, ctx);
handle.profiler_scope = "resource:";
handle.name = name;
#if MXNET_USE_CUDA
profiler::GpuDeviceStorageProfiler::Get()->UpdateStorageInfo(handle);
#endif // MXNET_USE_CUDA
return handle.dptr;
}
inline void* GetHostSpace(size_t size) {
if (host_handle.size >= size) return host_handle.dptr;
Storage::Get()->DirectFree(host_handle);
host_handle = Storage::Get()->Alloc(size, Context());
return host_handle.dptr;
}
};
// Implements resource manager
class ResourceManagerImpl : public ResourceManager {
public:
ResourceManagerImpl() noexcept(false) {
cpu_temp_space_copy_ = dmlc::GetEnv("MXNET_CPU_TEMP_COPY", 4);
gpu_temp_space_copy_ = dmlc::GetEnv("MXNET_GPU_TEMP_COPY", 1);
cpu_native_rand_copy_ = dmlc::GetEnv("MXNET_CPU_PARALLEL_RAND_COPY", 1);
gpu_native_rand_copy_ = dmlc::GetEnv("MXNET_GPU_PARALLEL_RAND_COPY", 1);
#if MXNET_USE_CUDNN == 1
gpu_cudnn_dropout_state_copy_ = dmlc::GetEnv("MXNET_GPU_CUDNN_DROPOUT_STATE_COPY", 1);
#endif // MXNET_USE_CUDNN == 1
engine_ref_ = Engine::_GetSharedRef();
storage_ref_ = Storage::_GetSharedRef();
cpu_rand_ = std::make_unique<ResourceRandom<cpu>>(
Context::CPU(), global_seed_);
cpu_space_ = std::make_unique<ResourceTempSpace<ResourceRequest::kTempSpace>>(
Context::CPU(), cpu_temp_space_copy_);
cpu_parallel_rand_ = std::make_unique<ResourceParallelRandom<cpu>>(
Context::CPU(), cpu_native_rand_copy_, global_seed_);
}
~ResourceManagerImpl() override {
// need explicit delete, before engine get killed
cpu_rand_.reset(nullptr);
cpu_space_.reset(nullptr);
cpu_parallel_rand_.reset(nullptr);
#if MXNET_USE_CUDA
gpu_rand_.Clear();
gpu_space_.Clear();
gpu_parallel_rand_.Clear();
#if MXNET_USE_CUDNN == 1
gpu_cudnn_dropout_state_.Clear();
#endif // MXNET_USE_CUDNN == 1
#endif
if (engine_ref_ != nullptr) {
engine_ref_ = nullptr;
}
if (storage_ref_ != nullptr) {
storage_ref_ = nullptr;
}
}
// request resources
Resource Request(Context ctx, const ResourceRequest &req) override {
if (ctx.dev_mask() == Context::kCPU) {
switch (req.type) {
case ResourceRequest::kRandom: return cpu_rand_->resource;
case ResourceRequest::kTempSpace: return cpu_space_->GetNext();
case ResourceRequest::kParallelRandom: return cpu_parallel_rand_->GetNext();
default: LOG(FATAL) << "Unknown supported type " << req.type;
}
} else {
CHECK_EQ(ctx.dev_mask(), Context::kGPU);
#if MSHADOW_USE_CUDA
switch (req.type) {
case ResourceRequest::kRandom: {
return gpu_rand_.Get(ctx.dev_id, [ctx, this]() {
return new ResourceRandom<gpu>(ctx, global_seed_);
})->resource;
}
case ResourceRequest::kTempSpace: {
return gpu_space_.Get(ctx.dev_id, [ctx, this]() {
return new ResourceTempSpace<ResourceRequest::kTempSpace>(ctx, gpu_temp_space_copy_);
})->GetNext();
}
case ResourceRequest::kParallelRandom: {
return gpu_parallel_rand_.Get(ctx.dev_id, [ctx, this]() {
return new ResourceParallelRandom<gpu>(ctx, gpu_native_rand_copy_, global_seed_);
})->GetNext();
}
#if MXNET_USE_CUDNN == 1
case ResourceRequest::kCuDNNDropoutDesc: {
return gpu_cudnn_dropout_state_.Get(ctx.dev_id, [ctx, this]() {
return new ResourceTempSpace<ResourceRequest::kCuDNNDropoutDesc>(
ctx, gpu_cudnn_dropout_state_copy_);
})->GetNext();
}
#endif // MXNET_USE_CUDNN == 1
default: LOG(FATAL) << "Unknown supported type " << req.type;
}
#else
LOG(FATAL) << MXNET_GPU_NOT_ENABLED_ERROR;
#endif
}
Resource ret;
return ret;
}
void SeedRandom(uint32_t seed) override {
global_seed_ = seed;
cpu_rand_->SeedWithDeviceID(global_seed_);
cpu_parallel_rand_->SeedWithDeviceID(global_seed_);
#if MXNET_USE_CUDA
gpu_rand_.ForEach([seed](size_t i, ResourceRandom<gpu> *p) {
p->SeedWithDeviceID(seed);
});
gpu_parallel_rand_.ForEach([seed](size_t i, ResourceParallelRandom<gpu> *p) {
p->SeedWithDeviceID(seed);
});
#endif
}
void SeedRandom(Context ctx, uint32_t seed) override {
cpu_rand_->Seed(seed);
cpu_parallel_rand_->Seed(seed);
#if MXNET_USE_CUDA
if (ctx.dev_type == Context::kGPU) {
gpu_rand_.Get(ctx.dev_id, [ctx, seed, this]() {
return new ResourceRandom<gpu>(ctx, seed);
})->Seed(seed);
gpu_parallel_rand_.Get(ctx.dev_id, [ctx, seed, this]() {
return new ResourceParallelRandom<gpu>(ctx, gpu_native_rand_copy_, seed);
})->Seed(seed);
}
#endif
}
private:
/*! \brief Maximum number of GPUs */
static constexpr std::size_t kMaxNumGPUs = 16;
/*! \brief Random number magic number to seed different random numbers */
static constexpr uint32_t kRandMagic = 127UL;
// the random number resources
template<typename xpu>
struct ResourceRandom {
/*! \brief the context of the PRNG */
Context ctx;
/*! \brief pointer to PRNG */
mshadow::Random<xpu> *prnd;
/*! \brief resource representation */
Resource resource;
/*! \brief constructor */
explicit ResourceRandom(Context ctx, uint32_t global_seed)
: ctx(ctx) {
mshadow::SetDevice<xpu>(ctx.dev_id);
resource.var = Engine::Get()->NewVariable();
prnd = new mshadow::Random<xpu>(ctx.dev_id + global_seed * kRandMagic);
resource.ptr_ = prnd;
resource.req = ResourceRequest(ResourceRequest::kRandom);
}
~ResourceRandom() {
mshadow::Random<xpu> *r = prnd;
Engine::Get()->DeleteVariable(
[r](RunContext rctx) {
MSHADOW_CATCH_ERROR(delete r);
}, ctx, resource.var);
}
// set seed to a PRNG using global_seed and device id
inline void SeedWithDeviceID(uint32_t global_seed) {
Seed(ctx.dev_id + global_seed * kRandMagic);
}
// set seed to a PRNG
inline void Seed(uint32_t seed) {
mshadow::Random<xpu> *r = prnd;
Engine::Get()->PushAsync(
[r, seed](RunContext rctx, Engine::CallbackOnComplete on_complete) {
r->set_stream(rctx.get_stream<xpu>());
r->Seed(seed);
on_complete();
}, ctx, {}, {resource.var},
FnProperty::kNormal, 0, "ResourceRandomSetSeed");
}
};
// temporary space resource.
template<ResourceRequest::Type req>
struct ResourceTempSpace {
/*! \brief the context of the device */
Context ctx;
/*! \brief the underlying space */
std::vector<SpaceAllocator> space;
/*! \brief resource representation */
std::vector<Resource> resource;
/*! \brief current pointer to the round roubin allocator */
std::atomic<size_t> curr_ptr;
/*! \brief constructor */
explicit ResourceTempSpace(Context ctx, size_t ncopy)
: ctx(ctx), space(ncopy), resource(ncopy), curr_ptr(0) {
for (size_t i = 0; i < space.size(); ++i) {
resource[i].var = Engine::Get()->NewVariable();
resource[i].id = static_cast<int32_t>(i);
resource[i].ptr_ = &space[i];
resource[i].req = ResourceRequest(req);
space[i].ctx = ctx;
CHECK_EQ(space[i].handle.size, 0U);
}
}
~ResourceTempSpace() {
for (size_t i = 0; i < space.size(); ++i) {
SpaceAllocator r = space[i];
Engine::Get()->DeleteVariable(
[r](RunContext rctx){
SpaceAllocator rcpy = r;
MSHADOW_CATCH_ERROR(rcpy.ReleaseAll());
}, ctx, resource[i].var);
}
}
// get next resource in round roubin matter
inline Resource GetNext() {
const size_t kMaxDigit = std::numeric_limits<size_t>::max() / 2;
size_t ptr = ++curr_ptr;
// reset ptr to avoid undefined behavior during overflow
// usually this won't happen
if (ptr > kMaxDigit) {
curr_ptr.store((ptr + 1) % space.size());
}
return resource[ptr % space.size()];
}
};
// the parallel random sampler resources
// it use device API for GPU
template<typename xpu>
struct ResourceParallelRandom {
/*! \brief the context of the PRNG */
Context ctx;
/*! \brief pointers to sampler */
std::vector<common::random::RandGenerator<xpu> *> sampler;
/*! \brief resource representation */
std::vector<Resource> resource;
/*! \brief current pointer to the round roubin allocator */
std::atomic<size_t> curr_ptr;
/*! \brief constructor */
explicit ResourceParallelRandom(Context ctx, size_t ncopy, uint32_t global_seed)
: ctx(ctx), sampler(ncopy), resource(ncopy), curr_ptr(0) {
for (size_t i = 0; i < sampler.size(); ++i) {
const uint32_t seed = ctx.dev_id + i * kMaxNumGPUs + global_seed * kRandMagic;
resource[i].var = Engine::Get()->NewVariable();
common::random::RandGenerator<xpu> *r = new common::random::RandGenerator<xpu>();
Engine::Get()->PushSync(
[r, seed](RunContext rctx) {
common::random::RandGenerator<xpu>::AllocState(r);
r->Seed(rctx.get_stream<xpu>(), seed);
}, ctx, {}, {resource[i].var},
FnProperty::kNormal, 0, "ResourceParallelRandomSetSeed");
sampler[i] = r;
resource[i].ptr_ = sampler[i];
resource[i].req = ResourceRequest(ResourceRequest::kParallelRandom);
}
}
~ResourceParallelRandom() {
for (size_t i = 0; i < sampler.size(); ++i) {
common::random::RandGenerator<xpu> *r = sampler[i];
Engine::Get()->DeleteVariable(
[r](RunContext rctx) {
MSHADOW_CATCH_ERROR(common::random::RandGenerator<xpu>::FreeState(r));
MSHADOW_CATCH_ERROR(delete r);
}, ctx, resource[i].var);
}
}
// set seed to a sampler using global_seed and device id
inline void SeedWithDeviceID(uint32_t global_seed) {
for (size_t i = 0; i < sampler.size(); ++i) {
SeedOne(i, ctx.dev_id + i * kMaxNumGPUs + global_seed * kRandMagic);
}
// reset pointer to ensure the same result with the same seed.
curr_ptr.store(0);
}
// set seed to a sampler
inline void Seed(uint32_t seed) {
for (size_t i = 0; i < sampler.size(); ++i) {
SeedOne(i, i * kMaxNumGPUs + seed * kRandMagic);
}
// reset pointer to ensure the same result with the same seed.
curr_ptr.store(0);
}
// set seed to a sampler
inline void SeedOne(size_t i, uint32_t seed) {
common::random::RandGenerator<xpu> *r = sampler[i];
Engine::Get()->PushAsync(
[r, seed](RunContext rctx, Engine::CallbackOnComplete on_complete) {
r->Seed(rctx.get_stream<xpu>(), seed);
on_complete();
}, ctx, {}, {resource[i].var},
FnProperty::kNormal, 0, "ResourceNativeRandomSetSeed");
}
// get next resource in round roubin matter
inline Resource GetNext() {
const size_t kMaxDigit = std::numeric_limits<size_t>::max() / 2;
size_t ptr = ++curr_ptr;
// reset ptr to avoid undefined behavior during overflow
// usually this won't happen
if (ptr > kMaxDigit) {
curr_ptr.store((ptr + 1) % sampler.size());
}
return resource[ptr % sampler.size()];
}
};
/*! \brief number of copies in CPU temp space */
int cpu_temp_space_copy_;
/*! \brief number of copies in GPU temp space */
int gpu_temp_space_copy_;
/*! \brief number of copies in CPU native random sampler */
int cpu_native_rand_copy_;
/*! \brief number of copies in GPU native random sampler */
int gpu_native_rand_copy_;
/*! \brief Reference to the engine */
std::shared_ptr<Engine> engine_ref_;
/*! \brief Reference to the storage */
std::shared_ptr<Storage> storage_ref_;
/*! \brief internal seed to the random number generator */
uint32_t global_seed_{0};
/*! \brief CPU random number resources */
std::unique_ptr<ResourceRandom<cpu> > cpu_rand_;
/*! \brief CPU temp space resources */
std::unique_ptr<ResourceTempSpace<ResourceRequest::kTempSpace>> cpu_space_;
/*! \brief CPU parallel random number resources */
std::unique_ptr<ResourceParallelRandom<cpu> > cpu_parallel_rand_;
#if MXNET_USE_CUDA
/*! \brief random number generator for GPU */
common::LazyAllocArray<ResourceRandom<gpu> > gpu_rand_;
/*! \brief temp space for GPU */
common::LazyAllocArray<ResourceTempSpace<ResourceRequest::kTempSpace>> gpu_space_;
/*! \brief GPU parallel (on device) random number resources */
common::LazyAllocArray<ResourceParallelRandom<gpu> > gpu_parallel_rand_;
#if MXNET_USE_CUDNN == 1
/*! \brief number of copies in GPU cudnn dropout descriptor resources */
int gpu_cudnn_dropout_state_copy_;
/*! \brief GPU parallel (on device) random number resources */
common::LazyAllocArray<ResourceTempSpace<ResourceRequest::kCuDNNDropoutDesc>>
gpu_cudnn_dropout_state_;
#endif // MXNET_USE_CUDNN == 1
#endif
};
} // namespace resource
void* Resource::get_space_internal(size_t size,
const std::string &name) const {
return static_cast<resource::SpaceAllocator*>(ptr_)->GetSpace(size, name);
}
void* Resource::get_host_space_internal(size_t size) const {
return static_cast<resource::SpaceAllocator*>(ptr_)->GetHostSpace(size);
}
#if MXNET_USE_CUDNN == 1
void Resource::get_cudnn_dropout_desc(
cudnnDropoutDescriptor_t *dropout_desc,
mshadow::Stream<gpu> *stream,
const float dropout, uint64_t seed,
const std::string &name) const {
CHECK_EQ(req.type, ResourceRequest::kCuDNNDropoutDesc);
auto state_space = static_cast<resource::SpaceAllocator*>(ptr_);
CHECK_EQ(state_space->ctx.dev_id, stream->dev_id)
<< "The device id of cuDNN dropout state space doesn't match that from stream.";
CUDNN_CALL(cudnnCreateDropoutDescriptor(dropout_desc));
if (dropout <= 0) {
CUDNN_CALL(cudnnSetDropoutDescriptor(*dropout_desc, stream->dnn_handle_,
dropout,
nullptr,
0, seed));
} else if (!state_space->handle.size) {
// not initialized yet.
size_t dropout_state_size;
CUDNN_CALL(cudnnDropoutGetStatesSize(stream->dnn_handle_, &dropout_state_size));
// reserve GPU space
Storage::Get()->DirectFree(Storage::Get()->Alloc(dropout_state_size, state_space->ctx));
CUDNN_CALL(cudnnSetDropoutDescriptor(*dropout_desc, stream->dnn_handle_,
dropout,
state_space->GetSpace(dropout_state_size, name),
dropout_state_size, seed));
} else {
// cudnnRestoreDropoutDescriptor() introduced with cuDNN v7
STATIC_ASSERT_CUDNN_VERSION_GE(7000);
CUDNN_CALL(cudnnRestoreDropoutDescriptor(*dropout_desc, stream->dnn_handle_,
dropout,
state_space->handle.dptr,
state_space->handle.size,
seed));
}
}
#endif // MXNET_USE_CUDNN == 1
ResourceManager* ResourceManager::Get() {
typedef dmlc::ThreadLocalStore<resource::ResourceManagerImpl> inst;
return inst::Get();
}
} // namespace mxnet
|
#ifdef PEGASUS_OS_FREEBSD
#ifndef __UNIX_ELEMENTSOFTWAREIDENTITY_PRIVATE_H
#define __UNIX_ELEMENTSOFTWAREIDENTITY_PRIVATE_H
#endif
#endif
|
#pragma once
#include <type_traits>
namespace gal::toolbox::utils
{
/**
* @brief a simple auxiliary class for handling some continuous (accessible through operator[]) containers
* @note all invokes provide two invocation methods, one is to specify index_sequence by user (requires the same length as N), and the other is to use std::make_index_sequence<N>
*/
struct sequence_invoker
{
private:
template <
typename Sequence1,
typename Sequence2,
typename Func,
std::size_t...I1,
std::size_t...I2,
typename ...Args>
constexpr static void ternary_invoke_impl(
Sequence1& sequence1,
const Sequence2& sequence2,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>,
Args&&... args
)
noexcept((
noexcept(
std::invoke(
std::declval<decltype(std::forward<Func>(func))>(),
std::declval<decltype(sequence2[I2])>(),
std::declval<decltype(std::forward<Args>(args))>())
) && ...
))
{
((sequence1[I1] = std::invoke(std::forward<Func>(func), sequence2[I2], std::forward<Args>(args))), ...);
}
template <
typename Sequence1,
typename Sequence2,
typename Sequence3,
typename Func,
std::size_t...I1,
std::size_t...I2,
std::size_t...I3
>
constexpr static void ternary_invoke_seq_impl(
Sequence1& sequence1,
const Sequence2& sequence2,
const Sequence3& sequence3,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>,
std::index_sequence<I3...>)
noexcept((
noexcept(
std::invoke(
std::declval<decltype(std::forward<Func>(func))>(),
std::declval<decltype(sequence2[I2])>(),
std::declval<decltype(sequence3[I3])>()
)
) && ...
))
{
((sequence1[I1] = std::invoke(std::forward<Func>(func), sequence2[I2], sequence3[I3])), ...);
}
template <
typename Sequence1,
typename Sequence2,
typename T,
typename Func,
std::size_t...I1,
std::size_t...I2
>
constexpr static void ternary_invoke_dup_impl(
Sequence1& sequence1,
const Sequence2& sequence2,
T arg,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>)
noexcept((
noexcept(
std::invoke(
std::declval<decltype(std::forward<Func>(func))>(),
std::declval<decltype(sequence2[I2])>(),
std::declval<T>())
) && ...
))
{
((sequence1[I1] = std::invoke(std::forward<Func>(func), sequence2[I2], arg)), ...);
}
template <
bool HasRet,
bool All,
typename Sequence,
typename Func,
std::size_t...I,
typename... Args
>
constexpr static auto binary_invoke_impl(
Sequence& sequence,
Func&& func,
std::index_sequence<I...>,
Args&&... args
)
noexcept((
noexcept(
std::invoke(
std::declval<decltype(std::forward<Func>(func))>(),
std::declval<decltype(sequence[I])>(),
std::declval<decltype(std::forward<Args>(args))>())
) && ...
))
{
if constexpr (HasRet)
{
return [](std::convertible_to<bool> auto ...x)
{
if constexpr (All)
{
return (x && ...);
}
else
{
return (x || ...);
}
}(std::invoke(std::forward<Func>(func), sequence[I], args)...);
}
else
{
(std::invoke(std::forward<Func>(func), sequence[I], args), ...);
}
}
template <
bool HasRet,
bool All,
typename Sequence1,
typename Sequence2,
typename Func,
std::size_t...I1,
std::size_t...I2
>
constexpr static auto binary_invoke_seq_impl(
Sequence1& sequence1,
const Sequence2& sequence2,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>)
noexcept((
noexcept(
std::invoke(
std::declval<decltype(std::forward<Func>(func))>(),
std::declval<decltype(sequence1[I1])>(),
std::declval<decltype(sequence2[I2])>())
) && ...
))
{
if constexpr (HasRet)
{
return [](std::convertible_to<bool> auto ...x)
{
if constexpr (All)
{
return (x && ...);
}
else
{
return (x || ...);
}
}(std::invoke(std::forward<Func>(func), sequence1[I1], sequence2[I2])...);
}
else
{
(std::invoke(std::forward<Func>(func), sequence1[I1], sequence2[I2]), ...);
}
}
template <
bool HasRet,
bool All,
typename Sequence,
typename T,
typename Func,
std::size_t...I
>
constexpr static auto binary_invoke_dup_impl(
Sequence& sequence,
T arg,
Func&& func,
std::index_sequence<I...>)
noexcept((
noexcept(
std::invoke(
std::declval<decltype(std::forward<Func>(func))>(),
std::declval<decltype(sequence[I])>(),
std::declval<T>())
) && ...
))
{
if constexpr (HasRet)
{
return [](std::convertible_to<bool> auto ...x)
{
if constexpr (All)
{
return (x && ...);
}
else
{
return (x || ...);
}
}(std::invoke(std::forward<Func>(func), sequence[I], arg)...);
}
else
{
(std::invoke(std::forward<Func>(func), sequence[I], arg), ...);
}
}
template <
bool HasRet,
bool All,
typename Sequence,
typename Func,
std::size_t...I
>
constexpr static auto unary_invoke_impl(
Sequence& sequence,
Func&& func,
std::index_sequence<I...>)
noexcept((
noexcept(
std::invoke(
std::forward<Func>(func),
std::declval<decltype(sequence[I])>())
) && ...
))
{
if constexpr (HasRet)
{
return [](std::convertible_to<bool> auto ...x)
{
if constexpr (All)
{
return (x && ...);
}
else
{
return (x || ...);
}
}(std::invoke(std::forward<Func>(func), sequence[I])...);
}
else
{
(std::invoke(std::forward<Func>(func), sequence[I]), ...);
}
}
public:
/**
* @brief process a sequence with a sequence and a parameters pack
* @tparam N sequence length
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequenc2 and parameters pack)
* @tparam I1 user-defined index_sequence instead of using std::make_index_sequence
* @tparam I2 user-defined index_sequence instead of using std::make_index_sequence
* @tparam Args parameters pack type
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param func processing function
* @param args auxiliary processing args
*/
template <
std::size_t N,
typename Sequence1,
typename Sequence2,
typename Func,
std::size_t...I1,
std::size_t...I2,
typename... Args
>
requires (sizeof...(I1) == N) && (sizeof...(I2) == N) && (sizeof...(Args) == N)
constexpr static void ternary_invoke(
Sequence1& sequence1,
const Sequence2& sequence2,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>,
Args&&... args
)
noexcept(
noexcept(
sequence_invoker::ternary_invoke_impl(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I1...>>(),
std::declval<std::index_sequence<I2...>>(),
std::declval<decltype(std::forward<Args>(args))>()...
)
)
)
{
sequence_invoker::ternary_invoke_impl(
sequence1,
sequence2,
std::forward<Func>(func),
std::index_sequence<I1...>{},
std::index_sequence<I2...>{},
std::forward<Args>(args)...
);
}
/**
* @brief process a sequence with a sequence and a parameters pack
* @tparam N sequence length
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequenc2 and parameters pack)
* @tparam Args parameters pack type
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param func processing function
* @param args auxiliary processing args
*/
template <
std::size_t N,
typename Sequence1,
typename Sequence2,
typename Func,
typename... Args
>
requires (sizeof...(Args) == N)
constexpr static void ternary_invoke(
Sequence1& sequence1,
const Sequence2& sequence2,
Func&& func,
Args&&... args
)
noexcept(
noexcept(
sequence_invoker::ternary_invoke<N>(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<decltype(std::forward<Args>(args))>()...
)
)
)
{
sequence_invoker::ternary_invoke<N>(
sequence1,
sequence2,
std::forward<Func>(func),
std::make_index_sequence<N>{},
std::make_index_sequence<N>{},
std::forward<Args>(args)...
);
}
/**
* @brief process a sequence with two sequence
* @tparam N sequence length
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam Sequence3 sequence3 type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequenc2 and sequence3)
* @tparam I1 user-defined index_sequence instead of using std::make_index_sequence
* @tparam I2 user-defined index_sequence instead of using std::make_index_sequence
* @tparam I3 user-defined index_sequence instead of using std::make_index_sequence
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param sequence3 auxiliary processing sequence3
* @param func processing function
*/
template <
std::size_t N,
typename Sequence1,
typename Sequence2,
typename Sequence3,
typename Func,
std::size_t...I1,
std::size_t...I2,
std::size_t...I3
>
requires (sizeof...(I1) == N) && (sizeof...(I2) == N) && (sizeof...(I3) == N)
constexpr static void ternary_invoke_seq(
Sequence1& sequence1,
const Sequence2& sequence2,
const Sequence3& sequence3,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>,
std::index_sequence<I3...>)
noexcept(
noexcept(
sequence_invoker::ternary_invoke_seq_impl(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<decltype(sequence3)>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I1...>>(),
std::declval<std::index_sequence<I2...>>(),
std::declval<std::index_sequence<I3...>>()
)
)
)
{
sequence_invoker::ternary_invoke_seq_impl(
sequence1,
sequence2,
sequence3,
std::forward<Func>(func),
std::index_sequence<I1...>{},
std::index_sequence<I2...>{},
std::index_sequence<I3...>{}
);
}
/**
* @brief process a sequence with two sequence
* @tparam N sequence length
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam Sequence3 sequence3 type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequenc2 and sequence3)
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param sequence3 auxiliary processing sequence3
* @param func processing function
*/
template <
std::size_t N,
typename Sequence1,
typename Sequence2,
typename Sequence3,
typename Func
>
constexpr static void ternary_invoke_seq(
Sequence1& sequence1,
const Sequence2& sequence2,
const Sequence3& sequence3,
Func&& func
)
noexcept(
noexcept(
sequence_invoker::ternary_invoke_seq<N>(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<decltype(sequence3)>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<std::make_index_sequence<N>>()
)
)
)
{
sequence_invoker::ternary_invoke_seq<N>(
sequence1,
sequence2,
sequence3,
std::forward<Func>(func),
std::make_index_sequence<N>{},
std::make_index_sequence<N>{},
std::make_index_sequence<N>{}
);
}
/**
* @brief process a sequence with two sequence
* @tparam N sequence length
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam T duplicate value type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequenc2 and T)
* @tparam I1 user-defined index_sequence instead of using std::make_index_sequence
* @tparam I2 user-defined index_sequence instead of using std::make_index_sequence
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param dup_arg arg for duplicate
* @param func processing function
*/
template <
std::size_t N,
typename Sequence1,
typename Sequence2,
typename T,
typename Func,
std::size_t...I1,
std::size_t...I2
>
requires (sizeof...(I1) == N) && (sizeof...(I2) == N)
constexpr static void ternary_invoke_dup(
Sequence1& sequence1,
const Sequence2& sequence2,
T dup_arg,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>)
noexcept(
noexcept(
sequence_invoker::ternary_invoke_dup_impl(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<T>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I1...>>(),
std::declval<std::index_sequence<I2...>>()
)
)
)
{
sequence_invoker::ternary_invoke_dup_impl(
sequence1,
sequence2,
dup_arg,
std::forward<Func>(func),
std::index_sequence<I1...>{},
std::index_sequence<I2...>{}
);
}
/**
* @brief process a sequence with a sequence and a value
* @tparam N sequence length
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam T duplicate value type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequenc2 and T)
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param dup_arg arg for duplicate
* @param func processing function
*/
template <
std::size_t N,
typename Sequence1,
typename Sequence2,
typename T,
typename Func
>
constexpr static void ternary_invoke_dup(
Sequence1& sequence1,
const Sequence2& sequence2,
T dup_arg,
Func&& func
)
noexcept(
noexcept(
sequence_invoker::ternary_invoke_dup<N>(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<T>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<std::make_index_sequence<N>>()
)
)
)
{
sequence_invoker::ternary_invoke_dup<N>(
sequence1,
sequence2,
dup_arg,
std::forward<Func>(func),
std::make_index_sequence<N>{},
std::make_index_sequence<N>{}
);
}
/**
* @brief process a sequence with a parameters pack
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence sequence type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence and parameters pack)
* @tparam I user-defined index_sequence instead of using std::make_index_sequence
* @tparam Args parameters pack type
* @param sequence pending sequence
* @param func processing function
* @param args auxiliary processing args
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence,
typename Func,
std::size_t ...I,
typename... Args
>
requires (sizeof...(I) == N) && (sizeof...(Args) == N)
constexpr static auto binary_invoke(
Sequence& sequence,
Func&& func,
std::index_sequence<I...>,
Args&&... args
)
noexcept(
noexcept(
sequence_invoker::binary_invoke_impl<HasRet, All>(
std::declval<decltype(sequence)>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I...>>(),
std::declval<decltype(std::forward<Args>(args))>()...
)
)
)
{
return sequence_invoker::binary_invoke_impl<HasRet, All>(
sequence,
std::forward<Func>(func),
std::index_sequence<I...>{},
std::forward<Args>(args)...
);
}
/**
* @brief process a sequence with a parameters pack
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence sequence type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence and parameters pack)
* @tparam Args parameters pack type
* @param sequence pending sequence
* @param func processing function
* @param args auxiliary processing args
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence,
typename Func,
typename... Args
>
requires (sizeof...(Args) == N)
constexpr static auto binary_invoke(
Sequence& sequence,
Func&& func,
Args&&... args
)
noexcept(
noexcept(
sequence_invoker::binary_invoke<N, HasRet, All>(
std::declval<decltype(sequence)>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<decltype(std::forward<Args>(args))>()...
)
)
)
{
return sequence_invoker::binary_invoke<N, HasRet, All>(
sequence,
std::forward<Func>(func),
std::make_index_sequence<N>{},
std::forward<Args>(args)...
);
}
/**
* @brief process a sequence with a sequence
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence1 and sequence2)
* @tparam I1 user-defined index_sequence instead of using std::make_index_sequence
* @tparam I2 user-defined index_sequence instead of using std::make_index_sequence
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param func processing function
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence1,
typename Sequence2,
typename Func,
std::size_t...I1,
std::size_t...I2
>
requires (sizeof...(I1) == N) && (sizeof...(I2) == N)
constexpr static auto binary_invoke_seq(
Sequence1& sequence1,
const Sequence2& sequence2,
Func&& func,
std::index_sequence<I1...>,
std::index_sequence<I2...>)
noexcept(
noexcept(
sequence_invoker::binary_invoke_seq_impl<HasRet, All>(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I1...>>(),
std::declval<std::index_sequence<I2...>>()
)
)
)
{
return sequence_invoker::binary_invoke_seq_impl<HasRet, All>(
sequence1,
sequence2,
std::forward<Func>(func),
std::index_sequence<I1...>{},
std::index_sequence<I1...>{}
);
}
/**
* @brief process a sequence with a sequence
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence1 sequence1 type
* @tparam Sequence2 sequence2 type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence1 and sequence2)
* @param sequence1 pending sequence1
* @param sequence2 auxiliary processing sequence2
* @param func processing function
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence1,
typename Sequence2,
typename Func
>
constexpr static auto binary_invoke_seq(
Sequence1& sequence1,
const Sequence2& sequence2,
Func&& func
)
noexcept(
noexcept(
sequence_invoker::binary_invoke_seq<N, HasRet, All>(
std::declval<decltype(sequence1)>(),
std::declval<decltype(sequence2)>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>(),
std::declval<std::make_index_sequence<N>>()
)
)
)
{
return sequence_invoker::binary_invoke_seq<N, HasRet, All>(
sequence1,
sequence2,
std::forward<Func>(func),
std::make_index_sequence<N>{},
std::make_index_sequence<N>{}
);
}
/**
* @brief process a sequence with a value
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence sequence type
* @tparam T duplicate value type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence1 and T)
* @tparam I user-defined index_sequence instead of using std::make_index_sequence
* @param sequence pending sequence1
* @param dup_arg arg for duplicate
* @param func processing function
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence,
typename T,
typename Func,
std::size_t...I
>
requires (sizeof...(I) == N)
constexpr static auto binary_invoke_dup(
Sequence& sequence,
T dup_arg,
Func&& func,
std::index_sequence<I...>)
noexcept(
noexcept(
sequence_invoker::binary_invoke_dup_impl<HasRet, All>(
std::declval<decltype(sequence)>(),
std::declval<T>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I...>>()
)
)
)
{
return sequence_invoker::binary_invoke_dup_impl<HasRet, All>(
sequence,
dup_arg,
std::forward<Func>(func),
std::index_sequence<I...>{}
);
}
/**
* @brief process a sequence with a sequence
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence sequence type
* @tparam T duplicate value type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence1 and T)
* @param sequence pending sequence1
* @param dup_arg arg for duplicate
* @param func processing function
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence,
typename T,
typename Func
>
constexpr static auto binary_invoke_dup(
Sequence& sequence,
T dup_arg,
Func&& func
)
noexcept(
noexcept(
sequence_invoker::binary_invoke_dup<N, HasRet, All>(
std::declval<decltype(sequence)>(),
std::declval<T>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>()
)
)
)
{
return sequence_invoker::binary_invoke_dup<N, HasRet, All>(
sequence,
dup_arg,
std::forward<Func>(func),
std::make_index_sequence<N>{}
);
}
/**
* @brief process a sequence
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence sequence type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence)
* @tparam I user-defined index_sequence instead of using std::make_index_sequence
* @param sequence pending sequence
* @param func processing function
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence,
typename Func,
std::size_t...I
>
requires (sizeof...(I) == N)
constexpr static auto unary_invoke(
Sequence& sequence,
Func&& func,
std::index_sequence<I...>)
noexcept(
noexcept(
sequence_invoker::unary_invoke_impl<HasRet, All>(
std::declval<decltype(sequence)>(),
std::declval<decltype(func)>(),
std::declval<std::index_sequence<I...>>()
)
)
)
{
return sequence_invoker::unary_invoke_impl<HasRet, All>(
sequence,
std::forward<Func>(func),
std::index_sequence<I...>{}
);
}
/**
* @brief process a sequence
* @tparam N sequence length
* @tparam HasRet does the function require a return value
* @tparam All the superposition method of the return value (bool), is it All(&&) or Any(||)
* @tparam Sequence sequence type
* @tparam Func processing function type, it is required to accept two parameters (respectively the value_type of sequence)
* @param sequence pending sequence
* @param func processing function
*/
template <
std::size_t N,
bool HasRet = false,
bool All = true,
typename Sequence,
typename Func
>
constexpr static auto unary_invoke(
Sequence& sequence,
Func&& func
)
noexcept(
noexcept(
sequence_invoker::unary_invoke<N, HasRet, All>(
std::declval<decltype(sequence)>(),
std::declval<decltype(func)>(),
std::declval<std::make_index_sequence<N>>()
)
)
)
{
return sequence_invoker::unary_invoke<N, HasRet, All>(
sequence,
std::forward<Func>(func),
std::make_index_sequence<N>{}
);
}
};
}
|
#include "pch.h"
#include "resource.h"
#include "RawFileListView.h"
#include "mainfrm.h"
#include "HexView.h"
#include "Root.h"
#include "BmpBtn.h"
CRawFileListView rawFileListView;
BOOL CRawFileListView::PreTranslateMessage(MSG* pMsg)
{
if(pMsg)
{
if((pMsg->hwnd == m_hWnd) || ::IsChild(m_hWnd, pMsg->hwnd))
{
// We'll have the Accelerator send the WM_COMMAND to our view
//if(m_hAccel != NULL && ::TranslateAccelerator(m_hWnd, m_hAccel, pMsg))
//{
// return TRUE;
//}
}
}
return FALSE;
}
LRESULT CRawFileListView::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
// "base::OnCreate()"
LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
// "OnInitialUpdate"
Init();
bHandled = TRUE;
return lRet;
}
LRESULT CRawFileListView::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
BOOL bDestroy = m_ImageList.Destroy();
bDestroy; //avoid level 4 warning
// Say that we didn't handle it so that the treeview and anyone else
// interested gets to handle the message
bHandled = FALSE;
return 0;
}
void CRawFileListView::OnPaint ( CDCHandle /*dc*/ )
{
// this->GetItem
// CPaintDC dc(*this);
// Invalidate(false);
//dc.SetBkColor ( RGB(255,153,0) );
// dc.Rectangle(0, 30, 30, -30);
//dc.
SetMsgHandled(false);
}
void CRawFileListView::OnSize(UINT nType, CSize size)
{
SetColumnWidth(0, size.cx);
ShowScrollBar(SB_HORZ, FALSE);
}
void CRawFileListView::Init()
{
InsertColumn ( 0, _T("File Name"), LVCFMT_LEFT, 130, 0 );
//InsertColumn ( 1, _T("Type"), LVCFMT_LEFT, 90, 0 );
InitImageLists();
// On XP, set some additional properties of the list ctrl.
if ( g_bXPOrLater )
{
// Turning on LVS_EX_DOUBLEBUFFER also enables the transparent
// selection marquee.
SetExtendedListViewStyle ( LVS_EX_DOUBLEBUFFER, LVS_EX_DOUBLEBUFFER );
// Each tile will have 2 additional lines (3 lines total).
LVTILEVIEWINFO lvtvi = { sizeof(LVTILEVIEWINFO), LVTVIM_COLUMNS };
lvtvi.cLines = 2;
lvtvi.dwFlags = LVTVIF_AUTOSIZE;
SetTileViewInfo ( &lvtvi );
}
}
void CRawFileListView::InitImageLists()
{
nGenericFileIcon = -1;
HICON hiGenericFile = (HICON)::LoadImage(_Module.GetResourceInstance(),
MAKEINTRESOURCE(IDI_RAWFILE),
IMAGE_ICON, 16, 16, LR_SHARED);
BOOL bCreate = m_ImageList.Create ( 16, 16, ILC_COLOR32 | ILC_MASK, 3, 1 );
m_ImageList.SetBkColor(GetBkColor());
nGenericFileIcon = m_ImageList.AddIcon ( hiGenericFile );
DestroyIcon ( hiGenericFile );
SetImageList(m_ImageList, LVSIL_SMALL);
}
void CRawFileListView::AddFile(RawFile* newFile)
{
LVITEMW newItem;// = new LVITEMW();
newItem.lParam = (DWORD_PTR)newFile;
newItem.iItem = GetItemCount();
newItem.iSubItem = 0;
newItem.iImage = nGenericFileIcon;
//newItem.iGroupId = 0;
newItem.pszText = (LPWSTR)newFile->GetFileName();
newItem.mask = LVIF_PARAM | LVIF_TEXT | LVIF_IMAGE;// | LVIF_GROUPID;
InsertItem(&newItem);
//InsertItem(LVIF_PARAM | LVIF_TEXT | LVIF_IMAGE, GetItemCount(), newFile->GetFileName(), 0, 0, nIconIndexNormal, (DWORD_PTR)newFile);
// CTreeItem newItem = this->InsertItem(newFile->GetFileName(), nIconIndexNormal, nIconIndexSelected, TVI_ROOT, NULL);
// newItem.SetData((DWORD_PTR)newFile);
// items[newFile] = newItem;
//lItems.push_back(newItem);
// CBmpBtn* pButton = new CBmpBtn(BMPBTN_AUTOSIZE, m_ImageList, GetBkColor(), (DWORD)newFile);
// CRect rcNew;// = CRect(0,0,20,-20);
// GetItemRect(newItem.m_hTreeItem ,&rcNew, LVIR_BOUNDS);
// rcNew.left = rcNew.right-16;
// change the OK button extended style
//DWORD dw = BMPBTN_AUTOSIZE | BMPBTN_SHAREIMAGELISTS; /*BMPBTN_AUTO3D_SINGLE |*/
//pButton->SetBitmapButtonExtendedStyle(dw);
//pButton->SetImageList(m_ImageList); // OK button imagelist
// pButton->SetImages(0); //this can be appended to add icons for different states
// pButton->SetToolTipText(L"Close File");
//pButton->SubclassWindow(GetDlgItem(IDCANCEL));
// static int closeButtonCounter = 0;
// unsigned int id = IDC_FIRST_FILE_CLOSE_BUTTON+closeButtonCounter++;
// IDtoTreeItem[id] = newItem;
// TreeItemtoBtn[newItem] = pButton;
// btns.push_back(pButton);
// pButton->Create(m_hWnd, rcNew, L"", WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE/* | BS_FLAT*/, 0, id);
// if (closeButtonCounter > IDC_LAST_FILE_CLOSE_BUTTON - IDC_FIRST_FILE_CLOSE_BUTTON)
// closeButtonCounter = 0;
//pButton->Create(m_hWnd, rcNew, L"My Button", BS_FLAT);//m_nIDCount++);
//pButton->ShowWindow(SW_SHOWNORMAL);
}
void CRawFileListView::RemoveFile(RawFile* theFile)
{
// IDtoTreeItem.erase(GetDlgItem(TreeItemtoBtn[items[theFile]]->m_hWnd));
//TreeItemtoBtn[newItem] = pButton;
//for (list<CBmpBtn*>::iterator iter = btns.begin(); iter != btns.end(); ++iter)
//{
// iter->
LVFINDINFO findinfo;
findinfo.flags = LVFI_PARAM;
findinfo.lParam = (DWORD_PTR)theFile;
DeleteItem(FindItem(&findinfo, -1));//items[theFile]);
//items[theFile].Delete(); //remove CTreeItem from view
//items.erase(items.find(theFile)); //remove the CTreeItem from the item map
}
void CRawFileListView::OnKeyDown(TCHAR nChar, UINT repeats, UINT code)
{
switch (nChar)
{
case VK_DELETE:
OnCloseFile(0, 0, 0);
//SendMessage(IDC_CLOSEFILE, 0, 0);
break;
}
}
//LRESULT CRawFileListView::OnCloseButton(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
//{
// pRoot->CloseRawFile((RawFile*)IDtoTreeItem[wID].GetData()); //if WTL had FromHandle() (to get an object from HWND) there'd be no need for this map<> shit. but, alas
// bHandled = false;
// return 0;
//}
/*LRESULT CRawFileListView::OnCloseButtonClick(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
int i = 0;
bHandled = false;
return 0;
}*/
LRESULT CRawFileListView::OnTvnSelchanged(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
CTreeViewCtrlEx* treeview = reinterpret_cast<CTreeViewCtrlEx*>(pnmh);
CTreeItem treeitem = treeview->GetSelectedItem();
//fileView.SetCurFile((RawFile*)treeitem.GetData());
bHandled = false;
return 0;
}
LRESULT CRawFileListView::OnNMRClick(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
SendMessage(WM_CONTEXTMENU, (WPARAM)m_hWnd, GetMessagePos());
return 0;
}
LRESULT CRawFileListView::OnContextMenu(HWND hwndCtrl, CPoint ptClick )
{
//bHandled = TRUE;
//CTreeViewCtrlEx* treeview = (CTreeViewCtrlEx*)hwndCtrl;
// Build up the menu to show
CMenu mnuContext;
// if Shift-F10
if (ptClick.x == -1 && ptClick.y == -1)
ptClick = (CPoint) GetMessagePos();
ScreenToClient(&ptClick);
UINT uFlags;
//HTREEITEM htItem = GetTreeCtrl().HitTest( ptMousePos, &uFlags );
int iItem = HitTest( ptClick, &uFlags );
if( iItem == -1 )
return 0;
// Load from resource
mnuContext.LoadMenu(IDR_RAWFILE);
CMenuHandle pPopup = mnuContext.GetSubMenu(0);
ClientToScreen(&ptClick);
pPopup.TrackPopupMenu( TPM_LEFTALIGN, ptClick.x, ptClick.y, hwndCtrl );
// or build dynamically
// (being sure to enable/disable menu items as appropriate,
// and giving the appropriate IDs)
/*if(mnuContext.CreatePopupMenu())
{
int cchWindowText = this->GetWindowTextLength();
CString sWindowText;
this->GetWindowText(sWindowText.GetBuffer(cchWindowText+1), cchWindowText+1);
sWindowText.ReleaseBuffer();
CString sSave(_T("&Save '"));
sSave += sWindowText;
sSave += _T("'");
mnuContext.AppendMenu((MF_ENABLED | MF_STRING), ID_FILE_SAVE, sSave);
mnuContext.AppendMenu((MF_ENABLED | MF_STRING), ID_FILE_CLOSE, _T("&Close\tCtrl+F4"));
mnuContext.AppendMenu(MF_SEPARATOR);
mnuContext.AppendMenu((MF_ENABLED | MF_STRING), ID_VIEW_SOURCE, _T("&View Source"));
if(m_pCmdBar != NULL)
{
// NOTE: The CommandBarCtrl in our case is the mainframe's, so the commands
// would actually go to the main frame if we don't specify TPM_RETURNCMD.
// In the main frame's message map, if we don't specify
// CHAIN_MDI_CHILD_COMMANDS, we are not going to see those command
// messages. We have 2 choices here - either specify TPM_RETURNCMD,
// then send/post the message to our window, or don't specify
// TPM_RETURNCMD, and be sure to have CHAIN_MDI_CHILD_COMMANDS
// in the main frame's message map.
//m_pCmdBar->TrackPopupMenu(mnuContext, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERTICAL,
// ptPopup.x, ptPopup.y);
DWORD nSelection = m_pCmdBar->TrackPopupMenu(mnuContext, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERTICAL | TPM_RETURNCMD,
ptPopup.x, ptPopup.y);
if(nSelection != 0)
{
this->PostMessage(WM_COMMAND, MAKEWPARAM(nSelection, 0));
}
}
else
{
mnuContext.TrackPopupMenuEx(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERTICAL,
ptPopup.x, ptPopup.y, m_hWnd, NULL);
}
}*/
return 0;
}
void CRawFileListView::OnSaveAsRaw(UINT uCode, int nID, HWND hwndCtrl)
{
std::vector<RawFile*> files;
for (int i = GetNextItem(-1, LVNI_SELECTED); i != -1; i = GetNextItem(i, LVNI_SELECTED) )
{
LVITEM item;
item.iItem = i;
item.iSubItem = 0;
item.mask = LVIF_PARAM;
GetItem(&item);
files.push_back((RawFile*)item.lParam);
}
for (std::vector<RawFile*>::iterator it = files.begin(); it != files.end(); ++it)
{
(*it)->OnSaveAsRaw();
}
}
void CRawFileListView::OnCloseFile(UINT uCode, int nID, HWND hwndCtrl)
{
int iItem;
while ((iItem = GetNextItem(-1, LVNI_SELECTED)) != -1)
{
LVITEM item;
item.iItem = iItem;
item.iSubItem = 0;
item.mask = LVIF_PARAM;
GetItem(&item);
pRoot->CloseRawFile((RawFile*)item.lParam);
}
}
void CRawFileListView::OnCloseAllFiles(UINT uCode, int nID, HWND hwndCtrl) {
int iItem;
while ((iItem = GetNextItem(-1, LVNI_ALL)) != -1)
{
LVITEM item;
item.iItem = iItem;
item.iSubItem = 0;
item.mask = LVIF_PARAM;
GetItem(&item);
pRoot->CloseRawFile((RawFile*)item.lParam);
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_memmove_73b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml
Template File: sources-sink-73b.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sinks: memmove
* BadSink : Copy string to data using memmove()
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"
using namespace std;
namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE193_char_memmove_73
{
#ifndef OMITBAD
void badSink(list<char *> dataList)
{
/* copy data out of dataList */
char * data = dataList.back();
{
char source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memmove(data, source, (strlen(source) + 1) * sizeof(char));
printLine(data);
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList)
{
char * data = dataList.back();
{
char source[10+1] = SRC_STRING;
/* Copy length + 1 to include NUL terminator from source */
/* POTENTIAL FLAW: data may not have enough space to hold source */
memmove(data, source, (strlen(source) + 1) * sizeof(char));
printLine(data);
free(data);
}
}
#endif /* OMITGOOD */
} /* close namespace */
|
#include <torch/script.h>
#include <gtest/gtest.h>
#include <test/cpp/api/support.h>
using namespace torch::autograd;
using namespace torch::test;
TEST(GradModeTest, TestRequiresGradFunctionalOp) {
torch::AutoGradMode mode(false);
for (bool requires_grad : {true, false}) {
torch::Tensor c = torch::ones({1, 2, 3}).set_requires_grad(requires_grad);
torch::Tensor func_out = c * c;
ASSERT_FALSE(func_out.requires_grad());
ASSERT_TRUE(func_out.is_leaf());
}
}
TEST(GradModeTest, TestRequiresGradInplaceOp) {
torch::AutoGradMode mode(false);
for (bool requires_grad : {true, false}) {
torch::Tensor c = torch::ones({1, 2, 3}).set_requires_grad(requires_grad);
c.mul_(2);
ASSERT_EQ(c.requires_grad(), requires_grad);
}
}
TEST(GradModeTest, TestRequiresGradViewOp) {
torch::AutoGradMode mode(false);
for (bool requires_grad : {true, false}) {
torch::Tensor c = torch::ones({1, 2, 3}).set_requires_grad(requires_grad);
torch::Tensor view_out = c.view({2, 3});
ASSERT_EQ(view_out.requires_grad(), requires_grad);
ASSERT_TRUE(view_out.is_leaf());
}
}
TEST(GradModeTest, TestRequiresGradViewOpExiting) {
for (bool requires_grad: {true, false}) {
torch::Tensor s = torch::ones({1, 2, 3}).set_requires_grad(requires_grad);
torch::Tensor a = s.clone();
torch::Tensor view_out, tmp;
{
torch::AutoGradMode mode(false);
view_out = a.view({2, 3}); // go through kernels: VariableType, ADInplaceOrView, CPU
assert_tensor_creation_meta(view_out, torch::autograd::CreationMeta::NO_GRAD_MODE);
ASSERT_EQ(view_out.requires_grad(), requires_grad);
ASSERT_TRUE(view_out.is_leaf());
}
tmp = view_out * view_out;
ASSERT_EQ(tmp.requires_grad(), requires_grad);
if (requires_grad) {
tmp.backward(torch::ones_like(tmp));
// TODO: this behavior is a side effect of issue #11390.
ASSERT_FALSE(view_out.grad().defined());
}
if (requires_grad) {
ASSERT_THROWS_WITH(view_out.mul_(2), // go through kernels: VariableType, ADInplaceOrView, CPU
"A view was created in no_grad mode and is being modified inplace");
} else {
view_out.mul_(2);
}
tmp = view_out.view({2, 3});
ASSERT_EQ(tmp.requires_grad(), requires_grad);
assert_tensor_creation_meta(tmp, torch::autograd::CreationMeta::NO_GRAD_MODE);
}
}
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "util/internal/json_objectwriter.h"
#include <math.h>
#include "stubs/casts.h"
#include <contrib/libs/protobuf/stubs/logging.h>
#include "stubs/common.h"
#include "util/internal/utility.h"
#include "util/internal/json_escaping.h"
#include "stubs/strutil.h"
#include "stubs/mathlimits.h"
namespace google {
namespace protobuf {
namespace util {
namespace converter {
using strings::ArrayByteSource;
;
JsonObjectWriter::~JsonObjectWriter() {
if (!element_->is_root()) {
GOOGLE_LOG(WARNING) << "JsonObjectWriter was not fully closed.";
}
}
JsonObjectWriter* JsonObjectWriter::StartObject(StringPiece name) {
WritePrefix(name);
WriteChar('{');
PushObject();
return this;
}
JsonObjectWriter* JsonObjectWriter::EndObject() {
Pop();
WriteChar('}');
if (element()->is_root()) NewLine();
return this;
}
JsonObjectWriter* JsonObjectWriter::StartList(StringPiece name) {
WritePrefix(name);
WriteChar('[');
PushArray();
return this;
}
JsonObjectWriter* JsonObjectWriter::EndList() {
Pop();
WriteChar(']');
if (element()->is_root()) NewLine();
return this;
}
JsonObjectWriter* JsonObjectWriter::RenderBool(StringPiece name, bool value) {
return RenderSimple(name, value ? "true" : "false");
}
JsonObjectWriter* JsonObjectWriter::RenderInt32(StringPiece name, int32 value) {
return RenderSimple(name, SimpleItoa(value));
}
JsonObjectWriter* JsonObjectWriter::RenderUint32(StringPiece name,
uint32 value) {
return RenderSimple(name, SimpleItoa(value));
}
JsonObjectWriter* JsonObjectWriter::RenderInt64(StringPiece name, int64 value) {
WritePrefix(name);
WriteChar('"');
stream_->WriteString(SimpleItoa(value));
WriteChar('"');
return this;
}
JsonObjectWriter* JsonObjectWriter::RenderUint64(StringPiece name,
uint64 value) {
WritePrefix(name);
WriteChar('"');
stream_->WriteString(SimpleItoa(value));
WriteChar('"');
return this;
}
JsonObjectWriter* JsonObjectWriter::RenderDouble(StringPiece name,
double value) {
if (MathLimits<double>::IsFinite(value)) {
return RenderSimple(name, SimpleDtoa(value));
}
// Render quoted with NaN/Infinity-aware DoubleAsString.
return RenderString(name, DoubleAsString(value));
}
JsonObjectWriter* JsonObjectWriter::RenderFloat(StringPiece name, float value) {
if (MathLimits<float>::IsFinite(value)) {
return RenderSimple(name, SimpleFtoa(value));
}
// Render quoted with NaN/Infinity-aware FloatAsString.
return RenderString(name, FloatAsString(value));
}
JsonObjectWriter* JsonObjectWriter::RenderString(StringPiece name,
StringPiece value) {
WritePrefix(name);
WriteChar('"');
ArrayByteSource source(value);
JsonEscaping::Escape(&source, &sink_);
WriteChar('"');
return this;
}
JsonObjectWriter* JsonObjectWriter::RenderBytes(StringPiece name,
StringPiece value) {
WritePrefix(name);
string base64;
if (use_websafe_base64_for_bytes_)
WebSafeBase64EscapeWithPadding(value.ToString(), &base64);
else
Base64Escape(value, &base64);
WriteChar('"');
// TODO(wpoon): Consider a ByteSink solution that writes the base64 bytes
// directly to the stream, rather than first putting them
// into a string and then writing them to the stream.
stream_->WriteRaw(base64.data(), base64.size());
WriteChar('"');
return this;
}
JsonObjectWriter* JsonObjectWriter::RenderNull(StringPiece name) {
return RenderSimple(name, "null");
}
JsonObjectWriter* JsonObjectWriter::RenderNullAsEmpty(StringPiece name) {
return RenderSimple(name, "");
}
void JsonObjectWriter::WritePrefix(StringPiece name) {
bool not_first = !element()->is_first();
if (not_first) WriteChar(',');
if (not_first || !element()->is_root()) NewLine();
if (!name.empty() || element()->is_json_object()) {
WriteChar('"');
if (!name.empty()) {
ArrayByteSource source(name);
JsonEscaping::Escape(&source, &sink_);
}
stream_->WriteString("\":");
if (!indent_string_.empty()) WriteChar(' ');
}
}
} // namespace converter
} // namespace util
} // namespace protobuf
} // namespace google
|
/*
* =====================================================================================
*
* Filename: ex_2011.cpp
*
* Description: Exercise 20.11 - Palindrome Testing with Stacks
*
* Version: 1.0
* Created: 13/06/17 13:44:42
* Revision: none
* Compiler: g++
*
* Author: Siidney Watson - siidney.watson.work@gmail.com
* Organization: LolaDog Studio
*
* =====================================================================================
*/
#include <ctype.h>
#include <iostream>
#include <stack>
#include <string>
int main(int argc, const char* argv[]) {
std::string cData;
std::string cSanitised;
std::stack<char> cStack;
std::cout << "Enter a string for palindrome test: ";
std::getline(std::cin, cData);
// sanitise data - remove spaces and punctuation
for (char& c : cData) {
if (isspace(c) || ispunct(c)) { continue; }
cSanitised += tolower(c);
cStack.push(tolower(c));
}
// build comparison string from stack
std::string rData;
while (!cStack.empty()) {
rData += cStack.top();
cStack.pop();
}
std::cout << cData << " is"
<< (rData == cSanitised ? " " : " not ")
<< "a palindrome" << std::endl;
return 0;
}
|
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "loops.h"
#include "rectangle.h"
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Test calculate area function")
{
Rect area1(4,5);
REQUIRE(area1.get_area() == 20);
Rect area2(10, 10);
REQUIRE(area2.get_area() == 100);
Rect area3(100, 10);
REQUIRE(area3.get_area() == 1000);
}
|
/*************************************************************************/
/* */
/* Centre for Speech Technology Research */
/* University of Edinburgh, UK */
/* Copyright (c) 1996,1997 */
/* All Rights Reserved. */
/* */
/* Permission is hereby granted, free of charge, to use and distribute */
/* this software and its documentation without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of this work, and to */
/* permit persons to whom this work is furnished to do so, subject to */
/* the following conditions: */
/* 1. The code must retain the above copyright notice, this list of */
/* conditions and the following disclaimer. */
/* 2. Any modifications must be clearly marked as such. */
/* 3. Original authors' names are not deleted. */
/* 4. The authors' names are not used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK */
/* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */
/* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */
/* SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE */
/* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */
/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */
/* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */
/* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */
/* THIS SOFTWARE. */
/* */
/*************************************************************************/
/* Author : Alan W Black */
/* Date : November 1997 */
/*-----------------------------------------------------------------------*/
/* Build a WFST from some base: */
/* 1 a set of context dependent rewrite rules using the */
/* the algorithms from "An Efficient Compiler for Weighted Rewrite */
/* Rules", by Mehryar Mohri and Richard Sproat ACL 1996 */
/* and information from the techniques in Rithie el al. 1992 */
/* 2 A regular grammar (but can be written as a CFG as long as it */
/* contains no centre embedding */
/* 3 A regular expression */
/* 4 lts rules (but that doesn't work yet) */
/* */
/* or apply some operator on existing wfst(s): compose, concatenate, */
/* difference, union, */
/* */
/* Also allow determinizing and minimization as required */
/* */
/*=======================================================================*/
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
#include "EST.h"
#include "EST_WFST.h"
static int wfst_build_main(int argc, char **argv);
/** @name <command>wfst_build</command> <emphasis>Build a weighted finite-state transducer</emphasis>
@id wfst-build-manual
* @toc
*/
//@{
/**@name Synopsis
*/
//@{
//@synopsis
/**
Build and.or process weighted finite state transducers (WFSTs) form
various input formats. This program accepts descriptions
in the following formats and converts them to WFSTs
<itemizedlist>
<listitem><para>regular expressions</para></listitem>
<listitem><para>regular grammars</para></listitem>
<listitem><para>Koskenniemi/Kay/Kaplan context restriction rules</para></listitem>
</itemizedlist>
In addition various operations can be performed on two WFSTs
<itemizedlist>
<listitem><para>compose: form new WFST feeding output of first WFSTs into
second WFSTs.</para></listitem>
<listitem><para>union: form new WFST accepting the language both WFSTs
</para></listitem>
<listitem><para>intersect: form new WFST accepting only the language common
to both WFSTs
</para></listitem>
<listitem><para>concat: form new WFST accepting the language from the
concatenation of all strings in the first WFST to all strings in the
second.
</para></listitem>
</itemizedlist>
The newly formed WFSTs can be optionally determinized and minimzed.
The option asis allows a single WFSTs to be loaded and determinized
and/or minimized
*/
//@}
/**@name OPTIONS
*/
//@{
//@options
//@}
int main(int argc, char **argv)
{
wfst_build_main(argc,argv);
exit(0);
return 0;
}
static int wfst_build_main(int argc, char **argv)
{
// Top level function generates a WFST from rules
EST_Option al;
EST_StrList files;
EST_String outfile;
parse_command_line
(argc, argv,
EST_String("[option] [rulefile0] [rulefile1] ...\n")+
"Summary: Build a weighted finite state transducer from rules/wfsts\n"+
"-type <string> {kk} Input rule type: kk, lts, rg, tl, compose, regex\n"+
" union, intersect, concat, asis\n"+
"-determinize Determinize WFST before saving it\n"+
"-detmin Determinize and minimize WFST before saving it\n"+
"-o <ofile> Output file for saved WFST (default stdout)\n"+
"-otype <string> {ascii}\n"+
" Output type, ascii or binary\n"+
"-heap <int> {210000}\n"+
" Set size of Lisp heap, needed for large rulesets\n"+
"-q Quiet mode, no summary generated\n",
files, al);
if (al.present("-o"))
outfile = al.val("-o");
else
outfile = "-";
siod_init(al.ival("-heap"));
LISP ruleset;
LISP inalpha, outalpha;
EST_WFST *wfst = new EST_WFST;
gc_protect(&ruleset);
if (al.val("-type") == "kk")
{
ruleset = car(vload(files(files.head()),1));
kkcompile(ruleset,*wfst);
}
else if (al.val("-type") == "lts")
{
ruleset = car(vload(files(files.head()),1));
ltscompile(ruleset,*wfst);
}
else if (al.val("-type") == "rg")
{
ruleset = car(vload(files(files.head()),1));
rgcompile(ruleset,*wfst);
}
else if (al.val("-type") == "tl")
{
ruleset = car(vload(files(files.head()),1));
tlcompile(ruleset,*wfst);
}
else if (al.val("-type") == "asis")
{
if (wfst->load(files.nth(0)) != format_ok) exit(-1);
}
else if (al.val("-type") == "compose")
{
EST_WFST a,b;
if (files.length() != 2)
EST_error("compose requires two WFSTs to combine");
if (a.load(files.nth(0)) != format_ok) exit(-1);
if (b.load(files.nth(1)) != format_ok) exit(-1);
wfst->compose(a,b);
}
else if (al.val("-type") == "union")
{
EST_WFST a,b;
if (files.length() != 2)
EST_error("union requires two WFSTs to combine");
if (a.load(files.nth(0)) != format_ok) exit(-1);
if (b.load(files.nth(1)) != format_ok) exit(-1);
wfst->uunion(a,b);
}
else if (al.val("-type") == "intersect")
{
EST_WFST a,b;
if (files.length() != 2)
EST_error("intersect requires two WFSTs to combine");
if (a.load(files.nth(0)) != format_ok) exit(-1);
if (b.load(files.nth(1)) != format_ok) exit(-1);
wfst->intersection(a,b);
}
else if (al.val("-type") == "concat")
{
EST_WFST a,b;
if (files.length() != 2)
EST_error("concat requires two WFSTs to combine");
if (a.load(files.nth(0)) != format_ok) exit(-1);
if (b.load(files.nth(1)) != format_ok) exit(-1);
wfst->concat(a,b);
}
else if (al.val("-type") == "difference")
{
EST_WFST a,b;
if (files.length() != 2)
EST_error("difference requires two WFSTs to combine");
if (a.load(files.nth(0)) != format_ok) exit(-1);
if (b.load(files.nth(1)) != format_ok) exit(-1);
wfst->difference(a,b);
}
else if (al.val("-type") == "regex")
{
ruleset = car(vload(files(files.head()),1));
inalpha = siod_nth(0,ruleset);
outalpha = siod_nth(1,ruleset);
wfst->build_from_regex(inalpha,outalpha,car(cdr(cdr(ruleset))));
}
else
{
cerr << "wfst_build: unknown rule type \"" << al.val("-type")
<< "\"" << endl;
exit(-1);
}
if (al.present("-determinize"))
{
EST_WFST *dwfst = new EST_WFST;
dwfst->determinize(*wfst);
if (!al.present("-q"))
{
cout << "wfst_build summary: " << endl;
cout << " non-deterministic wfst: " <<
wfst->summary() << endl;
cout << " deterministic wfst: " <<
dwfst->summary() << endl;
}
delete wfst;
wfst = dwfst;
}
else if (al.present("-detmin"))
{
if (!al.present("-q"))
{
cout << "wfst_build summary: " << endl;
cout << " non-deterministic wfst: " <<
wfst->summary() << endl;
}
EST_WFST *dwfst = new EST_WFST;
dwfst->determinize(*wfst);
delete wfst;
if (!al.present("-q"))
cout << " deterministic wfst: " <<
dwfst->summary() << endl;
EST_WFST *mwfst = new EST_WFST;
mwfst->minimize(*dwfst);
if (!al.present("-q"))
cout << " minimized wfst: " <<
mwfst->summary() << endl;
delete dwfst;
wfst = mwfst;
}
else
{
if (!al.present("-q"))
cout << "wfst_build: " << wfst->summary() << endl;
}
wfst->save(outfile,al.val("-otype"));
delete wfst;
gc_unprotect(&ruleset);
return 0;
}
|
// { dg-do run { xfail sparc64-*-elf arm-*-pe } }
// { dg-options "-fexceptions" }
int err = 1;
struct A {
~A() {
--err;
}
};
struct B {
A a;
B() {
throw 1;
}
};
int main() {
try {
B b;
} catch (...) {
return err;
}
return 1;
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/s3/model/GetObjectLegalHoldRequest.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::S3::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws::Http;
GetObjectLegalHoldRequest::GetObjectLegalHoldRequest() :
m_bucketHasBeenSet(false),
m_keyHasBeenSet(false),
m_versionIdHasBeenSet(false),
m_requestPayer(RequestPayer::NOT_SET),
m_requestPayerHasBeenSet(false),
m_customizedAccessLogTagHasBeenSet(false)
{
}
Aws::String GetObjectLegalHoldRequest::SerializePayload() const
{
return "";
}
void GetObjectLegalHoldRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_versionIdHasBeenSet)
{
ss << m_versionId;
uri.AddQueryStringParameter("versionId", ss.str());
ss.str("");
}
if(!m_customizedAccessLogTag.empty())
{
// only accept customized LogTag which starts with "x-"
Aws::Map<Aws::String, Aws::String> collectedLogTags;
for(const auto& entry: m_customizedAccessLogTag)
{
if (!entry.first.empty() && !entry.second.empty() && entry.first.substr(0, 2) == "x-")
{
collectedLogTags.emplace(entry.first, entry.second);
}
}
if (!collectedLogTags.empty())
{
uri.AddQueryStringParameter(collectedLogTags);
}
}
}
Aws::Http::HeaderValueCollection GetObjectLegalHoldRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
Aws::StringStream ss;
if(m_requestPayerHasBeenSet)
{
headers.emplace("x-amz-request-payer", RequestPayerMapper::GetNameForRequestPayer(m_requestPayer));
}
return headers;
}
|
/*=============================================================================
Copyright (c) 2011-2012 Thomas Bernard
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(SPIRIT_KEYWORDS_DETAIL_MARCH_13_2007_1145PM)
#define SPIRIT_KEYWORDS_DETAIL_MARCH_13_2007_1145PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/fusion/include/nview.hpp>
#include <boost/spirit/home/qi/string/lit.hpp>
#include <boost/fusion/include/at.hpp>
namespace boost { namespace spirit { namespace repository { namespace qi { namespace detail {
// Variant visitor class which handles dispatching the parsing to the selected parser
// This also handles passing the correct attributes and flags/counters to the subject parsers
template<typename T>
struct is_distinct : T::distinct { };
template<typename T, typename Action>
struct is_distinct< spirit::qi::action<T,Action> > : T::distinct { };
template<typename T>
struct is_distinct< spirit::qi::hold_directive<T> > : T::distinct { };
template < typename Elements, typename Iterator ,typename Context ,typename Skipper
,typename Flags ,typename Counters ,typename Attribute, typename NoCasePass>
struct parse_dispatcher
: public boost::static_visitor<bool>
{
typedef Iterator iterator_type;
typedef Context context_type;
typedef Skipper skipper_type;
typedef Elements elements_type;
typedef typename add_reference<Attribute>::type attr_reference;
public:
parse_dispatcher(const Elements &elements,Iterator& first, Iterator const& last
, Context& context, Skipper const& skipper
, Flags &flags, Counters &counters, attr_reference attr) :
elements(elements), first(first), last(last)
, context(context), skipper(skipper)
, flags(flags),counters(counters), attr(attr)
{}
template<typename T> bool operator()(T& idx) const
{
return call(idx,typename traits::not_is_unused<Attribute>::type());
}
template <typename Subject,typename Index>
bool call_subject_unused(
Subject const &subject, Iterator &first, Iterator const &last
, Context& context, Skipper const& skipper
, Index& /*idx*/ ) const
{
Iterator save = first;
skipper_keyword_marker<Skipper,NoCasePass>
marked_skipper(skipper,flags[Index::value],counters[Index::value]);
if(subject.parse(first,last,context,marked_skipper,unused))
{
return true;
}
save = save;
return false;
}
template <typename Subject,typename Index>
bool call_subject(
Subject const &subject, Iterator &first, Iterator const &last
, Context& context, Skipper const& skipper
, Index& /*idx*/ ) const
{
Iterator save = first;
skipper_keyword_marker<Skipper,NoCasePass>
marked_skipper(skipper,flags[Index::value],counters[Index::value]);
if(subject.parse(first,last,context,marked_skipper,fusion::at_c<Index::value>(attr)))
{
return true;
}
save = save;
return false;
}
// Handle unused attributes
template <typename T> bool call(T &idx, mpl::false_) const{
typedef typename mpl::at<Elements,T>::type ElementType;
if(
(!is_distinct<ElementType>::value)
|| skipper.parse(first,last,unused,unused,unused)
){
spirit::qi::skip_over(first, last, skipper);
return call_subject_unused(fusion::at_c<T::value>(elements), first, last, context, skipper, idx );
}
return false;
}
// Handle normal attributes
template <typename T> bool call(T &idx, mpl::true_) const{
typedef typename mpl::at<Elements,T>::type ElementType;
if(
(!is_distinct<ElementType>::value)
|| skipper.parse(first,last,unused,unused,unused)
){
return call_subject(fusion::at_c<T::value>(elements), first, last, context, skipper, idx);
}
return false;
}
const Elements &elements;
Iterator &first;
const Iterator &last;
Context & context;
const Skipper &skipper;
Flags &flags;
Counters &counters;
attr_reference attr;
};
// string keyword loop handler
template <typename Elements, typename StringKeywords, typename IndexList, typename FlagsType, typename Modifiers>
struct string_keywords
{
// Create a variant type to be able to store parser indexes in the embedded symbols parser
typedef typename
spirit::detail::as_variant<
IndexList >::type parser_index_type;
///////////////////////////////////////////////////////////////////////////
// build_char_type_sequence
//
// Build a fusion sequence from the kwd directive specified character type.
///////////////////////////////////////////////////////////////////////////
template <typename Sequence >
struct build_char_type_sequence
{
struct element_char_type
{
template <typename T>
struct result;
template <typename F, typename Element>
struct result<F(Element)>
{
typedef typename Element::char_type type;
};
template <typename F, typename Element,typename Action>
struct result<F(spirit::qi::action<Element,Action>) >
{
typedef typename Element::char_type type;
};
template <typename F, typename Element>
struct result<F(spirit::qi::hold_directive<Element>)>
{
typedef typename Element::char_type type;
};
// never called, but needed for decltype-based result_of (C++0x)
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename Element>
typename result<element_char_type(Element)>::type
operator()(Element&&) const;
#endif
};
// Compute the list of character types of the child kwd directives
typedef typename
fusion::result_of::transform<Sequence, element_char_type>::type
type;
};
///////////////////////////////////////////////////////////////////////////
// get_keyword_char_type
//
// Collapses the character type comming from the subject kwd parsers and
// and checks that they are all identical (necessary in order to be able
// to build a tst parser to parse the keywords.
///////////////////////////////////////////////////////////////////////////
template <typename Sequence>
struct get_keyword_char_type
{
// Make sure each of the types occur only once in the type list
typedef typename
mpl::fold<
Sequence, mpl::vector<>,
mpl::if_<
mpl::contains<mpl::_1, mpl::_2>,
mpl::_1, mpl::push_back<mpl::_1, mpl::_2>
>
>::type
no_duplicate_char_types;
// If the compiler traps here this means you mixed
// character type for the keywords specified in the
// kwd directive sequence.
BOOST_MPL_ASSERT_RELATION( mpl::size<no_duplicate_char_types>::value, ==, 1 );
typedef typename mpl::front<no_duplicate_char_types>::type type;
};
// Get the character type for the tst parser
typedef typename build_char_type_sequence< StringKeywords >::type char_types;
typedef typename get_keyword_char_type<
typename mpl::if_<
mpl::equal_to<
typename mpl::size < char_types >::type
, mpl::int_<0>
>
, mpl::vector< boost::spirit::standard::char_type >
, char_types >::type
>::type char_type;
// Our symbols container
typedef spirit::qi::tst< char_type, parser_index_type> keywords_type;
// Filter functor used for case insensitive parsing
template <typename CharEncoding>
struct no_case_filter
{
char_type operator()(char_type ch) const
{
return static_cast<char_type>(CharEncoding::tolower(ch));
}
};
///////////////////////////////////////////////////////////////////////////
// build_case_type_sequence
//
// Build a fusion sequence from the kwd/ikwd directives
// in order to determine if case sensitive and case insensitive
// keywords have been mixed.
///////////////////////////////////////////////////////////////////////////
template <typename Sequence >
struct build_case_type_sequence
{
struct element_case_type
{
template <typename T>
struct result;
template <typename F, typename Element>
struct result<F(Element)>
{
typedef typename Element::no_case_keyword type;
};
template <typename F, typename Element,typename Action>
struct result<F(spirit::qi::action<Element,Action>) >
{
typedef typename Element::no_case_keyword type;
};
template <typename F, typename Element>
struct result<F(spirit::qi::hold_directive<Element>)>
{
typedef typename Element::no_case_keyword type;
};
// never called, but needed for decltype-based result_of (C++0x)
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename Element>
typename result<element_case_type(Element)>::type
operator()(Element&&) const;
#endif
};
// Compute the list of character types of the child kwd directives
typedef typename
fusion::result_of::transform<Sequence, element_case_type>::type
type;
};
///////////////////////////////////////////////////////////////////////////
// get_nb_case_types
//
// Counts the number of entries in the case type sequence matching the
// CaseType parameter (mpl::true_ -> case insensitve
// , mpl::false_ -> case sensitive
///////////////////////////////////////////////////////////////////////////
template <typename Sequence,typename CaseType>
struct get_nb_case_types
{
// Make sure each of the types occur only once in the type list
typedef typename
mpl::count_if<
Sequence, mpl::equal_to<mpl::_,CaseType>
>::type type;
};
// Build the case type sequence
typedef typename build_case_type_sequence< StringKeywords >::type case_type_sequence;
// Count the number of case sensitive entries and case insensitve entries
typedef typename get_nb_case_types<case_type_sequence,mpl::true_>::type ikwd_count;
typedef typename get_nb_case_types<case_type_sequence,mpl::false_>::type kwd_count;
// Get the size of the original sequence
typedef typename mpl::size<IndexList>::type nb_elements;
// Determine if all the kwd directive are case sensitive/insensitive
typedef typename mpl::and_<
typename mpl::greater< nb_elements, mpl::int_<0> >::type
, typename mpl::equal_to< ikwd_count, nb_elements>::type
>::type all_ikwd;
typedef typename mpl::and_<
typename mpl::greater< nb_elements, mpl::int_<0> >::type
, typename mpl::equal_to< kwd_count, nb_elements>::type
>::type all_kwd;
typedef typename mpl::or_< all_kwd, all_ikwd >::type all_directives_of_same_type;
// Do we have a no case modifier
typedef has_modifier<Modifiers, spirit::tag::char_code_base<spirit::tag::no_case> > no_case_modifier;
// Should the no_case filter always be used ?
typedef typename mpl::or_<
no_case_modifier,
mpl::and_<
all_directives_of_same_type
,all_ikwd
>
>::type
no_case;
typedef no_case_filter<
typename spirit::detail::get_encoding_with_case<
Modifiers
, char_encoding::standard
, no_case::value>::type>
nc_filter;
// Determine the standard case filter type
typedef typename mpl::if_<
no_case
, nc_filter
, spirit::qi::tst_pass_through >::type
first_pass_filter_type;
typedef typename mpl::or_<
all_directives_of_same_type
, no_case_modifier
>::type requires_one_pass;
// Functor which adds all the keywords/subject parser indexes
// collected from the subject kwd directives to the keyword tst parser
struct keyword_entry_adder
{
typedef int result_type;
keyword_entry_adder(shared_ptr<keywords_type> lookup,FlagsType &flags, Elements &elements) :
lookup(lookup)
,flags(flags)
,elements(elements)
{}
template <typename T>
int operator()(const T &index) const
{
return call(fusion::at_c<T::value>(elements),index);
}
template <typename T, typename Position, typename Action>
int call(const spirit::qi::action<T,Action> &parser, const Position position ) const
{
// Make the keyword/parse index entry in the tst parser
lookup->add(
traits::get_begin<char_type>(get_string(parser.subject.keyword)),
traits::get_end<char_type>(get_string(parser.subject.keyword)),
position
);
// Get the initial state of the flags array and store it in the flags initializer
flags[Position::value]=parser.subject.iter.flag_init();
return 0;
}
template <typename T, typename Position>
int call( const T & parser, const Position position) const
{
// Make the keyword/parse index entry in the tst parser
lookup->add(
traits::get_begin<char_type>(get_string(parser.keyword)),
traits::get_end<char_type>(get_string(parser.keyword)),
position
);
// Get the initial state of the flags array and store it in the flags initializer
flags[Position::value]=parser.iter.flag_init();
return 0;
}
template <typename T, typename Position>
int call( const spirit::qi::hold_directive<T> & parser, const Position position) const
{
// Make the keyword/parse index entry in the tst parser
lookup->add(
traits::get_begin<char_type>(get_string(parser.subject.keyword)),
traits::get_end<char_type>(get_string(parser.subject.keyword)),
position
);
// Get the initial state of the flags array and store it in the flags initializer
flags[Position::value]=parser.subject.iter.flag_init();
return 0;
}
template <typename String, bool no_attribute>
const String get_string(const boost::spirit::qi::literal_string<String,no_attribute> &parser) const
{
return parser.str;
}
template <typename String, bool no_attribute>
const typename boost::spirit::qi::no_case_literal_string<String,no_attribute>::string_type &
get_string(const boost::spirit::qi::no_case_literal_string<String,no_attribute> &parser) const
{
return parser.str_lo;
}
shared_ptr<keywords_type> lookup;
FlagsType & flags;
Elements &elements;
};
string_keywords(Elements &elements,FlagsType &flags_init) : lookup(new keywords_type())
{
// Loop through all the subject parsers to build the keyword parser symbol parser
IndexList indexes;
keyword_entry_adder f1(lookup,flags_init,elements);
fusion::for_each(indexes,f1);
}
template <typename Iterator,typename ParseVisitor, typename Skipper>
bool parse(
Iterator &first,
const Iterator &last,
const ParseVisitor &parse_visitor,
const Skipper &/*skipper*/) const
{
if(parser_index_type* val_ptr =
lookup->find(first,last,first_pass_filter_type()))
{
if(!apply_visitor(parse_visitor,*val_ptr)){
return false;
}
return true;
}
return false;
}
template <typename Iterator,typename ParseVisitor, typename NoCaseParseVisitor,typename Skipper>
bool parse(
Iterator &first,
const Iterator &last,
const ParseVisitor &parse_visitor,
const NoCaseParseVisitor &no_case_parse_visitor,
const Skipper &/*skipper*/) const
{
Iterator saved_first = first;
if(parser_index_type* val_ptr =
lookup->find(first,last,first_pass_filter_type()))
{
if(!apply_visitor(parse_visitor,*val_ptr)){
return false;
}
return true;
}
// Second pass case insensitive
else if(parser_index_type* val_ptr
= lookup->find(saved_first,last,nc_filter()))
{
first = saved_first;
if(!apply_visitor(no_case_parse_visitor,*val_ptr)){
return false;
}
return true;
}
return false;
}
shared_ptr<keywords_type> lookup;
};
struct empty_keywords_list
{
typedef mpl::true_ requires_one_pass;
empty_keywords_list()
{}
template<typename Elements>
empty_keywords_list(const Elements &)
{}
template<typename Elements, typename FlagsInit>
empty_keywords_list(const Elements &, const FlagsInit &)
{}
template <typename Iterator,typename ParseVisitor, typename NoCaseParseVisitor,typename Skipper>
bool parse(
Iterator &/*first*/,
const Iterator &/*last*/,
const ParseVisitor &/*parse_visitor*/,
const NoCaseParseVisitor &/*no_case_parse_visitor*/,
const Skipper &/*skipper*/) const
{
return false;
}
template <typename Iterator,typename ParseVisitor, typename Skipper>
bool parse(
Iterator &/*first*/,
const Iterator &/*last*/,
const ParseVisitor &/*parse_visitor*/,
const Skipper &/*skipper*/) const
{
return false;
}
template <typename ParseFunction>
bool parse( ParseFunction &/*function*/ ) const
{
return false;
}
};
template<typename ComplexKeywords>
struct complex_keywords
{
// Functor which performs the flag initialization for the complex keyword parsers
template <typename FlagsType, typename Elements>
struct flag_init_value_setter
{
typedef int result_type;
flag_init_value_setter(Elements &elements,FlagsType &flags)
:flags(flags)
,elements(elements)
{}
template <typename T>
int operator()(const T &index) const
{
return call(fusion::at_c<T::value>(elements),index);
}
template <typename T, typename Position, typename Action>
int call(const spirit::qi::action<T,Action> &parser, const Position /*position*/ ) const
{
// Get the initial state of the flags array and store it in the flags initializer
flags[Position::value]=parser.subject.iter.flag_init();
return 0;
}
template <typename T, typename Position>
int call( const T & parser, const Position /*position*/) const
{
// Get the initial state of the flags array and store it in the flags initializer
flags[Position::value]=parser.iter.flag_init();
return 0;
}
template <typename T, typename Position>
int call( const spirit::qi::hold_directive<T> & parser, const Position /*position*/) const
{
// Get the initial state of the flags array and store it in the flags initializer
flags[Position::value]=parser.subject.iter.flag_init();
return 0;
}
FlagsType & flags;
Elements &elements;
};
template <typename Elements, typename Flags>
complex_keywords(Elements &elements, Flags &flags)
{
flag_init_value_setter<Flags,Elements> flag_initializer(elements,flags);
fusion::for_each(complex_keywords_inst,flag_initializer);
}
template <typename ParseFunction>
bool parse( ParseFunction &function ) const
{
return fusion::any(complex_keywords_inst,function);
}
ComplexKeywords complex_keywords_inst;
};
// This helper class enables jumping over intermediate directives
// down the kwd parser iteration count checking policy
struct register_successful_parse
{
template <typename Subject>
static bool call(Subject const &subject,bool &flag, int &counter)
{
return subject.iter.register_successful_parse(flag,counter);
}
template <typename Subject, typename Action>
static bool call(spirit::qi::action<Subject, Action> const &subject,bool &flag, int &counter)
{
return subject.subject.iter.register_successful_parse(flag,counter);
}
template <typename Subject>
static bool call(spirit::qi::hold_directive<Subject> const &subject,bool &flag, int &counter)
{
return subject.subject.iter.register_successful_parse(flag,counter);
}
};
// This helper class enables jumping over intermediate directives
// down the kwd parser
struct extract_keyword
{
template <typename Subject>
static Subject const& call(Subject const &subject)
{
return subject;
}
template <typename Subject, typename Action>
static Subject const& call(spirit::qi::action<Subject, Action> const &subject)
{
return subject.subject;
}
template <typename Subject>
static Subject const& call(spirit::qi::hold_directive<Subject> const &subject)
{
return subject.subject;
}
};
template <typename ParseDispatcher>
struct complex_kwd_function
{
typedef typename ParseDispatcher::iterator_type Iterator;
typedef typename ParseDispatcher::context_type Context;
typedef typename ParseDispatcher::skipper_type Skipper;
complex_kwd_function(
Iterator& first, Iterator const& last
, Context& context, Skipper const& skipper, ParseDispatcher &dispatcher)
: first(first)
, last(last)
, context(context)
, skipper(skipper)
, dispatcher(dispatcher)
{
}
template <typename Component>
bool operator()(Component const& component)
{
Iterator save = first;
if(
extract_keyword::call(
fusion::at_c<
Component::value
,typename ParseDispatcher::elements_type
>(dispatcher.elements)
)
.keyword.parse(
first
,last
,context
,skipper
,unused)
)
{
if(!dispatcher(component)){
first = save;
return false;
}
return true;
}
return false;
}
Iterator& first;
Iterator const& last;
Context& context;
Skipper const& skipper;
ParseDispatcher const& dispatcher;
private:
// silence MSVC warning C4512: assignment operator could not be generated
complex_kwd_function& operator= (complex_kwd_function const&);
};
}}}}}
#endif
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <shared_test_classes/single_layer/activation.hpp>
#include "shared_test_classes/base/ov_subgraph.hpp"
#include "functional_test_utils/ov_tensor_utils.hpp"
#include "test_utils/cpu_test_utils.hpp"
using namespace InferenceEngine;
using namespace CPUTestUtils;
using namespace ngraph::helpers;
using namespace ov::test;
namespace CPULayerTestsDefinitions {
using ActivationLayerCPUTestParamSet = std::tuple<
std::vector<InputShape>, // Input shapes
std::vector<size_t>, // Activation shapes
std::pair<ngraph::helpers::ActivationTypes, std::vector<float>>, // Activation type and constant value
InferenceEngine::Precision, // Net precision
InferenceEngine::Precision, // Input precision
InferenceEngine::Precision, // Output precision
CPUSpecificParams>;
class ActivationLayerCPUTest : public testing::WithParamInterface<ActivationLayerCPUTestParamSet>,
virtual public SubgraphBaseTest, public CPUTestsBase {
public:
ActivationTypes activationType;
static std::string getTestCaseName(const testing::TestParamInfo<ActivationLayerCPUTestParamSet> &obj) {
std::vector<InputShape> inputShapes;
std::vector<size_t> activationShapes;
std::pair<ngraph::helpers::ActivationTypes, std::vector<float>> activationTypeAndConstValue;
Precision netPrecision, inPrecision, outPrecision;
CPUSpecificParams cpuParams;
std::tie(inputShapes, activationShapes, activationTypeAndConstValue, netPrecision, inPrecision, outPrecision, cpuParams) = obj.param;
std::ostringstream result;
result << LayerTestsDefinitions::activationNames[activationTypeAndConstValue.first] << "_";
if (inputShapes.front().first.size() != 0) {
result << "IS=(";
for (const auto &shape : inputShapes) {
result << CommonTestUtils::partialShape2str({shape.first}) << "_";
}
result.seekp(-1, result.cur);
result << ")_";
}
result << "TS=";
for (const auto& shape : inputShapes) {
for (const auto& item : shape.second) {
result << CommonTestUtils::vec2str(item) << "_";
}
}
result << "AS=" << CommonTestUtils::vec2str(activationShapes) << "_";
result << "ConstantsValue=" << CommonTestUtils::vec2str(activationTypeAndConstValue.second) << "_";
result << "netPRC=" << netPrecision.name() << "_";
result << "inPRC=" << inPrecision.name() << "_";
result << "outPRC=" << outPrecision.name() << "_";
result << CPUTestsBase::getTestCaseName(cpuParams);
return result.str();
}
void generate_inputs(const std::vector<ngraph::Shape>& targetInputStaticShapes) override {
int32_t startFrom;
uint32_t range;
int32_t resolution;
if (activationType == ActivationTypes::Exp && netPrecision == Precision::BF16) {
startFrom = 0;
range = 2;
resolution = 32768;
} else if (activationType == ActivationTypes::Acosh) {
startFrom = 2;
range = 2;
resolution = 128;
} else {
startFrom = 0;
range = 15;
resolution = 32768;
}
inputs.clear();
const auto& funcInputs = function->inputs();
for (int i = 0; i < funcInputs.size(); ++i) {
const auto& funcInput = funcInputs[i];
ov::Tensor tensor;
if (funcInput.get_element_type().is_real()) {
tensor = ov::test::utils::create_and_fill_tensor(funcInput.get_element_type(), targetInputStaticShapes[i],
range, startFrom, resolution);
} else {
tensor = ov::test::utils::create_and_fill_tensor(funcInput.get_element_type(), targetInputStaticShapes[i]);
}
inputs.insert({funcInput.get_node_shared_ptr(), tensor});
}
}
protected:
void SetUp() override {
targetDevice = CommonTestUtils::DEVICE_CPU;
std::vector<InputShape> inputShapes;
std::vector<size_t> activationShapes;
std::pair<ngraph::helpers::ActivationTypes, std::vector<float>> activationTypeAndConstValue;
Precision inPrecision, outPrecision;
CPUSpecificParams cpuParams;
std::tie(inputShapes, activationShapes, activationTypeAndConstValue, netPrecision, inPrecision, outPrecision, cpuParams) = this->GetParam();
std::tie(inFmts, outFmts, priority, selectedType) = cpuParams;
activationType = activationTypeAndConstValue.first;
auto constantsValue = activationTypeAndConstValue.second;
inType = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(inPrecision);
outType = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(outPrecision);
selectedType = getPrimitiveType() + "_" + netPrecision.name();
init_input_shapes(inputShapes);
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision);
auto params = ngraph::builder::makeDynamicParams(ngPrc, {inputDynamicShapes.front()});
auto activation = ngraph::builder::makeActivation(params[0], ngPrc, activationType, activationShapes, constantsValue);
activation->get_rt_info() = getCPUInfo();
function = std::make_shared<ngraph::Function>(ngraph::NodeVector{activation}, params, "Activation");
}
InferenceEngine::Precision netPrecision;
};
TEST_P(ActivationLayerCPUTest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
run();
CheckPluginRelatedResults(compiledModel, "Eltwise");
}
namespace {
// list only types supported by eltwise
const std::vector<size_t> activationShapes = {};
const std::map<ActivationTypes, std::vector<std::vector<float>>> activationTypes = {
{Sqrt, {{}}},
{Sigmoid, {{}}},
{Tanh, {{}}},
{Relu, {{}}},
{Exp, {{}}},
{Clamp, {{-2.0f, 2.0f}}},
{Elu, {{0.1f}}},
{Swish, {{0.1f}}},
{HSwish, {{}}},
{Mish, {{}}},
{PReLu, {{-0.01f}}},
{GeluErf, {{}}},
{GeluTanh, {{}}}
};
std::vector<Precision> netPrc = {
Precision::BF16,
Precision::FP32
};
/* ============= Activation (1D) ============= */
std::vector<CPUSpecificParams> cpuParams_3D = {
CPUSpecificParams({nCw16c}, {nCw16c}, {}, {}),
CPUSpecificParams({nwc}, {nwc}, {}, {}),
CPUSpecificParams({ncw}, {ncw}, {}, {})
};
std::vector<std::vector<ov::Shape>> basic3D = {
{{2, 4, 4}},
{{2, 17, 5}},
};
const auto basicCases3D = ::testing::Combine(
::testing::ValuesIn(static_shapes_to_test_representation(basic3D)),
::testing::Values(activationShapes),
::testing::ValuesIn(CommonTestUtils::combineParams(activationTypes)),
::testing::ValuesIn(netPrc),
::testing::Values(Precision::FP32),
::testing::Values(Precision::FP32),
::testing::ValuesIn(filterCPUSpecificParams(cpuParams_3D))
);
INSTANTIATE_TEST_SUITE_P(smoke_Activation3D_Eltwise_CPU_BF16, ActivationLayerCPUTest, basicCases3D, ActivationLayerCPUTest::getTestCaseName);
/* ============= Activation (2D) ============= */
std::vector<CPUSpecificParams> cpuParams_4D = {
CPUSpecificParams({nChw16c}, {nChw16c}, {}, {}),
CPUSpecificParams({nhwc}, {nhwc}, {}, {}),
CPUSpecificParams({nchw}, {nchw}, {}, {})
};
std::vector<std::vector<ov::Shape>> basic4D = {
{{2, 4, 4, 1}},
{{2, 17, 5, 4}}
};
const auto basicCases4D = ::testing::Combine(
::testing::ValuesIn(static_shapes_to_test_representation(basic4D)),
::testing::Values(activationShapes),
::testing::ValuesIn(CommonTestUtils::combineParams(activationTypes)),
::testing::ValuesIn(netPrc),
::testing::Values(Precision::FP32),
::testing::Values(Precision::FP32),
::testing::ValuesIn(filterCPUSpecificParams(cpuParams_4D))
);
INSTANTIATE_TEST_SUITE_P(smoke_Activation4D_Eltwise_CPU_BF16, ActivationLayerCPUTest, basicCases4D, ActivationLayerCPUTest::getTestCaseName);
/* ============= Activation (3D) ============= */
std::vector<CPUSpecificParams> cpuParams_5D = {
CPUSpecificParams({nCdhw16c}, {nCdhw16c}, {}, {}),
CPUSpecificParams({ndhwc}, {ndhwc}, {}, {}),
CPUSpecificParams({ncdhw}, {ncdhw}, {}, {})
};
std::vector<std::vector<ov::Shape>> basic5D = {
{{2, 4, 3, 4, 1}},
{{2, 17, 7, 5, 4}}
};
const auto basicCases5D = ::testing::Combine(
::testing::ValuesIn(static_shapes_to_test_representation(basic5D)),
::testing::Values(activationShapes),
::testing::ValuesIn(CommonTestUtils::combineParams(activationTypes)),
::testing::ValuesIn(netPrc),
::testing::Values(Precision::FP32),
::testing::Values(Precision::FP32),
::testing::ValuesIn(filterCPUSpecificParams(cpuParams_5D))
);
INSTANTIATE_TEST_SUITE_P(smoke_Activation5D_Eltwise_CPU_BF16, ActivationLayerCPUTest, basicCases5D, ActivationLayerCPUTest::getTestCaseName);
const std::map<ActivationTypes, std::vector<std::vector<float>>> activationTypesDynamicMath = {
{Log, {{}}},
{Sign, {{}}},
{Acos, {{}}},
{Acosh, {{}}},
{Asin, {{}}},
{Asinh, {{}}},
{Atan, {{}}},
{Atanh, {{}}},
{Cos, {{}}},
{Cosh, {{}}},
{Tan, {{}}},
{HardSigmoid, {{0.2f, 0.5f}}},
{Selu, {{1.6732f, 1.0507f}}},
{Ceiling, {{}}}
};
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32
};
std::vector<CPUSpecificParams> cpuParamsDynamicMath = {
CPUSpecificParams({}, {}, {}, {})
};
std::vector<std::vector<InputShape>> dynamicMathBasic = {
{
{{{-1, -1}, {{1, 50}, {5, 128}, {3, 64}}}},
{{{-1, -1, -1, -1, -1, -1, -1, -1}, {{2, 2, 2, 2, 2, 2, 2, 2}, {2, 3, 2, 3, 2, 3, 2, 3}, {3, 3, 3, 3, 3, 3, 3, 3}}}},
{{{{1, 5}, 128}, {{1, 128}, {3, 128}, {5, 128}}}}
}
};
const auto dynamicMathBasicCases = ::testing::Combine(
::testing::ValuesIn(dynamicMathBasic),
::testing::Values(activationShapes),
::testing::ValuesIn(CommonTestUtils::combineParams(activationTypesDynamicMath)),
::testing::ValuesIn(netPrecisions),
::testing::Values(Precision::FP32),
::testing::Values(Precision::FP32),
::testing::ValuesIn(cpuParamsDynamicMath)
);
INSTANTIATE_TEST_SUITE_P(smoke_Activation5D_dynamicMath_CPU, ActivationLayerCPUTest, dynamicMathBasicCases, ActivationLayerCPUTest::getTestCaseName);
} // namespace
} // namespace CPULayerTestsDefinitions
|
//
// Commodore.cpp
// Clock Signal
//
// Created by Thomas Harte on 06/11/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "Commodore.hpp"
std::wstring Storage::Data::Commodore::petscii_from_bytes(const uint8_t *string, int length, bool shifted) {
std::wstring result;
wchar_t unshifted_characters[256] = {
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u000d', u'\u0000', u'\u0000',
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0008', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000',
u'\u0020', u'\u0021', u'\u0022', u'\u0023', u'\u0024', u'\u0025', u'\u0026', u'\u0027', u'\u0028', u'\u0029', u'\u002a', u'\u002b', u'\u002c', u'\u002d', u'\u002e', u'\u002f',
u'\u0030', u'\u0031', u'\u0032', u'\u0033', u'\u0034', u'\u0035', u'\u0036', u'\u0037', u'\u0038', u'\u0039', u'\u0022', u'\u003b', u'\u003c', u'\u003d', u'\u003e', u'\u003f',
u'\u0040', u'\u0041', u'\u0042', u'\u0043', u'\u0044', u'\u0045', u'\u0046', u'\u0047', u'\u0048', u'\u0049', u'\u004a', u'\u004b', u'\u004c', u'\u004d', u'\u004e', u'\u004f',
u'\u0050', u'\u0051', u'\u0052', u'\u0053', u'\u0054', u'\u0055', u'\u0056', u'\u0057', u'\u0058', u'\u0059', u'\u005a', u'\u005b', u'\u00a3', u'\u005d', u'\u2191', u'\u2190',
u'\u2500', u'\u2660', u'\u2502', u'\u2500', u'\ufffd', u'\ufffd', u'\ufffd', u'\ufffd', u'\ufffd', u'\u256e', u'\u2570', u'\u256f', u'\ufffd', u'\u2572', u'\u2571', u'\ufffd',
u'\ufffd', u'\u25cf', u'\ufffd', u'\u2665', u'\ufffd', u'\u256d', u'\u2573', u'\u25cb', u'\u2663', u'\ufffd', u'\u2666', u'\u253c', u'\ufffd', u'\u2502', u'\u03c0', u'\u25e5',
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u000d', u'\u0000', u'\u0000',
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0008', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000',
u'\u0020', u'\u258c', u'\u2584', u'\u2594', u'\u2581', u'\u258f', u'\u2592', u'\u2595', u'\ufffd', u'\u25e4', u'\ufffd', u'\u251c', u'\u2597', u'\u2514', u'\u2510', u'\u2582',
u'\u250c', u'\u2534', u'\u252c', u'\u2524', u'\u258e', u'\u258d', u'\ufffd', u'\ufffd', u'\ufffd', u'\u2583', u'\ufffd', u'\u2596', u'\u259d', u'\u2518', u'\u2598', u'\u259a',
u'\u2500', u'\u2660', u'\u2502', u'\u2500', u'\ufffd', u'\ufffd', u'\ufffd', u'\ufffd', u'\ufffd', u'\u256e', u'\u2570', u'\u256f', u'\ufffd', u'\u2572', u'\u2571', u'\ufffd',
u'\ufffd', u'\u25cf', u'\ufffd', u'\u2665', u'\ufffd', u'\u256d', u'\u2573', u'\u25cb', u'\u2663', u'\ufffd', u'\u2666', u'\u253c', u'\ufffd', u'\u2502', u'\u03c0', u'\u25e5',
u'\u0020', u'\u258c', u'\u2584', u'\u2594', u'\u2581', u'\u258f', u'\u2592', u'\u2595', u'\ufffd', u'\u25e4', u'\ufffd', u'\u251c', u'\u2597', u'\u2514', u'\u2510', u'\u2582',
u'\u250c', u'\u2534', u'\u252c', u'\u2524', u'\u258e', u'\u258d', u'\ufffd', u'\ufffd', u'\ufffd', u'\u2583', u'\ufffd', u'\u2596', u'\u259d', u'\u2518', u'\u2598', u'\u03c0'
};
wchar_t shifted_characters[256] = {
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u000d', u'\u0000', u'\u0000',
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0008', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000',
u'\u0020', u'\u0021', u'\u0022', u'\u0023', u'\u0024', u'\u0025', u'\u0026', u'\u0027', u'\u0028', u'\u0029', u'\u002a', u'\u002b', u'\u002c', u'\u002d', u'\u002e', u'\u002f',
u'\u0030', u'\u0031', u'\u0032', u'\u0033', u'\u0034', u'\u0035', u'\u0036', u'\u0037', u'\u0038', u'\u0039', u'\u0022', u'\u003b', u'\u003c', u'\u003d', u'\u003e', u'\u003f',
u'\u0040', u'\u0061', u'\u0062', u'\u0063', u'\u0064', u'\u0065', u'\u0066', u'\u0067', u'\u0068', u'\u0069', u'\u006a', u'\u006b', u'\u006c', u'\u006d', u'\u006e', u'\u006f',
u'\u0070', u'\u0071', u'\u0072', u'\u0073', u'\u0074', u'\u0075', u'\u0076', u'\u0077', u'\u0078', u'\u0079', u'\u007a', u'\u005b', u'\u00a3', u'\u005d', u'\u2191', u'\u2190',
u'\u2500', u'\u0041', u'\u0042', u'\u0043', u'\u0044', u'\u0045', u'\u0046', u'\u0047', u'\u0048', u'\u0049', u'\u004a', u'\u004b', u'\u004c', u'\u004d', u'\u004e', u'\u004f',
u'\u0050', u'\u0051', u'\u0052', u'\u0053', u'\u0054', u'\u0055', u'\u0056', u'\u0057', u'\u0058', u'\u0059', u'\u005a', u'\u253c', u'\ufffd', u'\u2502', u'\u2592', u'\u25e5',
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u000d', u'\u0000', u'\u0000',
u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0008', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000',
u'\u0020', u'\u258c', u'\u2584', u'\u2594', u'\u2581', u'\u258f', u'\u2592', u'\u2595', u'\ufffd', u'\ufffd', u'\ufffd', u'\u251c', u'\u2597', u'\u2514', u'\u2510', u'\u2582',
u'\u250c', u'\u2534', u'\u252c', u'\u2524', u'\u258e', u'\u258d', u'\ufffd', u'\ufffd', u'\ufffd', u'\u2583', u'\u2713', u'\u2596', u'\u259d', u'\u2518', u'\u2598', u'\u259a',
u'\u2500', u'\u0041', u'\u0042', u'\u0043', u'\u0044', u'\u0045', u'\u0046', u'\u0047', u'\u0048', u'\u0049', u'\u004a', u'\u004b', u'\u004c', u'\u004d', u'\u004e', u'\u004f',
u'\u0050', u'\u0051', u'\u0052', u'\u0053', u'\u0054', u'\u0055', u'\u0056', u'\u0057', u'\u0058', u'\u0059', u'\u005a', u'\u253c', u'\ufffd', u'\u2502', u'\u2592', u'\ufffd',
u'\u0020', u'\u258c', u'\u2584', u'\u2594', u'\u2581', u'\u258f', u'\u2592', u'\u2595', u'\ufffd', u'\ufffd', u'\ufffd', u'\u251c', u'\u2597', u'\u2514', u'\u2510', u'\u2582',
u'\u250c', u'\u2534', u'\u252c', u'\u2524', u'\u258e', u'\u258d', u'\ufffd', u'\ufffd', u'\ufffd', u'\u2583', u'\u2713', u'\u2596', u'\u259d', u'\u2518', u'\u2598', u'\u2592'
};
wchar_t *table = shifted ? shifted_characters : unshifted_characters;
for(int c = 0; c < length; c++) {
wchar_t next_character = table[string[c]];
if(next_character) result.push_back(next_character);
}
return result;
}
|
#include <player.h>
#include <Engine.hpp>
namespace godot
{
Player::Player()
{
}
Player::~Player()
{
}
void Player::_register_methods()
{
// Register methods
register_method((char*)"_ready", &Player::_ready);
register_method((char*)"_process", &Player::_process);
// Register properties
// register_property((char*)"category/float_var", &Player::float_var, 0.0f);
}
void Player::_ready()
{
}
void Player::_process()
{
if (Engine::get_singleton()->is_editor_hint())
{
return;
}
Vector2 current_position = get_global_position();
float move_value = 100;
current_position.x += move_value;
current_position.y += move_value;
set_global_position(current_position);
}
}
|
//============================================================================
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#include "VIcon.hpp"
#include <QDebug>
#include <QImage>
#include <QImageReader>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "ExprAst.hpp"
#include "Submittable.hpp"
#include "DirectoryHandler.hpp"
#include "IconProvider.hpp"
#include "UserMessage.hpp"
#include "VConfigLoader.hpp"
#include "VFilter.hpp"
#include "VNode.hpp"
#include "VProperty.hpp"
#include "VConfig.hpp"
#include "VSettings.hpp"
std::map<std::string,VIcon*> VIcon::items_;
std::vector<VIcon*> VIcon::itemsVec_;
std::vector<std::string> VIcon::lastNames_;
//==========================================================
//
// Define VIcon subclasses implementing the various icons.
// These do not need to be visible outside the class so we
// define them here in the cpp file.
//
//==========================================================
class VWaitIcon : public VIcon
{
public:
explicit VWaitIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VRerunIcon : public VIcon
{
public:
explicit VRerunIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VNodeLogIcon : public VIcon
{
public:
explicit VNodeLogIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VCompleteIcon : public VIcon
{
public:
explicit VCompleteIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VTimeIcon : public VIcon
{
public:
explicit VTimeIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VTimeFreeIcon : public VIcon
{
public:
explicit VTimeFreeIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VDateIcon : public VIcon
{
public:
explicit VDateIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VZombieIcon : public VIcon
{
public:
explicit VZombieIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VLateIcon : public VIcon
{
public:
explicit VLateIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VSlowIcon : public VIcon
{
public:
explicit VSlowIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VKilledIcon : public VIcon
{
public:
explicit VKilledIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VArchivedIcon : public VIcon
{
public:
explicit VArchivedIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VRestoredIcon : public VIcon
{
public:
explicit VRestoredIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VSlowJobCreationIcon : public VIcon
{
public:
explicit VSlowJobCreationIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VNoLogIcon : public VIcon
{
public:
explicit VNoLogIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
class VCheckpointErrorIcon : public VIcon
{
public:
explicit VCheckpointErrorIcon(const std::string& name) : VIcon(name) {}
bool show(VNode*) override;
};
//==========================================================
//
// Create VIcon instances
//
//==========================================================
//This also defines the order the icons will appear in the views
static VNodeLogIcon nodeLogIcon("message");
static VRerunIcon rerunIcon("rerun");
static VCompleteIcon completeIcon("complete");
static VLateIcon lateIcon("late");
static VTimeIcon timeIcon("time");
static VTimeFreeIcon timeFreeIcon("time_free");
static VDateIcon dateIcon("date");
static VWaitIcon waitIcon("wait");
static VZombieIcon zombieIcon("zombie");
static VKilledIcon killedIcon("killed");
static VSlowIcon slowIcon("slow");
static VArchivedIcon archivedIcon("archived");
static VRestoredIcon restoredIcon("restored");
static VSlowJobCreationIcon slowJobCreationIcon("slow_job");
static VNoLogIcon noLog("no_log");
static VCheckpointErrorIcon noCheckptIcon("checkpt_err");
//==========================================================
//
// The VIcon baseclass
//
//==========================================================
VIcon::VIcon(const std::string& name) :
VParam(name),
pixId_(-1)
{
items_[name]=this;
itemsVec_.push_back(this);
}
VIcon::~VIcon()
= default;
void VIcon::initPixmap()
{
if(!prop_)
{
UserMessage::message(UserMessage::WARN, true,
std::string("Warning! VIcon::initPixmap() unable to create icon image for: " + strName()));
return;
}
//Add icon to iconprovider
if(VProperty* ip=prop_->findChild("icon"))
{
pixId_=IconProvider::add(":/viewer/" + ip->value().toString(),name());
}
}
QPixmap VIcon::pixmap(int size)
{
return IconProvider::pixmap(name(),size);
}
//===============================================================
//
// Static methods
//
//===============================================================
std::vector<VParam*> VIcon::filterItems()
{
std::vector<VParam*> v;
for(std::map<std::string,VIcon*>::const_iterator it=items_.begin(); it != items_.end(); ++it)
{
v.push_back(it->second);
}
return v;
}
VIcon* VIcon::find(const std::string& name)
{
std::map<std::string,VIcon*>::const_iterator it=items_.find(name);
if(it != items_.end())
return it->second;
return nullptr;
}
//Create the pixmap containing all the relevant icons for the given node according to the filter.
QVariantList VIcon::pixmapList(VNode *vnode,VParamSet *filter)
{
QVariantList lst;
if(!vnode)
return lst;
for(std::vector<VIcon*>::const_iterator it=itemsVec_.begin(); it != itemsVec_.end(); ++it)
{
VIcon *v=*it;
if(!filter || filter->isSet(v))
{
if(v->show(vnode))
{
lst << v->pixId_;
}
}
}
return lst;
}
//Create the pixmap containing all the relevant icons for the given node according to the filter.
int VIcon::pixmapNum(VNode *vnode,VParamSet *filter)
{
if(!vnode)
return 0;
int ret=0;
for(std::vector<VIcon*>::const_iterator it=itemsVec_.begin(); it != itemsVec_.end(); ++it)
{
VIcon *v=*it;
if(!filter || filter->isSet(v))
{
if(v->show(vnode))
{
ret++;
}
}
}
return ret;
}
QString VIcon::toolTip(VNode *vnode,VParamSet *filter)
{
if(!filter || filter->isEmpty())
return QString();
int iconSize=16;
QString txt;
for(std::vector<VIcon*>::const_iterator it=itemsVec_.begin(); it != itemsVec_.end(); ++it)
{
VIcon *v=*it;
if(!filter || filter->isSet(v))
{
if(v->show(vnode))
{
if(txt.isEmpty())
{
txt+="<br><b>Icons:</b><table cellpadding=\'1\'>";
}
txt+="<tr><td><img src=\'" + IconProvider::path(v->pixId_) + "\' width=\'" +
QString::number(iconSize) + "\' height=\'" + QString::number(iconSize) + "\'></td><td>" + v->shortDescription() + "</tr>";
}
}
}
if(!txt.isEmpty())
txt+="</table>";
return txt;
}
QString VIcon::shortDescription() const
{
QString v;
if(prop_)
v=prop_->param("shortDesc");
if(v.isEmpty())
v=name();
return v;
}
void VIcon::names(std::vector<std::string>& v)
{
for(std::map<std::string,VIcon*>::const_iterator it=items_.begin(); it != items_.end(); ++it)
v.push_back(it->first);
}
void VIcon::saveLastNames()
{
lastNames_.clear();
for(std::map<std::string,VIcon*>::const_iterator it=items_.begin(); it != items_.end(); ++it)
lastNames_.push_back(it->first);
std::string iconFile = DirectoryHandler::concatenate(DirectoryHandler::configDir(), "last_icons.txt");
VSettings vs(iconFile);
vs.clear();
vs.put("icons",lastNames_);
vs.write();
}
void VIcon::initLastNames()
{
//It has to be called only once
assert(lastNames_.empty());
std::string iconFile = DirectoryHandler::concatenate(DirectoryHandler::configDir(), "last_icons.txt");
VSettings vs(iconFile);
if(vs.read(false))
vs.get("icons",lastNames_);
}
void VIcon::load(VProperty* group)
{
Q_FOREACH(VProperty* p,group->children())
{
if(VIcon* obj=VIcon::find(p->strName()))
{
obj->setProperty(p);
obj->initPixmap();
}
}
}
static SimpleLoader<VIcon> loader("icon");
//==========================================================
// Wait
//==========================================================
//Task only
bool VWaitIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
return n->isFlagSet(ecf::Flag::WAIT);
}
//==========================================================
// Rerun
//==========================================================
//Task only
bool VRerunIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
node_ptr node=n->node();
if(!node.get()) return false;
if(Submittable* s = node->isSubmittable())
{
return (s->try_no() > 1);
}
return false;
}
//==========================================================
// Message
//==========================================================
//Node and server
bool VNodeLogIcon::show(VNode *n)
{
if(!n)
return false;
return n->isFlagSet(ecf::Flag::MESSAGE);
}
//==========================================================
// Complete
//==========================================================
//Task only
bool VCompleteIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
if(!n->node())
return false;
node_ptr node=n->node();
if(!node.get()) return false;
if(n->isDefaultStateComplete())
return true;
if(AstTop* t = node->completeAst())
{
if(t->evaluate())
return true;
}
return false;
}
//==========================================================
// Date
//==========================================================
//Node only?
bool VDateIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
node_ptr node=n->node();
if(!node.get()) return false;
return (node->days().size() > 0 || node->dates().size() > 0);
}
//==========================================================
// Time - hasTimeHolding in ecflowview
//==========================================================
//Node only?
bool VTimeIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
node_ptr node=n->node();
if(!node) return false;
bool b = node->time_today_cron_is_free();
return !b &&
(node->timeVec().size() > 0 ||
node->todayVec().size() > 0 ||
node->crons().size() > 0);
}
//==========================================================
// TimeFree - hasTime in ecflowview
//==========================================================
//Node only?
bool VTimeFreeIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
node_ptr node=n->node();
if(!node) return false;
return node->time_today_cron_is_free();
}
//==========================================================
// Zombie
//==========================================================
//Node only?
bool VZombieIcon::show(VNode *n)
{
if(!n)
return false;
return n->isFlagSet(ecf::Flag::ZOMBIE);
}
//==========================================================
// Late
//==========================================================
//Node and server
bool VLateIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
return n->isFlagSet(ecf::Flag::LATE);
}
//==========================================================
// Slow
//==========================================================
//Server only
bool VSlowIcon::show(VNode *n)
{
if(!n || !n->isServer())
return false;
return n->isFlagSet(ecf::Flag::LATE);
}
//==========================================================
// Killed
//==========================================================
//Node only?
bool VKilledIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
return n->isFlagSet(ecf::Flag::KILLED);
}
//==========================================================
// Archived
//==========================================================
//Node only?
bool VArchivedIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
return n->isFlagSet(ecf::Flag::ARCHIVED);
}
//==========================================================
// Restored
//==========================================================
//Node only?
bool VRestoredIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
return n->isFlagSet(ecf::Flag::RESTORED);
}
//==========================================================
// Slow job creation
//==========================================================
//Node only?
bool VSlowJobCreationIcon::show(VNode *n)
{
if(!n || n->isServer())
return false;
return n->isFlagSet(ecf::Flag::THRESHOLD);
}
//==========================================================
// No log - cannot be open/write
//==========================================================
//Server only
bool VNoLogIcon::show(VNode *n)
{
if(!n || !n->isServer())
return false;
return n->isFlagSet(ecf::Flag::LOG_ERROR);
}
//==========================================================
// Cannot open/write to checkpoint
//==========================================================
//Server only
bool VCheckpointErrorIcon::show(VNode *n)
{
if(!n || !n->isServer())
return false;
return n->isFlagSet(ecf::Flag::CHECKPT_ERROR);
}
|
/*
* psql - the openGauss interactive terminal
*
* Copyright (c) 2000-2012, PostgreSQL Global Development Group
*
* src/bin/psql/tab-complete.c
*/
/* ----------------------------------------------------------------------
* This file implements a somewhat more sophisticated readline "TAB
* completion" in psql. It is not intended to be AI, to replace
* learning SQL, or to relieve you from thinking about what you're
* doing. Also it does not always give you all the syntactically legal
* completions, only those that are the most common or the ones that
* the programmer felt most like implementing.
*
* CAVEAT: Tab completion causes queries to be sent to the backend.
* The number of tuples returned gets limited, in most default
* installations to 1000, but if you still don't like this prospect,
* you can turn off tab completion in your ~/.inputrc (or else
* ${INPUTRC}) file so:
*
* $if psql
* set disable-completion on
* $endif
*
* See `man 3 readline' or `info readline' for the full details. Also,
* hence the
*
* BUGS:
*
* - If you split your queries across lines, this whole thing gets
* confused. (To fix this, one would have to read psql's query
* buffer rather than readline's line buffer, which would require
* some major revisions of things.)
*
* - Table or attribute names with spaces in it may confuse it.
*
* - Quotes, parenthesis, and other funny characters are not handled
* all that gracefully.
* ----------------------------------------------------------------------
*/
#include "settings.h"
#include "postgres_fe.h"
#include "input.h"
#include "tab-complete.h"
/* If we don't have this, we might as well forget about the whole thing: */
#ifdef USE_READLINE
#include <ctype.h>
#include "libpq/libpq-fe.h"
#include "libpq/pqexpbuffer.h"
#include "common.h"
#include "stringutils.h"
#ifndef WIN32
#include "libpq/libpq-int.h"
#endif
/* Store maximum number of records we want from database queries
* (implemented via SELECT ... LIMIT xx).
*/
static int completion_max_records;
#ifdef HAVE_READLINE_READLINE_H
/*
* Communication variables set by COMPLETE_WITH_FOO macros and then used by
* the completion callback functions. Ugly but there is no better way.
*/
static const char* completion_charp; /* to pass a string */
static const char* const* completion_charpp; /* to pass a list of strings */
static const char* completion_info_charp; /* to pass a second string */
static const char* completion_info_charp2; /* to pass a third string */
static const SchemaQuery* completion_squery; /* to pass a SchemaQuery */
static bool completion_case_sensitive; /* completion is case sensitive */
static char** PsqlCompletion(const char *text, int start, int end);
static char* CreateCommandGenerator(const char* text, int state);
static char* DropCommandGenerator(const char* text, int state);
static char* CompleteFromQuery(const char* text, int state);
static char* CompleteFromSchemaQuery(const char* text, int state);
static char* _CompleteFromQuery(int isSchemaQuery, const char* text, int state);
static char* CompleteFromList(const char* text, int state);
static char* CompleteFromConst(const char* text, int state);
static char** CompleteFromVariables(const char* text, const char* prefix, const char* suffix);
static char* CompleteFromFiles(const char* text, int state);
static char* pg_strdup_keyword_case(const char* s, const char* ref);
static PGresult* ExecQuery(const char* query);
static void GetPreviousWords(int point, char** previousWords, int nwords);
/*
* A few macros to ease typing. You can use these to complete the given
* string with
* 1) The results from a query you pass it. (Perhaps one of those below?)
* 2) The results from a schema query you pass it.
* 3) The items from a null-pointer-terminated list.
* 4) A string constant.
* 5) The list of attributes of the given table (possibly schema-qualified).
*/
#define COMPLETE_WITH_QUERY(query) do { \
completion_charp = query; \
matches = completion_matches(text, CompleteFromQuery); \
} while (0)
#define COMPLETE_WITH_SCHEMA_QUERY(query, addon) do { \
completion_squery = &(query); \
completion_charp = addon; \
matches = completion_matches(text, CompleteFromSchemaQuery); \
} while (0)
#define COMPLETE_WITH_LIST_CS(list) do { \
completion_charpp = list; \
completion_case_sensitive = true; \
matches = completion_matches(text, CompleteFromList); \
} while (0)
#define COMPLETE_WITH_LIST(list) do { \
completion_charpp = list; \
completion_case_sensitive = false; \
matches = completion_matches(text, CompleteFromList); \
} while (0)
#define COMPLETE_WITH_CONST(string) do { \
completion_charp = string; \
completion_case_sensitive = false; \
matches = completion_matches(text, CompleteFromConst); \
} while (0)
#define COMPLETE_WITH_ATTR(relation, addon) \
do { \
char *_completion_schema; \
char *_completion_table; \
_completion_schema = strtokx(relation, " \t\n\r", ".", "\"", 0, false, false, pset.encoding); \
(void)strtokx(NULL, " \t\n\r", ".", "\"", 0, false, false, pset.encoding); \
_completion_table = strtokx(NULL, " \t\n\r", ".", "\"", 0, false, false, pset.encoding); \
if (_completion_table == NULL) { \
completion_charp = Query_for_list_of_attributes addon; \
completion_info_charp = relation; \
} else { \
completion_charp = Query_for_list_of_attributes_with_schema addon; \
completion_info_charp = _completion_table; \
completion_info_charp2 = _completion_schema; \
} \
matches = completion_matches(text, CompleteFromQuery); \
} while (0)
/*
* Assembly instructions for schema queries
*/
static const SchemaQuery Query_for_list_of_aggregates = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
"p.proisagg",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
"p.pronamespace",
/* result */
"pg_catalog.quote_ident(p.proname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_datatypes = {
/* catname */
"pg_catalog.pg_type t",
/* selcondition --- ignore table rowtypes and array types */
"(t.typrelid = 0 "
" OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) "
"AND t.typname !~ '^_'",
/* viscondition */
"pg_catalog.pg_type_is_visible(t.oid)",
/* namespace */
"t.typnamespace",
/* result */
"pg_catalog.format_type(t.oid, NULL)",
/* qualresult */
"pg_catalog.quote_ident(t.typname)"
};
static const SchemaQuery Query_for_list_of_domains = {
/* catname */
"pg_catalog.pg_type t",
/* selcondition */
"t.typtype = 'd'",
/* viscondition */
"pg_catalog.pg_type_is_visible(t.oid)",
/* namespace */
"t.typnamespace",
/* result */
"pg_catalog.quote_ident(t.typname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_functions = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
"p.prokind != 'p'",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
"p.pronamespace",
/* result */
"pg_catalog.quote_ident(p.proname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_procedures[] = {
/* catname */
"pg_catalog.pg_proc p",
/* selcondition */
"p.prokind = 'p'",
/* viscondition */
"pg_catalog.pg_function_is_visible(p.oid)",
/* namespace */
"p.pronamespace",
/* result */
"pg_catalog.quote_ident(p.proname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_indexes = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('i')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_sequences = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('S')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_foreign_tables = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('f')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_tables = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('r', 'f')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
/* The bit masks for the following three functions come from
* src/include/catalog/pg_trigger.h.
*/
static const SchemaQuery Query_for_list_of_insertables = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"(c.relkind IN ('r', 'f') OR (c.relkind = 'v' AND c.relhastriggers AND EXISTS "
"(SELECT 1 FROM pg_catalog.pg_trigger t WHERE t.tgrelid = c.oid AND t.tgtype & (1 << 2) <> 0)))",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_deletables = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"(c.relkind = 'r' OR (c.relkind = 'v' AND c.relhastriggers AND EXISTS "
"(SELECT 1 FROM pg_catalog.pg_trigger t WHERE t.tgrelid = c.oid AND t.tgtype & (1 << 3) <> 0)))",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_updatables = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"(c.relkind = 'r' OR (c.relkind = 'v' AND c.relhastriggers AND EXISTS "
"(SELECT 1 FROM pg_catalog.pg_trigger t WHERE t.tgrelid = c.oid AND t.tgtype & (1 << 4) <> 0)))",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_relations = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
NULL,
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_tsvmf = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('r', 'S', 'v', 'm', 'f')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_tmf = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('r', 'm', 'f')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_tm = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('r', 'm')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_tmi = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('r', 'm', 'i')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_views = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('v')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_matviews = {
/* catname */
"pg_catalog.pg_class c",
/* selcondition */
"c.relkind IN ('m')",
/* viscondition */
"pg_catalog.pg_table_is_visible(c.oid)",
/* namespace */
"c.relnamespace",
/* result */
"pg_catalog.quote_ident(c.relname)",
/* qualresult */
NULL
};
static const SchemaQuery Query_for_list_of_constraints_with_schema = {
/* catname */
"pg_catalog.pg_constraint c",
/* selcondition */
"c.conrelid <> 0",
/* viscondition */
"true",
/* namespace */
"c.connamespace",
/* result */
"pg_catalog.quote_ident(c.conname)",
/* qualresult */
NULL
};
static const pgsql_thing_t words_after_create[] = {
{"AGGREGATE", NULL, &Query_for_list_of_aggregates, 0},
{"APP WORKLOAD GROUP", NULL, NULL, 0},
{"APP WORKLOAD GROUP MAPPING", NULL, NULL, 0},
#ifdef PGXC
{"BARRIER", NULL, NULL, 0}, /* Comes barrier name next, so skip it */
#endif
{"CAST", NULL, NULL, 0}, /* Casts have complex structures for names, so
* skip it */
{"CLIENT MASTER KEY", NULL, NULL, 0},
{"COLLATION",
"SELECT pg_catalog.quote_ident(collname) FROM pg_catalog.pg_collation WHERE collencoding IN (-1, "
"pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding())) AND "
"substring(pg_catalog.quote_ident(collname),1,%d)='%s'",
NULL,
0},
{"COLUMN ENCRYPTION KEY", NULL, NULL, 0},
/*
* CREATE CONSTRAINT TRIGGER is not supported here because it is designed
* to be used only by pg_dump.
*/
{"CONFIGURATION", Query_for_list_of_ts_configurations, NULL, THING_NO_SHOW},
{"CONVERSION",
"SELECT pg_catalog.quote_ident(conname) FROM pg_catalog.pg_conversion WHERE "
"substring(pg_catalog.quote_ident(conname),1,%d)='%s'",
NULL,
0},
{"DATABASE", Query_for_list_of_databases, NULL, 0},
{"DICTIONARY", Query_for_list_of_ts_dictionaries, NULL, THING_NO_SHOW},
{"DOMAIN", NULL, &Query_for_list_of_domains, 0},
{"EXTENSION", Query_for_list_of_extensions, NULL, 0},
{"FOREIGN DATA WRAPPER", NULL, NULL, 0},
{"FOREIGN TABLE", NULL, NULL, 0},
{"FUNCTION", NULL, &Query_for_list_of_functions, 0},
{"GLOBAL", NULL, NULL, 0},
{"GROUP", Query_for_list_of_roles, NULL, 0},
{"INCREMENTAL MATERIALIZED VIEW", NULL, NULL, 0},
{"INDEX", NULL, &Query_for_list_of_indexes, 0},
{"LANGUAGE", Query_for_list_of_languages, NULL, 0},
{"LOCAL", NULL, NULL, 0},
{"MATERIALIZED VIEW", NULL, &Query_for_list_of_matviews, 0},
#ifdef PGXC
{"NODE", Query_for_list_of_available_nodenames, NULL, 0},
{"NODE GROUP", Query_for_list_of_available_nodegroup_names, NULL, 0},
#endif
{"OPERATOR", NULL, NULL, 0}, /* Querying for this is probably not such a good idea. */
{"OR REPLACE", NULL, NULL, THING_NO_DROP},
{"OWNED", NULL, NULL, THING_NO_CREATE}, /* for DROP OWNED BY ... */
{"PARSER", Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
{"POLICY", NULL, NULL, 0},
{"PROCEDURAL", NULL, NULL, 0},
{"PROCEDURE", NULL, Query_for_list_of_procedures, 0},
{"PUBLICATION", NULL, NULL, 0},
{"ROLE", Query_for_list_of_roles, NULL, 0},
{"RULE",
"SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE "
"substring(pg_catalog.quote_ident(rulename),1,%d)='%s'",
NULL,
0},
{"ROW LEVEL SECURITY POLICY", NULL, NULL, 0},
{"SCHEMA", Query_for_list_of_schemas, NULL, 0},
{"SEQUENCE", NULL, &Query_for_list_of_sequences, 0},
{"SERVER", Query_for_list_of_servers, NULL, 0},
{"SUBSCRIPTION", NULL, NULL, 0},
{"TABLE", NULL, &Query_for_list_of_tables, 0},
{"TABLESPACE", Query_for_list_of_tablespaces, NULL, 0},
{"TEMP", NULL, NULL, THING_NO_DROP}, /* for CREATE TEMP TABLE ... */
{"TEMPLATE", Query_for_list_of_ts_templates, NULL, THING_NO_SHOW},
{"TEMPORARY", NULL, NULL, THING_NO_DROP},
{"TEXT SEARCH", NULL, NULL, 0},
{"TRIGGER",
"SELECT pg_catalog.quote_ident(tgname) FROM pg_catalog.pg_trigger WHERE "
"substring(pg_catalog.quote_ident(tgname),1,%d)='%s'",
NULL,
0},
{"TRUSTED", NULL, NULL, THING_NO_DROP},
{"TYPE", NULL, &Query_for_list_of_datatypes, 0},
{"UNIQUE", NULL, NULL, THING_NO_DROP}, /* for CREATE UNIQUE INDEX ... */
{"UNLOGGED", NULL, NULL, THING_NO_DROP}, /* for CREATE UNLOGGED TABLE
* ... */
{"USER", Query_for_list_of_roles, NULL, 0},
#ifndef PGXC
{"USER MAPPING FOR", NULL, NULL, 0},
#endif
{"VIEW", NULL, &Query_for_list_of_views, 0},
{NULL, NULL, NULL, 0} /* end of list */
};
/*
* GENERATOR FUNCTIONS
*
* These functions do all the actual work of completing the input. They get
* passed the text so far and the count how many times they have been called
* so far with the same text.
* If you read the above carefully, you'll see that these don't get called
* directly but through the readline interface.
* The return value is expected to be the full completion of the text, going
* through a list each time, or NULL if there are no more matches. The string
* will be free()'d by readline, so you must run it through strdup() or
* something of that sort.
*/
/*
* Common routine for CreateCommandGenerator and DropCommandGenerator.
* Entries that have 'excluded' flags are not returned.
*/
static char *create_or_DropCommandGenerator(const char *text, int state, bits32 excluded)
{
static int listIndex, stringLength;
const char *name = NULL;
/* If this is the first time for this completion, init some values */
if (state == 0) {
listIndex = 0;
stringLength = strlen(text);
}
/* find something that matches */
while ((name = words_after_create[listIndex++].name)) {
if ((pg_strncasecmp(name, text, stringLength) == 0) && !(words_after_create[listIndex - 1].flags & excluded))
return pg_strdup_keyword_case(name, text);
}
/* if nothing matches, return NULL */
return NULL;
}
/*
* This one gives you one from a list of things you can put after CREATE
* as defined above.
*/
static char *CreateCommandGenerator(const char *text, int state)
{
return create_or_DropCommandGenerator(text, state, THING_NO_CREATE);
}
/*
* This function gives you a list of things you can put after a DROP command.
*/
static char *DropCommandGenerator(const char *text, int state)
{
return create_or_DropCommandGenerator(text, state, THING_NO_DROP);
}
/* The following two functions are wrappers for _CompleteFromQuery */
static char *CompleteFromQuery(const char *text, int state)
{
return _CompleteFromQuery(0, text, state);
}
static char *CompleteFromSchemaQuery(const char *text, int state)
{
return _CompleteFromQuery(1, text, state);
}
/*
* The completion function.
*
* According to readline spec this gets passed the text entered so far and its
* start and end positions in the readline buffer. The return value is some
* partially obscure list format that can be generated by readline's
* completion_matches() function, so we don't have to worry about it.
*/
static char** PsqlCompletion(const char *text, int start, int end)
{
/* This is the variable we'll return. */
char **matches = NULL;
/* This array will contain some scannage of the input line. */
char *previousWords[8];
/* For compactness, we use these macros to reference previous_words[]. */
#define PREV_WD (previousWords[0])
#define PREV2_WD (previousWords[1])
#define PREV3_WD (previousWords[2])
#define PREV4_WD (previousWords[3])
#define PREV5_WD (previousWords[4])
#define PREV6_WD (previousWords[5])
#define PREV7_WD (previousWords[6])
#define PREV8_WD (previousWords[7])
static const char* const sqlCommands[] = {
"ABORT", "ALTER", "ANALYSE", "ANALYZE", "BEGIN", "CALL", "CHECKPOINT", "CLOSE", "CLUSTER",
"COMMENT", "COMMIT", "COPY", "CREATE", "CURSOR", "DEALLOCATE", "DECLARE",
"DELETE FROM", "DISCARD", "DO", "DROP", "END", "EXECUTE", "EXPLAIN", "FETCH",
"GRANT", "INSERT", "LISTEN", "LOAD", "LOCK", "MOVE", "NOTIFY", "PREPARE",
"REASSIGN", "REFRESH", "REINDEX", "RELEASE", "RESET", "REVOKE", "ROLLBACK",
"SAVEPOINT", "SECURITY LABEL", "SELECT", "SET", "SHOW", "START",
"TABLE", "TRUNCATE", "UNLISTEN", "UPDATE", "VACUUM", "VALUES", "WITH",
NULL
};
static const char* const backslashCommands[] = {
"\\a",
"\\connect", "\\conninfo", "\\C", "\\cd", "\\copy", "\\copyright",
"\\d", "\\da", "\\db", "\\dc", "\\dC", "\\dd", "\\ddp", "\\dD", "\\ded",
"\\des", "\\det", "\\deu", "\\dew", "\\dE", "\\df", "\\dF", "\\dFd",
"\\dFp", "\\dFt", "\\dg", "\\di", "\\dl", "\\dL", "\\dn", "\\do", "\\dO",
"\\dp", "\\drds", "\\ds", "\\dt", "\\dT", "\\dv", "\\du", "\\dx",
"\\e", "\\echo", "\\ef", "\\encoding",
"\\f",
"\\g",
"\\h", "\\help", "\\H",
"\\i", "\\i+", "\\ir", "\\ir+",
"\\l", "\\lo_import", "\\lo_export", "\\lo_list", "\\lo_unlink",
"\\o",
"\\p", "\\parallel", "\\prompt", "\\pset",
"\\q", "\\qecho",
"\\r",
"\\set", "\\setenv", "\\sf",
"\\t", "\\T", "\\timing",
"\\unset",
"\\x",
"\\w",
"\\z",
"\\!", "\\?",
NULL
};
(void)end; /* not used */
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
rl_completion_append_character = ' ';
#endif
/* Clear a few things. */
completion_charp = NULL;
completion_charpp = NULL;
completion_info_charp = NULL;
completion_info_charp2 = NULL;
/*
* Scan the input line before our current position for the last few words.
* According to those we'll make some smart decisions on what the user is
* probably intending to type.
*/
GetPreviousWords(start, previousWords, lengthof(previousWords));
/* If a backslash command was started, continue */
if (text[0] == '\\') {
COMPLETE_WITH_LIST_CS(backslashCommands);
}
/* Variable interpolation */
else if (text[0] == ':' && text[1] != ':') {
if (text[1] == '\'') {
matches = CompleteFromVariables(text, ":'", "'");
}
else if (text[1] == '"') {
matches = CompleteFromVariables(text, ":\"", "\"");
}
else {
matches = CompleteFromVariables(text, ":", "");
}
}
/* If no previous word, suggest one of the basic sql commands */
else if (PREV_WD[0] == '\0') {
COMPLETE_WITH_LIST(sqlCommands);
}
/* CREATE */
/* complete with something you can create */
else if (pg_strcasecmp(PREV_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "GRANT") != 0 &&
pg_strcasecmp(PREV2_WD, "REVOKE") != 0)
matches = completion_matches(text, CreateCommandGenerator);
/* complete with something you can create or replace */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "OR") == 0 &&
pg_strcasecmp(PREV_WD, "REPLACE") == 0) {
static const char* const listCreateOrReplace[] = {"FUNCTION", "PROCEDURE", "LANGUAGE", "RULE", "VIEW",
"AGGREGATE", "TRANSFORM", "TRIGGER", NULL};
COMPLETE_WITH_LIST(listCreateOrReplace);
}
else if ((pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "DATABASE") == 0 &&
pg_strcasecmp(PREV_WD, "OWNER") == 0) || (pg_strcasecmp(PREV5_WD, "CREATE") == 0 &&
pg_strcasecmp(PREV4_WD, "DATABASE") == 0 && pg_strcasecmp(PREV2_WD, "OWNER") == 0 &&
pg_strcasecmp(PREV_WD, "=") == 0)) {
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
}
/* complete CREATE COLUMN ENCRYPTION KEY <name> with WITH VALUES ( */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "COLUMN") == 0 &&
pg_strcasecmp(PREV3_WD, "ENCRYPTION") == 0 && pg_strcasecmp(PREV2_WD, "KEY") == 0) {
COMPLETE_WITH_CONST("WITH VALUES (");
}
/* complete CREATE COLUMN ENCRYPTION KEY <name> WITH VALUES ( with CLIENT_MASTER_KEY = */
else if (pg_strcasecmp(PREV8_WD, "CREATE") == 0 && pg_strcasecmp(PREV7_WD, "COLUMN") == 0 &&
pg_strcasecmp(PREV6_WD, "ENCRYPTION") == 0 && pg_strcasecmp(PREV5_WD, "KEY") == 0 &&
pg_strcasecmp(PREV3_WD, "WITH") == 0 && pg_strcasecmp(PREV2_WD, "VALUES") == 0 &&
pg_strcasecmp(PREV_WD, "(") == 0) {
COMPLETE_WITH_CONST("CLIENT_MASTER_KEY =");
}
/* complete CREATE COLUMN ENCRYPTION KEY <name> WITH VALUES ( CLIENT_MASTER_KEY = <name>, with ALGORITHM = */
else if (pg_strcasecmp(PREV4_WD, "CLIENT_MASTER_KEY") == 0 && pg_strcasecmp(PREV3_WD, "=") == 0 &&
pg_strcasecmp(PREV_WD, ",") == 0) {
COMPLETE_WITH_CONST("ALGORITHM =");
}
else if (pg_strcasecmp(PREV8_WD, "CLIENT_MASTER_KEY") == 0 && pg_strcasecmp(PREV4_WD, "ALGORITHM") == 0 &&
pg_strcasecmp(PREV3_WD, "=") == 0 && pg_strcasecmp(PREV_WD, ",") == 0) {
COMPLETE_WITH_CONST("ENCRYPTED_VALUE =");
}
/* complete CREATE CLIENT MASTER KEY <name> with WITH ( */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "CLIENT") == 0 &&
pg_strcasecmp(PREV3_WD, "MASTER") == 0 && pg_strcasecmp(PREV2_WD, "KEY") == 0) {
COMPLETE_WITH_CONST("WITH (");
}
/* complete CREATE CLIENT MASTER KEY <name> WITH ( with KEY_STORE = */
else if (pg_strcasecmp(PREV7_WD, "CREATE") == 0 && pg_strcasecmp(PREV6_WD, "CLIENT") == 0 &&
pg_strcasecmp(PREV5_WD, "MASTER") == 0 && pg_strcasecmp(PREV4_WD, "KEY") == 0 &&
pg_strcasecmp(PREV2_WD, "WITH") == 0 && pg_strcasecmp(PREV_WD, "(") == 0) {
COMPLETE_WITH_CONST("KEY_STORE =");
}
else if (pg_strcasecmp(PREV4_WD, "KEY_STORE") == 0 && pg_strcasecmp(PREV3_WD, "=") == 0 &&
pg_strcasecmp(PREV_WD, ",") == 0) {
COMPLETE_WITH_CONST("KEY_PATH =");
}
else if (pg_strcasecmp(PREV4_WD, "KEY_PATH") == 0 && pg_strcasecmp(PREV3_WD, "=") == 0 &&
pg_strcasecmp(PREV_WD, ",") == 0) {
COMPLETE_WITH_CONST("ALGORITHM =");
}
/* complete with AUTHORIZATION in ALTER SCHEMA xxx */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "SCHEMA") == 0 &&
pg_strcasecmp(PREV_WD, "AUTHORIZATION") != 0)
COMPLETE_WITH_CONST("AUTHORIZATION");
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "SCHEMA") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_schemas "UNION SELECT 'AUTHORIZATION'");
/* DROP, but not DROP embedded in other commands */
/* complete with something you can drop */
else if (pg_strcasecmp(PREV_WD, "DROP") == 0 && PREV2_WD[0] == '\0')
matches = completion_matches(text, DropCommandGenerator);
else if (pg_strcasecmp(PREV3_WD, "PARTITION") == 0 && pg_strcasecmp(PREV_WD, "VALUES"))
COMPLETE_WITH_CONST("LESS THAN");
/* ALTER */
/*
* complete with what you can alter (TABLE, GROUP, USER, ...) unless we're
* in ALTER TABLE sth ALTER
*/
else if (pg_strcasecmp(PREV_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TABLE") != 0) {
static const char* const listAlter[] = {
"AGGREGATE", "APP WORKLOAD GROUP", "APP WORKLOAD GROUP MAPPING", "COLLATION", "CONVERSION",
"DATABASE", "DEFAULT PRIVILEGES", "DOMAIN", "EXTENSION", "FOREIGN DATA WRAPPER",
"FOREIGN TABLE", "FUNCTION", "GROUP", "INDEX", "LANGUAGE", "LARGE OBJECT",
"MATERIALIZED VIEW", "OPERATOR", "POLICY", "PROCEDURE", "PUBLICATION", "ROLE", "ROW LEVEL SECURITY POLICY",
"RULE", "SCHEMA", "SERVER", "SESSION", "SEQUENCE", "SUBSCRIPTION", "SYSTEM", "TABLE", "TABLESPACE",
"TEXT SEARCH", "TRIGGER", "TYPE", "USER", "USER MAPPING FOR", "VIEW", NULL
};
COMPLETE_WITH_LIST(listAlter);
}
/* ALTER AGGREGATE,FUNCTION,PROCEDURE <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && (pg_strcasecmp(PREV2_WD, "AGGREGATE") == 0 ||
pg_strcasecmp(PREV2_WD, "FUNCTION") == 0 || pg_strcasecmp(PREV2_WD, "PROCEDURE") == 0))
COMPLETE_WITH_CONST("(");
/* ALTER AGGREGATE,FUNCTION <name> (...) */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && (pg_strcasecmp(PREV3_WD, "AGGREGATE") == 0 ||
pg_strcasecmp(PREV3_WD, "FUNCTION") == 0 || pg_strcasecmp(PREV2_WD, "PROCEDURE") == 0)) {
if (PREV_WD[strlen(PREV_WD) - 1] == ')') {
static const char* const listAlterAgg[] = {"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterAgg);
} else {
size_t tmpLength = strlen(Query_for_list_of_arguments) + strlen(PREV2_WD);
char *tmpBuf = (char *)pg_malloc(tmpLength);
int rc = sprintf_s(tmpBuf, tmpLength, Query_for_list_of_arguments, PREV2_WD);
securec_check_ss_c(rc, "", "");
COMPLETE_WITH_QUERY(tmpBuf);
free(tmpBuf);
}
}
/* ALTER PUBLICATION <name> ... */
else if (pg_strcasecmp(PREV2_WD, "ALTER") == 0 && pg_strcasecmp(PREV_WD, "PUBLICATION") == 0) {
static const char * const listAlterPub[] = {"ADD TABLE", "DROP TABLE", "OWNER TO", "RENAME TO", "SET", NULL};
COMPLETE_WITH_LIST(listAlterPub);
}
/* ALTER PUBLICATION <name> SET */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "PUBLICATION") == 0 &&
pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char * const listAlterPubSet[] = {"(", "TABLE", NULL};
COMPLETE_WITH_LIST(listAlterPubSet);
}
/* ALTER PUBLICATION <name> SET ( */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "PUBLICATION") == 0 &&
pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "(") == 0) {
static const char * const listAlterPubSet2[] = {"publish", NULL};
COMPLETE_WITH_LIST(listAlterPubSet2);
}
/* ALTER SUBSCRIPTION <name> */
else if (pg_strcasecmp(PREV2_WD, "ALTER") == 0 && pg_strcasecmp(PREV_WD, "SUBSCRIPTION") == 0) {
static const char * const listAlterSub[] = {"CONNECTION", "ENABLE", "DISABLE", "OWNER TO", "RENAME TO",
"SET", NULL};
COMPLETE_WITH_LIST(listAlterSub);
}
/* ALTER SUBSCRIPTION <name> SET */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "SUBSCRIPTION") == 0 &&
pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char * const listAlterSubSet[] = {"(", "PUBLICATION", NULL};
COMPLETE_WITH_LIST(listAlterSubSet);
}
/* ALTER SUBSCRIPTION <name> SET ( */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "SUBSCRIPTION") == 0 &&
pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "(") == 0) {
static const char * const listAlterSubSet2[] = {"slot_name", "synchronous_commit", NULL};
COMPLETE_WITH_LIST(listAlterSubSet2);
}
/* ALTER SESSION */
else if (pg_strcasecmp(PREV2_WD, "ALTER") == 0 && pg_strcasecmp(PREV_WD, "SESSION") == 0)
COMPLETE_WITH_CONST("SET");
/* ALTER SYSTEM */
else if (pg_strcasecmp(PREV2_WD, "ALTER") == 0 && pg_strcasecmp(PREV_WD, "SYSTEM") == 0) {
static const char* const listAlterSystem[] = {"KILL SESSION", "SET", NULL};
COMPLETE_WITH_LIST(listAlterSystem);
}
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "SYSTEM") == 0 &&
pg_strcasecmp(PREV_WD, "SET") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_alter_system_set_vars);
/* ALTER SCHEMA <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "SCHEMA") == 0) {
static const char* const listAlterGen[] = {"OWNER TO", "RENAME TO", NULL};
COMPLETE_WITH_LIST(listAlterGen);
}
/* ALTER COLLATION <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "COLLATION") == 0) {
static const char* const listAlterGen[] = {"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterGen);
}
/* ALTER CONVERSION <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "CONVERSION") == 0) {
static const char* const listAlterGen[] = {"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterGen);
}
/* ALTER DATABASE <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "DATABASE") == 0) {
static const char* const listAlterDatabase[] = {
"WITH", "RESET", "SET", "OWNER TO", "RENAME TO", "CONNECTION LIMIT", "ENABLE PRIVATE OBJECT",
"DISABLE PRIVATE OBJECT", NULL
};
COMPLETE_WITH_LIST(listAlterDatabase);
} else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "DATABASE") == 0 &&
pg_strcasecmp(PREV_WD, "WITH") == 0) {
static const char* const listAlterDatabaseWith[] = {
"CONNECTION LIMIT", "ENABLE PRIVATE OBJECT", "DISABLE PRIVATE OBJECT", NULL
};
COMPLETE_WITH_LIST(listAlterDatabaseWith);
}
/* ALTER EXTENSION <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "EXTENSION") == 0) {
static const char* const listAlterExtension[] = {"ADD", "DROP", "UPDATE", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterExtension);
}
/* ALTER EXTENSION <name> UPDATE */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "EXTENSION") == 0 &&
pg_strcasecmp(PREV_WD, "UPDATE") == 0) {
COMPLETE_WITH_CONST("TO");
}
/* ALTER EXTENSION <name> UPDATE TO */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "EXTENSION") == 0 &&
pg_strcasecmp(PREV2_WD, "UPDATE") == 0 && pg_strcasecmp(PREV_WD, "TO") == 0) {
completion_info_charp = PREV3_WD;
COMPLETE_WITH_QUERY(Query_for_list_of_available_extension_versions);
}
/* ALTER EXTENSION <name> ADD/DROP */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "EXTENSION") == 0 &&
(pg_strcasecmp(PREV_WD, "ADD") == 0 || pg_strcasecmp(PREV_WD, "DROP"))) {
static const char* const listAlterExtensionMemberObject[] = {
"AGGREGATE", "CAST", "COLLATION", "CONVERSION", "DOMAIN", "EVENT TRIGGER", "FOREIGN DATA WRAPPER",
"FOREIGN TABLE", "FUNCTION", "MATERIALIZED VIEW", "OPERATOR", "OPERATOR CLASS", "OPERATOR FAMILY ",
"PROCEDURAL LANGUAGE", "LANGUAGE", "SCHEMA", "SEQUENCE", "SERVER", "TABLE", "TEXT SEARCH CONFIGURATION",
"TEXT SEARCH DICTIONARY", "TEXT SEARCH PARSER", "TEXT SEARCH TEMPLATE", "TYPE", "VIEW", NULL};
COMPLETE_WITH_LIST(listAlterExtensionMemberObject);
}
/* ALTER FOREIGN */
else if (pg_strcasecmp(PREV2_WD, "ALTER") == 0 && pg_strcasecmp(PREV_WD, "FOREIGN") == 0) {
static const char* const listAlterForeign[] = {"DATA WRAPPER", "TABLE", NULL};
COMPLETE_WITH_LIST(listAlterForeign);
}
/* ALTER FOREIGN DATA WRAPPER <name> */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "FOREIGN") == 0 &&
pg_strcasecmp(PREV3_WD, "DATA") == 0 && pg_strcasecmp(PREV2_WD, "WRAPPER") == 0) {
static const char* const listAlterFdw[] = {"HANDLER", "VALIDATOR", "OPTIONS", "OWNER TO", NULL};
COMPLETE_WITH_LIST(listAlterFdw);
}
/* ALTER FOREIGN TABLE <name> */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "FOREIGN") == 0 &&
pg_strcasecmp(PREV2_WD, "TABLE") == 0) {
static const char* const listAlterForeignTable[] = {"ALTER", "DROP", "RENAME", "OWNER TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterForeignTable);
}
/* ALTER INDEX <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "INDEX") == 0) {
static const char* const listAlterindex[] = {"OWNER TO", "RENAME TO", "SET", "RESET", NULL};
COMPLETE_WITH_LIST(listAlterindex);
}
/* ALTER INDEX <name> SET */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "INDEX") == 0 &&
pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char* const listAlterindexset[] = {"(", "TABLESPACE", NULL};
COMPLETE_WITH_LIST(listAlterindexset);
}
/* ALTER INDEX <name> RESET */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "INDEX") == 0 &&
pg_strcasecmp(PREV_WD, "RESET") == 0)
COMPLETE_WITH_CONST("(");
/* ALTER INDEX <foo> SET|RESET ( */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "INDEX") == 0 &&
(pg_strcasecmp(PREV2_WD, "SET") == 0 || pg_strcasecmp(PREV2_WD, "RESET") == 0) &&
pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listIndexOptions[] = {"fillfactor", "fastupdate", NULL};
COMPLETE_WITH_LIST(listIndexOptions);
}
/* ALTER LANGUAGE <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "LANGUAGE") == 0) {
static const char* const listAlterLanguage[] = {"OWNER TO", "RENAME TO", NULL};
COMPLETE_WITH_LIST(listAlterLanguage);
}
/* ALTER LARGE OBJECT <oid> */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "LARGE") == 0 &&
pg_strcasecmp(PREV2_WD, "OBJECT") == 0) {
static const char* const listAlterLargeObject[] = {"OWNER TO", NULL};
COMPLETE_WITH_LIST(listAlterLargeObject);
}
/* ALTER MATERIALIZED VIEW */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV2_WD, "VIEW") == 0) {
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
}
/* ALTER USER,ROLE <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 &&
!(pg_strcasecmp(PREV2_WD, "USER") == 0 && pg_strcasecmp(PREV_WD, "MAPPING") == 0) &&
(pg_strcasecmp(PREV2_WD, "USER") == 0 || pg_strcasecmp(PREV2_WD, "ROLE") == 0)) {
static const char* const listAlterUser[] = {
"ACCOUNT", "AUDITADMIN", "CONNECTION LIMIT", "CREATEDB",
"CREATEROLE", "CREATEUSER", "ENCRYPTED", "IDENT", "IDENTIFIED BY",
"INDEPENDENT", "INHERIT", "LOGIN", "MONADMIN", "NOAUDITADMIN",
"NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER", "NODE GROUP",
"NOINDEPENDENT", "NOINHERIT", "NOLOGIN", "NOMONADMIN", "NOOPRADMIN",
"NOPERSISTENCE", "NOPOLADMIN", "NOREPLICATION",
"NOSYSADMIN", "NOUSEFT", "NOVCADMIN", "OPRADMIN", "PASSWORD",
"PERM SPACE", "PERSISTENCE", "PGUSER", "POLADMIN", "RENAME TO",
"REPLICATION", "RESET", "RESOURCE POOL", "SET", "SPILL SPACE",
"SYSADMIN", "TEMP SPACE", "UNENCRYPTED", "USEFT",
"USER GROUP", "VALID", "VCADMIN", "WITH", NULL
};
COMPLETE_WITH_LIST(listAlterUser);
}
/* ALTER USER,ROLE <name> VALID*/
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 &&
!(pg_strcasecmp(PREV3_WD, "USER") == 0 && pg_strcasecmp(PREV2_WD, "MAPPING") == 0) &&
(pg_strcasecmp(PREV3_WD, "USER") == 0 || pg_strcasecmp(PREV3_WD, "ROLE") == 0) &&
pg_strcasecmp(PREV_WD, "VALID") == 0) {
static const char* const listAlterUserValid[] = {"BEGIN", "UNTIL", NULL};
COMPLETE_WITH_LIST(listAlterUserValid);
}
/* ALTER USER,ROLE <name> WITH */
else if ((pg_strcasecmp(PREV4_WD, "ALTER") == 0 &&
(pg_strcasecmp(PREV3_WD, "USER") == 0 || pg_strcasecmp(PREV3_WD, "ROLE") == 0) &&
pg_strcasecmp(PREV_WD, "WITH") == 0)) {
/* Similar to the above, but don't complete "WITH" again. */
static const char* const listAlterUserWith[] = {
"ACCOUNT", "AUDITADMIN", "CONNECTION LIMIT", "CREATEDB",
"CREATEROLE", "CREATEUSER", "ENCRYPTED", "IDENT", "IDENTIFIED BY",
"INDEPENDENT", "INHERIT", "LOGIN", "MONADMIN", "NOAUDITADMIN",
"NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER", "NODE GROUP",
"NOINDEPENDENT", "NOINHERIT", "NOLOGIN", "NOMONADMIN", "NOOPRADMIN",
"NOPERSISTENCE", "NOPOLADMIN", "NOREPLICATION",
"NOSYSADMIN", "NOUSEFT", "NOVCADMIN", "OPRADMIN", "PASSWORD",
"PERM SPACE", "PERSISTENCE", "PGUSER", "POLADMIN", "RENAME TO",
"REPLICATION", "RESET", "RESOURCE POOL", "SET", "SPILL SPACE",
"SYSADMIN", "TEMP SPACE", "UNENCRYPTED", "USEFT",
"USER GROUP", "VALID", "VCADMIN", NULL
};
COMPLETE_WITH_LIST(listAlterUserWith);
}
/* ALTER USER,ROLE <name> WITH VALID*/
else if ((pg_strcasecmp(PREV5_WD, "ALTER") == 0 &&
(pg_strcasecmp(PREV4_WD, "USER") == 0 || pg_strcasecmp(PREV4_WD, "ROLE") == 0) &&
pg_strcasecmp(PREV2_WD, "WITH") == 0) && pg_strcasecmp(PREV_WD, "VALID") == 0) {
/* Similar to the above, but don't complete "WITH" again. */
static const char* const listAlterUserWithValid[] = {"BEGIN", "UNTIL", NULL};
COMPLETE_WITH_LIST(listAlterUserWithValid);
}
/* ALTER USER,ROLE <name> ENCRYPTED,UNENCRYPTED */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 &&
(pg_strcasecmp(PREV3_WD, "ROLE") == 0 || pg_strcasecmp(PREV3_WD, "USER") == 0) &&
(pg_strcasecmp(PREV_WD, "ENCRYPTED") == 0 || pg_strcasecmp(PREV_WD, "UNENCRYPTED") == 0)) {
static const char* const listAlterUserEncrypted[] = {"IDENTIFIED BY", "PASSWORD", NULL};
COMPLETE_WITH_LIST(listAlterUserEncrypted);
}
/* ALTER USER,ROLE <name> WITH ENCRYPTED,UNENCRYPTED */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && (pg_strcasecmp(PREV4_WD, "ROLE") == 0 ||
pg_strcasecmp(PREV4_WD, "USER") == 0) && pg_strcasecmp(PREV2_WD, "WITH") == 0 &&
(pg_strcasecmp(PREV_WD, "ENCRYPTED") == 0 || pg_strcasecmp(PREV_WD, "UNENCRYPTED") == 0)) {
static const char* const listAlterUserWithEncrypted[] = {"IDENTIFIED BY", "PASSWORD", NULL};
COMPLETE_WITH_LIST(listAlterUserWithEncrypted);
}
/* ALTER DEFAULT PRIVILEGES */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "DEFAULT") == 0 &&
pg_strcasecmp(PREV_WD, "PRIVILEGES") == 0) {
static const char* const listAlterDefaultPrivileges[] = {"FOR ROLE", "FOR USER", "IN SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterDefaultPrivileges);
}
/* ALTER DEFAULT PRIVILEGES FOR */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "DEFAULT") == 0 &&
pg_strcasecmp(PREV2_WD, "PRIVILEGES") == 0 && pg_strcasecmp(PREV_WD, "FOR") == 0) {
static const char* const listAlterDefaultPrivileges_FOR[] = {"ROLE", "USER", NULL};
COMPLETE_WITH_LIST(listAlterDefaultPrivileges_FOR);
}
/* ALTER DEFAULT PRIVILEGES { FOR ROLE ... | IN SCHEMA ... } */
else if (pg_strcasecmp(PREV5_WD, "DEFAULT") == 0 && pg_strcasecmp(PREV4_WD, "PRIVILEGES") == 0 &&
(pg_strcasecmp(PREV3_WD, "FOR") == 0 || pg_strcasecmp(PREV3_WD, "IN") == 0)) {
static const char* const listAlterDefaultPrivilegesRest[] = {"GRANT", "REVOKE", NULL};
COMPLETE_WITH_LIST(listAlterDefaultPrivilegesRest);
}
/* ALTER DOMAIN <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "DOMAIN") == 0) {
static const char* const listAlterDomain[] = {
"ADD", "DROP", "OWNER TO", "RENAME", "SET", "VALIDATE CONSTRAINT", NULL
};
COMPLETE_WITH_LIST(listAlterDomain);
}
/* ALTER DOMAIN <sth> DROP */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "DOMAIN") == 0 &&
pg_strcasecmp(PREV_WD, "DROP") == 0) {
static const char* const listAlterDomain2[] = {"CONSTRAINT", "DEFAULT", "NOT NULL", NULL};
COMPLETE_WITH_LIST(listAlterDomain2);
}
/* ALTER DOMAIN <sth> RENAME */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "DOMAIN") == 0 &&
pg_strcasecmp(PREV_WD, "RENAME") == 0) {
static const char* const listAlterDomain[] = {"CONSTRAINT", "TO", NULL};
COMPLETE_WITH_LIST(listAlterDomain);
}
/* ALTER DOMAIN <sth> RENAME CONSTRAINT <sth> */
else if (pg_strcasecmp(PREV5_WD, "DOMAIN") == 0 && pg_strcasecmp(PREV3_WD, "RENAME") == 0 &&
pg_strcasecmp(PREV2_WD, "CONSTRAINT") == 0)
COMPLETE_WITH_CONST("TO");
/* ALTER DOMAIN <sth> SET */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "DOMAIN") == 0 &&
pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char* const listAlterDomain3[] = {"DEFAULT", "NOT NULL", "SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterDomain3);
}
/* ALTER SEQUENCE <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "SEQUENCE") == 0) {
static const char* const listAlterSequence[] = {
"MAXVALUE", "NO MAXVALUE", "NOMAXVALUE", "OWNED BY", "OWNER TO", NULL
};
COMPLETE_WITH_LIST(listAlterSequence);
}
/* ALTER SERVER <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "SERVER") == 0) {
static const char* const listAlterServer[] = {
"VERSION", "OPTIONS", "OWNER TO", "RENAME TO", NULL
};
COMPLETE_WITH_LIST(listAlterServer);
}
/* ALTER MATERIALIZED VIEW <name> */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV2_WD, "VIEW") == 0) {
static const char *const listAlterMatview[] = {
"ALTER COLUMN", "OWNER TO", "RENAME", "RESET (", "SET", NULL};
COMPLETE_WITH_LIST(listAlterMatview);
}
/* ALTER MATERIALIZED VIEW xxx RENAME */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV3_WD, "VIEW") == 0 && pg_strcasecmp(PREV_WD, "RENAME") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, " UNION SELECT 'COLUMN' UNION SELECT 'TO'");
else if (pg_strcasecmp(PREV6_WD, "ALTER") == 0 && pg_strcasecmp(PREV5_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV4_WD, "VIEW") == 0 && (pg_strcasecmp(PREV2_WD, "ALTER") == 0 ||
pg_strcasecmp(PREV2_WD, "RENAME") == 0) && pg_strcasecmp(PREV_WD, "COLUMN") == 0)
COMPLETE_WITH_ATTR(PREV3_WD, "");
/* ALTER MATERIALIZED VIEW xxx RENAME yyy */
else if (pg_strcasecmp(PREV6_WD, "ALTER") == 0 && pg_strcasecmp(PREV5_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV4_WD, "VIEW") == 0 && pg_strcasecmp(PREV2_WD, "RENAME") == 0 &&
pg_strcasecmp(PREV_WD, "TO") != 0)
COMPLETE_WITH_CONST("TO");
/* ALTER MATERIALIZED VIEW xxx RENAME COLUMN yyy */
else if (pg_strcasecmp(PREV7_WD, "ALTER") == 0 && pg_strcasecmp(PREV6_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV5_WD, "VIEW") == 0 && pg_strcasecmp(PREV3_WD, "RENAME") == 0 &&
pg_strcasecmp(PREV2_WD, "COLUMN") == 0 && pg_strcasecmp(PREV_WD, "TO") != 0)
COMPLETE_WITH_CONST("TO");
/* ALTER MATERIALIZED VIEW xxx SET */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV3_WD, "VIEW") == 0 && pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char *const listAlterS[] = {
"(", "SCHEMA", "TABLESPACE", "WITHOUT CLUSTER", NULL};
COMPLETE_WITH_LIST(listAlterS);
}
/* ALTER VIEW <name> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "VIEW") == 0) {
static const char* const listAlterview[] = {"ALTER COLUMN", "OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterview);
}
/* ALTER [ROW LEVEL SECURITY] POLICY <name> on <table> */
else if ((pg_strcasecmp(PREV8_WD, "ALTER") == 0 || pg_strcasecmp(PREV5_WD, "ALTER") == 0) &&
pg_strcasecmp(PREV4_WD, "POLICY") == 0 && pg_strcasecmp(PREV2_WD, "ON") == 0) {
static const char* const listAlterPolicy[] = {"RENAME TO", "TO", "USING (", NULL};
COMPLETE_WITH_LIST(listAlterPolicy);
}
/* ALTER TRIGGER <name>, add ON */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "TRIGGER") == 0)
COMPLETE_WITH_CONST("ON");
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TRIGGER") == 0) {
completion_info_charp = PREV2_WD;
COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
}
/*
* If we have ALTER TRIGGER <sth> ON, then add the correct tablename
*/
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TRIGGER") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
/* ALTER TRIGGER <name> ON <name> */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "TRIGGER") == 0 &&
pg_strcasecmp(PREV2_WD, "ON") == 0)
COMPLETE_WITH_CONST("RENAME TO");
/*
* If we detect ALTER TABLE <name>, suggest sub commands
*/
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "TABLE") == 0) {
static const char* const listAlteR2[] = {
"ADD", "ALTER", "CLUSTER ON", "DISABLE", "DROP", "ENABLE", "INHERIT",
"NO INHERIT", "RENAME", "RESET", "OWNER TO", "SET",
"VALIDATE CONSTRAINT", NULL
};
COMPLETE_WITH_LIST(listAlteR2);
}
/* ALTER TABLE xxx ENABLE */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TABLE") == 0 &&
pg_strcasecmp(PREV_WD, "ENABLE") == 0) {
static const char* const listAlterEnable[] = {"ALWAYS", "REPLICA", "RULE", "TRIGGER", NULL};
COMPLETE_WITH_LIST(listAlterEnable);
} else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "ENABLE") == 0 &&
(pg_strcasecmp(PREV_WD, "REPLICA") == 0 || pg_strcasecmp(PREV_WD, "ALWAYS") == 0)) {
static const char* const listAlterEnablE2[] = {"RULE", "TRIGGER", NULL};
COMPLETE_WITH_LIST(listAlterEnablE2);
} else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TABLE") == 0 &&
pg_strcasecmp(PREV_WD, "DISABLE") == 0) {
static const char* const listAlterDisable[] = {"RULE", "TRIGGER", NULL};
COMPLETE_WITH_LIST(listAlterDisable);
}
/* ALTER TABLE xxx ALTER */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TABLE") == 0 &&
pg_strcasecmp(PREV_WD, "ALTER") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, " UNION SELECT 'COLUMN'");
/* ALTER TABLE xxx RENAME */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TABLE") == 0 &&
pg_strcasecmp(PREV_WD, "RENAME") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, " UNION SELECT 'COLUMN' UNION SELECT 'CONSTRAINT' UNION SELECT 'TO'");
/*
* If we have TABLE <sth> ALTER COLUMN|RENAME COLUMN, provide list of
* columns
*/
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 &&
(pg_strcasecmp(PREV2_WD, "ALTER") == 0 || pg_strcasecmp(PREV2_WD, "RENAME") == 0) &&
pg_strcasecmp(PREV_WD, "COLUMN") == 0)
COMPLETE_WITH_ATTR(PREV3_WD, "");
/* ALTER TABLE xxx RENAME yyy */
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "RENAME") == 0 &&
pg_strcasecmp(PREV_WD, "CONSTRAINT") != 0 && pg_strcasecmp(PREV_WD, "TO") != 0)
COMPLETE_WITH_CONST("TO");
/* ALTER TABLE xxx RENAME COLUMN/CONSTRAINT yyy */
else if (pg_strcasecmp(PREV5_WD, "TABLE") == 0 && pg_strcasecmp(PREV3_WD, "RENAME") == 0 &&
(pg_strcasecmp(PREV2_WD, "COLUMN") == 0 || pg_strcasecmp(PREV2_WD, "CONSTRAINT") == 0) &&
pg_strcasecmp(PREV_WD, "TO") != 0)
COMPLETE_WITH_CONST("TO");
/* If we have TABLE <sth> DROP, provide COLUMN or CONSTRAINT */
else if (pg_strcasecmp(PREV3_WD, "TABLE") == 0 && pg_strcasecmp(PREV_WD, "DROP") == 0) {
static const char* const listTableDrop[] = {"COLUMN", "CONSTRAINT", NULL};
COMPLETE_WITH_LIST(listTableDrop);
}
/* If we have TABLE <sth> DROP COLUMN, provide list of columns */
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "DROP") == 0 &&
pg_strcasecmp(PREV_WD, "COLUMN") == 0)
COMPLETE_WITH_ATTR(PREV3_WD, "");
/* ALTER TABLE ALTER [COLUMN] <foo> */
else if ((pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "COLUMN") == 0) ||
(pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "ALTER") == 0)) {
static const char* const listColumnAlter[] = {"TYPE", "SET", "RESET", "DROP", NULL};
COMPLETE_WITH_LIST(listColumnAlter);
}
/* ALTER TABLE ALTER [COLUMN] <foo> SET */
else if (((pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "COLUMN") == 0) ||
(pg_strcasecmp(PREV5_WD, "TABLE") == 0 && pg_strcasecmp(PREV3_WD, "ALTER") == 0)) &&
pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char* const listColumnSet[] = {"(", "DEFAULT", "NOT NULL", "STATISTICS", "STORAGE", NULL};
COMPLETE_WITH_LIST(listColumnSet);
}
/* ALTER TABLE ALTER [COLUMN] <foo> SET ( */
else if (((pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "COLUMN") == 0) ||
pg_strcasecmp(PREV4_WD, "ALTER") == 0) &&
pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listColumnOptions[] = {"n_distinct", "n_distinct_inherited", NULL};
COMPLETE_WITH_LIST(listColumnOptions);
}
/* ALTER TABLE ALTER [COLUMN] <foo> SET STORAGE */
else if (((pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "COLUMN") == 0) ||
pg_strcasecmp(PREV4_WD, "ALTER") == 0) &&
pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "STORAGE") == 0) {
static const char* const listColumnStorage[] = {"PLAIN", "EXTERNAL", "EXTENDED", "MAIN", NULL};
COMPLETE_WITH_LIST(listColumnStorage);
}
/* ALTER TABLE ALTER [COLUMN] <foo> DROP */
else if (((pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "COLUMN") == 0) ||
(pg_strcasecmp(PREV5_WD, "TABLE") == 0 && pg_strcasecmp(PREV3_WD, "ALTER") == 0)) &&
pg_strcasecmp(PREV_WD, "DROP") == 0) {
static const char* const listColumnDrop[] = {"DEFAULT", "NOT NULL", NULL};
COMPLETE_WITH_LIST(listColumnDrop);
} else if (pg_strcasecmp(PREV3_WD, "TABLE") == 0 && pg_strcasecmp(PREV_WD, "CLUSTER") == 0)
COMPLETE_WITH_CONST("ON");
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "CLUSTER") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0) {
completion_info_charp = PREV3_WD;
COMPLETE_WITH_QUERY(Query_for_index_of_table);
}
/* If we have TABLE <sth> SET, provide WITHOUT,TABLESPACE and SCHEMA */
else if (pg_strcasecmp(PREV3_WD, "TABLE") == 0 && pg_strcasecmp(PREV_WD, "SET") == 0) {
static const char* const listTableSet[] = {"(", "WITHOUT", "TABLESPACE", "SCHEMA", NULL};
COMPLETE_WITH_LIST(listTableSet);
}
/* If we have TABLE <sth> SET TABLESPACE provide a list of tablespaces */
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "SET") == 0 &&
pg_strcasecmp(PREV_WD, "TABLESPACE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
/* If we have TABLE <sth> SET WITHOUT provide CLUSTER or OIDS */
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "SET") == 0 &&
pg_strcasecmp(PREV_WD, "WITHOUT") == 0) {
static const char* const listTableSet2[] = {"CLUSTER", "OIDS", NULL};
COMPLETE_WITH_LIST(listTableSet2);
}
/* ALTER TABLE <foo> RESET */
else if (pg_strcasecmp(PREV3_WD, "TABLE") == 0 && pg_strcasecmp(PREV_WD, "RESET") == 0)
COMPLETE_WITH_CONST("(");
/* ALTER TABLE <foo> SET|RESET ( */
else if (pg_strcasecmp(PREV4_WD, "TABLE") == 0 &&
(pg_strcasecmp(PREV2_WD, "SET") == 0 || pg_strcasecmp(PREV2_WD, "RESET") == 0) &&
pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listTableOptions[] = {
"autovacuum_analyze_scale_factor",
"autovacuum_analyze_threshold",
"autovacuum_enabled",
"autovacuum_freeze_max_age",
"autovacuum_freeze_min_age",
"autovacuum_freeze_table_age",
"autovacuum_vacuum_cost_delay",
"autovacuum_vacuum_cost_limit",
"autovacuum_vacuum_scale_factor",
"autovacuum_vacuum_threshold",
"fillfactor",
"toast.autovacuum_enabled",
"toast.autovacuum_freeze_max_age",
"toast.autovacuum_freeze_min_age",
"toast.autovacuum_freeze_table_age",
"toast.autovacuum_vacuum_cost_delay",
"toast.autovacuum_vacuum_cost_limit",
"toast.autovacuum_vacuum_scale_factor",
"toast.autovacuum_vacuum_threshold",
NULL
};
COMPLETE_WITH_LIST(listTableOptions);
}
/* ALTER TABLESPACE <foo> with RENAME TO, OWNER TO, SET, RESET */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "TABLESPACE") == 0) {
static const char* const listAlterTspc[] = {"RENAME TO", "OWNER TO", "SET", "RESET", NULL};
COMPLETE_WITH_LIST(listAlterTspc);
}
/* ALTER TABLESPACE <foo> SET|RESET */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TABLESPACE") == 0 &&
(pg_strcasecmp(PREV_WD, "SET") == 0 || pg_strcasecmp(PREV_WD, "RESET") == 0))
COMPLETE_WITH_CONST("(");
/* ALTER TABLESPACE <foo> SET|RESET ( */
else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "TABLESPACE") == 0 &&
(pg_strcasecmp(PREV2_WD, "SET") == 0 || pg_strcasecmp(PREV2_WD, "RESET") == 0) &&
pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listTablespaceOptions[] = {"seq_page_cost", "random_page_cost", NULL};
COMPLETE_WITH_LIST(listTablespaceOptions);
}
/* ALTER TEXT SEARCH */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV_WD, "SEARCH") == 0) {
static const char* const listAlterTextSearch[] = {"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
COMPLETE_WITH_LIST(listAlterTextSearch);
} else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV3_WD, "SEARCH") == 0 &&
(pg_strcasecmp(PREV2_WD, "TEMPLATE") == 0 || pg_strcasecmp(PREV2_WD, "PARSER") == 0)) {
static const char* const listAlterTextSearcH2[] = {"RENAME TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterTextSearcH2);
} else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV3_WD, "SEARCH") == 0 && pg_strcasecmp(PREV2_WD, "DICTIONARY") == 0) {
static const char* const listAlterTextSearch3[] = {"OWNER TO", "RENAME TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterTextSearch3);
} else if (pg_strcasecmp(PREV5_WD, "ALTER") == 0 && pg_strcasecmp(PREV4_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV3_WD, "SEARCH") == 0 && pg_strcasecmp(PREV2_WD, "CONFIGURATION") == 0) {
static const char* const listAlterTextSearch4[] = {
"ADD MAPPING FOR", "ALTER MAPPING", "DROP MAPPING FOR", "OWNER TO", "RENAME TO", "SET SCHEMA", NULL
};
COMPLETE_WITH_LIST(listAlterTextSearch4);
}
/* complete ALTER TYPE <foo> with actions */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "TYPE") == 0) {
static const char* const listAlterType[] = {
"ADD ATTRIBUTE", "ADD VALUE", "ALTER ATTRIBUTE", "DROP ATTRIBUTE",
"OWNER TO", "RENAME", "SET SCHEMA", NULL
};
COMPLETE_WITH_LIST(listAlterType);
}
/* complete ALTER TYPE <foo> ADD with actions */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TYPE") == 0 &&
pg_strcasecmp(PREV_WD, "ADD") == 0) {
static const char* const listAlterType[] = {"ATTRIBUTE", "VALUE", NULL};
COMPLETE_WITH_LIST(listAlterType);
}
/* ALTER TYPE <foo> RENAME */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "TYPE") == 0 &&
pg_strcasecmp(PREV_WD, "RENAME") == 0) {
static const char* const listAlterType[] = {"ATTRIBUTE", "TO", NULL};
COMPLETE_WITH_LIST(listAlterType);
}
/* ALTER TYPE xxx RENAME ATTRIBUTE yyy */
else if (pg_strcasecmp(PREV5_WD, "TYPE") == 0 && pg_strcasecmp(PREV3_WD, "RENAME") == 0 &&
pg_strcasecmp(PREV2_WD, "ATTRIBUTE") == 0)
COMPLETE_WITH_CONST("TO");
/*
* If we have TYPE <sth> ALTER/DROP/RENAME ATTRIBUTE, provide list of
* attributes
*/
else if (pg_strcasecmp(PREV4_WD, "TYPE") == 0 &&
(pg_strcasecmp(PREV2_WD, "ALTER") == 0 || pg_strcasecmp(PREV2_WD, "DROP") == 0 ||
pg_strcasecmp(PREV2_WD, "RENAME") == 0) &&
pg_strcasecmp(PREV_WD, "ATTRIBUTE") == 0)
COMPLETE_WITH_ATTR(PREV3_WD, "");
/* ALTER TYPE ALTER ATTRIBUTE <foo> */
else if ((pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "ATTRIBUTE") == 0)) {
COMPLETE_WITH_CONST("TYPE");
}
/* complete ALTER GROUP <foo> */
else if (pg_strcasecmp(PREV3_WD, "ALTER") == 0 && pg_strcasecmp(PREV2_WD, "GROUP") == 0) {
static const char* const listAlterGroup[] = {"ADD USER", "DROP USER", "RENAME TO", NULL};
COMPLETE_WITH_LIST(listAlterGroup);
}
/* complete ALTER GROUP <foo> ADD|DROP with USER */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "GROUP") == 0 &&
(pg_strcasecmp(PREV_WD, "ADD") == 0 || pg_strcasecmp(PREV_WD, "DROP") == 0))
COMPLETE_WITH_CONST("USER");
/* complete {ALTER} GROUP <foo> ADD|DROP USER with a user name */
else if (pg_strcasecmp(PREV4_WD, "GROUP") == 0 &&
(pg_strcasecmp(PREV2_WD, "ADD") == 0 || pg_strcasecmp(PREV2_WD, "DROP") == 0) &&
pg_strcasecmp(PREV_WD, "USER") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
/* BEGIN, END, ABORT */
else if (pg_strcasecmp(PREV_WD, "BEGIN") == 0 || pg_strcasecmp(PREV_WD, "END") == 0 ||
pg_strcasecmp(PREV_WD, "ABORT") == 0) {
static const char* const listTrans[] = {"WORK", "TRANSACTION", NULL};
COMPLETE_WITH_LIST(listTrans);
}
/* COMMIT */
else if (pg_strcasecmp(PREV_WD, "COMMIT") == 0) {
static const char* const listCommit[] = {"WORK", "TRANSACTION", "PREPARED", NULL};
COMPLETE_WITH_LIST(listCommit);
}
/* RELEASE SAVEPOINT */
else if (pg_strcasecmp(PREV_WD, "RELEASE") == 0)
COMPLETE_WITH_CONST("SAVEPOINT");
/* ROLLBACK */
else if (pg_strcasecmp(PREV_WD, "ROLLBACK") == 0) {
static const char* const listTrans[] = {"WORK", "TRANSACTION", "TO SAVEPOINT", "PREPARED", NULL};
COMPLETE_WITH_LIST(listTrans);
}
/* CLUSTER */
/*
* If the previous word is CLUSTER and not without produce list of tables
*/
else if (pg_strcasecmp(PREV_WD, "CLUSTER") == 0 && pg_strcasecmp(PREV2_WD, "WITHOUT") != 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
/* If we have CLUSTER <sth>, then add "USING" */
else if (pg_strcasecmp(PREV2_WD, "CLUSTER") == 0 && pg_strcasecmp(PREV_WD, "ON") != 0) {
COMPLETE_WITH_CONST("USING");
}
/*
* If we have CLUSTER <sth> USING, then add the index as well.
*/
else if (pg_strcasecmp(PREV3_WD, "CLUSTER") == 0 && pg_strcasecmp(PREV_WD, "USING") == 0) {
completion_info_charp = PREV2_WD;
COMPLETE_WITH_QUERY(Query_for_index_of_table);
}
/* COMMENT */
else if (pg_strcasecmp(PREV_WD, "COMMENT") == 0)
COMPLETE_WITH_CONST("ON");
else if (pg_strcasecmp(PREV2_WD, "COMMENT") == 0 && pg_strcasecmp(PREV_WD, "ON") == 0) {
static const char* const listComment[] = {
"CAST", "COLLATION", "CONVERSION", "DATABASE", "EXTENSION",
"FOREIGN DATA WRAPPER", "FOREIGN TABLE",
"SERVER", "INDEX", "LANGUAGE", "RULE", "SCHEMA", "SEQUENCE",
"TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN", "AGGREGATE", "FUNCTION",
"OPERATOR", "TRIGGER", "CONSTRAINT", "DOMAIN", "LARGE OBJECT",
"TABLESPACE", "TEXT SEARCH", "ROLE", NULL
};
COMPLETE_WITH_LIST(listComment);
} else if (pg_strcasecmp(PREV3_WD, "COMMENT") == 0 && pg_strcasecmp(PREV2_WD, "ON") == 0 &&
pg_strcasecmp(PREV_WD, "FOREIGN") == 0) {
static const char* const listTrans2[] = {"DATA WRAPPER", "TABLE", NULL};
COMPLETE_WITH_LIST(listTrans2);
} else if (pg_strcasecmp(PREV4_WD, "COMMENT") == 0 && pg_strcasecmp(PREV3_WD, "ON") == 0 &&
pg_strcasecmp(PREV2_WD, "TEXT") == 0 && pg_strcasecmp(PREV_WD, "SEARCH") == 0) {
static const char* const listTrans2[] = {"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
COMPLETE_WITH_LIST(listTrans2);
} else if (pg_strcasecmp(PREV4_WD, "COMMENT") == 0 && pg_strcasecmp(PREV3_WD, "ON") == 0 &&
pg_strcasecmp(PREV2_WD, "MATERIALIZED") == 0 && pg_strcasecmp(PREV_WD, "VIEW") == 0) {
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
} else if ((pg_strcasecmp(PREV4_WD, "COMMENT") == 0 && pg_strcasecmp(PREV3_WD, "ON") == 0) ||
(pg_strcasecmp(PREV5_WD, "COMMENT") == 0 && pg_strcasecmp(PREV4_WD, "ON") == 0) ||
(pg_strcasecmp(PREV6_WD, "COMMENT") == 0 && pg_strcasecmp(PREV5_WD, "ON") == 0))
COMPLETE_WITH_CONST("IS");
/* COPY */
/*
* If we have COPY [BINARY] (which you'd have to type yourself), offer
* list of tables (Also cover the analogous backslash command)
*/
else if (pg_strcasecmp(PREV_WD, "COPY") == 0 || pg_strcasecmp(PREV_WD, "\\copy") == 0 ||
(pg_strcasecmp(PREV2_WD, "COPY") == 0 && pg_strcasecmp(PREV_WD, "BINARY") == 0))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
/* If we have COPY|BINARY <sth>, complete it with "TO" or "FROM" */
else if ((pg_strcasecmp(PREV2_WD, "COPY") == 0 || pg_strcasecmp(PREV2_WD, "\\copy") == 0 ||
pg_strcasecmp(PREV2_WD, "BINARY") == 0) || ((pg_strcasecmp(PREV3_WD, "COPY") == 0 ||
pg_strcasecmp(PREV3_WD, "\\copy") == 0 || pg_strcasecmp(PREV3_WD, "BINARY") == 0) &&
PREV_WD[strlen(PREV_WD) - 1] == ')')) {
static const char* const listFromTo[] = {"FROM", "TO", NULL};
COMPLETE_WITH_LIST(listFromTo);
}
/* If we have COPY|BINARY <sth> FROM|TO, complete with filename */
else if ((pg_strcasecmp(PREV3_WD, "COPY") == 0 || pg_strcasecmp(PREV3_WD, "\\copy") == 0 ||
pg_strcasecmp(PREV3_WD, "BINARY") == 0) &&
(pg_strcasecmp(PREV_WD, "FROM") == 0 || pg_strcasecmp(PREV_WD, "TO") == 0)) {
completion_charp = "";
matches = completion_matches(text, CompleteFromFiles);
}
else if ((pg_strcasecmp(PREV6_WD, "COPY") == 0 || pg_strcasecmp(PREV6_WD, "\\copy") == 0) &&
(pg_strcasecmp(PREV4_WD, "TO") == 0 || pg_strcasecmp(PREV4_WD, "FROM") == 0) &&
pg_strcasecmp(PREV2_WD, "WITH") == 0 && pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listCopyFromToWith[] = {
"FORMAT", "OIDS", "DELIMITER", "NULL", "HEADER", "FILEHEADER",
"FREEZE", "QUOTE", "ESCAPE", "EOL", "NOESCAPING", "FORCE_QUOTE",
"FORCE_NOT_NULL", "ENCODING", "IGNORE_EXTRA_DATA", "FILL_MISSING_FIELDS",
"COMPATIBLE_ILLEGAL_CHARS", "DATE_FORMAT", "TIME_FORMAT", "TIMESTAMP_FORMAT",
"SMALLDATETIME_FORMAT", NULL
};
COMPLETE_WITH_LIST(listCopyFromToWith);
}
/* Handle COPY|BINARY <sth> FROM|TO filename */
else if ((pg_strcasecmp(PREV4_WD, "COPY") == 0 || pg_strcasecmp(PREV4_WD, "\\copy") == 0 ||
pg_strcasecmp(PREV4_WD, "BINARY") == 0) &&
(pg_strcasecmp(PREV2_WD, "FROM") == 0 || pg_strcasecmp(PREV2_WD, "TO") == 0)) {
static const char* const listCopy[] = {
"BINARY", "OIDS", "NULL", "CSV", "ENCODING", "HEADER", "FILEHEADER",
"FREEZE", "FORCE NOT NULL", "FORCE QUOTE", "QUOTE", "ESCAPE",
"EOL", "IGNORE_EXTRA_DATA", "FILL_MISSING_FIELDS", "FIXED FORMATTER",
"COMPATIBLE_ILLEGAL_CHARS", "DATE_FORMAT", "TIME_FORMAT", "TIMESTAMP_FORMAT",
"SMALLDATETIME_FORMAT", "WITH (", "WITHOUT ESCAPING", NULL
};
COMPLETE_WITH_LIST(listCopy);
}
/* Handle COPY|BINARY <sth> FROM|TO filename CSV */
else if (pg_strcasecmp(PREV_WD, "CSV") == 0 &&
(pg_strcasecmp(PREV3_WD, "FROM") == 0 || pg_strcasecmp(PREV3_WD, "TO") == 0)) {
static const char* const listCsv[] = {"HEADER", "QUOTE", "ESCAPE", "FORCE QUOTE", "FORCE NOT NULL", NULL};
COMPLETE_WITH_LIST(listCsv);
}
/* CREATE CAST */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "CAST") == 0) {
COMPLETE_WITH_CONST("(");
}
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "CAST") == 0 &&
pg_strcasecmp(PREV2_WD, "(") == 0) {
COMPLETE_WITH_CONST("AS");
}
else if (pg_strcasecmp(PREV6_WD, "CREATE") == 0 && pg_strcasecmp(PREV5_WD, "CAST") == 0 &&
pg_strcasecmp(PREV4_WD, "(") == 0 && pg_strcasecmp(PREV2_WD, "AS") == 0) {
COMPLETE_WITH_CONST(")");
}
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "CAST") == 0 &&
pg_strcasecmp(PREV_WD, "(") != 0) {
static const char* const listCreateCastOptions[] = {"WITH FUNCTION", "WITHOUT FUNCTION", "WITH INOUT", NULL};
COMPLETE_WITH_LIST(listCreateCastOptions);
}
/* CREATE DATABASE */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "DATABASE") == 0) {
static const char* const listDatabase[] = {
"WITH", "OWNER", "TEMPLATE", "ENCODING", "LC_COLLATE", "LC_CTYPE",
"DBCOMPATIBILITY", "TABLESPACE", "CONNECTION LIMIT", NULL
};
COMPLETE_WITH_LIST(listDatabase);
} else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "DATABASE") == 0 &&
pg_strcasecmp(PREV_WD, "WITH") == 0) {
static const char* const listDatabaseWith[] = {
"OWNER", "TEMPLATE", "ENCODING", "LC_COLLATE", "LC_CTYPE", "DBCOMPATIBILITY", "TABLESPACE",
"CONNECTION LIMIT", NULL
};
COMPLETE_WITH_LIST(listDatabaseWith);
} else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "DATABASE") == 0 &&
pg_strcasecmp(PREV_WD, "TEMPLATE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_template_databases);
/* CREATE EXTENSION */
/* Complete with available extensions rather than installed ones. */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "EXTENSION") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_available_extensions);
/* CREATE EXTENSION <name> */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "EXTENSION") == 0) {
static const char* const listCreateExtension[] = {"WITH", "SCHEMA", "VERSION", "FROM", NULL};
COMPLETE_WITH_LIST(listCreateExtension);
}
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "EXTENSION") == 0 &&
pg_strcasecmp(PREV_WD, "WITH") == 0) {
static const char* const listCreateExtensionWith[] = {"SCHEMA", "VERSION", "FROM", NULL};
COMPLETE_WITH_LIST(listCreateExtensionWith);
}
/* CREATE FOREIGN */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "FOREIGN") == 0) {
static const char* const listCreateForeign[] = {"DATA WRAPPER", "TABLE", NULL};
COMPLETE_WITH_LIST(listCreateForeign);
}
/* CREATE FOREIGN DATA WRAPPER */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "FOREIGN") == 0 &&
pg_strcasecmp(PREV3_WD, "DATA") == 0 && pg_strcasecmp(PREV2_WD, "WRAPPER") == 0) {
static const char* const listCreateForeignDataWrapper[] = {"HANDLER", "VALIDATOR", NULL};
COMPLETE_WITH_LIST(listCreateForeignDataWrapper);
}
/* CREATE INDEX */
/* First off we complete CREATE UNIQUE with "INDEX" */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "UNIQUE") == 0)
COMPLETE_WITH_CONST("INDEX");
/* If we have CREATE|UNIQUE INDEX, then add "ON" and existing indexes */
else if (pg_strcasecmp(PREV_WD, "INDEX") == 0 &&
(pg_strcasecmp(PREV2_WD, "CREATE") == 0 || pg_strcasecmp(PREV2_WD, "UNIQUE") == 0))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, " UNION SELECT 'ON'"
" UNION SELECT 'CONCURRENTLY'");
/* Complete ... INDEX [<name>] ON with a list of tables */
else if ((pg_strcasecmp(PREV3_WD, "INDEX") == 0 || pg_strcasecmp(PREV2_WD, "INDEX") == 0 ||
pg_strcasecmp(PREV2_WD, "CONCURRENTLY") == 0) &&
pg_strcasecmp(PREV_WD, "ON") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tmf, NULL);
/* If we have CREATE|UNIQUE INDEX <sth> CONCURRENTLY, then add "ON" */
else if ((pg_strcasecmp(PREV3_WD, "INDEX") == 0 || pg_strcasecmp(PREV2_WD, "INDEX") == 0) &&
pg_strcasecmp(PREV_WD, "CONCURRENTLY") == 0)
COMPLETE_WITH_CONST("ON");
/* If we have CREATE|UNIQUE INDEX <sth>, then add "ON" or "CONCURRENTLY" */
else if ((pg_strcasecmp(PREV3_WD, "CREATE") == 0 || pg_strcasecmp(PREV3_WD, "UNIQUE") == 0) &&
pg_strcasecmp(PREV2_WD, "INDEX") == 0) {
static const char* const listCreateIndex[] = {"CONCURRENTLY", "ON", NULL};
COMPLETE_WITH_LIST(listCreateIndex);
}
/*
* Complete INDEX <name> ON <table> with a list of table columns (which
* should really be in parens)
*/
else if ((pg_strcasecmp(PREV4_WD, "INDEX") == 0 || pg_strcasecmp(PREV3_WD, "INDEX") == 0 ||
pg_strcasecmp(PREV3_WD, "CONCURRENTLY") == 0) &&
pg_strcasecmp(PREV2_WD, "ON") == 0) {
static const char* const listCreateIndex2[] = {"(", "USING", NULL};
COMPLETE_WITH_LIST(listCreateIndex2);
} else if ((pg_strcasecmp(PREV5_WD, "INDEX") == 0 || pg_strcasecmp(PREV4_WD, "INDEX") == 0 ||
pg_strcasecmp(PREV4_WD, "CONCURRENTLY") == 0) &&
pg_strcasecmp(PREV3_WD, "ON") == 0 && pg_strcasecmp(PREV_WD, "(") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, "");
/* same if you put in USING */
else if (pg_strcasecmp(PREV5_WD, "ON") == 0 && pg_strcasecmp(PREV3_WD, "USING") == 0 &&
pg_strcasecmp(PREV_WD, "(") == 0)
COMPLETE_WITH_ATTR(PREV4_WD, "");
/* Complete USING with an index method */
else if (pg_strcasecmp(PREV_WD, "USING") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_access_methods);
else if (pg_strcasecmp(PREV4_WD, "ON") == 0 && pg_strcasecmp(PREV2_WD, "USING") == 0 &&
pg_strcasecmp(PREV6_WD, "POLICY") != 0)
COMPLETE_WITH_CONST("(");
/* CREATE OR REPLACE */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "OR") == 0)
COMPLETE_WITH_CONST("REPLACE");
/* CREATE|DROP|ALTER PROCEDURAL|TRUSTED LANGUAGE */
else if ((pg_strcasecmp(PREV2_WD, "CREATE") == 0 || pg_strcasecmp(PREV2_WD, "DROP") == 0 ||
pg_strcasecmp(PREV2_WD, "ALTER") == 0) && (pg_strcasecmp(PREV_WD, "PROCEDURAL") == 0 ||
pg_strcasecmp(PREV_WD, "TRUSTED") == 0))
COMPLETE_WITH_CONST("LANGUAGE");
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "LANGUAGE") == 0) {
static const char* const createLanguage[] = {"HANDLER", "INLINE", "VALIDATOR", NULL};
COMPLETE_WITH_LIST(createLanguage);
}
/* CREATE AGGREGATE xxx (input_data_type) ( */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "AGGREGATE") == 0 &&
PREV2_WD[strlen(PREV2_WD) - 1] == ')' && pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listCreateAggregate[] = {"SFUNC", "STYPE", "FINALFUNC", "INITCOND", "SORTOP", NULL};
COMPLETE_WITH_LIST(listCreateAggregate);
}
/* CREATE AGGREGATE xxx ( */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "AGGREGATE") == 0 &&
pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listCreateAggregateOld[] = {
"BASETYPE", "SFUNC", "STYPE", "FINALFUNC", "INITCOND", "SORTOP", NULL
};
COMPLETE_WITH_LIST(listCreateAggregateOld);
}
/* CREATE TYPE xxx */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "TYPE") == 0) {
static const char* const listCreateType[] = {"AS", "AS ENUM", NULL};
COMPLETE_WITH_LIST(listCreateType);
}
/* CREATE TYPE xxx ( */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "TYPE") == 0 &&
pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listCreateTypeArgs[] = {
"INPUT", "OUTPUT", "RECEIVE", "SEND", "TYPMOD_IN", "TYPMOD_OUT",
"ANALYZE", "INTERNALLENGTH", "PASSEDBYVALUE", "ALIGNMENT", "STORAGE",
"LIKE", "CATEGORY", "PREFERRED", "DEFAULT", "ELEMENT", "DELIMITER",
"COLLATABLE", NULL
};
COMPLETE_WITH_LIST(listCreateTypeArgs);
}
/* CREATE OPERATOR xxx ( */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "OPERATOR") == 0 &&
pg_strcasecmp(PREV_WD, "(") == 0) {
static const char* const listCreateTypeArgs[] = {
"PROCEDURE", "LEFTARG", "RIGHTARG", "COMMUTATOR", "NEGATOR", "RESTRICT",
"JOIN", "HASHES", "MERGES", NULL
};
COMPLETE_WITH_LIST(listCreateTypeArgs);
}
/* ALTER OPERATOR xxx (...) */
else if (pg_strcasecmp(PREV4_WD, "ALTER") == 0 && pg_strcasecmp(PREV3_WD, "OPERATOR") == 0 &&
PREV_WD[strlen(PREV_WD) - 1] == ')') {
static const char* const listAlterOperator[] = {"OWNER TO", "SET SCHEMA", NULL};
COMPLETE_WITH_LIST(listAlterOperator);
}
/* CREATE POLICY */
/* Complete "CREATE ROW LEVEL SECURITY POLICY */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "ROW") == 0 &&
pg_strcasecmp(PREV2_WD, "LEVEL") == 0 && pg_strcasecmp(PREV_WD, "SECURITY") == 0)
COMPLETE_WITH_CONST("POLICY");
/* Complete "CREATE POLICY <name> ON" */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "POLICY") == 0)
COMPLETE_WITH_CONST("ON");
/* Complete "CREATE POLICY <name> ON <table>" */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
/* Complete "CREATE POLICY <name> ON <table> AS|FOR|TO|USING" */
else if ((pg_strcasecmp(PREV5_WD, "CREATE") == 0 || pg_strcasecmp(PREV8_WD, "CREATE") == 0) &&
pg_strcasecmp(PREV4_WD, "POLICY") == 0 && pg_strcasecmp(PREV2_WD, "ON") == 0) {
static const char* const createPolicyOn[] = {"AS", "FOR", "TO", "USING (", NULL};
COMPLETE_WITH_LIST(createPolicyOn);
}
/* CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE */
else if (pg_strcasecmp(PREV6_WD, "CREATE") == 0 && pg_strcasecmp(PREV5_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV3_WD, "ON") == 0 && pg_strcasecmp(PREV_WD, "AS") == 0) {
static const char* const createPolicyOnAs[] = {"PERMISSIVE", "RESTRICTIVE", NULL};
COMPLETE_WITH_LIST(createPolicyOnAs);
}
/*
* CREATE POLICY <name> ON <table> AS PERMISSIVE|RESTRICTIVE
* FOR|TO|USING
*/
else if (pg_strcasecmp(PREV7_WD, "CREATE") == 0 && pg_strcasecmp(PREV6_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV4_WD, "ON") == 0 && pg_strcasecmp(PREV2_WD, "AS") == 0) {
static const char* const createPolicyOnAsSth[] = {"FOR", "TO", "USING", NULL};
COMPLETE_WITH_LIST(createPolicyOnAsSth);
}
/* CREATE POLICY <name> ON <table> FOR ALL|SELECT|INSERT|UPDATE|DELETE */
else if (pg_strcasecmp(PREV6_WD, "CREATE") == 0 && pg_strcasecmp(PREV5_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV3_WD, "ON") == 0 && pg_strcasecmp(PREV_WD, "FOR") == 0) {
static const char* const createPolicyOnFor[] = {"ALL", "SELECT", "INSERT", "UPDATE", "DELETE", NULL};
COMPLETE_WITH_LIST(createPolicyOnFor);
}
/* Complete "CREATE POLICY <name> ON <table> FOR INSERT TO" */
else if (pg_strcasecmp(PREV7_WD, "CREATE") == 0 && pg_strcasecmp(PREV6_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV4_WD, "ON") == 0 && pg_strcasecmp(PREV2_WD, "FOR") == 0 &&
pg_strcasecmp(PREV_WD, "INSERT") == 0)
COMPLETE_WITH_CONST("TO");
/* Complete "CREATE POLICY <name> ON <table> FOR SELECT|DELETE|ALL|UPDATE TO|USING" */
else if (pg_strcasecmp(PREV7_WD, "CREATE") == 0 && pg_strcasecmp(PREV6_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV4_WD, "ON") == 0 && pg_strcasecmp(PREV2_WD, "FOR") == 0 &&
(pg_strcasecmp(PREV_WD, "SELECT") == 0 || pg_strcasecmp(PREV_WD, "DELETE") == 0 ||
pg_strcasecmp(PREV_WD, "ALL") == 0 || pg_strcasecmp(PREV_WD, "UPDATE") == 0)) {
static const char* const createPolicyOnForSd[] = {"TO", "USING (", NULL};
COMPLETE_WITH_LIST(createPolicyOnForSd);
}
/* Complete "CREATE POLICY <name> ON <table> TO <role>" */
else if (pg_strcasecmp(PREV6_WD, "CREATE") == 0 && pg_strcasecmp(PREV5_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV3_WD, "ON") == 0 && pg_strcasecmp(PREV_WD, "TO") == 0) {
COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
}
/* Complete "CREATE POLICY <name> ON <table> USING (" */
else if (pg_strcasecmp(PREV6_WD, "CREATE") == 0 && pg_strcasecmp(PREV5_WD, "POLICY") == 0 &&
pg_strcasecmp(PREV3_WD, "ON") == 0 && pg_strcasecmp(PREV_WD, "USING") == 0) {
COMPLETE_WITH_CONST("(");
}
/* CREATE PUBLICATION */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "PUBLICATION") == 0) {
static const char * const createPub[] = {"FOR TABLE", "FOR ALL TABLES", "WITH (", NULL};
COMPLETE_WITH_LIST(createPub);
}
/* CREATE PUBLICATION <name> FOR */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "PUBLICATION") == 0 &&
pg_strcasecmp(PREV_WD, "FOR") == 0) {
static const char * const createPub2[] = {"TABLE", "ALL TABLES", NULL};
COMPLETE_WITH_LIST(createPub2);
}
/* CREATE PUBLICATION <name> FOR TABLE <table>, ... */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "PUBLICATION") == 0 &&
pg_strcasecmp(PREV2_WD, "FOR") == 0 && pg_strcasecmp(PREV_WD, "TABLE") == 0) {
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
}
/* CREATE SUBSCRIPTION */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "SUBSCRIPTION") == 0) {
COMPLETE_WITH_CONST("CONNECTION");
}
/* CREATE RULE */
/* Complete "CREATE RULE <sth>" with "AS" */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "RULE") == 0)
COMPLETE_WITH_CONST("AS");
/* Complete "CREATE RULE <sth> AS with "ON" */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "RULE") == 0 &&
pg_strcasecmp(PREV_WD, "AS") == 0)
COMPLETE_WITH_CONST("ON");
/* Complete "RULE * AS ON" with SELECT|UPDATE|DELETE|INSERT */
else if (pg_strcasecmp(PREV4_WD, "RULE") == 0 && pg_strcasecmp(PREV2_WD, "AS") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0) {
static const char* const ruleEvents[] = {"SELECT", "UPDATE", "INSERT", "DELETE", NULL};
COMPLETE_WITH_LIST(ruleEvents);
}
/* Complete "AS ON <sth with a 'T' :)>" with a "TO" */
else if (pg_strcasecmp(PREV3_WD, "AS") == 0 && pg_strcasecmp(PREV2_WD, "ON") == 0 &&
(pg_toupper((unsigned char)PREV_WD[4]) == 'T' || pg_toupper((unsigned char)PREV_WD[5]) == 'T'))
COMPLETE_WITH_CONST("TO");
/* Complete "AS ON <sth> TO" with a table name */
else if (pg_strcasecmp(PREV4_WD, "AS") == 0 && pg_strcasecmp(PREV3_WD, "ON") == 0 &&
pg_strcasecmp(PREV_WD, "TO") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
else if ((pg_strcasecmp(PREV4_WD, "CREATE") == 0 || pg_strcasecmp(PREV3_WD, "CREATE") == 0) &&
pg_strcasecmp(PREV2_WD, "SEQUENCE") == 0) {
static const char* const listCreateSequence[] = {
"INCREMENT", "MINVALUE", "NOMINVALUE", "MAXVALUE", "NOMAXVALUE",
"START WITH", "NO", "CACHE", "CYCLE", "NOCYCLE", "OWNED BY", NULL
};
COMPLETE_WITH_LIST(listCreateSequence);
}
else if ((pg_strcasecmp(PREV4_WD, "CREATE") == 0 || pg_strcasecmp(PREV3_WD, "CREATE") == 0) &&
pg_strcasecmp(PREV3_WD, "SEQUENCE") == 0 && pg_strcasecmp(PREV_WD, "NO") == 0) {
static const char* const listCreateSequencE2[] = {"MINVALUE", "MAXVALUE", "CYCLE", NULL};
COMPLETE_WITH_LIST(listCreateSequencE2);
}
/* CREATE SERVER <name> */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "SERVER") == 0) {
static const char* const listCreateServer[] = {"TYPE", "VERSION", "FOREIGN DATA WRAPPER", NULL};
COMPLETE_WITH_LIST(listCreateServer);
}
else if (pg_strcasecmp(PREV7_WD, "CREATE") == 0 && pg_strcasecmp(PREV6_WD, "SERVER") == 0 &&
pg_strcasecmp(PREV4_WD, "foreign") == 0 && pg_strcasecmp(PREV3_WD, "data") == 0 &&
pg_strcasecmp(PREV2_WD, "wrapper") == 0)
COMPLETE_WITH_CONST("OPTIONS");
/* CREATE TABLE */
/* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 &&
(pg_strcasecmp(PREV_WD, "TEMP") == 0 || pg_strcasecmp(PREV_WD, "TEMPORARY") == 0)) {
static const char* const listTemp[] = {"SEQUENCE", "TABLE", "VIEW", NULL};
COMPLETE_WITH_LIST(listTemp);
}
/* Complete "CREATE UNLOGGED" with TABLE */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "UNLOGGED") == 0) {
COMPLETE_WITH_CONST("TABLE");
}
else if ((pg_strcasecmp(PREV5_WD, "CREATE") == 0 || pg_strcasecmp(PREV4_WD, "CREATE") == 0) &&
pg_strcasecmp(PREV3_WD, "TABLE") == 0 && PREV_WD[strlen(PREV_WD) - 1] == ')') {
static const char* const listCreateTable[] = {
"WITH (", "ON COMMIT", "COMPRESS", "NOCOMPRESS", "TABLESPACE", "PARTITION BY", NULL
};
COMPLETE_WITH_LIST(listCreateTable);
}
else if ((pg_strcasecmp(PREV7_WD, "CREATE") == 0 || pg_strcasecmp(PREV6_WD, "CREATE") == 0) &&
pg_strcasecmp(PREV5_WD, "TABLE") == 0 && PREV3_WD[strlen(PREV3_WD) - 1] == ')' &&
pg_strcasecmp(PREV2_WD, "WITH") == 0 && pg_strcasecmp(PREV_WD, "(") == 0 ) {
static const char* const listCreateTableWith[] = {
"FILLFACTOR", "ORIENTATION", "COMPRESSION", "MAX_BATCHROW", "PARTIAL_CLUSTER_ROWS",
"DELTAROW_THRESHOLD", NULL
};
COMPLETE_WITH_LIST(listCreateTableWith);
}
/* CREATE TABLESPACE */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "TABLESPACE") == 0) {
static const char* const listCreateTablespace[] = {"OWNER", "LOCATION", "RELATIVE LOCATION", NULL};
COMPLETE_WITH_LIST(listCreateTablespace);
}
/* Complete CREATE TABLESPACE name OWNER name with "LOCATION" */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "TABLESPACE") == 0 &&
pg_strcasecmp(PREV2_WD, "OWNER") == 0) {
static const char* const listCreateTablespaceOwner[] = {"LOCATION", "RELATIVE LOCATION", NULL};
COMPLETE_WITH_LIST(listCreateTablespaceOwner);
}
/* CREATE TEXT SEARCH */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV_WD, "SEARCH") == 0) {
static const char* const listCreateTextSearch[] = {"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
COMPLETE_WITH_LIST(listCreateTextSearch);
} else if (pg_strcasecmp(PREV4_WD, "TEXT") == 0 && pg_strcasecmp(PREV3_WD, "SEARCH") == 0 &&
pg_strcasecmp(PREV2_WD, "CONFIGURATION") == 0)
COMPLETE_WITH_CONST("(");
/* CREATE TRIGGER */
/* complete CREATE TRIGGER <name> with BEFORE,AFTER */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "TRIGGER") == 0) {
static const char* const listCreateTrigger[] = {"BEFORE", "AFTER", "INSTEAD OF", NULL};
COMPLETE_WITH_LIST(listCreateTrigger);
}
/* complete CREATE TRIGGER <name> BEFORE,AFTER with an event */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "TRIGGER") == 0 &&
(pg_strcasecmp(PREV_WD, "BEFORE") == 0 || pg_strcasecmp(PREV_WD, "AFTER") == 0)) {
static const char* const listCreateTriggerEvents[] = {"INSERT", "DELETE", "UPDATE", "TRUNCATE", NULL};
COMPLETE_WITH_LIST(listCreateTriggerEvents);
}
/* complete CREATE TRIGGER <name> INSTEAD OF with an event */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "TRIGGER") == 0 &&
pg_strcasecmp(PREV2_WD, "INSTEAD") == 0 && pg_strcasecmp(PREV_WD, "OF") == 0) {
static const char* const listCreateTriggerEvents[] = {"INSERT", "DELETE", "UPDATE", NULL};
COMPLETE_WITH_LIST(listCreateTriggerEvents);
}
/* complete CREATE TRIGGER <name> BEFORE,AFTER sth with OR,ON */
else if ((pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "TRIGGER") == 0 &&
(pg_strcasecmp(PREV2_WD, "BEFORE") == 0 || pg_strcasecmp(PREV2_WD, "AFTER") == 0)) ||
(pg_strcasecmp(PREV5_WD, "TRIGGER") == 0 && pg_strcasecmp(PREV3_WD, "INSTEAD") == 0 &&
pg_strcasecmp(PREV2_WD, "OF") == 0)) {
static const char* const listCreateTrigger2[] = {"ON", "OR", NULL};
COMPLETE_WITH_LIST(listCreateTrigger2);
}
/*
* complete CREATE TRIGGER <name> BEFORE,AFTER event ON with a list of
* tables
*/
else if (pg_strcasecmp(PREV5_WD, "TRIGGER") == 0 &&
(pg_strcasecmp(PREV3_WD, "BEFORE") == 0 || pg_strcasecmp(PREV3_WD, "AFTER") == 0) &&
pg_strcasecmp(PREV_WD, "ON") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
/* complete CREATE TRIGGER ... INSTEAD OF event ON with a list of views */
else if (pg_strcasecmp(PREV4_WD, "INSTEAD") == 0 && pg_strcasecmp(PREV3_WD, "OF") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
/* complete CREATE TRIGGER ... EXECUTE with PROCEDURE */
else if (pg_strcasecmp(PREV_WD, "EXECUTE") == 0 && PREV2_WD[0] != '\0')
COMPLETE_WITH_CONST("DIRECT");
/* CREATE ROLE,USER,GROUP <name> */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 &&
!(pg_strcasecmp(PREV2_WD, "USER") == 0 && pg_strcasecmp(PREV_WD, "MAPPING") == 0) &&
(pg_strcasecmp(PREV2_WD, "ROLE") == 0 || pg_strcasecmp(PREV2_WD, "GROUP") == 0 ||
pg_strcasecmp(PREV2_WD, "USER") == 0)) {
static const char* const listCreateRole[] = {
"ADMIN", "AUDITADMIN", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
"CREATEUSER", "DEFAULT TABLESPACE", "ENCRYPTED", "IDENTIFIED BY", "IN",
"IN GROUP", "IN ROLE", "INDEPENDENT", "INHERIT", "LOGIN", "MONADMIN",
"NOAUDITADMIN", "NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER", "NODE GROUP",
"NOINDEPENDENT", "NOINHERIT", "NOLOGIN", "NOMONADMIN", "NOOPRADMIN",
"NOPERSISTENCE", "NOPOLADMIN", "NOREPLICATION", "NOSYSADMIN",
"NOUSEFT", "NOVCADMIN", "OPRADMIN", "PASSWORD", "PERM SPACE", "PERSISTENCE",
"PGUSER", "POLADMIN", "PROFILE", "PROFILE DEFAULT", "REPLICATION",
"RESOURCE POOL", "ROLE", "SPILL SPACE", "SYSADMIN", "SYSID",
"TEMP SPACE", "UNENCRYPTED", "USEFT", "USER", "USER GROUP", "VALID",
"VCADMIN", "WITH", NULL
};
COMPLETE_WITH_LIST(listCreateRole);
}
/* CREATE ROLE,USER,GROUP <name> VALID*/
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 &&
!(pg_strcasecmp(PREV3_WD, "USER") == 0 && pg_strcasecmp(PREV2_WD, "MAPPING") == 0) &&
(pg_strcasecmp(PREV3_WD, "ROLE") == 0 || pg_strcasecmp(PREV3_WD, "GROUP") == 0 ||
pg_strcasecmp(PREV3_WD, "USER") == 0) && pg_strcasecmp(PREV_WD, "VALID") == 0) {
static const char* const listCreateRoleValid[] = {"BEGIN", "UNTIL", NULL};
COMPLETE_WITH_LIST(listCreateRoleValid);
}
/* CREATE ROLE,USER,GROUP <name> WITH */
else if ((pg_strcasecmp(PREV4_WD, "CREATE") == 0 &&
(pg_strcasecmp(PREV3_WD, "ROLE") == 0 || pg_strcasecmp(PREV3_WD, "GROUP") == 0 ||
pg_strcasecmp(PREV3_WD, "USER") == 0) &&
pg_strcasecmp(PREV_WD, "WITH") == 0)) {
/* Similar to the above, but don't complete "WITH" again. */
static const char* const listCreateRoleWith[] = {
"ADMIN", "AUDITADMIN", "CONNECTION LIMIT", "CREATEDB", "CREATEROLE",
"CREATEUSER", "DEFAULT TABLESPACE", "ENCRYPTED", "IDENTIFIED BY", "IN",
"IN GROUP", "IN ROLE", "INDEPENDENT", "INHERIT", "LOGIN", "MONADMIN",
"NOAUDITADMIN", "NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER", "NODE GROUP",
"NOINDEPENDENT", "NOINHERIT", "NOLOGIN", "NOMONADMIN", "NOOPRADMIN",
"NOPERSISTENCE", "NOPOLADMIN", "NOREPLICATION", "NOSYSADMIN",
"NOUSEFT", "NOVCADMIN", "OPRADMIN", "PASSWORD", "PERM SPACE", "PERSISTENCE",
"PGUSER", "POLADMIN", "PROFILE", "PROFILE DEFAULT", "REPLICATION",
"RESOURCE POOL", "ROLE", "SPILL SPACE", "SYSADMIN", "SYSID",
"TEMP SPACE", "UNENCRYPTED", "USEFT", "USER", "USER GROUP", "VALID",
"VCADMIN", NULL
};
COMPLETE_WITH_LIST(listCreateRoleWith);
}
/* CREATE ROLE,USER,GROUP <name> WITH */
else if ((pg_strcasecmp(PREV5_WD, "CREATE") == 0 &&
(pg_strcasecmp(PREV4_WD, "ROLE") == 0 || pg_strcasecmp(PREV4_WD, "GROUP") == 0 ||
pg_strcasecmp(PREV4_WD, "USER") == 0) &&
pg_strcasecmp(PREV2_WD, "WITH") == 0) && pg_strcasecmp(PREV_WD, "VALID") == 0) {
/* Similar to the above, but don't complete "WITH" again. */
static const char* const listCreateRoleWithValid[] = {"BEGIN", "UNTIL", NULL};
COMPLETE_WITH_LIST(listCreateRoleWithValid);
}
/*
* complete CREATE ROLE,USER,GROUP <name> ENCRYPTED,UNENCRYPTED with
* PASSWORD
*/
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 &&
(pg_strcasecmp(PREV3_WD, "ROLE") == 0 || pg_strcasecmp(PREV3_WD, "GROUP") == 0 ||
pg_strcasecmp(PREV3_WD, "USER") == 0) &&
(pg_strcasecmp(PREV_WD, "ENCRYPTED") == 0 || pg_strcasecmp(PREV_WD, "UNENCRYPTED") == 0)) {
static const char* const listCreateRoleWithEncrypted[] = {"PASSWORD", "IDENTIFIED BY", NULL};
COMPLETE_WITH_LIST(listCreateRoleWithEncrypted);
}
/* complete CREATE ROLE,USER,GROUP <name> IN with ROLE,GROUP */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 &&
(pg_strcasecmp(PREV3_WD, "ROLE") == 0 || pg_strcasecmp(PREV3_WD, "GROUP") == 0 ||
pg_strcasecmp(PREV3_WD, "USER") == 0) &&
pg_strcasecmp(PREV_WD, "IN") == 0) {
static const char* const listCreateRole3[] = {"GROUP", "ROLE", NULL};
COMPLETE_WITH_LIST(listCreateRole3);
}
/* CREATE VIEW */
/* Complete CREATE VIEW <name> with AS */
else if (pg_strcasecmp(PREV3_WD, "CREATE") == 0 && pg_strcasecmp(PREV2_WD, "VIEW") == 0)
COMPLETE_WITH_CONST("AS");
/* Complete "CREATE VIEW <sth> AS with "SELECT" */
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "VIEW") == 0 &&
pg_strcasecmp(PREV_WD, "AS") == 0)
COMPLETE_WITH_CONST("SELECT");
/* CREATE MATERIALIZED VIEW */
else if (pg_strcasecmp(PREV2_WD, "CREATE") == 0 && pg_strcasecmp(PREV_WD, "MATERIALIZED") == 0)
COMPLETE_WITH_CONST("VIEW");
/* Complete CREATE MATERIALIZED VIEW <name> with AS|TABLESPACE */
else if ((pg_strcasecmp(PREV5_WD, "CREATE") == 0 || pg_strcasecmp(PREV4_WD, "CREATE") == 0) &&
pg_strcasecmp(PREV3_WD, "MATERIALIZED") == 0 && pg_strcasecmp(PREV2_WD, "VIEW") == 0) {
static const char* const listCreateMaterializedView[] = {"AS", "TABLESPACE", NULL};
COMPLETE_WITH_LIST(listCreateMaterializedView);
}
/* Complete "CREATE MATERIALIZED VIEW <sth> AS with "SELECT" */
else if (pg_strcasecmp(PREV5_WD, "CREATE") == 0 && pg_strcasecmp(PREV4_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV3_WD, "VIEW") == 0 && pg_strcasecmp(PREV_WD, "AS") == 0)
COMPLETE_WITH_CONST("SELECT");
/* DECLARE */
else if (pg_strcasecmp(PREV2_WD, "DECLARE") == 0) {
static const char* const listDeclare[] = {"BINARY", "INSENSITIVE", "SCROLL", "NO SCROLL", "CURSOR", NULL};
COMPLETE_WITH_LIST(listDeclare);
}
/* CURSOR */
else if (pg_strcasecmp(PREV2_WD, "CURSOR") == 0) {
static const char* const listDeclareCursor[] = {
"BINARY", "SCROLL", "NO SCROLL","INSENSITIVE","FOR", NULL
};
COMPLETE_WITH_LIST(listDeclareCursor);
}
/* DELETE */
/*
* Complete DELETE with FROM (only if the word before that is not "ON"
* (cf. rules) or "BEFORE" or "AFTER" (cf. triggers) or GRANT)
*/
else if (pg_strcasecmp(PREV_WD, "DELETE") == 0 &&
!(pg_strcasecmp(PREV2_WD, "ON") == 0 || pg_strcasecmp(PREV2_WD, "GRANT") == 0 ||
pg_strcasecmp(PREV2_WD, "BEFORE") == 0 || pg_strcasecmp(PREV2_WD, "AFTER") == 0))
COMPLETE_WITH_CONST("FROM");
/* Complete DELETE FROM with a list of tables */
else if (pg_strcasecmp(PREV2_WD, "DELETE") == 0 && pg_strcasecmp(PREV_WD, "FROM") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_deletables, NULL);
/* Complete DELETE FROM <table> */
else if (pg_strcasecmp(PREV3_WD, "DELETE") == 0 && pg_strcasecmp(PREV2_WD, "FROM") == 0) {
static const char* const listDelete[] = {"USING", "WHERE", "SET", NULL};
COMPLETE_WITH_LIST(listDelete);
}
/* XXX: implement tab completion for DELETE ... USING */
/* DISCARD */
else if (pg_strcasecmp(PREV_WD, "DISCARD") == 0) {
static const char* const listDiscard[] = {"ALL", "PLANS", "TEMP", NULL};
COMPLETE_WITH_LIST(listDiscard);
}
/* DO */
/*
* Complete DO with LANGUAGE.
*/
else if (pg_strcasecmp(PREV_WD, "DO") == 0) {
static const char* const listDo[] = {"LANGUAGE", NULL};
COMPLETE_WITH_LIST(listDo);
}
/* DROP (when not the previous word) */
/* DROP AGGREGATE */
else if (pg_strcasecmp(PREV3_WD, "DROP") == 0 && pg_strcasecmp(PREV2_WD, "AGGREGATE") == 0)
COMPLETE_WITH_CONST("(");
/* DROP object with CASCADE / RESTRICT */
else if ((pg_strcasecmp(PREV3_WD, "DROP") == 0 && (pg_strcasecmp(PREV2_WD, "COLLATION") == 0 ||
pg_strcasecmp(PREV2_WD, "CONVERSION") == 0 || pg_strcasecmp(PREV2_WD, "DOMAIN") == 0 ||
pg_strcasecmp(PREV2_WD, "EXTENSION") == 0 || pg_strcasecmp(PREV2_WD, "FUNCTION") == 0 ||
pg_strcasecmp(PREV2_WD, "INDEX") == 0 || pg_strcasecmp(PREV2_WD, "LANGUAGE") == 0 ||
pg_strcasecmp(PREV2_WD, "PUBLICATION") == 0 ||
pg_strcasecmp(PREV2_WD, "SCHEMA") == 0 || pg_strcasecmp(PREV2_WD, "SEQUENCE") == 0 ||
pg_strcasecmp(PREV2_WD, "SERVER") == 0 || pg_strcasecmp(PREV2_WD, "SUBSCRIPTION") == 0 ||
pg_strcasecmp(PREV2_WD, "TABLE") == 0 ||
pg_strcasecmp(PREV2_WD, "TYPE") == 0 || pg_strcasecmp(PREV2_WD, "VIEW") == 0 ||
pg_strcasecmp(PREV2_WD, "USER") == 0)) ||
(pg_strcasecmp(PREV4_WD, "DROP") == 0 && pg_strcasecmp(PREV3_WD, "AGGREGATE") == 0 &&
PREV_WD[strlen(PREV_WD) - 1] == ')') ||
(pg_strcasecmp(PREV5_WD, "DROP") == 0 && pg_strcasecmp(PREV4_WD, "FOREIGN") == 0 &&
pg_strcasecmp(PREV3_WD, "DATA") == 0 && pg_strcasecmp(PREV2_WD, "WRAPPER") == 0) ||
(pg_strcasecmp(PREV5_WD, "DROP") == 0 && pg_strcasecmp(PREV4_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV3_WD, "SEARCH") == 0 &&
(pg_strcasecmp(PREV2_WD, "CONFIGURATION") == 0 || pg_strcasecmp(PREV2_WD, "DICTIONARY") == 0 ||
pg_strcasecmp(PREV2_WD, "PARSER") == 0 || pg_strcasecmp(PREV2_WD, "TEMPLATE") == 0))) {
if (pg_strcasecmp(PREV3_WD, "DROP") == 0 && pg_strcasecmp(PREV2_WD, "FUNCTION") == 0) {
COMPLETE_WITH_CONST("(");
} else {
static const char* const listDropCr[] = {"CASCADE", "RESTRICT", NULL};
COMPLETE_WITH_LIST(listDropCr);
}
} else if (pg_strcasecmp(PREV2_WD, "DROP") == 0 && pg_strcasecmp(PREV_WD, "FOREIGN") == 0) {
static const char* const dropCreateForeign[] = {"DATA WRAPPER", "TABLE", NULL};
COMPLETE_WITH_LIST(dropCreateForeign);
/* DROP MATERIALIZED VIEW */
} else if (pg_strcasecmp(PREV2_WD, "DROP") == 0 && pg_strcasecmp(PREV_WD, "MATERIALIZED") == 0) {
COMPLETE_WITH_CONST("VIEW");
} else if (pg_strcasecmp(PREV3_WD, "DROP") == 0 && pg_strcasecmp(PREV2_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV_WD, "VIEW") == 0) {
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
} else if (pg_strcasecmp(PREV4_WD, "DROP") == 0 &&
(pg_strcasecmp(PREV3_WD, "AGGREGATE") == 0 || pg_strcasecmp(PREV3_WD, "FUNCTION") == 0) &&
pg_strcasecmp(PREV_WD, "(") == 0) {
size_t tmpLength = strlen(Query_for_list_of_arguments) + strlen(PREV2_WD);
char *tmpBuf = (char *)pg_malloc(tmpLength);
int rc = sprintf_s(tmpBuf, tmpLength, Query_for_list_of_arguments, PREV2_WD);
securec_check_ss_c(rc,"","");
COMPLETE_WITH_QUERY(tmpBuf);
free(tmpBuf);
}
/* DROP OWNED BY */
else if (pg_strcasecmp(PREV2_WD, "DROP") == 0 && pg_strcasecmp(PREV_WD, "OWNED") == 0)
COMPLETE_WITH_CONST("BY");
else if (pg_strcasecmp(PREV3_WD, "DROP") == 0 && pg_strcasecmp(PREV2_WD, "OWNED") == 0 &&
pg_strcasecmp(PREV_WD, "BY") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
else if (pg_strcasecmp(PREV3_WD, "DROP") == 0 && pg_strcasecmp(PREV2_WD, "TEXT") == 0 &&
pg_strcasecmp(PREV_WD, "SEARCH") == 0) {
static const char* const listAlterTextSearch[] = {"CONFIGURATION", "DICTIONARY", "PARSER", "TEMPLATE", NULL};
COMPLETE_WITH_LIST(listAlterTextSearch);
}
/* DROP TRIGGER */
else if (pg_strcasecmp(PREV3_WD, "DROP") == 0 && pg_strcasecmp(PREV2_WD, "TRIGGER") == 0)
COMPLETE_WITH_CONST("ON");
else if (pg_strcasecmp(PREV4_WD, "DROP") == 0 && pg_strcasecmp(PREV3_WD, "TRIGGER") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0) {
completion_info_charp = PREV2_WD;
COMPLETE_WITH_QUERY(Query_for_list_of_tables_for_trigger);
}
else if (pg_strcasecmp(PREV5_WD, "DROP") == 0 && pg_strcasecmp(PREV4_WD, "TRIGGER") == 0 &&
pg_strcasecmp(PREV2_WD, "ON") == 0) {
static const char* const listDropTriggerOn[] = {"CASCADE", "RESTRICT", NULL};
COMPLETE_WITH_LIST(listDropTriggerOn);
}
/* EXECUTE, but not EXECUTE embedded in other commands */
else if (pg_strcasecmp(PREV_WD, "EXECUTE") == 0 && PREV2_WD[0] == '\0')
COMPLETE_WITH_QUERY(Query_for_list_of_prepared_statements);
/* EXPLAIN */
/*
* Complete EXPLAIN [ANALYZE] [VERBOSE] with list of EXPLAIN-able commands
*/
else if (pg_strcasecmp(PREV_WD, "EXPLAIN") == 0) {
static const char* const listExplain[] = {
"SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE", "ANALYZE", "VERBOSE",
"COSTS", "CPU", "DETAIL", "NODES", "NUM_NODES", "BUFFERS", "TIMING",
"PLAN", "FORMAT", "ANALYSE", "PERFORMANCE", NULL
};
COMPLETE_WITH_LIST(listExplain);
} else if (pg_strcasecmp(PREV2_WD, "EXPLAIN") == 0 && pg_strcasecmp(PREV_WD, "ANALYZE") == 0) {
static const char* const listExplain[] = {"SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE", "VERBOSE", NULL};
COMPLETE_WITH_LIST(listExplain);
} else if ((pg_strcasecmp(PREV2_WD, "EXPLAIN") == 0 && pg_strcasecmp(PREV_WD, "VERBOSE") == 0) ||
(pg_strcasecmp(PREV3_WD, "EXPLAIN") == 0 && pg_strcasecmp(PREV2_WD, "ANALYZE") == 0 &&
pg_strcasecmp(PREV_WD, "VERBOSE") == 0)) {
static const char* const listExplain[] = {"SELECT", "INSERT", "DELETE", "UPDATE", "DECLARE", NULL};
COMPLETE_WITH_LIST(listExplain);
}
/* FETCH && MOVE */
/* Complete FETCH with one of FORWARD, BACKWARD, RELATIVE */
else if (pg_strcasecmp(PREV_WD, "FETCH") == 0 || pg_strcasecmp(PREV_WD, "MOVE") == 0) {
static const char* const listFetch1[] = {"ABSOLUTE", "BACKWARD", "FORWARD", "RELATIVE", NULL};
COMPLETE_WITH_LIST(listFetch1);
}
/* Complete FETCH <sth> with one of ALL, NEXT, PRIOR */
else if (pg_strcasecmp(PREV2_WD, "FETCH") == 0 || pg_strcasecmp(PREV2_WD, "MOVE") == 0) {
static const char* const list_FETCH2[] = {"ALL", "NEXT", "PRIOR", NULL};
COMPLETE_WITH_LIST(list_FETCH2);
}
/*
* Complete FETCH <sth1> <sth2> with "FROM" or "IN". These are equivalent,
* but we may as well tab-complete both: perhaps some users prefer one
* variant or the other.
*/
else if (pg_strcasecmp(PREV3_WD, "FETCH") == 0 || pg_strcasecmp(PREV3_WD, "MOVE") == 0) {
static const char* const listFromin[] = {"FROM", "IN", NULL};
COMPLETE_WITH_LIST(listFromin);
}
/* FOREIGN DATA WRAPPER */
/* applies in ALTER/DROP FDW and in CREATE SERVER */
else if (pg_strcasecmp(PREV4_WD, "CREATE") != 0 && pg_strcasecmp(PREV3_WD, "FOREIGN") == 0 &&
pg_strcasecmp(PREV2_WD, "DATA") == 0 && pg_strcasecmp(PREV_WD, "WRAPPER") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
/* FOREIGN TABLE */
else if (pg_strcasecmp(PREV3_WD, "CREATE") != 0 && pg_strcasecmp(PREV2_WD, "FOREIGN") == 0 &&
pg_strcasecmp(PREV_WD, "TABLE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_foreign_tables, NULL);
/* GRANT && REVOKE */
/* Complete GRANT/REVOKE with a list of roles and privileges */
else if (pg_strcasecmp(PREV_WD, "GRANT") == 0 || pg_strcasecmp(PREV_WD, "REVOKE") == 0) {
COMPLETE_WITH_QUERY(Query_for_list_of_roles " UNION SELECT 'SELECT'"
" UNION SELECT 'INSERT'"
" UNION SELECT 'UPDATE'"
" UNION SELECT 'DELETE'"
" UNION SELECT 'TRUNCATE'"
" UNION SELECT 'REFERENCES'"
" UNION SELECT 'TRIGGER'"
" UNION SELECT 'CREATE'"
" UNION SELECT 'CONNECT'"
" UNION SELECT 'TEMPORARY'"
" UNION SELECT 'EXECUTE'"
" UNION SELECT 'USAGE'"
" UNION SELECT 'ALL'"
" UNION SELECT 'ALTER'"
" UNION SELECT 'DROP'"
" UNION SELECT 'COMMENT'"
" UNION SELECT 'INDEX'"
" UNION SELECT 'VACUUM'"
" UNION SELECT 'READ'"
" UNION SELECT 'WRITE'");
}
/*
* Complete GRANT/REVOKE <privilege> with "ON", GRANT/REVOKE <role> with
* TO/FROM
*/
else if (pg_strcasecmp(PREV2_WD, "GRANT") == 0 || pg_strcasecmp(PREV2_WD, "REVOKE") == 0) {
if (pg_strcasecmp(PREV_WD, "SELECT") == 0 || pg_strcasecmp(PREV_WD, "INSERT") == 0 ||
pg_strcasecmp(PREV_WD, "UPDATE") == 0 || pg_strcasecmp(PREV_WD, "DELETE") == 0 ||
pg_strcasecmp(PREV_WD, "TRUNCATE") == 0 || pg_strcasecmp(PREV_WD, "REFERENCES") == 0 ||
pg_strcasecmp(PREV_WD, "TRIGGER") == 0 || pg_strcasecmp(PREV_WD, "CREATE") == 0 ||
pg_strcasecmp(PREV_WD, "CONNECT") == 0 || pg_strcasecmp(PREV_WD, "TEMPORARY") == 0 ||
pg_strcasecmp(PREV_WD, "TEMP") == 0 || pg_strcasecmp(PREV_WD, "EXECUTE") == 0 ||
pg_strcasecmp(PREV_WD, "USAGE") == 0)
COMPLETE_WITH_CONST("ON");
else if (pg_strcasecmp(PREV_WD, "ALL") == 0){
static const char* const listGrantAll[] = {"ON", "PRIVILEGES", NULL};
COMPLETE_WITH_LIST(listGrantAll);
}else {
if (pg_strcasecmp(PREV2_WD, "GRANT") == 0)
COMPLETE_WITH_CONST("TO");
else
COMPLETE_WITH_CONST("FROM");
}
}
else if ((pg_strcasecmp(PREV3_WD, "GRANT") == 0 || pg_strcasecmp(PREV3_WD, "REVOKE") == 0) &&
pg_strcasecmp(PREV2_WD, "ALL") == 0 && pg_strcasecmp(PREV_WD, "PRIVILEGES") == 0) {
COMPLETE_WITH_CONST("ON");
}
/*
* Complete GRANT/REVOKE <sth> ON with a list of tables, views, sequences,
* and indexes
*
* keywords DATABASE, FUNCTION, LANGUAGE, SCHEMA added to query result via
* UNION; seems to work intuitively
*
* Note: GRANT/REVOKE can get quite complex; tab-completion as implemented
* here will only work if the privilege list contains exactly one
* privilege
*/
else if ((pg_strcasecmp(PREV3_WD, "GRANT") == 0 || pg_strcasecmp(PREV3_WD, "REVOKE") == 0) &&
pg_strcasecmp(PREV_WD, "ON") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, " UNION SELECT 'DATABASE'"
" UNION SELECT 'DOMAIN'"
" UNION SELECT 'FOREIGN DATA WRAPPER'"
" UNION SELECT 'FOREIGN SERVER'"
" UNION SELECT 'FUNCTION'"
" UNION SELECT 'LANGUAGE'"
" UNION SELECT 'LARGE OBJECT'"
" UNION SELECT 'SCHEMA'"
" UNION SELECT 'TABLESPACE'"
" UNION SELECT 'TYPE'"
" UNION SELECT 'TABLE'"
" UNION SELECT 'DIRECTORY'"
" UNION SELECT 'NODE GROUP'"
" UNION SELECT 'DATA SOURCE'");
else if ((pg_strcasecmp(PREV4_WD, "GRANT") == 0 || pg_strcasecmp(PREV4_WD, "REVOKE") == 0) &&
pg_strcasecmp(PREV2_WD, "ON") == 0 && pg_strcasecmp(PREV_WD, "FOREIGN") == 0) {
static const char* const listPrivilegeForeign[] = {"DATA WRAPPER", "SERVER", NULL};
COMPLETE_WITH_LIST(listPrivilegeForeign);
}
/* Complete "GRANT/REVOKE * ON * " with "TO/FROM" */
else if ((pg_strcasecmp(PREV4_WD, "GRANT") == 0 || pg_strcasecmp(PREV4_WD, "REVOKE") == 0) &&
pg_strcasecmp(PREV2_WD, "ON") == 0) {
if (pg_strcasecmp(PREV_WD, "DATABASE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_databases);
else if (pg_strcasecmp(PREV_WD, "DOMAIN") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
else if (pg_strcasecmp(PREV_WD, "FUNCTION") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (pg_strcasecmp(PREV_WD, "LANGUAGE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_languages);
else if (pg_strcasecmp(PREV_WD, "SCHEMA") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
else if (pg_strcasecmp(PREV_WD, "TABLESPACE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
else if (pg_strcasecmp(PREV_WD, "TYPE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
else if (pg_strcasecmp(PREV_WD, "DATA") == 0)
COMPLETE_WITH_CONST("SOURCE");
else if (pg_strcasecmp(PREV4_WD, "GRANT") == 0)
COMPLETE_WITH_CONST("TO");
else
COMPLETE_WITH_CONST("FROM");
}
else if ((pg_strcasecmp(PREV2_WD, "tablespace") == 0 && pg_strcasecmp(PREV_WD, "=") == 0) ||
pg_strcasecmp(PREV_WD, "tablespace") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
/* Complete "GRANT/REVOKE * ON * TO/FROM" with username, GROUP, or PUBLIC */
else if (pg_strcasecmp(PREV5_WD, "GRANT") == 0 && pg_strcasecmp(PREV3_WD, "ON") == 0) {
if (pg_strcasecmp(PREV_WD, "TO") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
else
COMPLETE_WITH_CONST("TO");
} else if (pg_strcasecmp(PREV5_WD, "REVOKE") == 0 && pg_strcasecmp(PREV3_WD, "ON") == 0) {
if (pg_strcasecmp(PREV_WD, "FROM") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
else
COMPLETE_WITH_CONST("FROM");
}
/* Complete "GRANT/REVOKE * ON SCHEMA/.. * TO" with username, GROUP, or PUBLIC */
else if (pg_strcasecmp(PREV6_WD, "GRANT") == 0 && pg_strcasecmp(PREV4_WD, "ON") == 0) {
if (pg_strcasecmp(PREV_WD, "TO") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
else
COMPLETE_WITH_CONST("TO");
}
/* Complete "GRANT/REVOKE * TO/FROM" with username, GROUP, or PUBLIC */
else if (pg_strcasecmp(PREV3_WD, "GRANT") == 0 && pg_strcasecmp(PREV_WD, "TO") == 0) {
COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
} else if (pg_strcasecmp(PREV3_WD, "REVOKE") == 0 && pg_strcasecmp(PREV_WD, "FROM") == 0) {
COMPLETE_WITH_QUERY(Query_for_list_of_grant_roles);
}
/* GROUP BY */
else if (pg_strcasecmp(PREV3_WD, "FROM") == 0 && pg_strcasecmp(PREV_WD, "GROUP") == 0)
COMPLETE_WITH_CONST("BY");
/* INSERT */
/* Complete INSERT with "INTO" */
else if (pg_strcasecmp(PREV_WD, "INSERT") == 0)
COMPLETE_WITH_CONST("INTO");
/* Complete INSERT INTO with table names */
else if (pg_strcasecmp(PREV2_WD, "INSERT") == 0 && pg_strcasecmp(PREV_WD, "INTO") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_insertables, NULL);
/* Complete "INSERT INTO <table> (" with attribute names */
else if (pg_strcasecmp(PREV4_WD, "INSERT") == 0 && pg_strcasecmp(PREV3_WD, "INTO") == 0 &&
pg_strcasecmp(PREV_WD, "(") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, "");
/*
* Complete INSERT INTO <table> with "(" or "VALUES" or "SELECT" or
* "TABLE" or "DEFAULT VALUES"
*/
else if (pg_strcasecmp(PREV3_WD, "INSERT") == 0 && pg_strcasecmp(PREV2_WD, "INTO") == 0) {
static const char* const listInsert[] = {"(", "DEFAULT VALUES", "SELECT", "TABLE", "VALUES", NULL};
COMPLETE_WITH_LIST(listInsert);
}
/*
* Complete INSERT INTO <table> (attribs) with "VALUES" or "SELECT" or
* "TABLE"
*/
else if (pg_strcasecmp(PREV4_WD, "INSERT") == 0 && pg_strcasecmp(PREV3_WD, "INTO") == 0 &&
PREV_WD[strlen(PREV_WD) - 1] == ')') {
static const char* const listInsert[] = {"SELECT", "TABLE", "VALUES", NULL};
COMPLETE_WITH_LIST(listInsert);
}
/* Insert an open parenthesis after "VALUES" */
else if (pg_strcasecmp(PREV_WD, "VALUES") == 0 && pg_strcasecmp(PREV2_WD, "DEFAULT") != 0)
COMPLETE_WITH_CONST("(");
/* LOCK */
/* Complete LOCK [TABLE] with a list of tables */
else if (pg_strcasecmp(PREV_WD, "LOCK") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, " UNION SELECT 'TABLE'");
else if (pg_strcasecmp(PREV_WD, "TABLE") == 0 && pg_strcasecmp(PREV2_WD, "LOCK") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, " UNION ALL SELECT 'ONLY'");
/* For the following, handle the case of a single table only for now */
/* Complete LOCK [TABLE] <table> with "IN" */
else if ((pg_strcasecmp(PREV2_WD, "LOCK") == 0 && pg_strcasecmp(PREV_WD, "TABLE") != 0) ||
(pg_strcasecmp(PREV2_WD, "TABLE") == 0 && pg_strcasecmp(PREV3_WD, "LOCK") == 0)) {
static const char* const lockTableList[] = {"IN", "NOWAIT", NULL};
COMPLETE_WITH_LIST(lockTableList);
}
/* Complete LOCK [TABLE] <table> IN with a lock mode */
else if (pg_strcasecmp(PREV_WD, "IN") == 0 && (pg_strcasecmp(PREV3_WD, "LOCK") == 0 ||
(pg_strcasecmp(PREV3_WD, "TABLE") == 0 && pg_strcasecmp(PREV4_WD, "LOCK") == 0))) {
static const char* const lockModes[] = {
"ACCESS SHARE MODE",
"ROW SHARE MODE", "ROW EXCLUSIVE MODE",
"SHARE UPDATE EXCLUSIVE MODE", "SHARE MODE",
"SHARE ROW EXCLUSIVE MODE",
"EXCLUSIVE MODE", "ACCESS EXCLUSIVE MODE", NULL
};
COMPLETE_WITH_LIST(lockModes);
}
else if ((pg_strcasecmp(PREV_WD, "ACCESS") == 0 || pg_strcasecmp(PREV_WD, "ROW") == 0) &&
pg_strcasecmp(PREV2_WD, "IN") == 0 && (pg_strcasecmp(PREV4_WD, "LOCK") == 0 ||
(pg_strcasecmp(PREV4_WD, "TABLE") == 0 && pg_strcasecmp(PREV5_WD, "LOCK") == 0))) {
static const char* const lockModesAccess[] = {"SHARE MODE", "EXCLUSIVE MODE", NULL};
COMPLETE_WITH_LIST(lockModesAccess);
}
else if (pg_strcasecmp(PREV_WD, "SHARE") == 0&& pg_strcasecmp(PREV2_WD, "IN") == 0 &&
(pg_strcasecmp(PREV4_WD, "LOCK") == 0 || (pg_strcasecmp(PREV4_WD, "TABLE") == 0 &&
pg_strcasecmp(PREV5_WD, "LOCK") == 0))) {
static const char* const lockModesAccess[] = {"UPDATE EXCLUSIVE MODE", "ROW EXCLUSIVE MODE", "MODE", NULL};
COMPLETE_WITH_LIST(lockModesAccess);
}
/* NOTIFY */
else if (pg_strcasecmp(PREV_WD, "NOTIFY") == 0)
COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(channel) FROM pg_catalog.pg_listening_channels() AS channel "
"WHERE substring(pg_catalog.quote_ident(channel),1,%d)='%s'");
/* OPTIONS */
else if (pg_strcasecmp(PREV_WD, "OPTIONS") == 0)
COMPLETE_WITH_CONST("(");
/* OWNER TO - complete with available roles */
else if (pg_strcasecmp(PREV2_WD, "OWNER") == 0 && pg_strcasecmp(PREV_WD, "TO") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
/* ORDER BY */
else if (pg_strcasecmp(PREV3_WD, "FROM") == 0 && pg_strcasecmp(PREV_WD, "ORDER") == 0)
COMPLETE_WITH_CONST("BY");
else if (pg_strcasecmp(PREV4_WD, "FROM") == 0 && pg_strcasecmp(PREV2_WD, "ORDER") == 0 &&
pg_strcasecmp(PREV_WD, "BY") == 0)
COMPLETE_WITH_ATTR(PREV3_WD, "");
/* PREPARE xx AS */
else if (pg_strcasecmp(PREV_WD, "AS") == 0 && pg_strcasecmp(PREV3_WD, "PREPARE") == 0) {
static const char* const listPrepare[] = {"SELECT", "UPDATE", "INSERT", "DELETE", NULL};
COMPLETE_WITH_LIST(listPrepare);
}
/*
* PREPARE TRANSACTION is missing on purpose. It's intended for transaction
* managers, not for manual use in interactive sessions.
*/
/* REASSIGN OWNED BY xxx TO yyy */
else if (pg_strcasecmp(PREV_WD, "REASSIGN") == 0)
COMPLETE_WITH_CONST("OWNED");
else if (pg_strcasecmp(PREV_WD, "OWNED") == 0 && pg_strcasecmp(PREV2_WD, "REASSIGN") == 0)
COMPLETE_WITH_CONST("BY");
else if (pg_strcasecmp(PREV_WD, "BY") == 0 && pg_strcasecmp(PREV2_WD, "OWNED") == 0 &&
pg_strcasecmp(PREV3_WD, "REASSIGN") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
else if (pg_strcasecmp(PREV2_WD, "BY") == 0 && pg_strcasecmp(PREV3_WD, "OWNED") == 0 &&
pg_strcasecmp(PREV4_WD, "REASSIGN") == 0)
COMPLETE_WITH_CONST("TO");
else if (pg_strcasecmp(PREV_WD, "TO") == 0 && pg_strcasecmp(PREV3_WD, "BY") == 0 &&
pg_strcasecmp(PREV4_WD, "OWNED") == 0 && pg_strcasecmp(PREV5_WD, "REASSIGN") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
/* REFRESH MATERIALIZED VIEW */
else if (pg_strcasecmp(PREV_WD, "REFRESH") == 0) {
static const char* const refreshObject[] = {"MATERIALIZED VIEW", "INCREMENTAL MATERIALIZED VIEW", NULL};
COMPLETE_WITH_LIST(refreshObject);
}
else if (pg_strcasecmp(PREV2_WD, "REFRESH") == 0 && pg_strcasecmp(PREV_WD, "MATERIALIZED") == 0)
COMPLETE_WITH_CONST("VIEW");
else if (pg_strcasecmp(PREV3_WD, "REFRESH") == 0 && pg_strcasecmp(PREV2_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV_WD, "VIEW") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
else if (pg_strcasecmp(PREV4_WD, "REFRESH") == 0 && pg_strcasecmp(PREV3_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV2_WD, "VIEW") == 0)
COMPLETE_WITH_CONST("WITH");
else if (pg_strcasecmp(PREV5_WD, "REFRESH") == 0 && pg_strcasecmp(PREV4_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV3_WD, "VIEW") == 0 && pg_strcasecmp(PREV_WD, "WITH") == 0) {
static const char *const listWithData[] = {
"NO DATA", "DATA", NULL};
COMPLETE_WITH_LIST(listWithData);
} else if (pg_strcasecmp(PREV6_WD, "REFRESH") == 0 && pg_strcasecmp(PREV5_WD, "MATERIALIZED") == 0 &&
pg_strcasecmp(PREV4_WD, "VIEW") == 0 && pg_strcasecmp(PREV2_WD, "WITH") == 0 &&
pg_strcasecmp(PREV_WD, "NO") == 0)
COMPLETE_WITH_CONST("DATA");
/* REINDEX */
else if (pg_strcasecmp(PREV_WD, "REINDEX") == 0) {
static const char* const listReindex[] = {"TABLE", "INDEX", "SYSTEM", "DATABASE", NULL};
COMPLETE_WITH_LIST(listReindex);
} else if (pg_strcasecmp(PREV2_WD, "REINDEX") == 0) {
if (pg_strcasecmp(PREV_WD, "TABLE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
else if (pg_strcasecmp(PREV_WD, "INDEX") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
else if (pg_strcasecmp(PREV_WD, "SYSTEM") == 0 || pg_strcasecmp(PREV_WD, "DATABASE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_databases);
}
/* SECURITY LABEL */
else if (pg_strcasecmp(PREV_WD, "SECURITY") == 0 && PREV2_WD[0] == '\0')
COMPLETE_WITH_CONST("LABEL");
else if (pg_strcasecmp(PREV2_WD, "SECURITY") == 0 && pg_strcasecmp(PREV_WD, "LABEL") == 0) {
static const char* const listSecurityLabelPreposition[] = {"ON", "FOR"};
COMPLETE_WITH_LIST(listSecurityLabelPreposition);
} else if (pg_strcasecmp(PREV4_WD, "SECURITY") == 0 && pg_strcasecmp(PREV3_WD, "LABEL") == 0 &&
pg_strcasecmp(PREV2_WD, "FOR") == 0)
COMPLETE_WITH_CONST("ON");
else if ((pg_strcasecmp(PREV3_WD, "SECURITY") == 0 && pg_strcasecmp(PREV2_WD, "LABEL") == 0 &&
pg_strcasecmp(PREV_WD, "ON") == 0) ||
(pg_strcasecmp(PREV5_WD, "SECURITY") == 0 && pg_strcasecmp(PREV4_WD, "LABEL") == 0 &&
pg_strcasecmp(PREV3_WD, "FOR") == 0 && pg_strcasecmp(PREV_WD, "ON") == 0)) {
static const char* const listSecurityLabel[] = {
"LANGUAGE", "SCHEMA", "SEQUENCE", "TABLE", "TYPE", "VIEW", "MATERIALIZED VIEW", "COLUMN",
"AGGREGATE", "FUNCTION", "DOMAIN", "LARGE OBJECT", NULL
};
COMPLETE_WITH_LIST(listSecurityLabel);
} else if (pg_strcasecmp(PREV5_WD, "SECURITY") == 0 && pg_strcasecmp(PREV4_WD, "LABEL") == 0 &&
pg_strcasecmp(PREV3_WD, "ON") == 0)
COMPLETE_WITH_CONST("IS");
/* SELECT */
/* naah . . . */
/* SET, RESET, SHOW */
/* Complete with a variable name */
else if ((pg_strcasecmp(PREV_WD, "SET") == 0 && pg_strcasecmp(PREV3_WD, "UPDATE") != 0) ||
pg_strcasecmp(PREV_WD, "RESET") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_set_vars);
else if (pg_strcasecmp(PREV_WD, "SHOW") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_show_vars);
/* Complete "SET TRANSACTION" */
else if ((pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "TRANSACTION") == 0) ||
(pg_strcasecmp(PREV2_WD, "START") == 0 && pg_strcasecmp(PREV_WD, "TRANSACTION") == 0) ||
(pg_strcasecmp(PREV2_WD, "BEGIN") == 0 && pg_strcasecmp(PREV_WD, "WORK") == 0) ||
(pg_strcasecmp(PREV2_WD, "BEGIN") == 0 && pg_strcasecmp(PREV_WD, "TRANSACTION") == 0) ||
(pg_strcasecmp(PREV4_WD, "SESSION") == 0 && pg_strcasecmp(PREV3_WD, "CHARACTERISTICS") == 0 &&
pg_strcasecmp(PREV2_WD, "AS") == 0 && pg_strcasecmp(PREV_WD, "TRANSACTION") == 0)) {
static const char* const myList[] = {"ISOLATION LEVEL", "READ", NULL};
COMPLETE_WITH_LIST(myList);
} else if ((pg_strcasecmp(PREV3_WD, "SET") == 0 || pg_strcasecmp(PREV3_WD, "BEGIN") == 0 ||
pg_strcasecmp(PREV3_WD, "START") == 0 ||
(pg_strcasecmp(PREV4_WD, "CHARACTERISTICS") == 0 && pg_strcasecmp(PREV3_WD, "AS") == 0)) &&
(pg_strcasecmp(PREV2_WD, "TRANSACTION") == 0 || pg_strcasecmp(PREV2_WD, "WORK") == 0) &&
pg_strcasecmp(PREV_WD, "ISOLATION") == 0)
COMPLETE_WITH_CONST("LEVEL");
else if ((pg_strcasecmp(PREV4_WD, "SET") == 0 || pg_strcasecmp(PREV4_WD, "BEGIN") == 0 ||
pg_strcasecmp(PREV4_WD, "START") == 0 || pg_strcasecmp(PREV4_WD, "AS") == 0) &&
(pg_strcasecmp(PREV3_WD, "TRANSACTION") == 0 || pg_strcasecmp(PREV3_WD, "WORK") == 0) &&
pg_strcasecmp(PREV2_WD, "ISOLATION") == 0 && pg_strcasecmp(PREV_WD, "LEVEL") == 0) {
static const char* const myList[] = {"READ", "REPEATABLE", "SERIALIZABLE", NULL};
COMPLETE_WITH_LIST(myList);
} else if ((pg_strcasecmp(PREV4_WD, "TRANSACTION") == 0 || pg_strcasecmp(PREV4_WD, "WORK") == 0) &&
pg_strcasecmp(PREV3_WD, "ISOLATION") == 0 && pg_strcasecmp(PREV2_WD, "LEVEL") == 0 &&
pg_strcasecmp(PREV_WD, "READ") == 0) {
static const char* const myList[] = {"UNCOMMITTED", "COMMITTED", NULL};
COMPLETE_WITH_LIST(myList);
} else if ((pg_strcasecmp(PREV4_WD, "TRANSACTION") == 0 || pg_strcasecmp(PREV4_WD, "WORK") == 0) &&
pg_strcasecmp(PREV3_WD, "ISOLATION") == 0 && pg_strcasecmp(PREV2_WD, "LEVEL") == 0 &&
pg_strcasecmp(PREV_WD, "REPEATABLE") == 0)
COMPLETE_WITH_CONST("READ");
else if ((pg_strcasecmp(PREV3_WD, "SET") == 0 || pg_strcasecmp(PREV3_WD, "BEGIN") == 0 ||
pg_strcasecmp(PREV3_WD, "START") == 0 || pg_strcasecmp(PREV3_WD, "AS") == 0) &&
(pg_strcasecmp(PREV2_WD, "TRANSACTION") == 0 || pg_strcasecmp(PREV2_WD, "WORK") == 0) &&
pg_strcasecmp(PREV_WD, "READ") == 0) {
static const char* const myList[] = {"ONLY", "WRITE", NULL};
COMPLETE_WITH_LIST(myList);
}
else if (pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "CONSTRAINTS") == 0) {
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_constraints_with_schema, " UNION SELECT 'ALL'");
}
/* Complete SET CONSTRAINTS <foo> with DEFERRED|IMMEDIATE */
else if (pg_strcasecmp(PREV3_WD, "SET") == 0 && pg_strcasecmp(PREV2_WD, "CONSTRAINTS") == 0) {
static const char* const constraintList[] = {"DEFERRED", "IMMEDIATE", NULL};
COMPLETE_WITH_LIST(constraintList);
}
/* Complete SET ROLE */
else if (pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV_WD, "ROLE") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
/* Complete SET SESSION with AUTHORIZATION or CHARACTERISTICS... */
else if (pg_strcasecmp(PREV2_WD, "SET") == 0 &&
(pg_strcasecmp(PREV_WD, "SESSION") == 0 || pg_strcasecmp(PREV_WD, "LOCAL") == 0)) {
static const char* const myList[] = {"AUTHORIZATION", "CHARACTERISTICS AS TRANSACTION", NULL};
COMPLETE_WITH_LIST(myList);
}
/* Complete SET SESSION AUTHORIZATION with username */
else if (pg_strcasecmp(PREV3_WD, "SET") == 0 && pg_strcasecmp(PREV2_WD, "SESSION") == 0 &&
pg_strcasecmp(PREV_WD, "AUTHORIZATION") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles " UNION SELECT 'DEFAULT'");
/* Complete RESET SESSION with AUTHORIZATION */
else if (pg_strcasecmp(PREV2_WD, "RESET") == 0 && pg_strcasecmp(PREV_WD, "SESSION") == 0)
COMPLETE_WITH_CONST("AUTHORIZATION");
/* Complete SET <var> with "TO" */
else if (pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV4_WD, "UPDATE") != 0 &&
pg_strcasecmp(PREV_WD, "TABLESPACE") != 0 && pg_strcasecmp(PREV_WD, "SCHEMA") != 0 &&
PREV_WD[strlen(PREV_WD) - 1] != ')' && pg_strcasecmp(PREV4_WD, "DOMAIN") != 0 &&
pg_strcasecmp(PREV_WD, "CONSTRAINTS") != 0)
COMPLETE_WITH_CONST("TO");
/* Suggest possible variable values */
else if (pg_strcasecmp(PREV3_WD, "SET") == 0 && (pg_strcasecmp(PREV_WD, "TO") == 0 || strcmp(PREV_WD, "=") == 0)) {
if (pg_strcasecmp(PREV2_WD, "DateStyle") == 0) {
static const char* const myList[] = {
"ISO", "SQL", "Postgres", "German",
"YMD", "DMY", "MDY",
"US", "European", "NonEuropean",
"DEFAULT", NULL
};
COMPLETE_WITH_LIST(myList);
} else if (pg_strcasecmp(PREV2_WD, "IntervalStyle") == 0) {
static const char* const myList[] = {"postgres", "postgres_verbose", "sql_standard", "iso_8601", NULL};
COMPLETE_WITH_LIST(myList);
} else if (pg_strcasecmp(PREV2_WD, "GEQO") == 0) {
static const char* const myList[] = {"ON", "OFF", "DEFAULT", NULL};
COMPLETE_WITH_LIST(myList);
} else {
static const char* const myList[] = {"DEFAULT", NULL};
COMPLETE_WITH_LIST(myList);
}
}
/* START TRANSACTION */
else if (pg_strcasecmp(PREV_WD, "START") == 0)
COMPLETE_WITH_CONST("TRANSACTION");
/* TABLE, but not TABLE embedded in other commands */
else if (pg_strcasecmp(PREV_WD, "TABLE") == 0 && PREV2_WD[0] == '\0')
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations, NULL);
/* TRUNCATE */
else if (pg_strcasecmp(PREV_WD, "TRUNCATE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
" UNION SELECT 'TABLE'"
" UNION SELECT 'ONLY'");
else if (pg_strcasecmp(PREV2_WD, "TRUNCATE") == 0 && pg_strcasecmp(PREV_WD, "TABLE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables,
" UNION SELECT 'ONLY'");
else if (((pg_strcasecmp(PREV3_WD, "TRUNCATE") == 0 && pg_strcasecmp(PREV2_WD, "TABLE")) ||
(pg_strcasecmp(PREV2_WD, "TRUNCATE") == 0)) && pg_strcasecmp(PREV_WD, "ONLY") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
/* UNLISTEN */
else if (pg_strcasecmp(PREV_WD, "UNLISTEN") == 0)
COMPLETE_WITH_QUERY("SELECT pg_catalog.quote_ident(channel) FROM pg_catalog.pg_listening_channels() AS channel "
"WHERE substring(pg_catalog.quote_ident(channel),1,%d)='%s' UNION SELECT '*'");
/* UPDATE */
/* If prev. word is UPDATE suggest a list of tables */
else if (pg_strcasecmp(PREV_WD, "UPDATE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_updatables, NULL);
/* Complete UPDATE <table> with "SET" */
else if (pg_strcasecmp(PREV2_WD, "UPDATE") == 0)
COMPLETE_WITH_CONST("SET");
/*
* If the previous word is SET (and it wasn't caught above as the _first_
* word) the word before it was (hopefully) a table name and we'll now
* make a list of attributes.
*/
else if (pg_strcasecmp(PREV_WD, "SET") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, "");
/* UPDATE xx SET yy = */
else if (pg_strcasecmp(PREV2_WD, "SET") == 0 && pg_strcasecmp(PREV4_WD, "UPDATE") == 0)
COMPLETE_WITH_CONST("=");
/* USER MAPPING */
else if ((pg_strcasecmp(PREV3_WD, "ALTER") == 0 || pg_strcasecmp(PREV3_WD, "CREATE") == 0 ||
pg_strcasecmp(PREV3_WD, "DROP") == 0) &&
pg_strcasecmp(PREV2_WD, "USER") == 0 && pg_strcasecmp(PREV_WD, "MAPPING") == 0)
COMPLETE_WITH_CONST("FOR");
else if (pg_strcasecmp(PREV4_WD, "CREATE") == 0 && pg_strcasecmp(PREV3_WD, "USER") == 0 &&
pg_strcasecmp(PREV2_WD, "MAPPING") == 0 && pg_strcasecmp(PREV_WD, "FOR") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles " UNION SELECT 'CURRENT_USER'"
" UNION SELECT 'PUBLIC'"
" UNION SELECT 'USER'");
else if ((pg_strcasecmp(PREV4_WD, "ALTER") == 0 || pg_strcasecmp(PREV4_WD, "DROP") == 0) &&
pg_strcasecmp(PREV3_WD, "USER") == 0 && pg_strcasecmp(PREV2_WD, "MAPPING") == 0 &&
pg_strcasecmp(PREV_WD, "FOR") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
else if ((pg_strcasecmp(PREV5_WD, "CREATE") == 0 || pg_strcasecmp(PREV5_WD, "ALTER") == 0 ||
pg_strcasecmp(PREV5_WD, "DROP") == 0) &&
pg_strcasecmp(PREV4_WD, "USER") == 0 && pg_strcasecmp(PREV3_WD, "MAPPING") == 0 &&
pg_strcasecmp(PREV2_WD, "FOR") == 0)
COMPLETE_WITH_CONST("SERVER");
/*
* VACUUM [ FULL | FREEZE ] [ VERBOSE ] [ table ]
* VACUUM [ FULL | FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]
*/
else if (pg_strcasecmp(PREV_WD, "VACUUM") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'FULL'"
" UNION SELECT 'FREEZE'"
" UNION SELECT 'ANALYZE'"
" UNION SELECT 'VERBOSE'"
" UNION SELECT 'DELTAMERGE'"
" UNION SELECT 'HDFSDIRECTORY'"
" UNION SELECT 'COMPACT'"
" UNION SELECT 'ANALYSE'"
" UNION SELECT 'PARTITION'");
else if (pg_strcasecmp(PREV2_WD, "VACUUM") == 0 && pg_strcasecmp(PREV_WD, "FULL") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'ANALYZE'"
" UNION SELECT 'VERBOSE'"
" UNION SELECT 'COMPACT'");
else if (pg_strcasecmp(PREV2_WD, "VACUUM") == 0 && pg_strcasecmp(PREV_WD, "FREEZE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'ANALYZE'"
" UNION SELECT 'VERBOSE'");
else if (pg_strcasecmp(PREV3_WD, "VACUUM") == 0 && pg_strcasecmp(PREV_WD, "ANALYZE") == 0 &&
(pg_strcasecmp(PREV2_WD, "FULL") == 0 || pg_strcasecmp(PREV2_WD, "FREEZE") == 0))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'VERBOSE'");
else if (pg_strcasecmp(PREV3_WD, "VACUUM") == 0 && pg_strcasecmp(PREV_WD, "VERBOSE") == 0 &&
(pg_strcasecmp(PREV2_WD, "FULL") == 0 || pg_strcasecmp(PREV2_WD, "FREEZE") == 0))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'ANALYZE'");
else if (pg_strcasecmp(PREV2_WD, "VACUUM") == 0 && pg_strcasecmp(PREV_WD, "VERBOSE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'ANALYZE'");
else if (pg_strcasecmp(PREV2_WD, "VACUUM") == 0 && pg_strcasecmp(PREV_WD, "ANALYZE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, " UNION SELECT 'VERBOSE'");
else if ((pg_strcasecmp(PREV_WD, "ANALYZE") == 0 && pg_strcasecmp(PREV2_WD, "VERBOSE") == 0) ||
(pg_strcasecmp(PREV_WD, "VERBOSE") == 0 && pg_strcasecmp(PREV2_WD, "ANALYZE") == 0))
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tm, NULL);
/* WITH [RECURSIVE] */
/*
* Only match when WITH is the first word, as WITH may appear in many
* other contexts.
*/
else if (pg_strcasecmp(PREV_WD, "WITH") == 0 && PREV2_WD[0] == '\0')
COMPLETE_WITH_CONST("RECURSIVE");
/* ANALYZE */
/* If the previous word is ANALYZE, produce list of tables */
else if (pg_strcasecmp(PREV_WD, "ANALYZE") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tmf, " UNION SELECT 'VERBOSE'"
" UNION SELECT 'VERIFY'"
" UNION SELECT 'PARTITION'");
else if (pg_strcasecmp(PREV2_WD, "ANALYZE") == 0 && pg_strcasecmp(PREV_WD, "VERIFY") == 0) {
static const char* const listAnalizeVerify[] = {"FAST", "COMPLETE", NULL};
COMPLETE_WITH_LIST_CS(listAnalizeVerify);
}
else if (pg_strcasecmp(PREV3_WD, "ANALYZE") == 0 && pg_strcasecmp(PREV2_WD, "VERIFY") == 0 &&
(pg_strcasecmp(PREV_WD, "FAST") == 0 || pg_strcasecmp(PREV_WD, "COMPLETE") == 0)) {
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tmi, NULL);
}
/* WHERE */
/* Simple case of the word before the where being the table name */
else if (pg_strcasecmp(PREV_WD, "WHERE") == 0)
COMPLETE_WITH_ATTR(PREV2_WD, "");
/* ... FROM ... */
else if (pg_strcasecmp(PREV_WD, "FROM") == 0 && pg_strcasecmp(PREV3_WD, "COPY") != 0 &&
pg_strcasecmp(PREV3_WD, "\\copy") != 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
/* ... JOIN ... */
else if (pg_strcasecmp(PREV_WD, "JOIN") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
/* Backslash commands */
else if (strcmp(PREV_WD, "\\connect") == 0 || strcmp(PREV_WD, "\\c") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_databases);
else if (strncmp(PREV_WD, "\\da", strlen("\\da")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_aggregates, NULL);
else if (strncmp(PREV_WD, "\\db", strlen("\\db")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_tablespaces);
else if (strncmp(PREV_WD, "\\dD", strlen("\\dD")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_domains, NULL);
else if (strncmp(PREV_WD, "\\des", strlen("\\des")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_servers);
else if (strncmp(PREV_WD, "\\deu", strlen("\\deu")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_user_mappings);
else if (strncmp(PREV_WD, "\\dew", strlen("\\dew")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_fdws);
else if (strncmp(PREV_WD, "\\df", strlen("\\df")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (strncmp(PREV_WD, "\\dFd", strlen("\\dFd")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_ts_dictionaries);
else if (strncmp(PREV_WD, "\\dFp", strlen("\\dFp")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_ts_parsers);
else if (strncmp(PREV_WD, "\\dFt", strlen("\\dFt")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_ts_templates);
/* must be at end of \dF */
else if (strncmp(PREV_WD, "\\dF", strlen("\\dF")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_ts_configurations);
else if (strncmp(PREV_WD, "\\di", strlen("\\di")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_indexes, NULL);
else if (strncmp(PREV_WD, "\\dL", strlen("\\dL")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_languages);
else if (strncmp(PREV_WD, "\\dn", strlen("\\dn")) == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_schemas);
else if (strncmp(PREV_WD, "\\dp", strlen("\\dp")) == 0 || strncmp(PREV_WD, "\\z", strlen("\\z")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tsvmf, NULL);
else if (strncmp(PREV_WD, "\\ds", strlen("\\ds")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_sequences, NULL);
else if (strncmp(PREV_WD, "\\dt", strlen("\\dt")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_tables, NULL);
else if (strncmp(PREV_WD, "\\dT", strlen("\\dT")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_datatypes, NULL);
else if (strncmp(PREV_WD, "\\du", strlen("\\du")) == 0 || (strncmp(PREV_WD, "\\dg", strlen("\\dg")) == 0))
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
else if (strncmp(PREV_WD, "\\dv", strlen("\\dv")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_views, NULL);
else if (strncmp(PREV_WD, "\\dm", strlen("\\dm")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_matviews, NULL);
/* must be at end of \d list */
else if (strncmp(PREV_WD, "\\d", strlen("\\d")) == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_relations, NULL);
else if (strcmp(PREV_WD, "\\ef") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (strcmp(PREV_WD, "\\encoding") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_encodings);
else if (strcmp(PREV_WD, "\\h") == 0 || strcmp(PREV_WD, "\\help") == 0)
COMPLETE_WITH_LIST(sqlCommands);
else if ((strcmp(PREV2_WD, "\\h") == 0 || strcmp(PREV2_WD, "\\help") == 0) &&
pg_strcasecmp(PREV_WD, "DROP") == 0) {
matches = completion_matches(text, DropCommandGenerator);
}
else if (strcmp(PREV_WD, "\\password") == 0)
COMPLETE_WITH_QUERY(Query_for_list_of_roles);
else if (strcmp(PREV_WD, "\\pset") == 0) {
static const char* const myList[] = {
"format", "border", "expanded",
"null", "fieldsep", "tuples_only", "title", "tableattr",
"linestyle", "pager", "recordsep", NULL
};
COMPLETE_WITH_LIST_CS(myList);
} else if (strcmp(PREV2_WD, "\\pset") == 0) {
if (strcmp(PREV_WD, "format") == 0) {
static const char* const myList[] = {"unaligned", "aligned", "wrapped", "html", "latex", "troff-ms", NULL};
COMPLETE_WITH_LIST_CS(myList);
} else if (strcmp(PREV_WD, "linestyle") == 0) {
static const char* const myList[] = {"ascii", "old-ascii", "unicode", NULL};
COMPLETE_WITH_LIST_CS(myList);
}
} else if (strcmp(PREV_WD, "\\set") == 0) {
matches = CompleteFromVariables(text, "", "");
} else if (strcmp(PREV_WD, "\\sf") == 0 || strcmp(PREV_WD, "\\sf+") == 0)
COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
else if (strcmp(PREV_WD, "\\cd") == 0 || strcmp(PREV_WD, "\\e") == 0 || strcmp(PREV_WD, "\\edit") == 0 ||
strcmp(PREV_WD, "\\g") == 0 || strcmp(PREV_WD, "\\i") == 0 || strcmp(PREV_WD, "\\include") == 0 ||
strcmp(PREV_WD, "\\ir") == 0 || strcmp(PREV_WD, "\\include_relative") == 0 || strcmp(PREV_WD, "\\o") == 0 ||
strcmp(PREV_WD, "\\out") == 0 || strcmp(PREV_WD, "\\s") == 0 || strcmp(PREV_WD, "\\w") == 0 ||
strcmp(PREV_WD, "\\write") == 0) {
completion_charp = "\\";
matches = completion_matches(text, CompleteFromFiles);
}
/*
* Finally, we look through the list of "things", such as TABLE, INDEX and
* check if that was the previous word. If so, execute the query to get a
* list of them.
*/
else {
int i;
for (i = 0; words_after_create[i].name; i++) {
if (pg_strcasecmp(PREV_WD, words_after_create[i].name) == 0) {
if (words_after_create[i].query) {
COMPLETE_WITH_QUERY(words_after_create[i].query);
}
else if (words_after_create[i].squery) {
COMPLETE_WITH_SCHEMA_QUERY(*words_after_create[i].squery, NULL);
}
break;
}
}
}
/*
* If we still don't have anything to match we have to fabricate some sort
* of default list. If we were to just return NULL, readline automatically
* attempts filename completion, and that's usually no good.
*/
if (matches == NULL) {
COMPLETE_WITH_CONST("");
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
rl_completion_append_character = '\0';
#endif
}
/* free storage */
{
int i;
for (i = 0; i < (int)lengthof(previousWords); i++)
free(previousWords[i]);
}
/* Return our Grand List O' Matches */
return matches;
}
/*
* This creates a list of matching things, according to a query pointed to
* by completion_charp.
* The query can be one of two kinds:
*
* 1. A simple query which must contain a %d and a %s, which will be replaced
* by the string length of the text and the text itself. The query may also
* have up to four more %s in it; the first two such will be replaced by the
* value of completion_info_charp, the next two by the value of
* completion_info_charp2.
*
* 2. A schema query used for completion of both schema and relation names.
* These are more complex and must contain in the following order:
* %d %s %d %s %d %s %s %d %s
* where %d is the string length of the text and %s the text itself.
*
* It is assumed that strings should be escaped to become SQL literals
* (that is, what is in the query is actually ... '%s' ...)
*
* See top of file for examples of both kinds of query.
*/
static char *_CompleteFromQuery(int isSchemaQuery, const char *text, int state)
{
static int listIndex, stringLength;
static PGresult *result = NULL;
/*
* If this is the first time for this completion, we fetch a list of our
* "things" from the backend.
*/
if (state == 0) {
PQExpBufferData queryBuffer;
char *eText = NULL;
char *eInfoCharp = NULL;
char *eInfoCharp2 = NULL;
listIndex = 0;
stringLength = strlen(text);
/* Free any prior result */
PQclear(result);
result = NULL;
/* Set up suitably-escaped copies of textual inputs */
eText = (char *)pg_malloc(stringLength * 2 + 1);
PQescapeString(eText, text, stringLength);
if (NULL != completion_info_charp) {
size_t charpLen;
charpLen = strlen(completion_info_charp);
eInfoCharp = (char *)pg_malloc(charpLen * 2 + 1);
PQescapeString(eInfoCharp, completion_info_charp, charpLen);
} else
eInfoCharp = NULL;
if (NULL != completion_info_charp2) {
size_t charpLen;
charpLen = strlen(completion_info_charp2);
eInfoCharp2 = (char *)pg_malloc(charpLen * 2 + 1);
PQescapeString(eInfoCharp2, completion_info_charp2, charpLen);
} else
eInfoCharp2 = NULL;
initPQExpBuffer(&queryBuffer);
if (isSchemaQuery) {
/* completion_squery gives us the pieces to assemble */
const char *qualresult = completion_squery->qualresult;
if (qualresult == NULL)
qualresult = completion_squery->result;
/* Get unqualified names matching the input-so-far */
appendPQExpBuffer(&queryBuffer, "SELECT %s FROM %s WHERE ", completion_squery->result,
completion_squery->catname);
if (NULL != completion_squery->selcondition)
appendPQExpBuffer(&queryBuffer, "%s AND ", completion_squery->selcondition);
appendPQExpBuffer(&queryBuffer, "substring(%s,1,%d)='%s'", completion_squery->result, stringLength,
eText);
appendPQExpBuffer(&queryBuffer, " AND %s", completion_squery->viscondition);
/*
* When fetching relation names, suppress system catalogs unless
* the input-so-far begins with "pg_". This is a compromise
* between not offering system catalogs for completion at all, and
* having them swamp the result when the input is just "p".
*/
if (strcmp(completion_squery->catname, "pg_catalog.pg_class c") == 0 &&
strncmp(text, "pg_", 3) != 0 && strncmp(text, "gs_", 3) != 0) {
appendPQExpBuffer(&queryBuffer, " AND c.relnamespace <> (SELECT oid FROM"
" pg_catalog.pg_namespace WHERE nspname = 'pg_catalog')");
}
/*
* Add in matching schema names, but only if there is more than
* one potential match among schema names.
*/
appendPQExpBuffer(&queryBuffer,
"\nUNION\n"
"SELECT pg_catalog.quote_ident(n.nspname) || '.' "
"FROM pg_catalog.pg_namespace n "
"WHERE substring(pg_catalog.quote_ident(n.nspname) || '.',1,%d)='%s'",
stringLength, eText);
appendPQExpBuffer(&queryBuffer,
" AND (SELECT pg_catalog.count(*)"
" FROM pg_catalog.pg_namespace"
" WHERE substring(pg_catalog.quote_ident(nspname) || '.',1,%d) ="
" substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(nspname))+1)) > 1",
stringLength, eText);
/*
* Add in matching qualified names, but only if there is exactly
* one schema matching the input-so-far.
*/
appendPQExpBuffer(&queryBuffer,
"\nUNION\n"
"SELECT pg_catalog.quote_ident(n.nspname) || '.' || %s "
"FROM %s, pg_catalog.pg_namespace n "
"WHERE %s = n.oid AND ",
qualresult, completion_squery->catname, completion_squery->nameSpace);
if (completion_squery->selcondition != NULL)
appendPQExpBuffer(&queryBuffer, "%s AND ", completion_squery->selcondition);
appendPQExpBuffer(&queryBuffer, "substring(pg_catalog.quote_ident(n.nspname) || '.' || %s,1,%d)='%s'",
qualresult, stringLength, eText);
/*
* This condition exploits the single-matching-schema rule to
* speed up the query
*/
appendPQExpBuffer(&queryBuffer,
" AND substring(pg_catalog.quote_ident(n.nspname) || '.',1,%d) ="
" substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(n.nspname))+1)",
stringLength, eText);
appendPQExpBuffer(&queryBuffer,
" AND (SELECT pg_catalog.count(*)"
" FROM pg_catalog.pg_namespace"
" WHERE substring(pg_catalog.quote_ident(nspname) || '.',1,%d) ="
" substring('%s',1,pg_catalog.length(pg_catalog.quote_ident(nspname))+1)) = 1",
stringLength, eText);
/* If an addon query was provided, use it */
if (NULL != completion_charp)
appendPQExpBuffer(&queryBuffer, "\n%s", completion_charp);
} else {
/* completion_charp is an sprintf-style format string */
appendPQExpBuffer(&queryBuffer, completion_charp, stringLength, eText, eInfoCharp, eInfoCharp,
eInfoCharp2, eInfoCharp2);
}
/* Limit the number of records in the result */
appendPQExpBuffer(&queryBuffer, "\nLIMIT %d", completion_max_records);
result = ExecQuery(queryBuffer.data);
termPQExpBuffer(&queryBuffer);
free(eText);
eText = NULL;
if (eInfoCharp != NULL) {
free(eInfoCharp);
eInfoCharp = NULL;
}
if (eInfoCharp2 != NULL) {
free(eInfoCharp2);
eInfoCharp2 = NULL;
}
}
/* Find something that matches */
if (result && PQresultStatus(result) == PGRES_TUPLES_OK) {
const char *item = NULL;
while (listIndex < PQntuples(result) && (item = PQgetvalue(result, listIndex++, 0)))
if (pg_strncasecmp(text, item, stringLength) == 0)
return pg_strdup(item);
}
/* If nothing matches, free the db structure and return null */
PQclear(result);
result = NULL;
return NULL;
}
/*
* This function returns in order one of a fixed, NULL pointer terminated list
* of strings (if matching). This can be used if there are only a fixed number
* SQL words that can appear at certain spot.
*/
static char *CompleteFromList(const char *text, int state)
{
static int stringLength, listIndex, matches;
static bool casesensitive = false;
const char *item = NULL;
/* need to have a list */
psql_assert(completion_charpp);
/* Initialization */
if (state == 0) {
listIndex = 0;
stringLength = strlen(text);
casesensitive = completion_case_sensitive;
matches = 0;
}
while ((item = completion_charpp[listIndex++])) {
/* First pass is case sensitive */
if (casesensitive && strncmp(text, item, stringLength) == 0) {
matches++;
return pg_strdup(item);
}
/* Second pass is case insensitive, don't bother counting matches */
if (!casesensitive && pg_strncasecmp(text, item, stringLength) == 0) {
if (completion_case_sensitive)
return pg_strdup(item);
else
/*
* If case insensitive matching was requested initially,
* adjust the case according to setting.
*/
return pg_strdup_keyword_case(item, text);
}
}
/*
* No matches found. If we're not case insensitive already, lets switch to
* being case insensitive and try again
*/
if (casesensitive && matches == 0) {
casesensitive = false;
listIndex = 0;
state++;
return CompleteFromList(text, state);
}
/* If no more matches, return null. */
return NULL;
}
/*
* This function returns one fixed string the first time even if it doesn't
* match what's there, and nothing the second time. This should be used if
* there is only one possibility that can appear at a certain spot, so
* misspellings will be overwritten. The string to be passed must be in
* completion_charp.
*/
static char *CompleteFromConst(const char *text, int state)
{
psql_assert(completion_charp);
if (state == 0) {
if (completion_case_sensitive)
return pg_strdup(completion_charp);
else
/*
* If case insensitive matching was requested initially, adjust
* the case according to setting.
*/
return pg_strdup_keyword_case(completion_charp, text);
} else
return NULL;
}
/*
* This function supports completion with the name of a psql variable.
* The variable names can be prefixed and suffixed with additional text
* to support quoting usages.
*/
static char **CompleteFromVariables(const char *text, const char *prefix, const char *suffix)
{
char **matches = NULL;
int overhead = strlen(prefix) + strlen(suffix) + 1;
char **varnames = NULL;
int nvars = 0;
int maxvars = 100;
int i;
struct _variable *ptr = NULL;
int rc;
size_t sz = 0;
varnames = (char **)pg_malloc((maxvars + 1) * sizeof(char *));
ptr = (pset.vars != NULL) ? pset.vars->next : NULL;
for (; ptr != NULL; ptr = ptr->next) {
char *buffer = NULL;
if (nvars >= maxvars) {
maxvars *= 2;
varnames = (char **)psql_realloc(varnames, (maxvars + 1) * sizeof(char *), (maxvars + 1) * sizeof(char *));
if (varnames == NULL) {
psql_error("out of memory\n");
exit(EXIT_FAILURE);
}
}
sz = strlen(ptr->name) + overhead;
buffer = (char *)pg_malloc(sz);
rc = sprintf_s(buffer, sz, "%s%s%s", prefix, ptr->name, suffix);
check_sprintf_s(rc);
varnames[nvars++] = buffer;
}
varnames[nvars] = NULL;
COMPLETE_WITH_LIST_CS((const char * const *)varnames);
for (i = 0; i < nvars; i++) {
free(varnames[i]);
varnames[i] = NULL;
}
free(varnames);
varnames = NULL;
return matches;
}
/*
* This function wraps rl_filename_completion_function() to strip quotes from
* the input before searching for matches and to quote any matches for which
* the consuming command will require it.
*/
static char *CompleteFromFiles(const char *text, int state)
{
static const char *unquotedText = NULL;
char *unquotedMatch = NULL;
char *ret = NULL;
if (state == 0) {
/* Initialization: stash the unquoted input. */
unquotedText = strtokx(text, "", NULL, "'", *completion_charp, false, true, pset.encoding);
/* expect a NULL return for the empty string only */
if (NULL == unquotedText) {
psql_assert(!*text);
unquotedText = text;
}
}
unquotedMatch = filename_completion_function(unquotedText, state);
if (unquotedMatch != NULL) {
/*
* Caller sets completion_charp to a zero- or one-character string
* containing the escape character. This is necessary since \copy has
* no escape character, but every other backslash command recognizes
* "\" as an escape character. Since we have only two callers, don't
* bother providing a macro to simplify this.
*/
ret = quote_if_needed(unquotedMatch, " \t\r\n\"`", '\'', *completion_charp, pset.encoding);
if (ret != NULL) {
free(unquotedMatch);
unquotedMatch = NULL;
} else
ret = unquotedMatch;
}
return ret;
}
/* HELPER FUNCTIONS */
/*
* Make a pg_strdup copy of s and convert the case according to
* COMP_KEYWORD_CASE variable, using ref as the text that was already entered.
*/
static char *pg_strdup_keyword_case(const char *s, const char *ref)
{
char *ret = NULL;
char *p = NULL;
unsigned char first = ref[0];
int tocase;
const char *varval = NULL;
varval = GetVariable(pset.vars, "COMP_KEYWORD_CASE");
if (varval == NULL)
tocase = 0;
else if (strcmp(varval, "lower") == 0)
tocase = -2;
else if (strcmp(varval, "preserve-lower") == 0)
tocase = -1;
else if (strcmp(varval, "preserve-upper") == 0)
tocase = +1;
else if (strcmp(varval, "upper") == 0)
tocase = +2;
else
tocase = 0;
/* default */
if (tocase == 0)
tocase = +1;
ret = pg_strdup(s);
if (tocase == -2 || ((tocase == -1 || tocase == +1) && islower(first)) || (tocase == -1 && !isalpha(first)))
for (p = ret; *p; p++)
*p = pg_tolower((unsigned char)*p);
else
for (p = ret; *p; p++)
*p = pg_toupper((unsigned char)*p);
return ret;
}
/*
* Execute a query and report any errors. This should be the preferred way of
* talking to the database in this file.
*/
static PGresult *ExecQuery(const char *query)
{
PGresult *result = NULL;
if (query == NULL || pset.db == NULL || PQstatus(pset.db) != CONNECTION_OK)
return NULL;
result = PQexec(pset.db, query);
if (PQresultStatus(result) != PGRES_TUPLES_OK) {
PQclear(result);
result = NULL;
}
return result;
}
/*
* Return the nwords word(s) before point. Words are returned right to left,
* that is, previousWords[0] gets the last word before point.
* If we run out of words, remaining array elements are set to empty strings.
* Each array element is filled with a malloc'd string.
*/
static void GetPreviousWords(int point, char **previousWords, int nwords)
{
const char *buf = rl_line_buffer; /* alias */
int i;
errno_t rc = EOK;
/* first we look for a non-word char before the current point */
for (i = point - 1; i >= 0; i--)
if (strchr(WORD_BREAKS, buf[i]))
break;
point = i;
while (nwords-- > 0) {
int start, end;
char *s = NULL;
/* now find the first non-space which then constitutes the end */
end = -1;
for (i = point; i >= 0; i--) {
if (!isspace((unsigned char)buf[i])) {
end = i;
break;
}
}
/*
* If no end found we return an empty string, because there is no word
* before the point
*/
if (end < 0) {
point = end;
s = pg_strdup("");
} else {
/*
* Otherwise we now look for the start. The start is either the
* last character before any word-break character going backwards
* from the end, or it's simply character 0. We also handle open
* quotes and parentheses.
*/
bool inquotes = false;
int parentheses = 0;
for (start = end; start > 0; start--) {
if (buf[start] == '"')
inquotes = !inquotes;
if (!inquotes) {
if (buf[start] == ')')
parentheses++;
else if (buf[start] == '(') {
if (--parentheses <= 0)
break;
} else if (parentheses == 0 && strchr(WORD_BREAKS, buf[start - 1]))
break;
}
}
point = start - 1;
/* make a copy of chars from start to end inclusive */
s = (char *)pg_malloc(end - start + 2);
rc = strncpy_s(s, end - start + 2, &buf[start], end - start + 1);
s[end - start + 1] = '\0';
securec_check_c(rc, "\0", "\0");
}
*previousWords++ = s;
}
}
#endif /* HAVE_READLINE_READLINE_H */
/*
* Initialize the readline library for our purposes.
*/
void initialize_readline(void)
{
rl_readline_name = (char *)pset.progname;
#ifdef HAVE_READLINE_READLINE_H
/* PsqlCompletion is deleted because it's too complex and not be used at all. */
rl_attempted_completion_function = PsqlCompletion;
#else
rl_attempted_completion_function = NULL;
#endif
rl_basic_word_break_characters = WORD_BREAKS;
completion_max_records = 1000;
/*
* There is a variable rl_completion_query_items for this but apparently
* it's not defined everywhere.
*/
}
#endif /* USE_READLINE */
|
/* Copyright (c) 2021 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "common/base/Base.h"
#include <rocksdb/db.h>
#include <folly/Benchmark.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include "utils/MemoryLockWrapper.h"
#include "utils/NebulaKeyUtils.h"
DEFINE_int64(total_spaces, 10000, "total spaces number");
DEFINE_int64(num_threads, 100, "threads number");
DEFINE_int32(num_batch, 10000, "batch write number");
namespace nebula {
namespace storage {
using ThreadPool = folly::IOThreadPoolExecutor;
using Tuple = std::tuple<int32_t, int32_t, int32_t, std::string>;
using TupleLock = MemoryLockCore<Tuple>;
using StringLock = MemoryLockCore<std::string>;
void forTuple(TupleLock* lock, int64_t spaceId) noexcept {
std::vector<Tuple> toLock;
for (int32_t j = 0; j < FLAGS_num_batch; j++) {
toLock.emplace_back(std::make_tuple(spaceId, j, j, folly::to<std::string>(j)));
}
nebula::MemoryLockGuard<Tuple> lg(lock, std::move(toLock));
}
void forString(StringLock* lock, int64_t spaceId) noexcept {
std::vector<std::string> toLock;
size_t vIdLen = 32;
for (int32_t j = 0; j < FLAGS_num_batch; j++) {
toLock.emplace_back(folly::to<std::string>(spaceId) +
NebulaKeyUtils::vertexKey(vIdLen, j, folly::to<std::string>(j), j));
}
nebula::MemoryLockGuard<std::string> lg(lock, std::move(toLock));
}
BENCHMARK(TupleKey) {
std::unique_ptr<TupleLock> lock = std::make_unique<TupleLock>();
auto pool = std::make_unique<ThreadPool>(FLAGS_num_threads);
for (auto i = 0; i < FLAGS_total_spaces; ++i) {
pool->add(std::bind(forTuple, lock.get(), i));
}
pool->join();
}
BENCHMARK_RELATIVE(StringKey) {
std::unique_ptr<StringLock> lock = std::make_unique<StringLock>();
auto pool = std::make_unique<ThreadPool>(FLAGS_num_threads);
for (auto i = 0; i < FLAGS_total_spaces; ++i) {
pool->add(std::bind(forString, lock.get(), i));
}
pool->join();
}
} // namespace storage
} // namespace nebula
int main(int argc, char **argv) {
folly::init(&argc, &argv, true);
folly::runBenchmarks();
return 0;
}
// ============================================================================
// /MemoryLockBenchmark.cpp relative time/iter iters/s
// ============================================================================
// TupleKey 4.85s 206.07m
// StringKey 90.23% 5.38s 185.94m
// ============================================================================
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECOREPYTHON_POINTERFROMSWIG_INL
#define IECOREPYTHON_POINTERFROMSWIG_INL
#include "boost/python.hpp"
namespace IECorePython
{
namespace Detail
{
struct PySwigObject
{
PyObject_HEAD
void * ptr;
};
static void *extractSWIGPointer( PyObject *o )
{
if( !PyObject_HasAttrString( o, "this" ) )
{
return 0;
}
PyObject *thisAttr = PyObject_GetAttrString( o, "this" );
if( !thisAttr )
{
return 0;
}
return (((PySwigObject *)thisAttr)->ptr);
}
} // namespace Detail
template<typename T>
PointerFromSWIG<T>::PointerFromSWIG()
{
boost::python::converter::registry::insert( &Detail::extractSWIGPointer, boost::python::type_id<T>() );
}
} // namespace IECorePython
#endif // IECOREPYTHON_POINTERFROMSWIG_INL
|
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/source/platform/platform.h"
#include "cl_api_tests.h"
using namespace NEO;
typedef api_tests clRetainReleaseDeviceTests;
namespace ULT {
TEST_F(clRetainReleaseDeviceTests, GivenRootDeviceWhenRetainingThenReferenceCountIsOne) {
cl_uint numEntries = numRootDevices;
cl_device_id devices[numRootDevices];
retVal = clGetDeviceIDs(pPlatform, CL_DEVICE_TYPE_GPU, numEntries, devices,
nullptr);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = clRetainDevice(devices[testedRootDeviceIndex]);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = clRetainDevice(devices[testedRootDeviceIndex]);
EXPECT_EQ(CL_SUCCESS, retVal);
cl_uint theRef;
retVal = clGetDeviceInfo(devices[testedRootDeviceIndex], CL_DEVICE_REFERENCE_COUNT,
sizeof(cl_uint), &theRef, NULL);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, theRef);
}
TEST_F(clRetainReleaseDeviceTests, GivenRootDeviceWhenReleasingThenReferenceCountIsOne) {
constexpr cl_uint numEntries = numRootDevices;
cl_device_id devices[numRootDevices];
auto retVal = clGetDeviceIDs(pPlatform, CL_DEVICE_TYPE_GPU, numEntries, devices,
nullptr);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = clReleaseDevice(devices[testedRootDeviceIndex]);
EXPECT_EQ(CL_SUCCESS, retVal);
retVal = clReleaseDevice(devices[testedRootDeviceIndex]);
EXPECT_EQ(CL_SUCCESS, retVal);
cl_uint theRef;
retVal = clGetDeviceInfo(devices[testedRootDeviceIndex], CL_DEVICE_REFERENCE_COUNT,
sizeof(cl_uint), &theRef, NULL);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(1u, theRef);
}
} // namespace ULT
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef REALM_UTIL_ANY_HPP
#define REALM_UTIL_ANY_HPP
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <typeinfo>
#include <realm/util/backtrace.hpp>
namespace realm {
namespace util {
using bad_cast = std::bad_cast;
// A naive implementation of C++17's std::any
// This does not perform the small-object optimization or make any particular
// attempt at being performant
class Any final {
public:
// Constructors
Any() = default;
Any(Any&&) noexcept = default;
~Any() = default;
Any& operator=(Any&&) noexcept = default;
Any(Any const& rhs)
: m_value(rhs.m_value ? rhs.m_value->copy() : nullptr)
{
}
template<typename T, typename = typename std::enable_if<!std::is_same<typename std::decay<T>::type, Any>::value>::type>
Any(T&& value)
: m_value(std::make_unique<Value<typename std::decay<T>::type>>(std::forward<T>(value)))
{
}
Any& operator=(Any const& rhs)
{
m_value = rhs.m_value ? rhs.m_value->copy() : nullptr;
return *this;
}
template<typename T, typename = typename std::enable_if<!std::is_same<typename std::decay<T>::type, Any>::value>::type>
Any& operator=(T&& value)
{
m_value = std::make_unique<Value<typename std::decay<T>::type>>(std::forward<T>(value));
return *this;
}
// Modifiers
void reset() noexcept { m_value.reset(); }
void swap(Any& rhs) noexcept { std::swap(m_value, rhs.m_value); }
// Observers
bool has_value() const noexcept { return m_value != nullptr; }
std::type_info const& type() const noexcept { return m_value ? m_value->type() : typeid(void); }
private:
struct ValueBase {
virtual ~ValueBase() noexcept { }
virtual std::type_info const& type() const noexcept = 0;
virtual std::unique_ptr<ValueBase> copy() const = 0;
};
template<typename T>
struct Value : ValueBase {
T value;
template<typename U> Value(U&& v) : value(std::forward<U>(v)) { }
std::type_info const& type() const noexcept override { return typeid(T); }
std::unique_ptr<ValueBase> copy() const override
{
return std::make_unique<Value<T>>(value);
}
};
std::unique_ptr<ValueBase> m_value;
template<typename T>
friend const T* any_cast(const Any* operand) noexcept;
template<typename T>
friend T* any_cast(Any* operand) noexcept;
template<typename T>
const T* cast() const noexcept
{
return &static_cast<Value<T>*>(m_value.get())->value;
}
template<typename T>
T* cast() noexcept
{
return &static_cast<Value<T>*>(m_value.get())->value;
}
};
template<typename T>
T any_cast(Any const& value)
{
auto ptr = any_cast<typename std::add_const<typename std::remove_reference<T>::type>::type>(&value);
if (!ptr)
throw bad_cast();
return *ptr;
}
template<typename T>
T any_cast(Any& value)
{
auto ptr = any_cast<typename std::remove_reference<T>::type>(&value);
if (!ptr)
throw bad_cast();
return *ptr;
}
template<typename T>
T any_cast(Any&& value)
{
auto ptr = any_cast<typename std::remove_reference<T>::type>(&value);
if (!ptr)
throw bad_cast();
return std::move(*ptr);
}
template<typename T>
T* any_cast(Any* value) noexcept
{
return value && value->type() == typeid(T) ? value->cast<T>() : nullptr;
}
template<typename T>
const T* any_cast(const Any* value) noexcept
{
return value && value->type() == typeid(T) ? value->cast<T>() : nullptr;
}
} // namespace util
} // namespace realm
namespace std {
inline void swap(realm::util::Any& lhs, realm::util::Any& rhs) noexcept
{
lhs.swap(rhs);
}
} // namespace std
#endif // REALM_UTIL_ANY_HPP
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020-2021 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <couchbase/utils/url_codec.hxx>
#include <couchbase/operations/management/group_upsert.hxx>
#include <couchbase/operations/management/error_utils.hxx>
#include <couchbase/errors.hxx>
#include <couchbase/utils/json.hxx>
namespace couchbase::operations::management
{
std::error_code
group_upsert_request::encode_to(encoded_request_type& encoded, http_context& /* context */) const
{
encoded.method = "PUT";
encoded.path = fmt::format("/settings/rbac/groups/{}", group.name);
std::vector<std::string> params{};
if (group.description) {
params.push_back(fmt::format("description={}", utils::string_codec::url_encode(group.description.value())));
}
if (group.ldap_group_reference) {
params.push_back(fmt::format("ldap_group_ref={}", utils::string_codec::url_encode(group.ldap_group_reference.value())));
}
std::vector<std::string> encoded_roles{};
encoded_roles.reserve(group.roles.size());
for (const auto& role : group.roles) {
std::string spec = role.name;
if (role.bucket) {
spec += fmt::format("[{}", role.bucket.value());
if (role.scope) {
spec += fmt::format(":{}", role.scope.value());
if (role.collection) {
spec += fmt::format(":{}", role.collection.value());
}
}
spec += "]";
}
encoded_roles.push_back(spec);
}
if (!encoded_roles.empty()) {
std::string concatenated = fmt::format("{}", fmt::join(encoded_roles, ","));
params.push_back(fmt::format("roles={}", utils::string_codec::url_encode(concatenated)));
}
encoded.body = fmt::format("{}", fmt::join(params, "&"));
encoded.headers["content-type"] = "application/x-www-form-urlencoded";
return {};
}
group_upsert_response
group_upsert_request::make_response(error_context::http&& ctx, const encoded_response_type& encoded) const
{
group_upsert_response response{ std::move(ctx) };
if (!response.ctx.ec) {
switch (encoded.status_code) {
case 200:
break;
case 400: {
response.ctx.ec = error::common_errc::invalid_argument;
tao::json::value payload{};
try {
payload = utils::json::parse(encoded.body);
} catch (const tao::pegtl::parse_error&) {
response.ctx.ec = error::common_errc::parsing_failure;
return response;
}
if (const auto* errors = payload.find("errors"); errors != nullptr && errors->is_object()) {
for (const auto& [code, message] : errors->get_object()) {
response.errors.emplace_back(fmt::format("{}: {}", code, message.get_string()));
}
}
} break;
default:
response.ctx.ec = extract_common_error_code(encoded.status_code, encoded.body);
break;
}
}
return response;
}
} // namespace couchbase::operations::management
|
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/stack_frame.h"
#include "platform/memory_sanitizer.h"
#include "vm/compiler/assembler/assembler.h"
#include "vm/compiler/runtime_api.h"
#include "vm/deopt_instructions.h"
#include "vm/heap/become.h"
#include "vm/isolate.h"
#include "vm/object.h"
#include "vm/object_store.h"
#include "vm/os.h"
#include "vm/parser.h"
#include "vm/raw_object.h"
#include "vm/reusable_handles.h"
#include "vm/reverse_pc_lookup_cache.h"
#include "vm/scopes.h"
#include "vm/stub_code.h"
#include "vm/visitor.h"
namespace dart {
DECLARE_FLAG(bool, enable_interpreter);
const FrameLayout invalid_frame_layout = {
/*.first_object_from_fp = */ -1,
/*.last_fixed_object_from_fp = */ -1,
/*.param_end_from_fp = */ -1,
/*.last_param_from_entry_sp = */ -1,
/*.first_local_from_fp = */ -1,
/*.dart_fixed_frame_size = */ -1,
/*.saved_caller_pp_from_fp = */ -1,
/*.code_from_fp = */ -1,
/*.exit_link_slot_from_entry_fp = */ -1,
};
const FrameLayout default_frame_layout = {
/*.first_object_from_fp = */ kFirstObjectSlotFromFp,
/*.last_fixed_object_from_fp = */ kLastFixedObjectSlotFromFp,
/*.param_end_from_fp = */ kParamEndSlotFromFp,
/*.last_param_from_entry_sp = */ kLastParamSlotFromEntrySp,
/*.first_local_from_fp = */ kFirstLocalSlotFromFp,
/*.dart_fixed_frame_size = */ kDartFrameFixedSize,
/*.saved_caller_pp_from_fp = */ kSavedCallerPpSlotFromFp,
/*.code_from_fp = */ kPcMarkerSlotFromFp,
/*.exit_link_slot_from_entry_fp = */ kExitLinkSlotFromEntryFp,
};
const FrameLayout bare_instructions_frame_layout = {
/*.first_object_from_pc =*/kFirstObjectSlotFromFp, // No saved PP slot.
/*.last_fixed_object_from_fp = */ kLastFixedObjectSlotFromFp +
2, // No saved CODE, PP slots
/*.param_end_from_fp = */ kParamEndSlotFromFp,
/*.last_param_from_entry_sp = */ kLastParamSlotFromEntrySp,
/*.first_local_from_fp =*/kFirstLocalSlotFromFp +
2, // No saved CODE, PP slots.
/*.dart_fixed_frame_size =*/kDartFrameFixedSize -
2, // No saved CODE, PP slots.
/*.saved_caller_pp_from_fp = */ 0, // No saved PP slot.
/*.code_from_fp = */ 0, // No saved CODE
/*.exit_link_slot_from_entry_fp = */ kExitLinkSlotFromEntryFp,
};
namespace compiler {
namespace target {
FrameLayout frame_layout = invalid_frame_layout;
}
} // namespace compiler
FrameLayout runtime_frame_layout = invalid_frame_layout;
int FrameLayout::FrameSlotForVariable(const LocalVariable* variable) const {
ASSERT(!variable->is_captured());
return this->FrameSlotForVariableIndex(variable->index().value());
}
int FrameLayout::FrameSlotForVariableIndex(int variable_index) const {
// Variable indices are:
// [1, 2, ..., M] for the M parameters.
// [0, -1, -2, ... -(N-1)] for the N [LocalVariable]s
// See (runtime/vm/scopes.h)
return variable_index <= 0 ? (variable_index + first_local_from_fp)
: (variable_index + param_end_from_fp);
}
void FrameLayout::Init() {
// By default we use frames with CODE_REG/PP in the frame.
compiler::target::frame_layout = default_frame_layout;
runtime_frame_layout = default_frame_layout;
if (FLAG_precompiled_mode && FLAG_use_bare_instructions) {
compiler::target::frame_layout = bare_instructions_frame_layout;
}
#if defined(DART_PRECOMPILED_RUNTIME)
if (FLAG_precompiled_mode && FLAG_use_bare_instructions) {
compiler::target::frame_layout = invalid_frame_layout;
runtime_frame_layout = bare_instructions_frame_layout;
}
#endif
}
Isolate* StackFrame::IsolateOfBareInstructionsFrame() const {
auto isolate = this->isolate();
if (isolate->object_store()->code_order_table() != Object::null()) {
auto rct = isolate->reverse_pc_lookup_cache();
if (rct->Contains(pc())) return isolate;
}
isolate = Dart::vm_isolate();
if (isolate->object_store()->code_order_table() != Object::null()) {
auto rct = isolate->reverse_pc_lookup_cache();
if (rct->Contains(pc())) return isolate;
}
return nullptr;
}
bool StackFrame::IsBareInstructionsDartFrame() const {
NoSafepointScope no_safepoint;
if (auto isolate = IsolateOfBareInstructionsFrame()) {
Code code;
auto rct = isolate->reverse_pc_lookup_cache();
code = rct->Lookup(pc());
const intptr_t cid = code.owner()->GetClassId();
ASSERT(cid == kNullCid || cid == kClassCid || cid == kFunctionCid);
return cid == kFunctionCid;
}
return false;
}
bool StackFrame::IsBareInstructionsStubFrame() const {
NoSafepointScope no_safepoint;
if (auto isolate = IsolateOfBareInstructionsFrame()) {
Code code;
auto rct = isolate->reverse_pc_lookup_cache();
code = rct->Lookup(pc());
const intptr_t cid = code.owner()->GetClassId();
ASSERT(cid == kNullCid || cid == kClassCid || cid == kFunctionCid);
return cid == kNullCid || cid == kClassCid;
}
return false;
}
bool StackFrame::IsStubFrame() const {
if (is_interpreted()) {
return false;
}
if (FLAG_precompiled_mode && FLAG_use_bare_instructions) {
return IsBareInstructionsStubFrame();
}
ASSERT(!(IsEntryFrame() || IsExitFrame()));
#if !defined(HOST_OS_WINDOWS) && !defined(HOST_OS_FUCHSIA)
// On Windows and Fuchsia, the profiler calls this from a separate thread
// where Thread::Current() is NULL, so we cannot create a NoSafepointScope.
NoSafepointScope no_safepoint;
#endif
RawCode* code = GetCodeObject();
ASSERT(code != Object::null());
const intptr_t cid = code->ptr()->owner_->GetClassId();
ASSERT(cid == kNullCid || cid == kClassCid || cid == kFunctionCid);
return cid == kNullCid || cid == kClassCid;
}
const char* StackFrame::ToCString() const {
ASSERT(thread_ == Thread::Current());
Zone* zone = Thread::Current()->zone();
if (IsDartFrame()) {
if (is_interpreted()) {
const Bytecode& bytecode = Bytecode::Handle(zone, LookupDartBytecode());
ASSERT(!bytecode.IsNull());
return zone->PrintToString("[%-8s : sp(%#" Px ") fp(%#" Px ") pc(%#" Px
" offset:0x%" Px ") %s ]",
GetName(), sp(), fp(), pc(),
pc() - bytecode.PayloadStart(),
bytecode.FullyQualifiedName());
}
const Code& code = Code::Handle(zone, LookupDartCode());
ASSERT(!code.IsNull());
const Object& owner = Object::Handle(zone, code.owner());
ASSERT(!owner.IsNull());
if (owner.IsFunction()) {
const char* opt = code.is_optimized() ? "*" : "";
const Function& function = Function::Cast(owner);
return zone->PrintToString(
"[%-8s : sp(%#" Px ") fp(%#" Px ") pc(%#" Px ") %s%s ]", GetName(),
sp(), fp(), pc(), opt, function.ToFullyQualifiedCString());
} else {
return zone->PrintToString(
"[%-8s : sp(%#" Px ") fp(%#" Px ") pc(%#" Px ") %s ]", GetName(),
sp(), fp(), pc(), owner.ToCString());
}
} else {
return zone->PrintToString("[%-8s : sp(%#" Px ") fp(%#" Px ") pc(%#" Px
")]",
GetName(), sp(), fp(), pc());
}
}
void ExitFrame::VisitObjectPointers(ObjectPointerVisitor* visitor) {
ASSERT(visitor != NULL);
// Visit pc marker and saved pool pointer, or, for interpreted frame, code
// object and function object.
RawObject** last_fixed =
reinterpret_cast<RawObject**>(fp()) +
(is_interpreted() ? kKBCLastFixedObjectSlotFromFp
: runtime_frame_layout.first_object_from_fp);
RawObject** first_fixed =
reinterpret_cast<RawObject**>(fp()) +
(is_interpreted() ? kKBCFirstObjectSlotFromFp
: runtime_frame_layout.last_fixed_object_from_fp);
if (first_fixed <= last_fixed) {
visitor->VisitPointers(first_fixed, last_fixed);
} else {
ASSERT(runtime_frame_layout.first_object_from_fp ==
runtime_frame_layout.first_local_from_fp);
}
}
void EntryFrame::VisitObjectPointers(ObjectPointerVisitor* visitor) {
ASSERT(visitor != NULL);
// Visit objects between SP and (FP - callee_save_area).
RawObject** first = is_interpreted() ? reinterpret_cast<RawObject**>(fp()) +
kKBCSavedArgDescSlotFromEntryFp
: reinterpret_cast<RawObject**>(sp());
RawObject** last = is_interpreted() ? reinterpret_cast<RawObject**>(sp())
: reinterpret_cast<RawObject**>(fp()) +
kExitLinkSlotFromEntryFp - 1;
// There may not be any pointer to visit; in this case, first > last.
visitor->VisitPointers(first, last);
}
void StackFrame::VisitObjectPointers(ObjectPointerVisitor* visitor) {
ASSERT(visitor != NULL);
// NOTE: This code runs while GC is in progress and runs within
// a NoHandleScope block. Hence it is not ok to use regular Zone or
// Scope handles. We use direct stack handles, the raw pointers in
// these handles are not traversed. The use of handles is mainly to
// be able to reuse the handle based code and avoid having to add
// helper functions to the raw object interface.
NoSafepointScope no_safepoint;
Code code;
if (auto isolate = IsolateOfBareInstructionsFrame()) {
code = isolate->reverse_pc_lookup_cache()->Lookup(pc());
} else {
RawObject* pc_marker = *(reinterpret_cast<RawObject**>(
fp() + ((is_interpreted() ? kKBCPcMarkerSlotFromFp
: runtime_frame_layout.code_from_fp) *
kWordSize)));
// May forward raw code. Note we don't just visit the pc marker slot first
// because the visitor's forwarding might not be idempotent.
visitor->VisitPointer(&pc_marker);
if (pc_marker->IsHeapObject() && (pc_marker->GetClassId() == kCodeCid)) {
code ^= pc_marker;
} else {
ASSERT(pc_marker == Object::null() ||
(is_interpreted() && (!pc_marker->IsHeapObject() ||
(pc_marker->GetClassId() == kBytecodeCid))));
}
}
if (!code.IsNull()) {
// Optimized frames have a stack map. We need to visit the frame based
// on the stack map.
CompressedStackMaps maps;
maps = code.compressed_stackmaps();
CompressedStackMaps global_table;
global_table =
this->isolate()->object_store()->canonicalized_stack_map_entries();
CompressedStackMapsIterator it(maps, global_table);
const uword start = code.PayloadStart();
const uint32_t pc_offset = pc() - start;
if (it.Find(pc_offset)) {
if (is_interpreted()) {
UNIMPLEMENTED();
}
RawObject** first = reinterpret_cast<RawObject**>(sp());
RawObject** last = reinterpret_cast<RawObject**>(
fp() + (runtime_frame_layout.first_local_from_fp * kWordSize));
// A stack map is present in the code object, use the stack map to
// visit frame slots which are marked as having objects.
//
// The layout of the frame is (lower addresses to the right):
// | spill slots | outgoing arguments | saved registers | slow-path args |
// |XXXXXXXXXXXXX|--------------------|XXXXXXXXXXXXXXXXX|XXXXXXXXXXXXXXXX|
//
// The spill slots and any saved registers are described in the stack
// map. The outgoing arguments are assumed to be tagged; the number
// of outgoing arguments is not explicitly tracked.
// Spill slots are at the 'bottom' of the frame.
intptr_t spill_slot_count = it.SpillSlotBitCount();
for (intptr_t bit = 0; bit < spill_slot_count; ++bit) {
if (it.IsObject(bit)) {
visitor->VisitPointer(last);
}
--last;
}
// The live registers at the 'top' of the frame comprise the rest of the
// stack map.
for (intptr_t bit = it.Length() - 1; bit >= spill_slot_count; --bit) {
if (it.IsObject(bit)) {
visitor->VisitPointer(first);
}
++first;
}
// The last slot can be one slot (but not more) past the last slot
// in the case that all slots were covered by the stack map.
ASSERT((last + 1) >= first);
visitor->VisitPointers(first, last);
// Now visit other slots which might be part of the calling convention.
first = reinterpret_cast<RawObject**>(
fp() + ((runtime_frame_layout.first_local_from_fp + 1) * kWordSize));
last = reinterpret_cast<RawObject**>(
fp() + (runtime_frame_layout.first_object_from_fp * kWordSize));
visitor->VisitPointers(first, last);
return;
}
// If we are missing a stack map for a given PC offset, this must either be
// unoptimized code, code with no stack map information at all, or the entry
// to an osr function. In each of these cases, all stack slots contain
// tagged pointers, so fall through.
ASSERT(!code.is_optimized() || maps.IsNull() ||
(pc_offset == code.EntryPoint() - code.PayloadStart()));
}
// For normal unoptimized Dart frames and Stub frames each slot
// between the first and last included are tagged objects.
if (is_interpreted()) {
// Do not visit caller's pc or caller's fp.
RawObject** first =
reinterpret_cast<RawObject**>(fp()) + kKBCFirstObjectSlotFromFp;
RawObject** last =
reinterpret_cast<RawObject**>(fp()) + kKBCLastFixedObjectSlotFromFp;
visitor->VisitPointers(first, last);
}
RawObject** first =
reinterpret_cast<RawObject**>(is_interpreted() ? fp() : sp());
RawObject** last = reinterpret_cast<RawObject**>(
is_interpreted()
? sp()
: fp() + (runtime_frame_layout.first_object_from_fp * kWordSize));
visitor->VisitPointers(first, last);
}
RawFunction* StackFrame::LookupDartFunction() const {
if (is_interpreted()) {
RawObject* result = *(reinterpret_cast<RawFunction**>(
fp() + kKBCFunctionSlotFromFp * kWordSize));
ASSERT((result == Object::null()) ||
(result->GetClassId() == kFunctionCid));
return reinterpret_cast<RawFunction*>(result);
}
const Code& code = Code::Handle(LookupDartCode());
if (!code.IsNull()) {
return code.function();
}
return Function::null();
}
RawCode* StackFrame::LookupDartCode() const {
// We add a no gc scope to ensure that the code below does not trigger
// a GC as we are handling raw object references here. It is possible
// that the code is called while a GC is in progress, that is ok.
#if !defined(HOST_OS_WINDOWS) && !defined(HOST_OS_FUCHSIA)
// On Windows and Fuchsia, the profiler calls this from a separate thread
// where Thread::Current() is NULL, so we cannot create a NoSafepointScope.
NoSafepointScope no_safepoint;
#endif
if (auto isolate = IsolateOfBareInstructionsFrame()) {
return isolate->reverse_pc_lookup_cache()->Lookup(pc());
}
RawCode* code = GetCodeObject();
if ((code != Code::null()) &&
(code->ptr()->owner_->GetClassId() == kFunctionCid)) {
return code;
}
return Code::null();
}
RawCode* StackFrame::GetCodeObject() const {
ASSERT(!is_interpreted());
if (auto isolate = IsolateOfBareInstructionsFrame()) {
return isolate->reverse_pc_lookup_cache()->Lookup(pc());
} else {
RawObject* pc_marker = *(reinterpret_cast<RawObject**>(
fp() + runtime_frame_layout.code_from_fp * kWordSize));
ASSERT((pc_marker == Object::null()) ||
(pc_marker->GetClassId() == kCodeCid));
return reinterpret_cast<RawCode*>(pc_marker);
}
}
RawBytecode* StackFrame::LookupDartBytecode() const {
// We add a no gc scope to ensure that the code below does not trigger
// a GC as we are handling raw object references here. It is possible
// that the code is called while a GC is in progress, that is ok.
#if !defined(HOST_OS_WINDOWS) && !defined(HOST_OS_FUCHSIA)
// On Windows and Fuchsia, the profiler calls this from a separate thread
// where Thread::Current() is NULL, so we cannot create a NoSafepointScope.
NoSafepointScope no_safepoint;
#endif
return GetBytecodeObject();
}
RawBytecode* StackFrame::GetBytecodeObject() const {
ASSERT(is_interpreted());
RawObject* pc_marker = *(
reinterpret_cast<RawObject**>(fp() + kKBCPcMarkerSlotFromFp * kWordSize));
ASSERT((pc_marker == Object::null()) ||
(pc_marker->GetClassId() == kBytecodeCid));
return reinterpret_cast<RawBytecode*>(pc_marker);
}
bool StackFrame::FindExceptionHandler(Thread* thread,
uword* handler_pc,
bool* needs_stacktrace,
bool* has_catch_all,
bool* is_optimized) const {
REUSABLE_CODE_HANDLESCOPE(thread);
Code& code = reused_code_handle.Handle();
REUSABLE_BYTECODE_HANDLESCOPE(thread);
Bytecode& bytecode = reused_bytecode_handle.Handle();
REUSABLE_EXCEPTION_HANDLERS_HANDLESCOPE(thread);
ExceptionHandlers& handlers = reused_exception_handlers_handle.Handle();
REUSABLE_PC_DESCRIPTORS_HANDLESCOPE(thread);
PcDescriptors& descriptors = reused_pc_descriptors_handle.Handle();
uword start;
if (is_interpreted()) {
bytecode = LookupDartBytecode();
ASSERT(!bytecode.IsNull());
start = bytecode.PayloadStart();
handlers = bytecode.exception_handlers();
} else {
code = LookupDartCode();
if (code.IsNull()) {
return false; // Stub frames do not have exception handlers.
}
start = code.PayloadStart();
handlers = code.exception_handlers();
descriptors = code.pc_descriptors();
*is_optimized = code.is_optimized();
}
HandlerInfoCache* cache = thread->isolate()->handler_info_cache();
ExceptionHandlerInfo* info = cache->Lookup(pc());
if (info != NULL) {
*handler_pc = start + info->handler_pc_offset;
*needs_stacktrace = (info->needs_stacktrace != 0);
*has_catch_all = (info->has_catch_all != 0);
return true;
}
if (handlers.num_entries() == 0) {
return false;
}
intptr_t try_index = -1;
if (is_interpreted()) {
try_index = bytecode.GetTryIndexAtPc(pc());
} else {
uword pc_offset = pc() - code.PayloadStart();
PcDescriptors::Iterator iter(descriptors, RawPcDescriptors::kAnyKind);
while (iter.MoveNext()) {
const intptr_t current_try_index = iter.TryIndex();
if ((iter.PcOffset() == pc_offset) && (current_try_index != -1)) {
try_index = current_try_index;
break;
}
}
}
if (try_index == -1) {
return false;
}
ExceptionHandlerInfo handler_info;
handlers.GetHandlerInfo(try_index, &handler_info);
*handler_pc = start + handler_info.handler_pc_offset;
*needs_stacktrace = (handler_info.needs_stacktrace != 0);
*has_catch_all = (handler_info.has_catch_all != 0);
cache->Insert(pc(), handler_info);
return true;
}
TokenPosition StackFrame::GetTokenPos() const {
if (is_interpreted()) {
const Bytecode& bytecode = Bytecode::Handle(LookupDartBytecode());
if (bytecode.IsNull()) {
return TokenPosition::kNoSource; // Stub frames do not have token_pos.
}
return bytecode.GetTokenIndexOfPC(pc());
}
const Code& code = Code::Handle(LookupDartCode());
if (code.IsNull()) {
return TokenPosition::kNoSource; // Stub frames do not have token_pos.
}
uword pc_offset = pc() - code.PayloadStart();
const PcDescriptors& descriptors =
PcDescriptors::Handle(code.pc_descriptors());
ASSERT(!descriptors.IsNull());
PcDescriptors::Iterator iter(descriptors, RawPcDescriptors::kAnyKind);
while (iter.MoveNext()) {
if (iter.PcOffset() == pc_offset) {
return TokenPosition(iter.TokenPos());
}
}
return TokenPosition::kNoSource;
}
bool StackFrame::IsValid() const {
if (IsEntryFrame() || IsExitFrame() || IsStubFrame()) {
return true;
}
if (is_interpreted()) {
return (LookupDartBytecode() != Bytecode::null());
}
return (LookupDartCode() != Code::null());
}
void StackFrame::DumpCurrentTrace() {
StackFrameIterator frames(ValidationPolicy::kDontValidateFrames,
Thread::Current(),
StackFrameIterator::kNoCrossThreadIteration);
StackFrame* frame = frames.NextFrame();
while (frame != nullptr) {
OS::PrintErr("%s\n", frame->ToCString());
frame = frames.NextFrame();
}
}
void StackFrameIterator::SetupLastExitFrameData() {
ASSERT(thread_ != NULL);
uword exit_marker = thread_->top_exit_frame_info();
frames_.fp_ = exit_marker;
if (FLAG_enable_interpreter) {
frames_.CheckIfInterpreted(exit_marker);
}
}
void StackFrameIterator::SetupNextExitFrameData() {
ASSERT(entry_.fp() != 0);
uword exit_address =
entry_.fp() + ((entry_.is_interpreted() ? kKBCExitLinkSlotFromEntryFp
: kExitLinkSlotFromEntryFp) *
kWordSize);
uword exit_marker = *reinterpret_cast<uword*>(exit_address);
frames_.fp_ = exit_marker;
frames_.sp_ = 0;
frames_.pc_ = 0;
if (FLAG_enable_interpreter) {
frames_.CheckIfInterpreted(exit_marker);
}
}
// Tell MemorySanitizer that generated code initializes part of the stack.
// TODO(koda): Limit to frames that are actually written by generated code.
static void UnpoisonStack(uword fp) {
ASSERT(fp != 0);
uword size = OSThread::GetSpecifiedStackSize();
MSAN_UNPOISON(reinterpret_cast<void*>(fp - size), 2 * size);
}
StackFrameIterator::StackFrameIterator(ValidationPolicy validation_policy,
Thread* thread,
CrossThreadPolicy cross_thread_policy)
: validate_(validation_policy == ValidationPolicy::kValidateFrames),
entry_(thread),
exit_(thread),
frames_(thread),
current_frame_(NULL),
thread_(thread) {
ASSERT(cross_thread_policy == kAllowCrossThreadIteration ||
thread_ == Thread::Current());
SetupLastExitFrameData(); // Setup data for last exit frame.
}
StackFrameIterator::StackFrameIterator(uword last_fp,
ValidationPolicy validation_policy,
Thread* thread,
CrossThreadPolicy cross_thread_policy)
: validate_(validation_policy == ValidationPolicy::kValidateFrames),
entry_(thread),
exit_(thread),
frames_(thread),
current_frame_(NULL),
thread_(thread) {
ASSERT(cross_thread_policy == kAllowCrossThreadIteration ||
thread_ == Thread::Current());
frames_.fp_ = last_fp;
frames_.sp_ = 0;
frames_.pc_ = 0;
if (FLAG_enable_interpreter) {
frames_.CheckIfInterpreted(last_fp);
}
}
StackFrameIterator::StackFrameIterator(uword fp,
uword sp,
uword pc,
ValidationPolicy validation_policy,
Thread* thread,
CrossThreadPolicy cross_thread_policy)
: validate_(validation_policy == ValidationPolicy::kValidateFrames),
entry_(thread),
exit_(thread),
frames_(thread),
current_frame_(NULL),
thread_(thread) {
ASSERT(cross_thread_policy == kAllowCrossThreadIteration ||
thread_ == Thread::Current());
frames_.fp_ = fp;
frames_.sp_ = sp;
frames_.pc_ = pc;
if (FLAG_enable_interpreter) {
frames_.CheckIfInterpreted(fp);
}
}
StackFrame* StackFrameIterator::NextFrame() {
// When we are at the start of iteration after having created an
// iterator object, current_frame_ will be NULL as we haven't seen
// any frames yet (unless we start iterating in the simulator from a given
// triplet of fp, sp, and pc). At this point, if NextFrame is called, it tries
// to set up the next exit frame by reading the top_exit_frame_info
// from the isolate. If we do not have any dart invocations yet,
// top_exit_frame_info will be 0 and so we would return NULL.
// current_frame_ will also be NULL, when we are at the end of having
// iterated through all the frames. If NextFrame is called at this
// point, we will try and set up the next exit frame, but since we are
// at the end of the iteration, fp_ will be 0 and we would return NULL.
if (current_frame_ == NULL) {
if (!HasNextFrame()) {
return NULL;
}
UnpoisonStack(frames_.fp_);
if (frames_.pc_ == 0) {
// Iteration starts from an exit frame given by its fp.
current_frame_ = NextExitFrame();
} else if (*(reinterpret_cast<uword*>(
frames_.fp_ +
((frames_.is_interpreted() ? kKBCSavedCallerFpSlotFromFp
: kSavedCallerFpSlotFromFp) *
kWordSize))) == 0) {
// Iteration starts from an entry frame given by its fp, sp, and pc.
current_frame_ = NextEntryFrame();
} else {
// Iteration starts from a Dart or stub frame given by its fp, sp, and pc.
current_frame_ = frames_.NextFrame(validate_);
}
return current_frame_;
}
ASSERT(!validate_ || current_frame_->IsValid());
if (current_frame_->IsEntryFrame()) {
if (HasNextFrame()) { // We have another chained block.
current_frame_ = NextExitFrame();
return current_frame_;
}
current_frame_ = NULL; // No more frames.
return current_frame_;
}
ASSERT(!validate_ || current_frame_->IsExitFrame() ||
current_frame_->IsDartFrame(validate_) ||
current_frame_->IsStubFrame());
// Consume dart/stub frames using StackFrameIterator::FrameSetIterator
// until we are out of dart/stub frames at which point we return the
// corresponding entry frame for that set of dart/stub frames.
current_frame_ =
(frames_.HasNext()) ? frames_.NextFrame(validate_) : NextEntryFrame();
return current_frame_;
}
void StackFrameIterator::FrameSetIterator::CheckIfInterpreted(
uword exit_marker) {
#if !defined(DART_PRECOMPILED_RUNTIME)
// TODO(regis): We should rely on a new thread vm_tag to identify an
// interpreter frame and not need the HasFrame() method.
ASSERT(FLAG_enable_interpreter);
Interpreter* interpreter = thread_->interpreter();
is_interpreted_ = (interpreter != NULL) && interpreter->HasFrame(exit_marker);
#endif // !defined(DART_PRECOMPILED_RUNTIME)
}
StackFrame* StackFrameIterator::FrameSetIterator::NextFrame(bool validate) {
StackFrame* frame;
ASSERT(HasNext());
frame = &stack_frame_;
frame->sp_ = sp_;
frame->fp_ = fp_;
frame->pc_ = pc_;
frame->is_interpreted_ = is_interpreted_;
sp_ = frame->GetCallerSp();
fp_ = frame->GetCallerFp();
pc_ = frame->GetCallerPc();
ASSERT(is_interpreted_ == frame->is_interpreted_);
ASSERT(!validate || frame->IsValid());
return frame;
}
ExitFrame* StackFrameIterator::NextExitFrame() {
exit_.sp_ = frames_.sp_;
exit_.fp_ = frames_.fp_;
exit_.pc_ = frames_.pc_;
exit_.is_interpreted_ = frames_.is_interpreted_;
frames_.sp_ = exit_.GetCallerSp();
frames_.fp_ = exit_.GetCallerFp();
frames_.pc_ = exit_.GetCallerPc();
ASSERT(frames_.is_interpreted_ == exit_.is_interpreted_);
ASSERT(!validate_ || exit_.IsValid());
return &exit_;
}
EntryFrame* StackFrameIterator::NextEntryFrame() {
ASSERT(!frames_.HasNext());
entry_.sp_ = frames_.sp_;
entry_.fp_ = frames_.fp_;
entry_.pc_ = frames_.pc_;
entry_.is_interpreted_ = frames_.is_interpreted_;
SetupNextExitFrameData(); // Setup data for next exit frame in chain.
ASSERT(!validate_ || entry_.IsValid());
return &entry_;
}
InlinedFunctionsIterator::InlinedFunctionsIterator(const Code& code, uword pc)
: index_(0),
num_materializations_(0),
dest_frame_size_(0),
code_(Code::Handle(code.raw())),
deopt_info_(TypedData::Handle()),
function_(Function::Handle()),
pc_(pc),
deopt_instructions_(),
object_table_(ObjectPool::Handle()) {
ASSERT(code_.is_optimized());
ASSERT(pc_ != 0);
ASSERT(code.ContainsInstructionAt(pc));
#if defined(DART_PRECOMPILED_RUNTIME)
ASSERT(deopt_info_.IsNull());
function_ = code_.function();
#else
ICData::DeoptReasonId deopt_reason = ICData::kDeoptUnknown;
uint32_t deopt_flags = 0;
deopt_info_ = code_.GetDeoptInfoAtPc(pc, &deopt_reason, &deopt_flags);
if (deopt_info_.IsNull()) {
// This is the case when a call without deopt info in optimized code
// throws an exception. (e.g. in the parameter copying prologue).
// In that case there won't be any inlined frames.
function_ = code_.function();
} else {
// Unpack deopt info into instructions (translate away suffixes).
const Array& deopt_table = Array::Handle(code_.deopt_info_array());
ASSERT(!deopt_table.IsNull());
DeoptInfo::Unpack(deopt_table, deopt_info_, &deopt_instructions_);
num_materializations_ = DeoptInfo::NumMaterializations(deopt_instructions_);
dest_frame_size_ = DeoptInfo::FrameSize(deopt_info_);
object_table_ = code_.GetObjectPool();
Advance();
}
#endif // defined(DART_PRECOMPILED_RUNTIME)
}
void InlinedFunctionsIterator::Advance() {
// Iterate over the deopt instructions and determine the inlined
// functions if any and iterate over them.
ASSERT(!Done());
#if defined(DART_PRECOMPILED_RUNTIME)
ASSERT(deopt_info_.IsNull());
SetDone();
return;
#else
if (deopt_info_.IsNull()) {
SetDone();
return;
}
ASSERT(deopt_instructions_.length() != 0);
while (index_ < deopt_instructions_.length()) {
DeoptInstr* deopt_instr = deopt_instructions_[index_++];
if (deopt_instr->kind() == DeoptInstr::kRetAddress) {
pc_ = DeoptInstr::GetRetAddress(deopt_instr, object_table_, &code_);
function_ = code_.function();
return;
}
}
SetDone();
#endif // defined(DART_PRECOMPILED_RUNTIME)
}
// Finds the potential offset for the current function's FP if the
// current frame were to be deoptimized.
intptr_t InlinedFunctionsIterator::GetDeoptFpOffset() const {
ASSERT(deopt_instructions_.length() != 0);
for (intptr_t index = index_; index < deopt_instructions_.length(); index++) {
DeoptInstr* deopt_instr = deopt_instructions_[index];
if (deopt_instr->kind() == DeoptInstr::kCallerFp) {
return index - num_materializations_;
}
}
UNREACHABLE();
return 0;
}
#if defined(DEBUG)
void ValidateFrames() {
StackFrameIterator frames(ValidationPolicy::kValidateFrames,
Thread::Current(),
StackFrameIterator::kNoCrossThreadIteration);
StackFrame* frame = frames.NextFrame();
while (frame != NULL) {
frame = frames.NextFrame();
}
}
#endif
} // namespace dart
|
/*
SPDX short identifier: MIT
Copyright 2018-2019 Jevgēnijs Protopopovs
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
|
// parameters.cpp
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/pch.h"
#include <set>
#include "mongo/base/init.h"
#include "mongo/client/replica_set_monitor.h"
#include "mongo/client/sasl_client_authenticate.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/security_key.h"
#include "mongo/db/commands.h"
#include "mongo/db/server_parameters.h"
#include "mongo/db/storage_options.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/ssl_manager.h"
#include "mongo/util/net/ssl_options.h"
namespace mongo {
namespace {
void appendParameterNames( stringstream& help ) {
help << "supported:\n";
const ServerParameter::Map& m = ServerParameterSet::getGlobal()->getMap();
for ( ServerParameter::Map::const_iterator i = m.begin(); i != m.end(); ++i ) {
help << " " << i->first << "\n";
}
}
}
class CmdGet : public Command {
public:
CmdGet() : Command( "getParameter" ) { }
virtual bool slaveOk() const { return true; }
virtual bool adminOnly() const { return true; }
virtual bool isWriteCommandForConfigServer() const { return false; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::getParameter);
out->push_back(Privilege(ResourcePattern::forClusterResource(), actions));
}
virtual void help( stringstream &help ) const {
help << "get administrative option(s)\nexample:\n";
help << "{ getParameter:1, notablescan:1 }\n";
appendParameterNames( help );
help << "{ getParameter:'*' } to get everything\n";
}
bool run(OperationContext* txn, const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl ) {
bool all = *cmdObj.firstElement().valuestrsafe() == '*';
int before = result.len();
const ServerParameter::Map& m = ServerParameterSet::getGlobal()->getMap();
for ( ServerParameter::Map::const_iterator i = m.begin(); i != m.end(); ++i ) {
if ( all || cmdObj.hasElement( i->first.c_str() ) ) {
i->second->append(txn, result, i->second->name() );
}
}
if ( before == result.len() ) {
errmsg = "no option found to get";
return false;
}
return true;
}
} cmdGet;
class CmdSet : public Command {
public:
CmdSet() : Command( "setParameter" ) { }
virtual bool slaveOk() const { return true; }
virtual bool adminOnly() const { return true; }
virtual bool isWriteCommandForConfigServer() const { return false; }
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::setParameter);
out->push_back(Privilege(ResourcePattern::forClusterResource(), actions));
}
virtual void help( stringstream &help ) const {
help << "set administrative option(s)\n";
help << "{ setParameter:1, <param>:<value> }\n";
appendParameterNames( help );
}
bool run(OperationContext* txn, const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl ) {
int numSet = 0;
bool found = false;
const ServerParameter::Map& parameterMap = ServerParameterSet::getGlobal()->getMap();
// First check that we aren't setting the same parameter twice and that we actually are
// setting parameters that we have registered and can change at runtime
BSONObjIterator parameterCheckIterator(cmdObj);
// We already know that "setParameter" will be the first element in this object, so skip
// past that
parameterCheckIterator.next();
// Set of all the parameters the user is attempting to change
std::map<std::string, BSONElement> parametersToSet;
// Iterate all parameters the user passed in to do the initial validation checks,
// including verifying that we are not setting the same parameter twice.
while (parameterCheckIterator.more()) {
BSONElement parameter = parameterCheckIterator.next();
std::string parameterName = parameter.fieldName();
ServerParameter::Map::const_iterator foundParameter =
parameterMap.find(parameterName);
// Check to see if this is actually a valid parameter
if (foundParameter == parameterMap.end()) {
errmsg = str::stream() << "attempted to set unrecognized parameter ["
<< parameterName
<< "], use help:true to see options ";
return false;
}
// Make sure we are allowed to change this parameter
if (!foundParameter->second->allowedToChangeAtRuntime()) {
errmsg = str::stream() << "not allowed to change [" << parameterName
<< "] at runtime";
return false;
}
// Make sure we are only setting this parameter once
if (parametersToSet.count(parameterName)) {
errmsg = str::stream() << "attempted to set parameter ["
<< parameterName
<< "] twice in the same setParameter command, "
<< "once to value: ["
<< parametersToSet[parameterName].toString(false)
<< "], and once to value: [" << parameter.toString(false)
<< "]";
return false;
}
parametersToSet[parameterName] = parameter;
}
// Iterate the parameters that we have confirmed we are setting and actually set them.
// Not that if setting any one parameter fails, the command will fail, but the user
// won't see what has been set and what hasn't. See SERVER-8552.
for (std::map<std::string, BSONElement>::iterator it = parametersToSet.begin();
it != parametersToSet.end(); ++it) {
BSONElement parameter = it->second;
std::string parameterName = it->first;
ServerParameter::Map::const_iterator foundParameter =
parameterMap.find(parameterName);
if (foundParameter == parameterMap.end()) {
errmsg = str::stream() << "Parameter: " << parameterName << " that was "
<< "avaliable during our first lookup in the registered "
<< "parameters map is no longer available.";
return false;
}
if (numSet == 0) {
foundParameter->second->append(txn, result, "was");
}
Status status = foundParameter->second->set(parameter);
if (status.isOK()) {
numSet++;
continue;
}
errmsg = status.reason();
result.append("code", status.code());
return false;
}
if (numSet == 0 && !found) {
errmsg = "no option found to set, use help:true to see options ";
return false;
}
return true;
}
} cmdSet;
namespace {
class LogLevelSetting : public ServerParameter {
public:
LogLevelSetting() : ServerParameter(ServerParameterSet::getGlobal(), "logLevel") {}
virtual void append(OperationContext* txn, BSONObjBuilder& b, const std::string& name) {
b << name << logger::globalLogDomain()->getMinimumLogSeverity().toInt();
}
virtual Status set(const BSONElement& newValueElement) {
typedef logger::LogSeverity LogSeverity;
int newValue;
if (!newValueElement.coerce(&newValue) || newValue < 0)
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for logLevel: " << newValueElement);
LogSeverity newSeverity = (newValue > 0) ? LogSeverity::Debug(newValue) :
LogSeverity::Log();
logger::globalLogDomain()->setMinimumLoggedSeverity(newSeverity);
return Status::OK();
}
virtual Status setFromString(const std::string& str) {
typedef logger::LogSeverity LogSeverity;
int newValue;
Status status = parseNumberFromString(str, &newValue);
if (!status.isOK())
return status;
if (newValue < 0)
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for logLevel: " << newValue);
LogSeverity newSeverity = (newValue > 0) ? LogSeverity::Debug(newValue) :
LogSeverity::Log();
logger::globalLogDomain()->setMinimumLoggedSeverity(newSeverity);
return Status::OK();
}
} logLevelSetting;
/**
* Component log levels.
* Non-negative value means this component is configured with a debug level.
* Negative value means log messages with this component will use the default log level.
*/
class ComponentLogLevelSetting : public ServerParameter {
MONGO_DISALLOW_COPYING(ComponentLogLevelSetting);
public:
explicit ComponentLogLevelSetting(logger::LogComponent component)
: ServerParameter(ServerParameterSet::getGlobal(),
"logLevel_" + component.getShortName()),
_component(component) {}
virtual void append(OperationContext* txn, BSONObjBuilder& b, const std::string& name) {
if (!logger::globalLogDomain()->hasMinimumLogSeverity(_component)) {
b << name << -1;
return;
}
b << name << logger::globalLogDomain()->getMinimumLogSeverity(_component).toInt();
}
virtual Status set(const BSONElement& newValueElement) {
typedef logger::LogSeverity LogSeverity;
int newValue;
if (!newValueElement.coerce(&newValue))
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for logLevel: " << newValueElement);
return _setLogLevel(newValue);
}
virtual Status setFromString(const std::string& str) {
typedef logger::LogSeverity LogSeverity;
int newValue;
Status status = parseNumberFromString(str, &newValue);
if (!status.isOK())
return status;
return _setLogLevel(newValue);
return Status::OK();
}
private:
Status _setLogLevel(int newValue) {
if (newValue < 0) {
logger::globalLogDomain()->clearMinimumLoggedSeverity(_component);
return Status::OK();
}
typedef logger::LogSeverity LogSeverity;
LogSeverity newSeverity = (newValue > 0) ? LogSeverity::Debug(newValue) :
LogSeverity::Log();
logger::globalLogDomain()->setMinimumLoggedSeverity(_component, newSeverity);
return Status::OK();
}
logger::LogComponent _component;
};
class SSLModeSetting : public ServerParameter {
public:
SSLModeSetting() : ServerParameter(ServerParameterSet::getGlobal(), "sslMode",
false, // allowedToChangeAtStartup
true // allowedToChangeAtRuntime
) {}
std::string sslModeStr() {
switch (sslGlobalParams.sslMode.load()) {
case SSLGlobalParams::SSLMode_disabled:
return "disabled";
case SSLGlobalParams::SSLMode_allowSSL:
return "allowSSL";
case SSLGlobalParams::SSLMode_preferSSL:
return "preferSSL";
case SSLGlobalParams::SSLMode_requireSSL:
return "requireSSL";
default:
return "undefined";
}
}
virtual void append(
OperationContext* txn, BSONObjBuilder& b, const std::string& name) {
b << name << sslModeStr();
}
virtual Status set(const BSONElement& newValueElement) {
try {
return setFromString(newValueElement.String());
}
catch (MsgAssertionException msg) {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for sslMode via setParameter command: "
<< newValueElement);
}
}
virtual Status setFromString(const std::string& str) {
#ifndef MONGO_SSL
return Status(ErrorCodes::IllegalOperation, mongoutils::str::stream() <<
"Unable to set sslMode, SSL support is not compiled into server");
#endif
if (str != "disabled" && str != "allowSSL" &&
str != "preferSSL" && str != "requireSSL") {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for sslMode via setParameter command: "
<< str);
}
int oldMode = sslGlobalParams.sslMode.load();
if (str == "preferSSL" && oldMode == SSLGlobalParams::SSLMode_allowSSL) {
sslGlobalParams.sslMode.store(SSLGlobalParams::SSLMode_preferSSL);
}
else if (str == "requireSSL" && oldMode == SSLGlobalParams::SSLMode_preferSSL) {
sslGlobalParams.sslMode.store(SSLGlobalParams::SSLMode_requireSSL);
}
else {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Illegal state transition for sslMode, attempt to change from "
<< sslModeStr() << " to " << str);
}
return Status::OK();
}
} sslModeSetting;
class ClusterAuthModeSetting : public ServerParameter {
public:
ClusterAuthModeSetting() :
ServerParameter(ServerParameterSet::getGlobal(), "clusterAuthMode",
false, // allowedToChangeAtStartup
true // allowedToChangeAtRuntime
) {}
std::string clusterAuthModeStr() {
switch (serverGlobalParams.clusterAuthMode.load()) {
case ServerGlobalParams::ClusterAuthMode_keyFile:
return "keyFile";
case ServerGlobalParams::ClusterAuthMode_sendKeyFile:
return "sendKeyFile";
case ServerGlobalParams::ClusterAuthMode_sendX509:
return "sendX509";
case ServerGlobalParams::ClusterAuthMode_x509:
return "x509";
default:
return "undefined";
}
}
virtual void append(
OperationContext* txn, BSONObjBuilder& b, const std::string& name) {
b << name << clusterAuthModeStr();
}
virtual Status set(const BSONElement& newValueElement) {
try {
return setFromString(newValueElement.String());
}
catch (MsgAssertionException msg) {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for clusterAuthMode via setParameter command: "
<< newValueElement);
}
}
virtual Status setFromString(const std::string& str) {
#ifndef MONGO_SSL
return Status(ErrorCodes::IllegalOperation, mongoutils::str::stream() <<
"Unable to set clusterAuthMode, " <<
"SSL support is not compiled into server");
#endif
if (str != "keyFile" && str != "sendKeyFile" &&
str != "sendX509" && str != "x509") {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Invalid value for clusterAuthMode via setParameter command: "
<< str);
}
int oldMode = serverGlobalParams.clusterAuthMode.load();
int sslMode = sslGlobalParams.sslMode.load();
if (str == "sendX509" &&
oldMode == ServerGlobalParams::ClusterAuthMode_sendKeyFile) {
if (sslMode == SSLGlobalParams::SSLMode_disabled ||
sslMode == SSLGlobalParams::SSLMode_allowSSL) {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Illegal state transition for clusterAuthMode, " <<
"need to enable SSL for outgoing connections");
}
serverGlobalParams.clusterAuthMode.store
(ServerGlobalParams::ClusterAuthMode_sendX509);
#ifdef MONGO_SSL
setInternalUserAuthParams(BSON(saslCommandMechanismFieldName <<
"MONGODB-X509" <<
saslCommandUserDBFieldName << "$external" <<
saslCommandUserFieldName <<
getSSLManager()->getClientSubjectName()));
#endif
}
else if (str == "x509" &&
oldMode == ServerGlobalParams::ClusterAuthMode_sendX509) {
serverGlobalParams.clusterAuthMode.store
(ServerGlobalParams::ClusterAuthMode_x509);
}
else {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Illegal state transition for clusterAuthMode, change from "
<< clusterAuthModeStr() << " to " << str);
}
return Status::OK();
}
} clusterAuthModeSetting;
ExportedServerParameter<bool> QuietSetting( ServerParameterSet::getGlobal(),
"quiet",
&serverGlobalParams.quiet,
true,
true );
ExportedServerParameter<int> MaxConsecutiveFailedChecksSetting(
ServerParameterSet::getGlobal(),
"replMonitorMaxFailedChecks",
&ReplicaSetMonitor::maxConsecutiveFailedChecks,
false, // allowedToChangeAtStartup
true); // allowedToChangeAtRuntime
ExportedServerParameter<bool> TraceExceptionsSetting(ServerParameterSet::getGlobal(),
"traceExceptions",
&DBException::traceExceptions,
false, // allowedToChangeAtStartup
true); // allowedToChangeAtRuntime
}
namespace {
//
// Command instances.
// Registers commands with the command system and make commands
// available to the client.
//
MONGO_INITIALIZER_WITH_PREREQUISITES(SetupComponentLogLevelSettings,
MONGO_NO_PREREQUISITES)(InitializerContext* context) {
for (int i = 0; i < int(logger::LogComponent::kNumLogComponents); ++i) {
logger::LogComponent component = static_cast<logger::LogComponent::Value>(i);
if (component == logger::LogComponent::kDefault) { continue; }
new ComponentLogLevelSetting(component);
}
return Status::OK();
}
} // namespace
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinamountfield.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "qvaluecombobox.h"
#include <QApplication>
#include <QAbstractSpinBox>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
/** QSpinBox that uses fixed-point numbers internally and uses our own
* formatting/parsing functions.
*/
class AmountSpinBox: public QAbstractSpinBox
{
Q_OBJECT
public:
explicit AmountSpinBox(QWidget *parent):
QAbstractSpinBox(parent),
currentUnit(BitcoinUnits::MGRC),
singleStep(100000) // satoshis
{
setAlignment(Qt::AlignRight);
connect(lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(valueChanged()));
}
QValidator::State validate(QString &text, int &pos) const
{
if(text.isEmpty())
return QValidator::Intermediate;
bool valid = false;
parse(text, &valid);
/* Make sure we return Intermediate so that fixup() is called on defocus */
return valid ? QValidator::Intermediate : QValidator::Invalid;
}
void fixup(QString &input) const
{
bool valid = false;
CAmount val = parse(input, &valid);
if(valid)
{
input = BitcoinUnits::format(currentUnit, val, false, BitcoinUnits::separatorAlways);
lineEdit()->setText(input);
}
}
CAmount value(bool *valid_out=0) const
{
return parse(text(), valid_out);
}
void setValue(const CAmount& value)
{
lineEdit()->setText(BitcoinUnits::format(currentUnit, value, false, BitcoinUnits::separatorAlways));
Q_EMIT valueChanged();
}
void stepBy(int steps)
{
bool valid = false;
CAmount val = value(&valid);
val = val + steps * singleStep;
val = qMin(qMax(val, CAmount(0)), BitcoinUnits::maxMoney());
setValue(val);
}
void setDisplayUnit(int unit)
{
bool valid = false;
CAmount val = value(&valid);
currentUnit = unit;
if(valid)
setValue(val);
else
clear();
}
void setSingleStep(const CAmount& step)
{
singleStep = step;
}
QSize minimumSizeHint() const
{
if(cachedMinimumSizeHint.isEmpty())
{
ensurePolished();
const QFontMetrics fm(fontMetrics());
int h = lineEdit()->minimumSizeHint().height();
int w = fm.width(BitcoinUnits::format(BitcoinUnits::MGRC, BitcoinUnits::maxMoney(), false, BitcoinUnits::separatorAlways));
w += 2; // cursor blinking space
QStyleOptionSpinBox opt;
initStyleOption(&opt);
QSize hint(w, h);
QSize extra(35, 6);
opt.rect.setSize(hint + extra);
extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
QStyle::SC_SpinBoxEditField, this).size();
// get closer to final result by repeating the calculation
opt.rect.setSize(hint + extra);
extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
QStyle::SC_SpinBoxEditField, this).size();
hint += extra;
hint.setHeight(h);
opt.rect = rect();
cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
.expandedTo(QApplication::globalStrut());
}
return cachedMinimumSizeHint;
}
private:
int currentUnit;
CAmount singleStep;
mutable QSize cachedMinimumSizeHint;
/**
* Parse a string into a number of base monetary units and
* return validity.
* @note Must return 0 if !valid.
*/
CAmount parse(const QString &text, bool *valid_out=0) const
{
CAmount val = 0;
bool valid = BitcoinUnits::parse(currentUnit, text, &val);
if(valid)
{
if(val < 0 || val > BitcoinUnits::maxMoney())
valid = false;
}
if(valid_out)
*valid_out = valid;
return valid ? val : 0;
}
protected:
bool event(QEvent *event)
{
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Comma)
{
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
return QAbstractSpinBox::event(&periodKeyEvent);
}
}
return QAbstractSpinBox::event(event);
}
StepEnabled stepEnabled() const
{
if (isReadOnly()) // Disable steps when AmountSpinBox is read-only
return StepNone;
if (text().isEmpty()) // Allow step-up with empty field
return StepUpEnabled;
StepEnabled rv = 0;
bool valid = false;
CAmount val = value(&valid);
if(valid)
{
if(val > 0)
rv |= StepDownEnabled;
if(val < BitcoinUnits::maxMoney())
rv |= StepUpEnabled;
}
return rv;
}
Q_SIGNALS:
void valueChanged();
};
#include "bitcoinamountfield.moc"
BitcoinAmountField::BitcoinAmountField(QWidget *parent) :
QWidget(parent),
amount(0)
{
amount = new AmountSpinBox(this);
amount->setLocale(QLocale::c());
amount->installEventFilter(this);
amount->setMaximumWidth(170);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new BitcoinUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, SIGNAL(valueChanged()), this, SIGNAL(valueChanged()));
connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int)));
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void BitcoinAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
void BitcoinAmountField::setEnabled(bool fEnabled)
{
amount->setEnabled(fEnabled);
unit->setEnabled(fEnabled);
}
bool BitcoinAmountField::validate()
{
bool valid = false;
value(&valid);
setValid(valid);
return valid;
}
void BitcoinAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// Clear invalid flag on focus
setValid(true);
}
return QWidget::eventFilter(object, event);
}
QWidget *BitcoinAmountField::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, amount);
QWidget::setTabOrder(amount, unit);
return unit;
}
CAmount BitcoinAmountField::value(bool *valid_out) const
{
return amount->value(valid_out);
}
void BitcoinAmountField::setValue(const CAmount& value)
{
amount->setValue(value);
}
void BitcoinAmountField::setReadOnly(bool fReadOnly)
{
amount->setReadOnly(fReadOnly);
}
void BitcoinAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt();
amount->setDisplayUnit(newUnit);
}
void BitcoinAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
void BitcoinAmountField::setSingleStep(const CAmount& step)
{
amount->setSingleStep(step);
}
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Guido Tack, 2004
*
* Last modified:
* $Date: 2010-09-03 16:36:31 +0200 (Fri, 03 Sep 2010) $ by $Author: schulte $
* $Revision: 11390 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <gecode/set/distinct.hh>
/*
* These propagators implement the scheme discussed in
*
* Andrew Sadler and Carment Gervet: Global Reasoning on Sets.
* FORMUL'01 workshop in conjunction with CP 2001.
*
* Todo: make the propagators incremental.
*/
namespace Gecode { namespace Set { namespace Distinct {
/*
* "AtMostOneIntersection" propagator
*
*/
Actor*
AtmostOne::copy(Space& home, bool share) {
return new (home) AtmostOne(home,share,*this);
}
ExecStatus
AtmostOne::propagate(Space& home, const ModEventDelta&) {
Region r(home);
LubRanges<SetView>* lubs = r.alloc<LubRanges<SetView> >(x.size());
for (int i = x.size(); i--; ) {
lubs[i].init(x[i]);
}
Iter::Ranges::NaryUnion<LubRanges<SetView> > bigT(r, lubs, x.size());
Iter::Ranges::ToValues<Iter::Ranges::NaryUnion<LubRanges<SetView> > >
as(bigT);
while (as()) {
int a = as.val(); ++as;
// cardSa is the number of sets that contain a in the glb
int cardSa = 0;
for (int i=x.size(); i--;)
if (x[i].contains(a))
cardSa++;
// bigTa is the union of all lubs that contain a
GLBndSet bigTa(home);
for (int i=x.size(); i--;) {
if (!x[i].notContains(a)) {
LubRanges<SetView> xilub(x[i]);
bigTa.includeI(home, xilub);
}
}
// maxa is the maximum number of sets that can contain a
int maxa = static_cast<int>((bigTa.size() - 1) / (c - 1));
bigTa.dispose(home);
// Conditional Rule A:
// If more sets already contain a than allowed, fail.
if (maxa < cardSa)
return ES_FAILED;
if (maxa == cardSa) {
// Conditional Rule B:
// All a used up. All other sets (those that don't have a in their
// glb already) cannot contain a.
for (int i=x.size(); i--;) {
if (!x[i].contains(a)) {
GECODE_ME_CHECK(x[i].exclude(home, a));
}
}
} else {
LubRanges<SetView>* lubs2 = r.alloc<LubRanges<SetView> >(x.size());
for (int i = x.size(); i--; ) {
lubs2[i].init(x[i]);
}
Iter::Ranges::NaryUnion<LubRanges<SetView> > bigT2(r, lubs2, x.size());
GlbRanges<SetView>* glbs = r.alloc<GlbRanges<SetView> >(cardSa);
int count = 0;
for (int i=x.size(); i--; ) {
if (x[i].contains(a)) {
glbs[count].init(x[i]);
count++;
}
}
Iter::Ranges::NaryUnion<GlbRanges<SetView> > glbsa(r, glbs, cardSa);
Iter::Ranges::Diff<Iter::Ranges::NaryUnion<LubRanges<SetView> >,
Iter::Ranges::NaryUnion<GlbRanges<SetView> > > deltaA(bigT2, glbsa);
Iter::Ranges::Cache<
Iter::Ranges::Diff<Iter::Ranges::NaryUnion<LubRanges<SetView> >,
Iter::Ranges::NaryUnion<GlbRanges<SetView> > > > deltaAC(r,deltaA);
// deltaAC contains all elements that are not yet known to be
// in a set together with a.
// Formally: \cup_i lub(x_i) - \cup_i {glb(s_i) | a\in glb(s_i)}
if (Iter::Ranges::size(deltaAC) == c - 1) {
// Conditional Rule C:
// If deltaA has exactly c-1 elements, all sets that are not yet
// known to contain a cannot contain a if it is impossible that
// they contain all of deltaA. Or the other way around:
// If a is added to the glb of a set s, deltaA must be a subset of
// s, because otherwise s would share at least one more element
// with another set that has a in its lower bound.
// Weird, eh?
for (int i=x.size(); i--; ) {
if (!x[i].contains(a) && !x[i].notContains(a)) {
deltaAC.reset();
LubRanges<SetView> xilub(x[i]);
if (!Iter::Ranges::subset(deltaAC, xilub)) {
GECODE_ME_CHECK(x[i].exclude(home, a));
}
}
}
}
}
}
return ES_NOFIX;
}
}}}
// STATISTICS: set-prop
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DmgType_Melee_Dino_Herbivore_Small_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
/**
* Copyright 2019-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ops/populate/populate_register.h"
#include "nnacl/arithmetic.h"
#include "src/ops/populate/arithmetic_populate.h"
namespace mindspore {
namespace lite {
namespace {
OpParameter *PopulateAddParameter(const void *prim) {
ArithmeticParameter *param = PopulateArithmeticCommonPara(prim);
if (param == nullptr) {
MS_LOG(ERROR) << "PopulateArithmeticCommonPara failed.";
return nullptr;
}
auto *primitive = static_cast<const schema::Primitive *>(prim);
param->op_parameter_.type_ = primitive->value_type();
auto add_prim = primitive->value_as_AddFusion();
param->activation_type_ = add_prim->activation_type();
return reinterpret_cast<OpParameter *>(param);
}
} // namespace
Registry g_addParameterRegistry(schema::PrimitiveType_AddFusion, PopulateAddParameter, SCHEMA_CUR);
} // namespace lite
} // namespace mindspore
|
/*
* Copyright 2015 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gtest/gtest.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/shared/utils/types.h"
#include "native_client/src/trusted/validator/ncvalidate.h"
#define CODE_SIZE 32
#define NOP 0x90
#define MOVNTI_CODE_SIZE 8
// mov %edi,%edi; movnti %rax,0x68(%r15,%rdi,1)
const char* movnti_code = "\x89\xff\x49\x0f\xc3\x44\x3f\x68";
class ValidationDisableNonTemporalsTests : public ::testing::Test {
protected:
NaClValidationMetadata *metadata_ptr;
const struct NaClValidatorInterface *validator;
NaClCPUFeatures *cpu_features;
unsigned char code_buffer[CODE_SIZE];
void SetUp() {
metadata_ptr = NULL;
validator = NaClCreateValidator();
cpu_features = (NaClCPUFeatures *) malloc(validator->CPUFeatureSize);
EXPECT_NE(cpu_features, (NaClCPUFeatures *) NULL);
memset(cpu_features, 0, validator->CPUFeatureSize);
validator->SetAllCPUFeatures(cpu_features);
memset(code_buffer, NOP, sizeof(code_buffer));
}
NaClValidationStatus Validate(uint32_t flags, Bool readonly_text) {
return validator->Validate(0, code_buffer, 32,
FALSE, /* stubout_mode */
flags,
readonly_text,
cpu_features,
metadata_ptr,
NULL);
}
void TearDown() {
free(cpu_features);
}
};
TEST_F(ValidationDisableNonTemporalsTests, NotDisableNonTemporals) {
memcpy(code_buffer, movnti_code, MOVNTI_CODE_SIZE);
NaClValidationStatus status = Validate(0, FALSE);
// If we are not disabling non-temporal instructions, we should rewrite
// them and return validation success.
EXPECT_EQ(NaClValidationSucceeded, status);
// Just make sure code has changed. The rewriting itself is tested in
// validation_rewrite_test.cc
EXPECT_NE(0, memcmp(code_buffer, movnti_code, MOVNTI_CODE_SIZE));
}
TEST_F(ValidationDisableNonTemporalsTests, FailAndNotRewriteWhenReadOnlyText) {
memcpy(code_buffer, movnti_code, MOVNTI_CODE_SIZE);
NaClValidationStatus status = Validate(0, TRUE);
// If we are not disabling non-temporal instructions, we should rewrite
// them. However, readonly_text = TRUE would make the text
// non-modifiable. In this case, we should return validation failed, and
// not do rewriting.
EXPECT_EQ(NaClValidationFailed, status);
EXPECT_EQ(0, memcmp(code_buffer, movnti_code, MOVNTI_CODE_SIZE));
}
TEST_F(ValidationDisableNonTemporalsTests, DisableNonTemporals) {
memcpy(code_buffer, movnti_code, MOVNTI_CODE_SIZE);
NaClValidationStatus status = Validate(NACL_DISABLE_NONTEMPORALS_X86, FALSE);
// Disable non-temporal instructions.
EXPECT_EQ(NaClValidationFailed, status);
// Code should not change.
EXPECT_EQ(0, memcmp(code_buffer, movnti_code, MOVNTI_CODE_SIZE));
}
int main(int argc, char *argv[]) {
// The IllegalInst test touches the log mutex deep inside the validator.
// This causes an SEH exception to be thrown on Windows if the mutex is not
// initialized.
// http://code.google.com/p/nativeclient/issues/detail?id=1696
NaClLogModuleInit();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <unistd.h>
#include <array>
#include <memory>
#include <vector>
#include <getopt.h>
#include <signal.h>
#include "perfetto/ext/base/event_fd.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/unix_socket.h"
#include "perfetto/ext/base/watchdog.h"
#include "perfetto/ext/tracing/ipc/default_socket.h"
#include "src/profiling/memory/heapprofd_producer.h"
#include "src/profiling/memory/java_hprof_producer.h"
#include "src/profiling/memory/wire_protocol.h"
#include "perfetto/ext/base/unix_task_runner.h"
// TODO(rsavitski): the task runner watchdog spawns a thread (normally for
// tracking cpu/mem usage) that we don't strictly need.
namespace perfetto {
namespace profiling {
namespace {
int StartChildHeapprofd(pid_t target_pid,
std::string target_cmdline,
base::ScopedFile inherited_sock_fd);
int StartCentralHeapprofd();
int GetListeningSocket() {
const char* sock_fd = getenv(kHeapprofdSocketEnvVar);
if (sock_fd == nullptr)
PERFETTO_FATAL("Did not inherit socket from init.");
char* end;
int raw_fd = static_cast<int>(strtol(sock_fd, &end, 10));
if (*end != '\0')
PERFETTO_FATAL("Invalid %s. Expected decimal integer.",
kHeapprofdSocketEnvVar);
return raw_fd;
}
base::EventFd* g_dump_evt = nullptr;
int HeapprofdMain(int argc, char** argv) {
bool cleanup_crash = false;
pid_t target_pid = base::kInvalidPid;
std::string target_cmdline;
base::ScopedFile inherited_sock_fd;
enum { kCleanupCrash = 256, kTargetPid, kTargetCmd, kInheritFd };
static struct option long_options[] = {
{"cleanup-after-crash", no_argument, nullptr, kCleanupCrash},
{"exclusive-for-pid", required_argument, nullptr, kTargetPid},
{"exclusive-for-cmdline", required_argument, nullptr, kTargetCmd},
{"inherit-socket-fd", required_argument, nullptr, kInheritFd},
{nullptr, 0, nullptr, 0}};
int option_index;
int c;
while ((c = getopt_long(argc, argv, "", long_options, &option_index)) != -1) {
switch (c) {
case kCleanupCrash:
cleanup_crash = true;
break;
case kTargetPid:
if (target_pid != base::kInvalidPid)
PERFETTO_FATAL("Duplicate exclusive-for-pid");
target_pid = static_cast<pid_t>(atoi(optarg));
break;
case kTargetCmd: // assumed to be already normalized
if (!target_cmdline.empty())
PERFETTO_FATAL("Duplicate exclusive-for-cmdline");
target_cmdline = std::string(optarg);
break;
case kInheritFd: // repetition not supported
if (inherited_sock_fd)
PERFETTO_FATAL("Duplicate inherit-socket-fd");
inherited_sock_fd = base::ScopedFile(atoi(optarg));
break;
default:
PERFETTO_ELOG("Usage: %s [--cleanup-after-crash]", argv[0]);
return 1;
}
}
if (cleanup_crash) {
PERFETTO_LOG(
"Recovering from crash: unsetting heapprofd system properties. "
"Expect SELinux denials for unrelated properties.");
SystemProperties::ResetHeapprofdProperties();
PERFETTO_LOG(
"Finished unsetting heapprofd system properties. "
"SELinux denials about properties are unexpected after "
"this point.");
return 0;
}
// If |target_pid| is given, we're supposed to be operating as a private
// heapprofd for that process. Note that we might not be a direct child due to
// reparenting.
bool tpid_set = target_pid != base::kInvalidPid;
bool tcmd_set = !target_cmdline.empty();
bool fds_set = !!inherited_sock_fd;
if (tpid_set || tcmd_set || fds_set) {
if (!tpid_set || !tcmd_set || !fds_set) {
PERFETTO_ELOG(
"If starting in child mode, requires all of: {--exclusive-for-pid, "
"--exclusive-for-cmdline, --inherit_socket_fd}");
return 1;
}
return StartChildHeapprofd(target_pid, target_cmdline,
std::move(inherited_sock_fd));
}
// Otherwise start as a central daemon.
return StartCentralHeapprofd();
}
int StartChildHeapprofd(pid_t target_pid,
std::string target_cmdline,
base::ScopedFile inherited_sock_fd) {
base::UnixTaskRunner task_runner;
base::Watchdog::GetInstance()->Start(); // crash on exceedingly long tasks
HeapprofdProducer producer(HeapprofdMode::kChild, &task_runner);
producer.SetTargetProcess(target_pid, target_cmdline,
std::move(inherited_sock_fd));
producer.ConnectWithRetries(GetProducerSocket());
producer.ScheduleActiveDataSourceWatchdog();
task_runner.Run();
return 0;
}
int StartCentralHeapprofd() {
// We set this up before launching any threads, so we do not have to use a
// std::atomic for g_dump_evt.
g_dump_evt = new base::EventFd();
base::UnixTaskRunner task_runner;
base::Watchdog::GetInstance()->Start(); // crash on exceedingly long tasks
HeapprofdProducer producer(HeapprofdMode::kCentral, &task_runner);
int listening_raw_socket = GetListeningSocket();
auto listening_socket = base::UnixSocket::Listen(
base::ScopedFile(listening_raw_socket), &producer.socket_delegate(),
&task_runner, base::SockFamily::kUnix, base::SockType::kStream);
struct sigaction action = {};
action.sa_handler = [](int) { g_dump_evt->Notify(); };
// Allow to trigger a full dump by sending SIGUSR1 to heapprofd.
// This will allow manually deciding when to dump on userdebug.
PERFETTO_CHECK(sigaction(SIGUSR1, &action, nullptr) == 0);
task_runner.AddFileDescriptorWatch(g_dump_evt->fd(), [&producer] {
g_dump_evt->Clear();
producer.DumpAll();
});
producer.ConnectWithRetries(GetProducerSocket());
// TODO(fmayer): Create one producer that manages both heapprofd and Java
// producers, so we do not have two connections to traced.
JavaHprofProducer java_producer(&task_runner);
java_producer.ConnectWithRetries(GetProducerSocket());
task_runner.Run();
return 0;
}
} // namespace
} // namespace profiling
} // namespace perfetto
int main(int argc, char** argv) {
return perfetto::profiling::HeapprofdMain(argc, argv);
}
|
/****************************************************************************************
* @author: * kzvd4729 created: Jan/08/2021 20:43
* solution_verdict: Accepted language: GNU C++14
* run_time: 46 ms memory_used: 0 KB
* problem: https://codeforces.com/contest/1467/problem/A
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;
cout<<9;int in=8;
for(int i=2;i<=n;i++)
{
cout<<in;in=(in+1)%10;
}
cout<<endl;
}
return 0;
}
|
#ifndef PORTABLE_BINARY_OARCHIVE_HPP
#define PORTABLE_BINARY_OARCHIVE_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#if defined(_MSC_VER)
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// portable_binary_oarchive.hpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <ostream>
#include <boost/serialization/string.hpp>
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/basic_binary_oprimitive.hpp>
#include <boost/archive/detail/common_oarchive.hpp>
#include <boost/archive/detail/register_archive.hpp>
#include "portable_binary_archive.hpp"
namespace boost {
namespace archive {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// exception to be thrown if integer read from archive doesn't fit
// variable being loaded
class portable_binary_oarchive_exception :
public virtual boost::archive::archive_exception
{
public:
typedef enum {
invalid_flags
} exception_code;
portable_binary_oarchive_exception(exception_code /* c */ )
{}
portable_binary_oarchive_exception( )
{}
virtual const char *what( ) const throw( )
{
const char *msg = "programmer error";
switch(code){
case invalid_flags:
msg = "cannot be both big and little endian";
default:
boost::archive::archive_exception::what();
}
return msg;
}
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// "Portable" output binary archive. This is a variation of the native binary
// archive. it addresses integer size and endienness so that binary archives can
// be passed across systems. Note:floating point types not addressed here
class portable_binary_oarchive :
public boost::archive::basic_binary_oprimitive<
portable_binary_oarchive,
std::ostream::char_type,
std::ostream::traits_type
>,
public boost::archive::detail::common_oarchive<
portable_binary_oarchive
>
{
typedef boost::archive::basic_binary_oprimitive<
portable_binary_oarchive,
std::ostream::char_type,
std::ostream::traits_type
> primitive_base_t;
typedef boost::archive::detail::common_oarchive<
portable_binary_oarchive
> archive_base_t;
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
public:
#else
friend archive_base_t;
friend primitive_base_t; // since with override save below
friend class boost::archive::detail::interface_oarchive<
portable_binary_oarchive
>;
friend class boost::archive::save_access;
protected:
#endif
unsigned int m_flags;
void save_impl(const boost::intmax_t l, const char maxsize);
// add base class to the places considered when matching
// save function to a specific set of arguments. Note, this didn't
// work on my MSVC 7.0 system so we use the sure-fire method below
// using archive_base_t::save;
// default fall through for any types not specified here
template<class T>
void save(const T & t){
save_impl(t, sizeof(T));
}
void save(const std::string & t){
this->primitive_base_t::save(t);
}
#ifndef BOOST_NO_STD_WSTRING
void save(const std::wstring & t){
this->primitive_base_t::save(t);
}
#endif
void save(const float & t){
this->primitive_base_t::save(t);
// floats not supported
//BOOST_STATIC_ASSERT(false);
}
void save(const double & t){
this->primitive_base_t::save(t);
// doubles not supported
//BOOST_STATIC_ASSERT(false);
}
void save(const char & t){
this->primitive_base_t::save(t);
}
void save(const unsigned char & t){
this->primitive_base_t::save(t);
}
// default processing - kick back to base class. Note the
// extra stuff to get it passed borland compilers
typedef boost::archive::detail::common_oarchive<portable_binary_oarchive>
detail_common_oarchive;
template<class T>
void save_override(T & t, BOOST_PFTO int){
this->detail_common_oarchive::save_override(t, 0);
}
// explicitly convert to char * to avoid compile ambiguities
void save_override(const boost::archive::class_name_type & t, int){
const std::string s(t);
* this << s;
}
// binary files don't include the optional information
void save_override(
const boost::archive::class_id_optional_type & /* t */,
int
){}
void init(unsigned int flags);
public:
portable_binary_oarchive(std::ostream & os, unsigned flags = 0) :
primitive_base_t(
* os.rdbuf(),
0 != (flags & boost::archive::no_codecvt)
),
archive_base_t(flags),
m_flags(flags & (endian_big | endian_little))
{
init(flags);
}
portable_binary_oarchive(
std::basic_streambuf<
std::ostream::char_type,
std::ostream::traits_type
> & bsb,
unsigned int flags
) :
primitive_base_t(
bsb,
0 != (flags & boost::archive::no_codecvt)
),
archive_base_t(flags),
m_flags(0)
{
init(flags);
}
};
} // namespace archive
} // namespace boost
// required by export in boost version > 1.34
#ifdef BOOST_SERIALIZATION_REGISTER_ARCHIVE
BOOST_SERIALIZATION_REGISTER_ARCHIVE(portable_binary_oarchive)
#endif
// required by export in boost <= 1.34
#define BOOST_ARCHIVE_CUSTOM_OARCHIVE_TYPES portable_binary_oarchive
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
#endif // PORTABLE_BINARY_OARCHIVE_HPP
|
// @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#include <Teuchos_ConfigDefs.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_TimeMonitor.hpp>
#include "Panzer_CellTopologyInfo.hpp"
namespace panzer {
TEUCHOS_UNIT_TEST(cell_topology_info, quad_test)
{
Teuchos::RCP<shards::CellTopology> topo =
Teuchos::rcp(new shards::CellTopology(shards::getCellTopologyData< shards::Quadrilateral<4> >()));
const int num_cells = 20;
const int num_dims = 2;
panzer::CellTopologyInfo cellTopoInfo(num_cells, topo);
TEST_ASSERT(cellTopoInfo.getNumCells() == 20);
TEST_ASSERT(cellTopoInfo.getDimension() == num_dims);
TEST_ASSERT(cellTopoInfo.getNumEdges() == 4);
TEST_ASSERT(cellTopoInfo.getCellName() == "Quadrilateral_4");
Teuchos::RCP<const shards::CellTopology> topology = cellTopoInfo.getCellTopology();
TEST_ASSERT(!Teuchos::is_null(topology));
const int num_edges = cellTopoInfo.getNumEdges();
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_scalar->size()) == num_cells*num_edges);
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_vector->size()) == num_cells*num_edges*num_dims);
}
TEUCHOS_UNIT_TEST(cell_topology_info, tri_test)
{
Teuchos::RCP<shards::CellTopology> topo =
Teuchos::rcp(new shards::CellTopology(shards::getCellTopologyData< shards::Triangle<3> >()));
const int num_cells = 20;
const int num_dims = 2;
panzer::CellTopologyInfo cellTopoInfo(num_cells, topo);
TEST_ASSERT(cellTopoInfo.getNumCells() == 20);
TEST_ASSERT(cellTopoInfo.getDimension() == num_dims);
TEST_ASSERT(cellTopoInfo.getNumEdges() == 3);
TEST_ASSERT(cellTopoInfo.getCellName() == "Triangle_3");
Teuchos::RCP<const shards::CellTopology> topology = cellTopoInfo.getCellTopology();
TEST_ASSERT(!Teuchos::is_null(topology));
const int num_edges = cellTopoInfo.getNumEdges();
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_scalar->size()) == num_cells*num_edges);
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_vector->size()) == num_cells*num_edges*num_dims);
}
TEUCHOS_UNIT_TEST(cell_topology_info, tet_test)
{
Teuchos::RCP<shards::CellTopology> topo =
Teuchos::rcp(new shards::CellTopology(shards::getCellTopologyData< shards::Tetrahedron<4> >()));
const int num_cells = 20;
const int num_dims = 3;
panzer::CellTopologyInfo cellTopoInfo(num_cells, topo);
TEST_ASSERT(cellTopoInfo.getNumCells() == 20);
TEST_ASSERT(cellTopoInfo.getDimension() == num_dims);
TEST_ASSERT(cellTopoInfo.getNumEdges() == 6);
TEST_ASSERT(cellTopoInfo.getCellName() == "Tetrahedron_4");
Teuchos::RCP<const shards::CellTopology> topology = cellTopoInfo.getCellTopology();
TEST_ASSERT(!Teuchos::is_null(topology));
const int num_edges = cellTopoInfo.getNumEdges();
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_scalar->size()) == num_cells*num_edges);
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_vector->size()) == num_cells*num_edges*num_dims);
}
TEUCHOS_UNIT_TEST(cell_topology_info, hex_test)
{
Teuchos::RCP<shards::CellTopology> topo =
Teuchos::rcp(new shards::CellTopology(shards::getCellTopologyData< shards::Hexahedron<8> >()));
const int num_cells = 20;
const int num_dims = 3;
panzer::CellTopologyInfo cellTopoInfo(num_cells, topo);
TEST_ASSERT(cellTopoInfo.getNumCells() == 20);
TEST_ASSERT(cellTopoInfo.getDimension() == num_dims);
TEST_ASSERT(cellTopoInfo.getNumEdges() == 12);
TEST_ASSERT(cellTopoInfo.getCellName() == "Hexahedron_8");
Teuchos::RCP<const shards::CellTopology> topology = cellTopoInfo.getCellTopology();
TEST_ASSERT(!Teuchos::is_null(topology));
const int num_edges = cellTopoInfo.getNumEdges();
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_scalar->size()) == num_cells*num_edges);
TEST_ASSERT(static_cast<int>(cellTopoInfo.edge_vector->size()) == num_cells*num_edges*num_dims);
}
}
|
/**
* Copyright 2019-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ops/populate/populate_register.h"
#include "nnacl/int8/quant_dtype_cast_int8.h"
using mindspore::schema::PrimitiveType_QuantDTypeCast;
namespace mindspore {
namespace lite {
OpParameter *PopulateQuantDTypeCastParameter(const void *prim) {
auto primitive = static_cast<const schema::Primitive *>(prim);
MS_ASSERT(primitive != nullptr);
auto value = primitive->value_as_QuantDTypeCast();
if (value == nullptr) {
MS_LOG(ERROR) << "value is nullptr";
return nullptr;
}
auto *param = reinterpret_cast<QuantDTypeCastParameter *>(malloc(sizeof(QuantDTypeCastParameter)));
if (param == nullptr) {
MS_LOG(ERROR) << "malloc QuantDTypeCastParameter failed.";
return nullptr;
}
memset(param, 0, sizeof(QuantDTypeCastParameter));
param->op_parameter_.type_ = primitive->value_type();
param->srcT = value->src_t();
param->dstT = value->dst_t();
return reinterpret_cast<OpParameter *>(param);
}
REG_POPULATE(PrimitiveType_QuantDTypeCast, PopulateQuantDTypeCastParameter, SCHEMA_CUR);
} // namespace lite
} // namespace mindspore
|
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/clipboard/common/clipboard-event-notifier-impl.h>
// EXTERNAL INCLUDES
#include <dali/public-api/object/type-registry.h>
#include <dali/devel-api/common/singleton-service.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
Dali::ClipboardEventNotifier ClipboardEventNotifier::New()
{
Dali::ClipboardEventNotifier notifier = Dali::ClipboardEventNotifier(new ClipboardEventNotifier());
return notifier;
}
Dali::ClipboardEventNotifier ClipboardEventNotifier::Get()
{
Dali::ClipboardEventNotifier notifier;
Dali::SingletonService service( SingletonService::Get() );
if ( service )
{
// Check whether the singleton is already created
Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ClipboardEventNotifier ) );
if(handle)
{
// If so, downcast the handle
notifier = Dali::ClipboardEventNotifier( dynamic_cast< ClipboardEventNotifier* >( handle.GetObjectPtr() ) );
}
else
{
notifier = Dali::ClipboardEventNotifier( ClipboardEventNotifier::New() );
service.Register( typeid( notifier ), notifier );
}
}
return notifier;
}
const std::string& ClipboardEventNotifier::GetContent() const
{
return mContent;
}
void ClipboardEventNotifier::SetContent( const std::string& content )
{
mContent = content;
}
void ClipboardEventNotifier::ClearContent()
{
mContent.clear();
}
void ClipboardEventNotifier::EmitContentSelectedSignal()
{
if ( !mContentSelectedSignal.Empty() )
{
Dali::ClipboardEventNotifier handle( this );
mContentSelectedSignal.Emit( handle );
}
}
ClipboardEventNotifier::ClipboardEventNotifier()
: mContent()
{
}
ClipboardEventNotifier::~ClipboardEventNotifier()
{
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
|
#include "configure.h"
#include "control.h"
#include "Total_operation/run.h"
int main()
{
WorKing run;
run.Run();
return 0;
}
|
// tkDNN YOLO PastaPi plugin
// Copyright (C) 2020 Pawel Adamski
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// This plugin uses tkDNN
// Licensed under terms of GPLv2
// https://github.com/ceccocats/tkDNN
#include "dnn_tkdnn.h"
#include <chrono>
namespace spaghetti::elements {
TkDnn::TkDnn()
{
setMinInputs(1);
setMaxInputs(8);
setMinOutputs(3);
setMaxOutputs(10);
addInput(ValueType::eMatrix, "Frame", IOSocket::eCanHoldMatrix | IOSocket::eCanChangeName);
setDefaultNewInputFlags(IOSocket::eCanHoldMatrix | IOSocket::eCanChangeName);
addOutput(ValueType::eBool, "Readdy", IOSocket::eCanHoldBool | IOSocket::eCanChangeName);
addOutput(ValueType::eFloat, "Inference time", IOSocket::eCanHoldFloat | IOSocket::eCanChangeName);
addOutput(ValueType::eDNNRectVector, "Output", IOSocket::eCanHoldDNNRectVector | IOSocket::eCanChangeName);
setDefaultNewOutputFlags(IOSocket::eCanHoldDNNRectVector | IOSocket::eCanChangeName);
}
void TkDnn::calculate()
{
if (m_configuration.syncInputs) {
for (auto const &input : m_inputs) {
if (!input.valueChanged) return;
}
}
if (!m_networkReaddy) return;
std::vector<std::pair<int, int>> resultFlow{};
for (unsigned i = 0; i < m_inputs.size() && i < m_outputs.size() + 2; i++) {
if (m_inputs[i].valueChanged) resultFlow.push_back({ i, i + 2 });
}
double totalInferenceTime = 0.0;
for (auto &flow : resultFlow) {
auto const FROM = flow.first;
auto const TO = flow.second;
std::vector<cv::Mat> batch{ m_inputs[FROM].getValue<cv::Mat>() };
if (batch.front().empty()) continue;
auto start = std::chrono::steady_clock::now();
m_lock.lock();
m_yoloNetwork.update(batch);
auto boxes = m_yoloNetwork.batchDetected;
m_lock.unlock();
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = end - start;
totalInferenceTime += elapsed.count();
DNNRectVector resultVec;
for (auto &box : boxes) {
for (auto &boxElement : box) {
DNNRect rect{ { static_cast<int>(boxElement.x), static_cast<int>(boxElement.y), static_cast<int>(boxElement.w),
static_cast<int>(boxElement.h) },
boxElement.cl,
boxElement.prob };
resultVec.push_back(rect);
}
}
m_outputs[TO].setValue(resultVec);
}
m_outputs[1].setValue<double>(totalInferenceTime);
}
void TkDnn::serialize(Json &a_json)
{
Element::serialize(a_json);
auto &properties = a_json["properties"];
properties["networkFilePath"] = m_configuration.networkFilePath;
properties["classes"] = m_configuration.classes;
properties["confidenceThreshold"] = m_configuration.confidenceThreshold;
properties["syncInputs"] = m_configuration.syncInputs;
}
void TkDnn::deserialize(Json const &a_json)
{
Element::deserialize(a_json);
TkDNNConfiguration config{};
auto const &PROPERTIES = a_json["properties"];
config.networkFilePath = PROPERTIES["networkFilePath"].get<std::string>();
config.classes = PROPERTIES["classes"].get<int>();
config.confidenceThreshold = PROPERTIES["confidenceThreshold"].get<double>();
config.syncInputs = PROPERTIES["syncInputs"].get<bool>();
confugure(config);
}
bool TkDnn::confugure(TkDNNConfiguration const a_configuration)
{
m_lock.lock();
if (!m_yoloNetwork.init(a_configuration.networkFilePath, a_configuration.classes, 1,
a_configuration.confidenceThreshold)) {
m_networkReaddy = false;
} else {
m_networkReaddy = true;
}
m_configuration = a_configuration;
m_outputs[0].setValue(m_networkReaddy);
m_lock.unlock();
return m_networkReaddy;
}
} // namespace spaghetti::elements
|
#ifndef PYTHONIC_NUMPY_MEDIAN_HPP
#define PYTHONIC_NUMPY_MEDIAN_HPP
#include "pythonic/include/numpy/median.hpp"
#include "pythonic/utils/functor.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/numpy/asarray.hpp"
#include <algorithm>
namespace pythonic
{
namespace numpy
{
template <class T, size_t N>
decltype(std::declval<T>() + 1.) median(types::ndarray<T, N> const &arr)
{
size_t n = arr.flat_size();
T *tmp = new T[n];
std::copy(arr.buffer, arr.buffer + n, tmp);
std::sort(tmp, tmp + n);
auto out = (tmp[n / 2] + tmp[(n - 1) / 2]) / double(2);
delete[] tmp;
return out;
}
template <class T, size_t N>
decltype(std::declval<T>() + 1.) median(types::ndarray<T, N> &&arr)
{
size_t n = arr.flat_size();
T *tmp = arr.buffer;
std::sort(tmp, tmp + n);
auto out = (tmp[n / 2] + tmp[(n - 1) / 2]) / double(2);
return out;
}
NUMPY_EXPR_TO_NDARRAY0_IMPL(median);
DEFINE_FUNCTOR(pythonic::numpy, median);
}
}
#endif
|
#include <core/RunEngine.hpp>
#include <iostream>
#include <string>
#include <BsPrerequisites.h>
#include <FileSystem/BsPath.h>
#include <core/Engine.hpp>
#include <log/logging.hpp>
using namespace REGoth;
int REGoth::runEngine(Engine& engine)
{
engine.initializeBsf();
REGOTH_LOG(Info, Uncategorized, "[Main] Running Engine");
REGOTH_LOG(Info, Uncategorized, "[Main] - Engine executable: {0}",
engine.config()->engineExecutablePath.toString());
REGOTH_LOG(Info, Uncategorized, "[Main] - Game directory: {0}",
engine.config()->originalAssetsPath.toString());
REGOTH_LOG(Info, Uncategorized, "[Main] Finding REGoth content-directory");
engine.findEngineContent();
REGOTH_LOG(Info, Uncategorized, "[Main] Loading original game packages");
engine.loadGamePackages();
if (!engine.hasFoundGameFiles())
{
REGOTH_LOG(Fatal, Uncategorized,
"No files loaded into the VDFS - is the game assets path correct?");
return EXIT_FAILURE;
}
REGOTH_LOG(Info, Uncategorized, "[Engine] Load cached resource manifests");
engine.loadCachedResourceManifests();
REGOTH_LOG(Info, Uncategorized, "[Engine] Loading Shaders");
engine.setShaders();
REGOTH_LOG(Info, Uncategorized, "[Engine] Caching original resources");
engine.populateResourceCache();
REGOTH_LOG(Info, Uncategorized, "[Engine] Setting up input");
engine.setupInput();
REGOTH_LOG(Info, Uncategorized, "[Engine] Setting up Main Camera");
engine.setupMainCamera();
REGOTH_LOG(Info, Uncategorized, "[Engine] Setting up Scene");
engine.setupScene();
REGOTH_LOG(Info, Uncategorized, "[Engine] Save cached resource manifests");
engine.saveCachedResourceManifests();
REGOTH_LOG(Info, Uncategorized, "[Engine] Run");
engine.run();
REGOTH_LOG(Info, Uncategorized, "[Engine] Save cached resource manifests");
engine.saveCachedResourceManifests();
REGOTH_LOG(Info, Uncategorized, "[Engine] Shutdown");
engine.shutdown();
return EXIT_SUCCESS;
}
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
int d[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class AverageCandyLifetime {
public:
double getAverage(vector <int> A) {
int x = 0;
int dd = 0;
int t = 0;
for (int i=0; i<(int)A.size(); ++i) {
dd += d[i];
t += A[i];
x += A[i] * dd;
}
return double(x)/t;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 60.5; verify_case(0, Arg1, getAverage(Arg0)); }
void test_case_1() { int Arr0[] = {0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 59.0; verify_case(1, Arg1, getAverage(Arg0)); }
void test_case_2() { int Arr0[] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 50, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 301.5882352941176; verify_case(2, Arg1, getAverage(Arg0)); }
void test_case_3() { int Arr0[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 252.80769230769232; verify_case(3, Arg1, getAverage(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
AverageCandyLifetime ___test;
___test.run_test(-1);
}
// END CUT HERE
|
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "GltfExport.h"
#include "GLTFExporter/Public/Exporters/GLTFLevelExporter.h"
#include "Misc/FileHelper.h"
#include "Ambit/Mode/GltfExporterExternal.h"
#include "AmbitUtils/MenuHelpers.h"
UGltfExport::UGltfExport() : IGltfExportInterface()
{
ExternalExporter = NewObject<UGltfExporterExternal>();
};
bool UGltfExport::Export(UWorld* World, const FString& Filename) const
{
// Set the filename for the Exporter to use.
// This is a global variable used by the UE exporter mechanism and needs to
// be manually assigned.
UExporter::CurrentFilename = Filename;
FString ErrorMessage;
// Find the exporter plugin object created during UE initialization.
if (!ExternalExporter->DoesExporterExist())
{
// The chances of this failing are extremely low (almost impossible)
// since the GLTF plugin is a required dependency for the Ambit plugin.
ErrorMessage = "glTF Export: glTF Exporter plugin is not installed. \
Follow the instructions in the User Guide to install the glTF Exporter plugin from the marketplace.";
FMenuHelpers::LogErrorAndPopup(ErrorMessage);
return false;
}
// Archive buffer to collect file data and write to file.
FBufferArchive Buffer;
const bool IsExportSuccess = ExternalExporter->ExportBinary(World, Buffer);
if (IsExportSuccess)
{
const bool IsWriteToFileSuccess = ExternalExporter->WriteToFile(Buffer, *Filename);
if (!IsWriteToFileSuccess)
{
ErrorMessage = "glTF Export: Error writing to file " + Filename;
FMenuHelpers::LogErrorAndPopup(ErrorMessage);
return false;
}
}
else
{
// There are two scenarios where the export fails:
// 1. The user cancels the export process.
// 2. Objects could not be written to the Buffer used when writing to a
// file.
//
// There is no straightforward way to determine which reason causes the
// ExportBinary function to fail so a generic failure error code is
// returned.
ErrorMessage = "glTF Export: Error completing export to " + Filename;
FMenuHelpers::LogErrorAndPopup(ErrorMessage);
return false;
}
// Reset the UExporter filename to empty, to not clash with other export
// mechanisms.
UExporter::CurrentFilename = TEXT("");
return true;
}
void UGltfExport::SetDependencies(IGltfExporterExternalInterface* Exporter)
{
ExternalExporter = Exporter;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.