array<System::Byte>^ zDBBinaryReader::ToBytes(int offset, int length) { const unsigned char* puData; // Pointer into raw data array<System::Byte>^ rg; // Managed byte array of data PinnedBytePtr pinRg; // Pinned pointer into rg[] CHECK_DISPOSED(m_disposed); if(offset < 0) throw gcnew ArgumentException(); if(length < 0) throw gcnew ArgumentException(); if((offset + length) > m_cb) throw gcnew ArgumentOutOfRangeException(); // Special case: If the caller wants zero bytes, don't go pinning // pointers and copying nothing. Just return what they want if(length == 0) return gcnew array<System::Byte>(0); rg = gcnew array<System::Byte>(length); // Create return array pinRg = &rg[0]; // Pin and get a pointer // Only copy the amount of data that the caller is looking for puData = reinterpret_cast<const unsigned char*>(sqlite3_column_blob(m_pStatement->Handle, m_ordinal)); memcpy_s(pinRg, length, puData + offset, length); return rg; }
void OpReplaceRepeated::Apply(Expression *expression, Calculator *calculator, int32 recursions) { if(expression->LeafCount() != 2) throw ArgumentException("ReplaceRepeated expects 2 arguments."); if(expression->LeafCount() != 2) throw ArgumentException("ReplaceRepeated expects 2 arguments."); string leafFunction = expression->Leaf(1)->FunctionName(); if(leafFunction != "Rule" && leafFunction != "RuleDelayed" && leafFunction != "List") throw ArgumentException("ReplaceRepeated expects its second argument to be a rule or a list of rules."); ExprVector rules; if(leafFunction == "List") { for(ExprVector::const_iterator item = expression->Leaf(1)->Leaves().begin(); item != expression->Leaf(1)->Leaves().end(); ++ item) if((*item)->FunctionName() != "Rule" && (*item)->FunctionName() != "RuleDelayed") throw ArgumentException("ReplaceRepeated expects its second argument to be a rule or a list of rules."); rules = expression->Leaf(1)->Leaves(); } else rules.push_back(expression->Leaf(1)); int32 iterations(0); Expression *result = expression->Leaf(0); while(true) { bool changed(false); if(!result->ReplaceAll(rules, calculator, &changed)) break; if(!changed) break; ++iterations; if(iterations >= Max_ReplaceRepeated_Iterations) throw LimitationException("Maximum number of iterations reached."); } expression->AssignLeaf(0); expression->Evaluate(calculator, recursions); }
double TMleastSquaresFit(const std::vector<double> &x, const std::vector<double> &y) { if(x.size() != y.size()) throw(ArgumentException("The two arrays given to leastSquaresFit must be of equal length")); if(x.size() <= 1) throw(ArgumentException("At least 2 data points must be given for leastSquaresFit to work")); size_t N = x.size(); double sumx = 0.0; double sumy = 0.0; double sumxx = 0.0; double sumyy = 0.0; double sumxy = 0.0; for(size_t i = 0; i < N; i++) { sumx += x[i]; sumy += y[i]; } double meanx = sumx / (double) N; double meany = sumy / (double) N; for(size_t i = 0; i < N; i++) { sumxx += sqr(x[i] - meanx); sumxy += (x[i] - meanx) * (y[i] - meany); } return sumxy / sumxx; }
/** Return a subvolume of this PixelBox. @param def Defines the bounds of the subregion to return @returns A pixel box describing the region and the data in it @remarks This function does not copy any data, it just returns a PixelBox object with a data pointer pointing somewhere inside the data of object. @throws Exception(ERR_INVALIDPARAMS) if def is not fully contained */ Mogre::PixelBox PixelBox::GetSubVolume(Box def) { if(PixelUtil::IsCompressed(format)) { if(def.left == box.left && def.top == box.top && def.front == box.front && def.right == box.right && def.bottom == box.bottom && def.back == box.back) { // Entire buffer is being queried return *this; } throw gcnew ArgumentException("Cannot return subvolume of compressed PixelBuffer", "def"); } if(!box.Contains(def)) throw gcnew ArgumentException("Bounds out of range", "def"); const size_t elemSize = PixelUtil::GetNumElemBytes(format); // Calculate new data origin PixelBox rval(def, format, (IntPtr)(void*) ( ((uint8*)(void*)data) + ((def.left-box.left)*elemSize) + ((def.top-box.top)*rowPitch*elemSize) + ((def.front-box.front)*slicePitch*elemSize) ) ); rval.rowPitch = rowPitch; rval.slicePitch = slicePitch; rval.format = format; return rval; }
void OpReplace::Apply(Expression *expression, Calculator *calculator, int32 recursions) { if(expression->LeafCount() != 2) throw ArgumentException("Replace expects 2 arguments."); string leafFunction = expression->Leaf(1)->FunctionName(); if(leafFunction != "Rule" && leafFunction != "RuleDelayed" && leafFunction != "List") throw ArgumentException("Replace expects its second argument to be a rule or a list of rules."); if(leafFunction == "List") { for(ExprVector::const_iterator item = expression->Leaf(1)->Leaves().begin(); item != expression->Leaf(1)->Leaves().end(); ++ item) if((*item)->FunctionName() != "Rule" && (*item)->FunctionName() != "RuleDelayed") throw ArgumentException("Replace expects its second argument to be a rule or a list of rules."); for(ExprVector::const_iterator rule = expression->Leaf(1)->Leaves().begin(); rule != expression->Leaf(1)->Leaves().end(); ++ rule) { if((*rule)->LeafCount() != 2) throw ArgumentException("Rule with 2 arguments expected."); if(expression->Leaf(0)->Replace(*rule, calculator)) break; } } else { if(expression->Leaf(1)->LeafCount() != 2) throw ArgumentException("Rule with 2 arguments expected."); expression->Leaf(0)->Replace(expression->Leaf(1), calculator); } expression->AssignLeaf(0); expression->Evaluate(calculator, recursions); }
VideoInfoHeader::VideoInfoHeader(int numColors) { if (numColors < 0) raise(ArgumentException()); if (numColors > 255) raise(ArgumentException()); vih = (VIDEOINFOHEADER*)new uint8[sizeof(VIDEOINFOHEADER) + sizeof(RGBQuad) * numColors]; memset(vih, 0, sizeof(VIDEOINFOHEADER) + sizeof(RGBQuad) * numColors); }
void PickAtomRanges::assertRanges(const MoleculeBase &molecule) const { ASSERT( m_StartAtomIndex.size() == m_NAtoms.size(), CodeException, "Internal array management failure!"); for( size_t i = 0; i < m_NAtoms.size(); i++ ) { if(getEndAtomIndex(i)>=molecule.atom.size()) throw(ArgumentException("End Atom Index must smaller/equal to number of atoms in this molecule\n")); if(getStartAtomIndex(i)>(getEndAtomIndex(i)+1)) throw(ArgumentException("End Atom Index must be greater than Start Atom Index\n")); } }
void Assembler::EncodeOperation(ast::Instruction& instr) { if (instr.op.type() == typeid(ast::Directive)){ return; } Op op = boost::get<Op>(instr.op); instr.encodedOp = EncodeOp(op); if (OneArg(op)){ //we're a jump if (instr.ArgB()){ //exactly one argument throw ArgumentException("One argument expected, got two or more.", instr.lineNumber); } if (ast::IsRegister(instr.ArgC())){ instr.encodedOp |= IBLIS_LS_MODE_BIT; } } else if (ThreeArgs(op)){ if (!instr.ArgA() || !instr.ArgB()){ throw ArgumentException("Three arguments expected.", instr.lineNumber); } if (!ast::IsRegister(instr.ArgC())){ throw EncodeException("C must be a register for arithmetic/compare operations.", instr.lineNumber); } if (!ast::IsRegister(instr.ArgA().get())){ instr.encodedOp |= IBLIS_LIT_A_BIT; } if (!ast::IsRegister(instr.ArgB().get())){ instr.encodedOp |= IBLIS_LIT_B_BIT; } } else { if (!instr.ArgB() || instr.ArgA()){ //exactly two arguments throw ArgumentException("Two arguments expected, got three.", instr.lineNumber); } if (ast::IsRegister(instr.ArgB().get())){ if (op == Op::CONST){ throw ArgumentException("Argument B for CONST cannot be a register reference.", instr.lineNumber); } instr.encodedOp |= IBLIS_LS_MODE_BIT; } else { if (op == Op::PUSH || op == Op::POP || op == Op::COPY){ throw EncodeException("Argument B for PUSH/POP/COPY must be a register.", instr.lineNumber); } } } }
void Buffer::BlockCopy(T src[], int srcOffset, T dst[], int dstOffset, int count) { if (src == null) throw ArgumentNullException("src"); if (dst == null) throw ArgumentNullException("dst"); if (srcOffset < 0) throw ArgumentOutOfRangeException("srcOffset", "Non-negative number required."); if (dstOffset < 0) throw ArgumentOutOfRangeException("dstOffset", "Non-negative number required."); if (count < 0) throw ArgumentOutOfRangeException("count", "Non-negative number required."); if ((srcOffset > ByteLength(src) - count) || (dstOffset > ByteLength(dst) - count)) throw ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); for(int i = srcOffset, j = dstOffset; i < (srcOffset + count); i++, j++) { dst[j] = src[i]; } }
void MemoryStream::Write(ByteArray& buffer, int32 offset, int32 count) { if(buffer.IsNull()) throw ArgumentNullException(L"buffer"); if (offset < 0 || count < 0) throw ArgumentOutOfRangeException (); if((int32)buffer.Length() - offset < count) throw ArgumentException(L"offset+count", L"The size of the buffer is less than offset + count."); CheckIfClosedThrowDisposed (); if(!CanWrite()) throw NotSupportedException(L"Cannot write to this stream."); // reordered to avoid possible integer overflow if(_position > _length - count) Expand(_position + count); Buffer::BlockCopy(buffer, offset, (*_internalBuffer), _position, count); _position += count; if(_position >= _length) _length = _position; }
int64 MemoryStream::Seek(int64 offset, SeekOrigin loc) { CheckIfClosedThrowDisposed (); if(offset > (int64)Int32::MaxValue) throw ArgumentOutOfRangeException(L"Offset out of range. " + offset); int32 refPoint; switch(loc) { case SeekOrigin::Begin: if(offset < 0) throw IOException(L"Attempted to seek before start of MemoryStream."); refPoint = _initialIndex; break; case SeekOrigin::Current: refPoint = _position; break; case SeekOrigin::End: refPoint = _length; break; default: throw ArgumentException(L"loc", L"Invalid SeekOrigin"); } refPoint += (int32)offset; if(refPoint < _initialIndex) throw IOException(L"Attempted to seek before start of MemoryStream."); _position = refPoint; return _position; }
void ShiftableBuffer::AdvanceRead(size_t aNumBytes) { if(aNumBytes > this->NumReadBytes()) throw ArgumentException(LOCATION, "Cannot be greater than the number of currently available reader bytes"); mReadPos += aNumBytes; }
void BitArray::CheckOperand(BitArray& operand) { if(&operand == nullptr) throw ArgumentNullException(); if(operand._length != _length) throw ArgumentException (); }
System::Object^ VowpalWabbitDynamicPredictionFactory::Create(vw* vw, example* ex) { if (ex == nullptr) throw gcnew ArgumentNullException("ex"); switch (vw->l->pred_type) { case prediction_type::scalar: return VowpalWabbitPredictionType::Scalar->Create(vw, ex); case prediction_type::scalars: return VowpalWabbitPredictionType::Scalars->Create(vw, ex); case prediction_type::multiclass: return VowpalWabbitPredictionType::Multiclass->Create(vw, ex); case prediction_type::multilabels: return VowpalWabbitPredictionType::Multilabel->Create(vw, ex); case prediction_type::action_scores: return VowpalWabbitPredictionType::ActionScore->Create(vw, ex); case prediction_type::prob: return VowpalWabbitPredictionType::Probability->Create(vw, ex); case prediction_type::multiclassprobs: return VowpalWabbitPredictionType::MultiClassProbabilities->Create(vw, ex); default: { auto sb = gcnew StringBuilder(); sb->Append("Unsupported prediction type: "); sb->Append(gcnew String(prediction_type::to_string(vw->l->pred_type))); throw gcnew ArgumentException(sb->ToString()); } } }
void NetworkPlan::createModelFromFile(const char* input) { if (input == NULL) throw ArgumentException("Необходимо указать имя файла с исходными данными"); ifstream infile(input); if (!infile) throw Exception("Не удалось открыть файл исходных данных"); const int bufSize = 128; char* chBuf = new char[bufSize]; vector<char*> lines; // Считываем входной файл построчно. Заполняем массив строк. while (infile.getline(chBuf, bufSize)) { lines.push_back(chBuf); chBuf = new char[bufSize]; } delete chBuf; infile.close(); // Создаём модель. createModel(lines); int size = lines.size(); // Удаляем ненужные более строки. for (int i = 0; i < size; i++) delete lines.at(i); }
void NetworkPlan::createModelFromString(const char* input) { if (input == NULL || strlen(input) == 0) throw ArgumentException("Не указан файл данных"); vector<char*> lines; istringstream* iss = new istringstream(input); const int bufSize = 128; char* chBuf = new char[bufSize]; // Считываем входную строку частями, с разбиением по символу переноса строки, // и заполняем массив строк. while (iss->getline(chBuf, bufSize)) { lines.push_back(chBuf); chBuf = new char[bufSize]; } delete chBuf; // Формируем модель. createModel(lines); int size = lines.size(); // Удаляем ненужные более строки. for (int i = 0; i < size; i++) delete lines.at(i); }
PhysLayerSettings PhysicalLayerMap ::GetSettings(const std::string& arName) { if(mSettingsMap.find(arName) == mSettingsMap.end()) throw ArgumentException(LOCATION, "Layer with that name doesn't exist"); return mSettingsMap[arName]; }
string parseUnixSocketAddress(const StaticString &address) { if (getSocketAddressType(address) != SAT_UNIX) { throw ArgumentException("Not a valid Unix socket address"); } return string(address.c_str() + sizeof("unix:") - 1, address.size() - sizeof("unix:") + 1); }
void AsyncDatabase::SetClass(apl::DataTypes aType, size_t aIndex, PointClass aClass) { switch(aType) { case(DT_BINARY): if(aIndex >= mBinaryVec.size()) throw Exception(LOCATION, "", ERR_INDEX_OUT_OF_BOUNDS); mBinaryVec[aIndex].mClass = aClass; break; case(DT_ANALOG): if(aIndex >= mAnalogVec.size()) throw Exception(LOCATION, "", ERR_INDEX_OUT_OF_BOUNDS); mAnalogVec[aIndex].mClass = aClass; break; case(DT_COUNTER): if(aIndex >= mCounterVec.size()) throw Exception(LOCATION, "", ERR_INDEX_OUT_OF_BOUNDS); mCounterVec[aIndex].mClass = aClass; break; case(DT_CONTROL_STATUS): if(aIndex >= mControlStatusVec.size()) throw Exception(LOCATION, "", ERR_INDEX_OUT_OF_BOUNDS); mControlStatusVec[aIndex].mClass = aClass; break; case(DT_SETPOINT_STATUS): if(aIndex >= mSetpointStatusVec.size()) throw Exception(LOCATION, "", ERR_INDEX_OUT_OF_BOUNDS); mSetpointStatusVec[aIndex].mClass = aClass; break; default: throw ArgumentException(LOCATION, "Class cannot be assigned for this type"); } }
void parseTcpSocketAddress(const StaticString &address, string &host, unsigned short &port) { if (getSocketAddressType(address) != SAT_TCP) { throw ArgumentException("Not a valid TCP socket address"); } vector<string> args; string begin(address.c_str() + sizeof("tcp://") - 1, address.size() - sizeof("tcp://") + 1); split(begin, ':', args); if (args.size() != 2) { throw ArgumentException("Not a valid TCP socket address"); } else { host = args[0]; port = atoi(args[1].c_str()); } }
void CommsProcessor::setHandoffQ( DoubleBufferedQueue<Event*> *q ) { if( q ) { this->handoffQ = q; } else { throw ArgumentException( "MessageCallback was attempted to be set to nullptr" ); } }
bool EnhancedVtoRouter::CheckIncomingVtoData(const VtoData& arData) { switch(arData.GetType()) { case(VTODT_DATA): if(mInstRemoteConnected) return true; else { LOG_BLOCK(LEV_WARNING, "Discarding received data, because remote side is offline"); this->HandleReceivingDataWhenRemoteClosed(); return false; } case(VTODT_REMOTE_OPENED): if(mInstRemoteConnected) { LOG_BLOCK(LEV_WARNING, "Remote side opened, but it was already open"); this->HandleDuplicateOpen(); return false; } else { mInstRemoteConnected = true; return true; } case(VTODT_REMOTE_CLOSED): if(mInstRemoteConnected) { mInstRemoteConnected = false; return true; } else { LOG_BLOCK(LEV_WARNING, "Remote side closed, but it was already closed"); this->HandleDuplicateClose(); return false; } default: throw ArgumentException(LOCATION, "Unknown VtoData type"); } }
// CommsProcessor class CommsProcessor::CommsProcessor( CommsProcessorRole r, Engine* owner ) { //TODO Make TTL variable and accessors instead of hardcoded this->owner = owner; this->role = r; this->sendSocket.setMulticastTTL( 1 ); this->running = true; this->announceSignaled = false; this->serverAddr = "255.255.255.255"; switch( r ) { case CommsProcessorRole::SERVER: this->listenThread = thread( &CommsProcessor::serverCallback, this ); break; case CommsProcessorRole::CLIENT: this->listenThread = thread( &CommsProcessor::clientCallback, this ); break; case CommsProcessorRole::LOOPBACK: throw NotImplementedException("This needs to be checked for accuracy post-merge"); //announceSignaled = true; break; case CommsProcessorRole::MONITOR: this->listenThread = thread( &CommsProcessor::monitorCallback, this ); break; case CommsProcessorRole::CUSTOM: throw NotImplementedException( "Custom is not yet implemented" ); default: throw ArgumentException( "An invalid mode was specified" ); } }
void Application::createDisplay(uint width, uint height, uint bpp, uint depthBits, uint stencilBits, DisplayMode mode, const std::string &title) { // call main version of createDisplay with individual values for rgba bits switch(bpp) { case 8: createDisplay(width, height, 3, 3, 2, 0, depthBits, stencilBits, mode, title); break; case 16: createDisplay(width, height, 5, 6, 5, 0, depthBits, stencilBits, mode, title); break; case 24: createDisplay(width, height, 8, 8, 8, 0, depthBits, stencilBits, mode, title); break; case 32: createDisplay(width, height, 8, 8, 8, 8, depthBits, stencilBits, mode, title); break; default: throw ArgumentException("bpp argument of createDisplay must be " "8,16,24, or 32, passed " + boost::lexical_cast<std::string>(bpp) ); } }
void ShiftableBuffer::AdvanceWrite(size_t aNumBytes) { if(aNumBytes > this->NumWriteBytes()) // This could indicate a buffer overflow throw ArgumentException(LOCATION, "Cannot be greater than the number of currently available writer bytes"); mWritePos += aNumBytes; }
PhysLayerSettings PhysicalLayerMap ::_GetSettings(const std::string& arName) { NameToSettingsMap::iterator i = mNameToSettingsMap.find(arName); if(i == mNameToSettingsMap.end()) throw ArgumentException(LOCATION, "Settings with name doesn't exist: " + arName); return i->second; }
void CommsProcessor::sendEvent( const Event* evt ) { BufferBuilder buffer; evt->serialize( buffer ); if( buffer.getSize() > (maxMsgSize - sizeof( Message )) ) { throw ArgumentException( "Message len is too big" ); } int port; string dstAddr; Message *buf = (Message*)sendBuf; memcpy( buf->payload, buffer.getBasePointer(), buffer.getSize() ); buf->header.reserved1 = 0; buf->header.len = buffer.getSize(); switch( role ) { case CommsProcessorRole::SERVER: buf->header.msgType = static_cast<uint8_t>(MessageType::SERVER_EVENT); dstAddr = mcastAddr; port = clntPort; break; case CommsProcessorRole::CLIENT: buf->header.msgType = static_cast<uint8_t>(MessageType::CLIENT_EVENT); dstAddr = serverAddr; port = svrPort; break; case CommsProcessorRole::LOOPBACK: { throw NotImplementedException("New event stuff broke loopback"); /* buf->header.msgType = static_cast<uint8_t>(MessageType::LOOPBACK_EVENT); dstAddr = selfAddr ? ; port = ? ; */ return; } case CommsProcessorRole::MONITOR: return; case CommsProcessorRole::CUSTOM: throw NotImplementedException( "Custom is not yet implemented" ); default: throw ArgumentException( "An invalid mode was specified" ); } sendSocket.sendTo( buf, sizeof( Message ) + buffer.getSize(), dstAddr, port ); }
CommandModes XmlToConfig::ConvertMode(const std::string& arMode) { if(arMode == "SBO") return CM_SBO_ONLY; if(arMode == "DO_ONLY") return CM_DO_ONLY; if(arMode == "SBO_OR_DO") return CM_SBO_OR_DO; throw ArgumentException(LOCATION, "invalid command mode"); }
PhysLayerInstance* PhysicalLayerMap ::_GetInstance(const std::string& arName) { NameToInstanceMap::iterator i = mNameToInstanceMap.find(arName); if(i == mNameToInstanceMap.end()) throw ArgumentException(LOCATION, "Instance with name doesn't exist: " + arName); return &(i->second); }
void PhysicalLayerManager::Remove(const std::string& arName) { NameToInstanceMap::iterator i = mNameToInstanceMap.find(arName); if(i == mNameToInstanceMap.end()) throw ArgumentException(LOCATION, "Unknown layer"); i->second.Release(); this->ReleaseLayer(arName); mNameToInstanceMap.erase(i); mNameToSettingsMap.erase(arName); }