size_t PacketStreamReader::Stream::read(char* target, size_t len) { _tag = 0; _frame.src = static_cast<decltype(_frame.src)>(-1); Base::read(target, len); if (_data_len) { _data_len = std::max( (int)_data_len - (int)gcount(), (int)0); } return gcount(); }
path ConcatDumps(const Config& c, path first, path second) { auto output_path = c.dump_dir() / boost::filesystem::unique_path(first.stem().native() + "%%%%-%%%%-%%%%-%%%%" + first.extension().c_str()); if (!fs::exists(first)) { if (!fs::exists(second)) { auto touch = c.ofstream(output_path); return output_path; } fs::copy_file(second, output_path); return output_path; } fs::copy_file(first, output_path); if (!fs::exists(second)) { return output_path; } auto previous = c.ifstream(second); auto append_to = c.ofstream(output_path, std::ios::app); char buffer[4 << 10]; while(!previous.fail()) { previous.read(buffer, sizeof(buffer)); append_to.write(buffer, previous.gcount()); } return output_path; }
STD1::uint32_t Document::writeIndex( std::FILE* out ) { STD1::uint32_t offset( 0 ); hdr->indexCount = 0; hdr->indexSize = 0; eHdr->gIndexCount = 0; if( !index.empty() ) { offset = std::ftell( out ); STD1::uint32_t count( 0 ); STD1::uint32_t gcount( 0 ); STD1::uint32_t size( 0 ); for( IndexIter itr = index.begin(); itr != index.end(); ++itr ) { size += ( *itr )->write( out ); count += ( *itr )->secondaryCount() + 1; if( ( *itr )->isGlobal() ) gcount += 1; } if( count > UINT16_MAX ) throw FatalError( ERR_LARGEINDEX ); hdr->indexCount = static_cast< STD1::uint16_t >( count ); hdr->indexSize = size; eHdr->gIndexCount = gcount; } return offset; }
std::shared_ptr<VersionManifest> ArchiveReader::read_manifest(){ auto stream = this->get_stream(); if (this->manifest_offset < 0){ const int uint64_length = sizeof(std::uint64_t); std::int64_t start = -uint64_length - sha256_digest_length; stream->seekg(start, std::ios::end); char temp[uint64_length]; stream->read(temp, uint64_length); if (stream->gcount() != uint64_length) throw ArchiveReadException("Invalid data: File is too small to possibly be valid"); deserialize_fixed_le_int(this->manifest_size, temp); start -= this->manifest_size; stream->seekg(start, std::ios::end); this->manifest_offset = stream->tellg(); }else stream->seekg(this->manifest_offset); { boost::iostreams::stream<BoundedInputFilter> bounded(*stream, this->manifest_size); boost::iostreams::stream<LzmaInputFilter> lzma(bounded); ImplementedDeserializerStream ds(lzma); this->version_manifest.reset(ds.begin_deserialization<VersionManifest>(config::include_typehashes)); if (!this->version_manifest) throw ArchiveReadException("Invalid data: Error during manifest deserialization"); } this->base_objects_offset = this->manifest_offset - this->version_manifest->archive_metadata.entries_size_in_archive; this->stream_ids = this->version_manifest->archive_metadata.stream_ids; this->stream_sizes = this->version_manifest->archive_metadata.stream_sizes; return this->version_manifest; }
void getData(char* buff, size_t length) throw(FFStreamError, EndOfFile) { try { read(buff, length); } catch(std::exception& exc) { if (gcount() != length && eof()) { EndOfFile err("EOF encountered"); GPSTK_THROW(err); } else { FFStreamError err(exc.what()); std::cout << err << std::endl; GPSTK_THROW(err); } } catch(...) { FFStreamError err("Unknown exception"); GPSTK_THROW(err); } } // end of getData(char*, size_t))
int main(int argc, char* argv[]) { if (argc != 3) { std::cout << "usage: " << argv[0] << " hash file " << std::endl; std::cout << " check the MD5 hash of a file" << std::endl; std::cout << " Adobe Source Libraries v" << ADOBE_VERSION_MAJOR << "." << ADOBE_VERSION_MINOR << "." << ADOBE_VERSION_SUBMINOR << std::endl; std::cout << " Boost v" << BOOST_VERSION / 100000 << "." << BOOST_VERSION / 100 % 1000 << "." << BOOST_VERSION % 100 << std::endl; return 1; } bool success = false; try { adobe::md5_t m; boost::filesystem::path file_path(argv[2]); boost::filesystem::ifstream stream(file_path, std::ios::binary | std::ios::in); while (stream.good()) { boost::array<std::ifstream::char_type, 256 * 1024> buffer; stream.read(&buffer[0], static_cast<std::streamsize>(buffer.size())); std::streamsize gcount(stream.gcount()); if (gcount > 0) m.update(&buffer[0], static_cast<std::size_t>(gcount)); } adobe::md5_t::digest_t hash(m.final()); adobe::md5_t::digest_t::iterator first(hash.begin()); adobe::md5_t::digest_t::iterator last(hash.end()); std::string actual; std::ostringstream oss(actual); for (; first != last; ++first) { oss.width(2); oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*first); } std::string expected(argv[1]); success = oss.str() == expected; if (!success) std::cout << "Expected: " << expected << " actual: " << oss.str() << std::endl; } catch (const std::exception& error) { std::cerr << "Exception: " << error.what() << std::endl; } catch (...) { std::cerr << "Unknown exception" << std::endl; } return success ? 0 : 1; }
size_t PacketStreamReader::Stream::skip(size_t len) { ignore(len); if (_data_len) { _data_len = std::max( (int)_data_len - (int)gcount(), (int)0); } _tag = 0; _frame.src = static_cast<decltype(_frame.src)>(-1); return len; }
void runtime·NumGoroutine(intgo ret) { ret = 0; FLUSH(&ret); #line 54 "C:\Users\ADMINI~1\AppData\Local\Temp\2\makerelease686069423\go\src\pkg\runtime\runtime1.goc" ret = runtime·gcount(); FLUSH(&ret); }
void runtime·NumGoroutine(intgo ret) { ret = 0; FLUSH(&ret); #line 54 "/home/14/ren/source/golang/go/src/pkg/runtime/runtime1.goc" ret = runtime·gcount(); FLUSH(&ret); }
size_t Http::priv::form_file_read_cb(char *buffer, size_t size, size_t nitems, void *userp) { auto stream = reinterpret_cast<fs::ifstream*>(userp); try { stream->read(buffer, size * nitems); } catch (...) { return CURL_READFUNC_ABORT; } return stream->gcount(); }
/** * read n bytes from stream to c. throws an exception if n!=0 and no bytes were read * * @param c output buffer space * @param n number of bytes to be read * @return *this **/ CheckedInputOutputStream & read(char * c, ::std::streamsize const n) { std::fstream::read(c,n); if ( (n != 0) && (! gcount()) ) { ::libmaus2::exception::LibMausException se; se.getStream() << "Failed to read from file " << filename << std::endl; se.finish(); throw se; } return *this; }
void Server::SendFile(std::pair<std::mutex*, UDPMetadata*>* _pair) { //auto mutex = &_pair->first; auto local_buffer = new char[UDP_BUFFER_SIZE]; auto metadata = _pair->second; auto file = metadata->file; while (!metadata->file->eof() && metadata->returnAllPackages || metadata->missedPackages.size() > 0) { { std::unique_lock<std::mutex> lock(*_pair->first); if (--metadata->currentDelay > 0) continue; metadata->currentDelay = metadata->delay; if (--metadata->packagesTillDrop <= 0) { //RemoveUDPClient(client); std::cout << "UDP client disconnected." << std::endl; break; //if (client == udpClients.end()) break; } /*if (metadata->missedPackages.size() > 0 ) std::cout << metadata->missedPackages.size() << std::endl;*/ if (metadata->missedPackages.size() > 0) { file->seekg(metadata->missedPackages[0] * UDP_BUFFER_SIZE); metadata->missedPackages.erase(metadata->missedPackages.begin()); } else { //file->seekg(metadata->progress); file->seekg(metadata->progress); metadata->progress += UDP_BUFFER_SIZE; } } auto packageNumber = file->tellg() / UDP_BUFFER_SIZE; std::cout << packageNumber << std::endl; file->read(local_buffer, UDP_BUFFER_SIZE); auto dataSize = file->gcount(); AddNumberToDatagram(local_buffer, dataSize, packageNumber); { std::unique_lock<std::mutex> lock(udpMutex); SendRawDataTo(_udp_socket, local_buffer, dataSize + UDP_NUMBER_SIZE, metadata->addr); } } std::cout << "UDP sending finished." << std::endl; }
void Server::SendBlock(CLIENT_INFO clientInfo) { char buffer[BUFFER_SIZE]; auto file = clientInfo->second; try { while (file) { file->read(buffer, BUFFER_SIZE); size_t read = file->gcount(); size_t realySent = SendRawData(clientInfo->first, buffer, read); if (realySent != read) { fpos_t pos = file->tellg(); file->seekg(pos - (read - realySent)); } } } catch(std::runtime_error e) { } FD_CLR(clientInfo->first, &clientsSet); file->close(); shutdown(clientInfo->first, SD_BOTH); closesocket(clientInfo->first); }
exec_type PROC editcore(void) { cmdtype cmd; extern bool s_wrapped; /* rcb[0] = 0; rcp = rcb; */ if (diddled) { setpos(skipws(curr)); /* set cursor x position.. */ yp = settop(LINES / 2); /* Y position */ } if (diddled || zotscreen) /* redisplay? */ redisplay(FALSE); mvcur(yp, xp); /* and move the cursor */ for (;;) { s_wrapped = 0; ch = readchar(); /* get a char */ gcount(); /* ... a possible count */ switch (cmd = movemap[ch]) { case FILE_C: wr_stat(); /* write file stats */ mvcur(yp, xp); break; case WINDOW_UP: case WINDOW_DOWN: scroll(cmd==WINDOW_UP); /* scroll the window */ break; case REDRAW_C: /* redraw the window */ redisplay(TRUE); mvcur(yp, xp); break; case MARKER_C: /* set a marker */ ch = tolower(readchar()); if (ch >= 'a' && ch <= 'z') contexts[ch-'`'] = curr; else if (ch != ESC) error(); break; case REDO_C: if (rcb[0] != 0) { zerostack(&undo); insertmacro(rcb, 1); redoing = TRUE; } break; case REWINDOW: zdraw(readchar()); /* shift the window */ break; case DEBUG_C: /* debugging stuff -- unused */ break; case ZZ_C: /* shortcut for :xit */ ch = readchar(); if (ch == 'Z') insertmacro(":x\r", 1); else if (ch != ESC) error(); break; case EDIT_C: /* drop into line mode */ return E_EDIT; case COLIN_C: /* do one exec mode command */ return E_VISUAL; case HARDMACRO: macrocommand(); /* 'hard-wired' macros */ break; case SOFTMACRO: exmacro(); /* run a macro */ break; case INSMACRO: /* macro for insert mode */ case BAD_COMMAND: error(); break; default: if (cmd < DELETE_C) movearound(cmd); else /*if (cmd < HARDMACRO)*/ docommand(cmd); break; } lastexec = 0; } /* never exits here */ }
bool DSN6File::readHeader() throw() { // first read the complete 512 bytes of header information char header[512]; std::fstream::read(header, 512); if (gcount() != 512) { Log.error() << "DSN6File::readHeader(): File does not contain a proper DSN6 header. Aborting read." << std::endl; return false; } // to determine whether we have to swap bytes in the header (depending on the version of // the DSN6 - File and on the byte order on the machine) we try to reproduce the known value // of 100 in header[2*18] short int header_value = readHeaderValue_(header, 18); if (header_value != 100) { // try to change endianness swap_bytes_ = true; header_value = readHeaderValue_(header, 18); if (header_value != 100) { Log.error() << "DSN6File::readHeader(): Corrupt DSN6 header: header[16] != 100. Aborting read." << std::endl; return false; } } header_value = readHeaderValue_(header, 0); start_.x = (float)header_value; header_value = readHeaderValue_(header, 1); start_.y = (float)header_value; header_value = readHeaderValue_(header, 2); start_.z = (float)header_value; header_value = readHeaderValue_(header, 3); extent_.x = (float)header_value; header_value = readHeaderValue_(header, 4); extent_.y = (float)header_value; header_value = readHeaderValue_(header, 5); extent_.z = (float)header_value; header_value = readHeaderValue_(header, 6); sampling_rate_.x = (float)header_value; header_value = readHeaderValue_(header, 7); sampling_rate_.y = (float)header_value; header_value = readHeaderValue_(header, 8); sampling_rate_.z = (float)header_value; header_value = readHeaderValue_(header, 17); cell_scaling_ = (float)header_value; header_value = readHeaderValue_(header, 9); crystal_dimension_.x = (float)header_value / (cell_scaling_ * sampling_rate_.x); header_value = readHeaderValue_(header, 10); crystal_dimension_.y = (float)header_value / (cell_scaling_ * sampling_rate_.y); header_value = readHeaderValue_(header, 11); crystal_dimension_.z = (float)header_value / (cell_scaling_ * sampling_rate_.z); header_value = readHeaderValue_(header, 12); alpha_ = Angle((float)header_value / cell_scaling_, false); header_value = readHeaderValue_(header, 13); beta_ = Angle((float)header_value / cell_scaling_, false); header_value = readHeaderValue_(header, 14); gamma_ = Angle((float)header_value / cell_scaling_, false); header_value = readHeaderValue_(header, 15); prod_ = (float)header_value / 100.; header_value = readHeaderValue_(header, 16); plus_ = (float)header_value; // convert from grid space to cartesian coordinates (inspired by the VMD code :-) ) Vector3 x_tmp(crystal_dimension_.x, 0., 0.); Vector3 y_tmp(cos(gamma_.toRadian()), sin(gamma_.toRadian()), 0.); y_tmp *= crystal_dimension_.y; Vector3 z_tmp( cos(beta_.toRadian()), (cos(alpha_.toRadian()) - cos(beta_.toRadian())*cos(gamma_.toRadian())) / sin(gamma_.toRadian()), 0.); z_tmp.z = sqrt(1.0 - z_tmp.x*z_tmp.x - z_tmp.y*z_tmp.y); z_tmp *= crystal_dimension_.z; origin_.x = x_tmp.x * start_.x + y_tmp.x * start_.y + z_tmp.x * start_.z; origin_.y = y_tmp.y * start_.y + z_tmp.y * start_.z; origin_.z = z_tmp.z * start_.z; xaxis_.x = x_tmp.x * (extent_.x - 1); xaxis_.y = 0.; xaxis_.z = 0.; yaxis_.x = y_tmp.x * (extent_.y - 1); yaxis_.y = y_tmp.y * (extent_.y - 1); yaxis_.z = 0.; zaxis_.x = z_tmp.x * (extent_.z - 1); zaxis_.y = z_tmp.y * (extent_.z - 1); zaxis_.z = z_tmp.z * (extent_.z - 1); // that's it. we're done return true; }
bool DSN6File::read(RegularData3D& density_map) throw() { // first read the header if (!readHeader()) { Log.error() << "DSN6File::read(): readHeader() failed. Aborting read." << std::endl; return false; } // and then the individual bricks. each brick contains 8^3 grid points, stored as bytes // which are converted to floats using the formula // density = (byte_value - plus) / prod float factor = 1./prod_; // how many bricks do we have? Size number_of_bricks_x = (Size) ceil(extent_.x / 8.0); Size number_of_bricks_y = (Size) ceil(extent_.y / 8.0); Size number_of_bricks_z = (Size) ceil(extent_.z / 8.0); Size global_index = 0; Size brick_index = 0; char brick[512]; unsigned char* brick_pointer; RegularData3D::IndexType size; size.x = (Size) extent_.x; size.y = (Size) extent_.y; size.z = (Size) extent_.z; density_map = RegularData3D(origin_, xaxis_, yaxis_, zaxis_, size); // NOTE: this currently only works for orthogonal maps!!! // TODO: implement a simple volumetric data type. all we need to do currently // is to set a matrix converting between the given coordinate system of // the volumetric data set and 3D space density_map.setDimension(Vector3(xaxis_.x, yaxis_.y, zaxis_.z)); Size brick_x, brick_y, brick_z; // the ordering in both the individual bricks and the whole filw // is (fastest to slowest) x - y - z for (brick_z = 0; brick_z < number_of_bricks_z; brick_z++) { for (brick_y = 0; brick_y < number_of_bricks_y; brick_y++) { for (brick_x = 0; brick_x < number_of_bricks_x; brick_x++) { brick_index = 0; // read the next brick std::fstream::read(brick, 512); brick_pointer = (unsigned char*)brick; if (gcount() != 512) { Log.error() << "DSN6File::read(): Could not read next brick. Aborting read." << std::endl; return false; } // and swap its bytes convertBrick_(brick); // code is inspired by the VMD code :-) Size x, y, z; for (z=0; z<8; z++) // iterate over z of the current brick { if ((z + brick_z*8) >= extent_.z) { global_index += (Size)((8-z)*extent_.x*extent_.y); break; } for (y=0; y<8; y++) { if ((y + brick_y*8) >= extent_.y) { global_index += (Size)((8-y)*extent_.x); brick_index += (Size)((8-y)*8); break; } for (x=0; x<8; x++) { if ((x + brick_x*8) >= extent_.x) { global_index += (Size)(8 - x); brick_index += (Size)(8 - x); break; } float brick_value = (float)(*(brick_pointer+brick_index)); density_map[global_index] = factor * (brick_value - plus_); brick_index++; global_index++; } // for x... global_index += (Size)(extent_.x - 8); } // for y... global_index += (Size)(extent_.x*extent_.y - 8*extent_.x); } // for z... global_index += (Size)(8 - 8*extent_.x*extent_.y); } // for brick_x global_index += (Size)(8 * (extent_.x - number_of_bricks_x)); } // for brick_y global_index += (Size)(8 * (extent_.x*extent_.y - extent_.x*brick_y)); } // for brick_z // done. return true; }
static bool loadTestElf(const std::string &path, TestFile &tests) { // Open file auto file = std::ifstream { path, std::ifstream::binary }; auto buffer = std::vector<char> {}; if (!file.is_open()) { return false; } // Get size file.seekg(0, std::istream::end); auto size = (unsigned int)file.tellg(); file.seekg(0, std::istream::beg); // Read whole file buffer.resize(size); file.read(buffer.data(), size); assert(file.gcount() == size); file.close(); auto in = BigEndianView { buffer.data(), size }; auto header = elf::Header {}; auto info = elf::FileInfo {}; auto sections = std::vector<elf::Section> {}; // Read header if (!elf::readHeader(in, header)) { gLog->error("Failed elf::readHeader"); return false; } // Read sections if (!elf::readSections(in, header, sections)) { gLog->error("Failed elf::readSections"); return false; } // Find the code and symbol sections elf::Section *codeSection = nullptr; elf::Section *symbolSection = nullptr; for (auto §ion : sections) { if (section.header.type == elf::SHT_PROGBITS && (section.header.flags & elf::SHF_EXECINSTR)) { codeSection = §ion; } if (section.header.type == elf::SHT_SYMTAB) { symbolSection = §ion; } } if (!codeSection) { gLog->error("Could not find code section"); return false; } if (!symbolSection) { gLog->error("Could not find symbol section"); return false; } // Find all test functions (symbols) auto symView = BigEndianView { symbolSection->data.data(), symbolSection->data.size() }; auto symStrTab = sections[symbolSection->header.link].data.data(); auto symCount = symbolSection->data.size() / sizeof(elf::Symbol); for (auto i = 0u; i < symCount; ++i) { elf::Symbol symbol; elf::readSymbol(symView, symbol); auto type = symbol.info & 0xf; auto name = symbol.name + symStrTab; if (type == elf::STT_SECTION) { continue; } if (symbol.value == 0 && symbol.name == 0 && symbol.shndx == 0) { continue; } tests.tests[name].offset = symbol.value; } tests.code = std::move(codeSection->data); return true; }
// the reason for checking ffs.eof() in the try AND catch block is // because if the user enabled exceptions on the stream with exceptions() // then eof could throw an exception, in which case we need to catch it // and rethrow an EOF or FFStream exception. In any event, EndOfFile // gets thrown whenever there's an EOF and expectEOF is true void FFTextStream::formattedGetLine( std::string& line, const bool expectEOF ) throw(EndOfFile, FFStreamError, gpstk::StringUtils::StringException) { try { // The following constant used to be 256, but with the change to // RINEX3 formats the possible length of a line increased // considerably. A RINEX3 observation file line for Galileo may // be 1277 characters long (taking into account all the possible // types of observations available, plus the end of line // characters), so this constant was conservatively set to // 1500 characters. Dagoberto Salazar. const int MAX_LINE_LENGTH = 1500; char templine[MAX_LINE_LENGTH + 1]; getline(templine, MAX_LINE_LENGTH); lineNumber++; //check if line was longer than 256 characters, if so error if(fail() && !eof()) { FFStreamError err("Line too long"); GPSTK_THROW(err); } line = templine; gpstk::StringUtils::stripTrailing(line, '\r'); // catch EOF when stream exceptions are disabled if ((gcount() == 0) && eof()) { if (expectEOF) { EndOfFile err("EOF encountered"); GPSTK_THROW(err); } else { FFStreamError err("Unexpected EOF encountered"); GPSTK_THROW(err); } } } catch(std::exception &e) { // catch EOF when exceptions are enabled if ( (gcount() == 0) && eof()) { if (expectEOF) { EndOfFile err("EOF encountered"); GPSTK_THROW(err); } else { FFStreamError err("Unexpected EOF"); GPSTK_THROW(err); } } else { FFStreamError err("Critical file error: " + std::string(e.what())); GPSTK_THROW(err); } // End of 'if ( (gcount() == 0) && eof())' } // End of 'try-catch' block } // End of method 'FFTextStream::formattedGetLine()'
int main() { register char * arrayp = (char *) 0; /* Will point to a mallocated array. */ register int i; /* For-loop control variable. */ register char * extrap; /* Pointer to another mallocated array. */ register int alpha; /* Counter for alphabet. */ printf( "Message MA01 from malloc.c: Hello, memory-allocating World!\n" ); /* Use malloc to allocate space for array */ arrayp = (char *) malloc( SIZE * sizeof( char ) ); /* Return values from library calls must always be checked. */ if( 0 == (int) arrayp ) { /* If malloc fails, it returns a null pointer. */ perror( "malloc for array failed" ); exit( 1 ); } /* End of return-value check for malloc */ /* Print info about our mallocated array. */ printf( "MA02: Main array successfully allocated, with size %d bytes.\n", SIZE ); printf( "MA03: Main array malloc returned address %d (dec), %08x (hex).\n", (int) arrayp, (int) arrayp ); /* Initialize array with an alphabet, repeated if necessary. */ alpha = 'a'; for( i = 0; i < (SIZE - 1); i += 1 ) { arrayp[ i ] = alpha; alpha += 1; if( alpha > 'z' ) alpha = 'a'; } /* Add null char at the end, to make array contain a valid C string. */ arrayp[ SIZE - 1 ] = 0; printf( "MA04: Main array now contains the following string:\n%s\n", arrayp ); gcount( arrayp, SIZE ); /* Call gcount, which uses malloc. */ /* Now mallocate room for a copy of Cowabunga! */ extrap = (char *) malloc( sizeof( cowabunga ) ); /* Return values from library calls must always be checked */ if( 0 == (int) extrap ) { /* malloc returned null pointer, print error message. */ perror( "malloc for cowabunga failed" ); exit( 2 ); } printf( "MA05: Cowabunga array successfully allocated, with size %d bytes.\n", (int) sizeof( cowabunga ) ); printf( "MA06: Cowabunga array malloc returned address %d (dec), %08x (hex).\n", (int) extrap, (int) extrap ); if( 0 != (int) extrap ) { strcpy( extrap, cowabunga ); printf( "MA07: Cowabunga array now contains the following string: %s\n", extrap ); /* Copy extrap to array, but stop if array is too small. */ strncpy( arrayp, extrap, SIZE ); /* Put null char at the end, in case strncpy had to stop early. */ arrayp[ SIZE - 1 ] = 0; } printf( "MA08: Main array now contains the following string:\n%s\n", arrayp ); gcount( arrayp, SIZE ); /* Call gcount, which uses malloc. */ /* Free mallocated memory. */ free( arrayp ); /* Free memory allocated to original array. */ printf( "MA09: Executed free( arrayp );\n" ); gcount( extrap, sizeof( cowabunga ) ); /* Call gcount, which uses malloc. */ free( extrap ); /* Free memory allocated to new array. */ printf( "MA10: Executed free( extrap );\n" ); } /* End of main program */
int creatures::get(int mid, int id) { int r; tags itype; object_creature* e; switch(id) { case Strenght: return objects[mid-FirstCreature].attr[id] + get(mid, Bruiser)*2 + get(mid, Gifted); case Perception: return objects[mid-FirstCreature].attr[id] + get(mid, Gifted); case Endurance: return objects[mid-FirstCreature].attr[id] + get(mid, Gifted); case Charisma: return objects[mid-FirstCreature].attr[id] + get(mid, Gifted); case Intellegence: return objects[mid-FirstCreature].attr[id] + get(mid, Gifted); case Agility: return objects[mid-FirstCreature].attr[id] + get(mid, SmallFrame) + get(mid, Gifted); case Luck: return objects[mid-FirstCreature].attr[id] + get(mid, Gifted); // Skills case SkillSmallGuns: return 5+get(mid, Agility)*4 + sbns(mid, id) - get(mid, GoodNatured)*10; case SkillBigGuns: case SkillEnergyWeapon: return get(mid, Agility)*2 + sbns(mid, id) - get(mid, GoodNatured)*10; case SkillUnarmed: return 30 + 2*(get(mid, Agility)+get(mid, Strenght)) + sbns(mid, id) - get(mid, GoodNatured)*10; case SkillMeleeWeapon: return 20 + 2*(get(mid, Agility)+get(mid, Strenght)) + sbns(mid, id) - get(mid, GoodNatured)*10; case SkillThrowing: return 4*get(mid, Agility) + sbns(mid, id) - get(mid, GoodNatured)*10; case SkillFirstAid: return 2*(get(mid, Perception)+get(mid, Intellegence)) + sbns(mid, id) + get(mid, GoodNatured)*15; case SkillDoctor: return 5 + get(mid, Perception) + get(mid, Intellegence) + sbns(mid, id) + get(mid, GoodNatured)*15; case SkillSneak: return 5 + 3*get(mid, Agility) + sbns(mid, id); case SkillLockpick: return 10 + get(mid, Perception) + get(mid, Agility) + sbns(mid, id); case SkillSteal: return 3*get(mid, Agility) + sbns(mid, id); case SkillTraps: return 10 + get(mid, Perception) + get(mid, Agility) + sbns(mid, id); case SkillScience: return 4*get(mid, Intellegence) + sbns(mid, id); case SkillRepair: return 3*get(mid, Intellegence) + sbns(mid, id); case SkillSpeech: return 5*get(mid, Charisma) + sbns(mid, id) + get(mid, GoodNatured)*15; case SkillBarter: return 4*get(mid, Charisma) + sbns(mid, id) + get(mid, GoodNatured)*15; case SkillGambling: return 5*get(mid, Luck) + sbns(mid, id); case SkillOutdoorsman: return 2*(get(mid, Endurance)+get(mid, Intellegence)) + sbns(mid, id); case SkillPoints: return 5 + 2*objects[mid-FirstCreature].attr[Intellegence]; case MaxHP: return 15 + 2*get(mid, Endurance) + get(mid, Strenght) + (objects[mid-FirstCreature].attr[Level])*(2+get(mid, Endurance)/2); case MaxAP: return 5 + get(mid, Agility)/2 - (get(mid, Bruiser) ? 2 : 0); case AC: return get(mid, Agility) + items::get(objects[mid-FirstCreature].gears.body, id); case CarryWeight: return 25 + (get(mid, SmallFrame) ? 15 : 25)*get(mid, Strenght); case MeleeDamage: return imax(1, get(mid, Strenght)-5) + get(mid, HeavyHanded)*4; case Stats: return gcount(mid, FirstStat, LastStat); case Traits: return gcountd(mid, FirstTraits, LastTraits); case Tags: return tagcount(mid); case PoisonResistance: return get(mid, FastMetabolism) ? 0 : (5 * get(mid, Endurance)); case RadiationResistance: return get(mid, FastMetabolism) ? 0 : (2 * get(mid, Endurance)); case Initiative: return 2 * get(mid, Perception); case HealthLevel: return imax(1, get(mid, FastMetabolism)*2 + get(mid, Endurance) / 3); case CriticalHitChance: return get(mid, Luck); case Age: return world::get(Year) - objects[mid-FirstCreature].attr[id]; case Gender: if(objects[mid-FirstCreature].attr[Race]==Female) return Female; return Male; case Race: return get(mid, Gender); case Weapon: return objects[mid-FirstCreature].gears.hands[0]; case Frame: e = &objects[mid-FirstCreature]; itype = items::type(e->gears.body); switch(get(mid, Race)) { case Male: return armour_appearance(itype, res::HMJMPS, false); case Female: return armour_appearance(itype, res::HFJMPS, true); default: return res::NABRWN; } case PositionX: return objects[mid-FirstCreature].position.x; case PositionY: return objects[mid-FirstCreature].position.y; case Action: return objects[mid-FirstCreature].action; case AnimationCicle: return modify_by_weapon(objects[mid-FirstCreature].action, get(mid, Weapon)); case AnimationFrame: return objects[mid-FirstCreature].frame; case AnimationStop: return objects[mid-FirstCreature].stop; case Direction: return objects[mid-FirstCreature].direction; case DamageNormal: case DamageFire: case DamageLaser: case DamageExplosive: case DamageElectrical: case DamageEMP: case DamagePlasma: case DamageResistanceNormal: case DamageResistanceLaser: case DamageResistanceFire: case DamageResistancePlasma: case DamageResistanceElectrical: case DamageResistanceEMP: case DamageResistanceExplosive: return items::get(objects[mid-FirstCreature].gears.body, id); case EquipmentWeight: r = items::get(objects[mid-FirstCreature].gears.hands[0], CarryWeight) + items::get(objects[mid-FirstCreature].gears.hands[1], CarryWeight) + items::get(objects[mid-FirstCreature].gears.body, CarryWeight); for(auto& m : inventories) { if(!m.mid) break; if(m.mid==mid) r += items::get(m.item, CarryWeight); } return r; case Position: e = &objects[mid-FirstCreature]; return map::xy2h(e->position.x, e->position.y); case Order: return objects[mid-FirstCreature].index; default: if(id>=FirstTraits && id<=LastTraits) return (objects[mid-FirstCreature].traits&(1<<(id-FirstTraits))) ? 1 : 0; else if(id<sizeof(objects[0].attr)/sizeof(objects[0].attr[0])) return objects[mid-FirstCreature].attr[id]; return 0; } }
size_t read_data(void* buffer, size_t size, size_t nmemb, void* instream) { auto body = (stringstream*) instream; body->read((char*) buffer, size*nmemb); return body->gcount(); }
bool CCP4File::readHeader() { // first read the complete 1024 bytes of header information char header[1024]; std::fstream::read(header, 1024); if (gcount() != 1024) { Log.error() << "CCP4File::readHeader(): File does not contain a proper CCP4 header. Aborting read." << std::endl; return false; } // Currently only data_mode=2 is allowed, which stores density values as 4-byte float values Index data_mode = readBinValueasInt_(header, 3); if (data_mode != 2) { // try to change endianness swap_bytes_= true; data_mode = readBinValueasInt_(header, 3); if (data_mode != 2) { Log.error() << "CCP4File::readHeader(): Corrupt CCP4 header: data mode not supported, only 32-bit float supported" << std::endl; return false; } } //check if file claims to have symmetry reocrds stored Size size_of_symops = readBinValueasInt_(header, 23); if (size_of_symops != 0) { offset_symops_ = size_of_symops; } // check internal ordering of coordinate axis col_axis_ = readBinValueasInt_(header, 16)-1; row_axis_ = readBinValueasInt_(header, 17)-1; sec_axis_ = readBinValueasInt_(header, 18)-1; extent_.x = (float)readBinValueasInt_(header, 0+col_axis_); extent_.y = (float)readBinValueasInt_(header, 0+row_axis_); extent_.z = (float)readBinValueasInt_(header, 0+sec_axis_); start_.x = (float)readBinValueasInt_(header, 4+col_axis_); start_.y = (float)readBinValueasInt_(header, 4+row_axis_); start_.z = (float)readBinValueasInt_(header, 4+sec_axis_); sampling_rate_.x = (float)readBinValueasInt_(header, 7); sampling_rate_.y = (float)readBinValueasInt_(header, 8); sampling_rate_.z = (float)readBinValueasInt_(header, 9); cell_dimension_.x = readBinValueasFloat_(header, 10); cell_dimension_.y = readBinValueasFloat_(header, 11); cell_dimension_.z = readBinValueasFloat_(header, 12); // Angle values of 0 don't make sense, set the Angles to 90 deg if ( readBinValueasFloat_(header, 13) == 0 || readBinValueasFloat_(header, 14) == 0 || readBinValueasFloat_(header, 15) == 0) { alpha_ = Angle(90.,false); beta_ = Angle(90.,false); gamma_ = Angle(90.,false); } else { alpha_ = Angle(readBinValueasFloat_(header, 13),false); beta_ = Angle(readBinValueasFloat_(header, 14),false); gamma_ = Angle(readBinValueasFloat_(header, 15),false); } mean_density_ = readBinValueasFloat_(header, 21); space_group_ = readBinValueasInt_(header, 22); deviation_sigma_ = readBinValueasFloat_(header, 54); Log.info() << "Mean from file: " << mean_density_ << std::endl; Log.info() << "Sigma from file: " << deviation_sigma_ << std::endl; // convert from grid space to cartesian coordinates Vector3 scaled_axes(cell_dimension_.x/sampling_rate_.x, cell_dimension_.y/sampling_rate_.y, cell_dimension_.z/sampling_rate_.z); Vector3 x_tmp(scaled_axes.x, 0., 0.); Vector3 y_tmp(cos(gamma_.toRadian()), sin(gamma_.toRadian()), 0.); y_tmp *= scaled_axes.y; Vector3 z_tmp( cos(beta_.toRadian()), (cos(alpha_.toRadian()) - cos(beta_.toRadian())*cos(gamma_.toRadian())) / sin(gamma_.toRadian()), 0.); z_tmp.z = sqrt(1.0 - z_tmp.x*z_tmp.x - z_tmp.y*z_tmp.y); z_tmp *= scaled_axes.z; origin_.x = x_tmp.x * start_.x + y_tmp.x * start_.y + z_tmp.x * start_.z; origin_.y = y_tmp.y * start_.y + z_tmp.y * start_.z; origin_.z = z_tmp.z * start_.z; xaxis_.x = x_tmp.x * (extent_.x - 1); xaxis_.y = 0.; xaxis_.z = 0.; yaxis_.x = y_tmp.x * (extent_.y - 1); yaxis_.y = y_tmp.y * (extent_.y - 1); yaxis_.z = 0.; zaxis_.x = z_tmp.x * (extent_.z - 1); zaxis_.y = z_tmp.y * (extent_.z - 1); zaxis_.z = z_tmp.z * (extent_.z - 1); // that's it. we're done return true; }
PROC docommand(cmdtype cmd) { cmdtype movecmd; /* movement command for y, d, c */ char cmdch; int oldc; /* old count */ int endp; /* end position before change */ extern bool s_wrapped; resetX(); /* un-derange the cursor */ oldc = newc = -1; endY = yp; newend = disp = curr; ok = TRUE; /* so far everything is working */ cmdch = ch; if (cmd != UNDO_C && cmd != YANK_C) { if (macro<0) zerostack(&undo); if (redoing != TRUE) { rcp = rcb; /* point at start of redo buffer */ if (count > 1) { /* put in a count? */ numtoa(rcb,count); rcp += strlen(rcb); } *rcp++ = cmdch; /* the command char goes in... */ xerox = TRUE; /* hoist the magical flags */ } } if (cmd <= YANK_C) { readchar(); if (ch >= '0' && ch <= '9') { oldc = count; gcount(); /* get a new count */ if (cmd == ADJUST_C) /* special for >>,<< wierdness */ swap(&count, &oldc); /* reverse sw & count */ else count = count*max(oldc,1); /* combine them */ } if (ch == cmdch) { /* diddle lines */ yank.lines = TRUE; endp = nextline(TRUE, curr, count); curr = bseekeol(curr); disp = curr; } else { /* diddle 'things' */ yank.lines = FALSE; movecmd = movemap[ch]; if (ok = (findCP(curr,&endp,movecmd) == LEGALMOVE)) { if (curr > endp) { swap(&curr,&endp); ok = (cmd != CHANGE_C); } if (adjcurr[movecmd]) curr++; if (adjendp[movecmd]) endp++; } if (!ok) { if (ch != ESC) error(); goto killredo; } } endY = setY(endp); newend = curr; disp = curr; switch (cmd) { case DELETE_C: ok = deletion(curr, endp); break; case ADJUST_C: adjuster((cmdch == '<'), endp-1, oldc); break; case CHANGE_C: if (endp <= pend+1) { mvcur(setY(endp-1), setX(endp-1)); printch('$'); mvcur(yp, xp); } if (deletion(curr, endp)) ok = ((newend = insertion(1, 0, &disp, &endY, TRUE)) >= 0); else ok = FALSE; break; case YANK_C: if (!doyank(curr, endp)) error(); return 0; /* xerox will not be true, nor will redoing */ } } else { endp = curr; endY = yp; switch (cmd) { case I_AT_NONWHITE: case A_AT_END: case APPEND_C: case INSERT_C: /* variations on insert */ if (cmd != INSERT_C) { if (cmd == APPEND_C) curr = min(curr+1, lend); else if (cmd == A_AT_END) curr = lend; else /* if (cmd == I_AT_NONWHITE) */ curr = skipws(lstart); xp = setX(curr); mvcur(yp,xp); } newend = insertion(count, 0, &disp, &endY, TRUE); ok = (newend >= 0); break; case OPEN_C: case OPENUP_C: newend = insertion(1,setstep[ (cmd==OPENUP_C)&1 ], &disp,&endY,TRUE)-1; ok = (newend >= 0); break; case REPLACE_C: case TWIDDLE_C: if (cmd == REPLACE_C) { if ((cmdch = readchar()) == ESC) goto killredo; } if (findCP(curr, &endp, GO_RIGHT) == LEGALMOVE) squiggle(endp-1, cmdch, (cmd==REPLACE_C)); break; case PUT_BEFORE: case PUT_AFTER: ok = put(cmd==PUT_AFTER); break; case BIG_REPL_C: bigreplace(); break; case RESUBST_C: ok = FALSE; if (dst[0] != 0) { newend = chop(curr, &lend, TRUE, &ok); if (newend >= 0) { endY = setY(newend+strlen(dst)); ok = TRUE; } } break; case JOIN_C: join(count); /* join lines */ break; case UNDO_C: /* undo last modification */ ok = fixcore(&newend) >= 0; disp = newend; endY = MAGICNUMBER; break; } } if (ok) { setpos((newc<0)?newend:newc); setend(); if (curr < ptop || curr > pend) { yp = settop(12); redisplay(TRUE); } else { yp = setY(curr); if (endY != setY(newend)) /* shuffled lines */ refresh(setY(disp), setX(disp), disp, pend, TRUE); else /* refresh to end position */ refresh(setY(disp), setX(disp), disp, newend, FALSE); } if (curr >= bufmax && bufmax > 0) { /* adjust off end of buffer */ setpos(bufmax-1); yp = setY(curr); } if (s_wrapped) { prompt(FALSE, "search wrapped around end of buffer"); s_wrapped = 0; } else clrprompt(); modified = TRUE; } else { error(); killredo: rcb[0] = 0; } mvcur(yp, xp); if (xerox) *rcp = 0; /* terminate the redo */ redoing = FALSE; xerox = FALSE; core[bufmax] = EOL; }