blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3a07bb05a01d0e57facdf0fcad011187bde1ccbe | cfdfb8b045feb9efc845dab5f7de6ce815b3246a | /xiangmu/4/Classes/ShareFunc.cpp | 51b03e63a795ddc70e79a6583848dae9e579637f | [] | no_license | joyfish/TowerTD | 814e3063a97bfff1ba9f6d0fa6392886cc787727 | ba793ad00c10adf923dd28a813e44f6ca9956977 | refs/heads/master | 2021-01-14T09:10:29.032591 | 2014-10-17T03:24:11 | 2014-10-17T03:24:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cpp | #include "ShareFunc.h"
#include "GameScene.h"
#include "Hero_SwordPlay.h"
ActionInterval * ShareFunc::getAct(std::string fileName, int begin, int count, float time, int loop)
{
std::string fileNameFirst;
fileName = fileName.substr(0, fileName.find_last_of(".") - 1);
Animation * ani = Animation::create();
for (int i = begin; i <= count; i++)
{
fileNameFirst = fileName + std::to_string(i) + ".png";
auto spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(fileNameFirst);
ani->addSpriteFrame(spriteFrame);
}
ani->setDelayPerUnit(time);
ani->setLoops(loop);
return Animate::create(ani);
}
bool ShareFunc::isFileName(std::string fileName){
std::string fileNameString(fileName);
if (fileNameString.empty())
{
return true;
}
return false;
}
GameScene* ShareFunc::getGameScene(){
return dynamic_cast<GameScene*>(Director::getInstance()->getRunningScene());
}
| [
"liuthou@163.com"
] | liuthou@163.com |
e9354952a5f5c2733630ce86fc7115c925bb241d | bb699fec1d8d2669a0bf02b34c92cab9d909f038 | /qsort.cpp | 7749473ef41ab689b082ada7657eb9757ac6baa7 | [] | no_license | haoweiliu/try-local | 7c0465f40f6e4cc9fd4d1cfd326bd7f339485019 | b1a5cb7de2b7e4239ad2f1f9db34cec3d23aefe2 | refs/heads/master | 2021-02-08T03:45:15.883262 | 2020-03-02T14:47:28 | 2020-03-02T14:47:28 | 244,105,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | #include<iostream>
using namespace std;
int getindex(int *a, int l, int r){
int stad = a[l];
while(l < r){
while(l < r && stad > a[l]){
l++;
}
while(l < r && stad < a[r]){
r--;
}
int temp = a[l];
a[l] = a[r];
a[r] = temp;
}
a[l] = stad;
return l;
}
void qsort(int *a, int l, int r){
if(l < r){
int index = getindex(a,l,r);
qsort(a,l,index-1);
qsort(a,index+1,r);
}
}
int main(){
int a[10];
for(int i = 0; i < 10; i++)
cin>>a[i];
qsort(a,0,9);
for(int i = 0; i < 10; i++)
cout<<a[i]<<endl;
return 0;
}
| [
"haowei_liu@foxmail.com"
] | haowei_liu@foxmail.com |
62e02a014f35e69737f475c2f75d5f9ea3f1c403 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/printscan/ui/uicommon/uiexthlp.h | 8031cf8f3f6df9a768eaf94404ca737cb5480a0c | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,556 | h | /*******************************************************************************
*
* (C) COPYRIGHT MICROSOFT CORPORATION, 1998
*
* TITLE: UIEXTHLP.H
*
* VERSION: 1.0
*
* AUTHOR: ShaunIv
*
* DATE: 7/8/1999
*
* DESCRIPTION: Helper functions for loading UI extensions for WIA devices
*
*******************************************************************************/
#ifndef __UIEXTHLP_H_INCLUDED
#define __UIEXTHLP_H_INCLUDED
#include <windows.h>
#include <objbase.h>
#include <wia.h>
namespace WiaUiExtensionHelper
{
HRESULT GetDeviceExtensionClassID(
LPCWSTR pszID,
LPCTSTR pszCategory,
IID &iidClassID
);
HRESULT CreateDeviceExtension(
LPCWSTR pszID,
LPCTSTR pszCategory,
const IID &iid,
void **ppvObject
);
HRESULT GetUiGuidFromWiaItem(
IWiaItem *pWiaItem,
LPWSTR pszGuid
);
HRESULT GetDeviceExtensionClassID(
IWiaItem *pWiaItem,
LPCTSTR pszCategory,
IID &iidClassID
);
HRESULT CreateDeviceExtension(
IWiaItem *pWiaItem,
LPCTSTR pszCategory,
const IID &iid,
void **ppvObject
);
HRESULT GetDeviceIcons(
BSTR bstrDeviceId,
LONG nDeviceType,
HICON *phIconSmall,
HICON *phIconLarge,
UINT nIconSize = 0 // 0 means default sizes
);
CSimpleString GetExtensionFromGuid(
IWiaItem *pWiaItem,
const GUID &guidFormat
);
}
#endif //__UIEXTHLP_H_INCLUDED
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
e33a0b6165d4755908595fdf03174a6dc5cb59af | 5e0cf563ee173dd09cc863a9466fbd5be3dfa437 | /dct.cpp | 57b2676793b8a39da7645f5e196eb77c852c75f4 | [] | no_license | nguyenvietquoc2569/AudioSurveillance | 20ad16be74d8dfed85a3e6a9844e85239fd0c75e | 2d1a5f1ebf94415475a91b64420b13ccdc186faf | refs/heads/master | 2020-03-19T12:26:08.101174 | 2018-06-07T18:40:57 | 2018-06-07T18:40:57 | 136,516,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | cpp | #include <stdlib.h>
#include <math.h>
#define PI 3.1415926535897932
double* DCT_II(double* x, int N)
{
double* X = (double*) malloc(sizeof(double) * N);
int k,n;
for(k = 0; k < N; k++)
{
X[k] = 0.0;
for(n = 0; n < N; n++)
{
X[k] = (X[k] + (x[n]*cos((PI/N)*(n-.5)*k)));
}
}
return X;
}
| [
"nvquoc.uit@gmail.com"
] | nvquoc.uit@gmail.com |
bdc518321324fca2bdd30b68519112ab35263cbb | ef7fa96059c37d4b58f2655bacf83d41a1250491 | /src/plugin/repeated_message_field.cpp | b47fd2be02064942174c8a91c7d3267912f8cd1c | [
"MIT"
] | permissive | Aniket21mathur/Chapel-protobuf | 1505ce5f2a9b9914699053cc2b4c274ba2ae0713 | 13fbd5a486e97f03f701b7cf75f235cf02d34964 | refs/heads/master | 2022-12-05T01:51:28.403837 | 2020-08-28T17:12:45 | 2020-08-28T17:12:45 | 255,540,522 | 16 | 0 | MIT | 2020-08-28T13:11:06 | 2020-04-14T07:30:34 | Chapel | UTF-8 | C++ | false | false | 1,209 | cpp | /*
* Copyright 2020 Hewlett Packard Enterprise Development LP
* Copyright 2004-2019 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <repeated_message_field.h>
namespace chapel {
RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(
const FieldDescriptor* descriptor)
: FieldGeneratorBase(descriptor) {
}
RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {
}
void RepeatedMessageFieldGenerator::GenerateMembers(Printer* printer) {
printer->Print(variables_, "var $name$: list($type_name$);\n");
}
} // namespace chapel
| [
"amathur@ec.iitr.ac.in"
] | amathur@ec.iitr.ac.in |
c808b7477e3ec35dbaed82a4bbb40e64d75d4a7d | 0ce54fabf8ac6235de5623483e00f411be556743 | /src/sensor/leapmotion/HandRepresentation.cpp | b51b31aa0ff3dd5d792f113f6ed369191b95be6f | [] | no_license | Dawars/handvr-viewer | 3a5060f362c2c30ab77b40bbad33940e840de03d | 23d2d8d6d9d43f7949c700871da8e194e414ec3c | refs/heads/master | 2020-03-08T16:15:06.649925 | 2018-05-13T21:51:04 | 2018-05-13T21:51:04 | 128,234,652 | 0 | 0 | null | 2018-04-17T21:10:45 | 2018-04-05T16:37:52 | CMake | UTF-8 | C++ | false | false | 1,444 | cpp | //
// Created by David Komorowicz on 2018. 04. 17..
//
#include "HandRepresentation.h"
HandRepresentation::HandRepresentation(HandPool *parent, std::shared_ptr<Leap::Hand> hand,
HandModelBase::Chirality repChirality) {
this->parent = parent;
this->HandID = hand->id();
this->RepChirality = repChirality;
this->MostRecentHand = hand;
}
int HandRepresentation::getHandID() const {
return HandID;
}
HandModelBase::Chirality HandRepresentation::getRepChirality() const {
return RepChirality;
}
const std::shared_ptr<Leap::Hand> &HandRepresentation::getMostRecentHand() const {
return MostRecentHand;
}
void HandRepresentation::UpdateRepresentation(std::shared_ptr<Leap::Hand> hand) {
MostRecentHand = hand;
handModel->SetLeapHand(hand); // update Leap::Hand
handModel->UpdateHand(); // update model based on Leap::Hand
}
void HandRepresentation::Finish() {
handModel->FinishHand();
handModel = nullptr;
parent->RemoveHandRepresentation(this);
}
void HandRepresentation::AddModel(std::shared_ptr<HandModelBase> model) {
handModel = model; // fixme add model
auto hand = model->GetLeapHand();
if (hand == nullptr) {
model->SetLeapHand(MostRecentHand);
model->InitHand();
model->BeginHand();
model->UpdateHand();
} else {
model->SetLeapHand(MostRecentHand);
model->BeginHand();
}
}
| [
"dawars00@gmail.com"
] | dawars00@gmail.com |
cb3219915afbc305a5579926bbad34f7ac9ad829 | e7291328b0809d9468f6bd7047e853d2ec4d859d | /164.cpp | 0614492a2bb1329cca25db5fb42843b3980a0ef7 | [] | no_license | ash/cpp-tut | d48967a513baa11d940e698555bf2869d79b6dad | af9f925481f7e502f0788680650acbddc91074b3 | refs/heads/master | 2021-01-18T13:14:47.401874 | 2019-11-10T10:22:44 | 2019-11-10T10:22:44 | 80,743,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135 | cpp | #include <iostream>
int main() {
int odd_data[] = {1, 3, 5, 7, 9};
for (auto x : odd_data)
std::cout << x << "\n";
}
| [
"andy@shitov.ru"
] | andy@shitov.ru |
65d653600b8a369a2a17d9e23ee57949e45f1aad | 2b40f3b29606e93ca2f41415fe24a28836668459 | /include/OptimizerParams/DFP_Params.hpp | f4aa0e36cc9e32ab382f433b8ac490c240583334 | [] | no_license | Shuang1997/NLOP | 35dfa0d12962f7db088f83db3bec5b459f99709c | 00cfafaa4aa50e61c5fbf9a6f9fd043b36c73c8e | refs/heads/master | 2022-11-14T03:48:24.921003 | 2020-07-11T09:46:10 | 2020-07-11T09:46:10 | 286,608,704 | 1 | 0 | null | 2020-08-11T00:40:20 | 2020-08-11T00:40:19 | null | UTF-8 | C++ | false | false | 1,492 | hpp | #ifndef DFP_PARAMS_HPP
#define DFP_PARAMS_HPP
#include <OptimizerParams/LineSearchParams.hpp>
namespace NLOP {
/// @class NLOP::DFP_Params
/// @brief Params of DFP Quasi-Newton method
class DFP_Params: public LineSearchParams
{
public:
/// @brief Constructor
DFP_Params() { setDefaults(); }
void setDefaults() override
{
max_iteration_times = 1000;
iteration_times = 0;
verbosity = SUMMARY;
log_file = false;
stepsize_method = WOLFEPOWELL;
stepsize_params = new WolfePowellParams;
min_gradient = 0.01;
}
/// @brief print params of optimizer
void print() override
{
std::cout << "DFP Optimization" << "\n";
std::cout << "*********************************************" << "\n";
std::cout << "maximum iterations: " << max_iteration_times << "\n";
std::cout << "verbosity: " << verbosityTranslator(verbosity) << "\n";
std::cout << "stepsize method: " << StepsizeMethodTranslator(stepsize_method) << "\n";
std::cout << "gradient thresthold: " << min_gradient << "\n";
std::cout << "*********************************************" << std::endl;
}
/// @brief Set and get mininum gradient to control iterations to stop
void setMinGradient(const double value) { min_gradient = value; }
double getMinGradient() const { return min_gradient; }
private:
double min_gradient = 0.01; // gradient threshold to stop iterations
};
}
#endif
| [
"942054225@qq.com"
] | 942054225@qq.com |
01d35735fc65e24da16089ea3b61d0e9414cee50 | e431a1685ace7e541da641d9005195db89cb1b6f | /373_v1.cpp | 53e4750edd87f0d0fe6ecdafc4393bf46b513c0e | [] | no_license | jianminchen/LeetCode-17 | 7f82230be3510fdfb60847bcee521e6796b33ea9 | 68080d07819bf81823a0c9d25ec84f2a19d422a6 | refs/heads/master | 2021-01-19T07:07:30.481800 | 2016-07-17T08:08:56 | 2016-07-17T08:08:56 | 67,087,459 | 1 | 0 | null | 2016-09-01T01:35:35 | 2016-09-01T01:35:34 | null | UTF-8 | C++ | false | false | 1,095 | cpp | /*
373_v1.cpp
Find K Pairs with Smallest Sums
I was trying to implement an O(K) algorithm initially but then failed. This
algorithm is non-optimal but it at least can get accepted on LeetCode. :p
*/
class PairComparer {
public:
bool operator()(pair<int, int>& a, pair<int, int>& b) {
return a.first + a.second > b.first + b.second;
}
};
class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2,
int k) {
vector<pair<int, int>> ret;
if (k == 0 || nums1.size() == 0 || nums2.size() == 0) return ret;
k = min((int)nums1.size() * (int)nums2.size(), k);
priority_queue<pair<int, int>, vector<pair<int, int>>, PairComparer> pq;
int p1 = 0;
while (ret.size() < k) {
if (p1 < nums1.size() &&
(pq.empty() ||
nums1[p1] + nums2[0] < pq.top().first + pq.top().second)) {
for (int i = 0; i < nums2.size(); i++) pq.emplace(nums1[p1], nums2[i]);
p1++;
}
ret.push_back(pq.top());
pq.pop();
}
return ret;
}
}; | [
"phoenixinter@gmail.com"
] | phoenixinter@gmail.com |
bb12361d0c4b3c96015dd07bf85e3f1f79489fc4 | bc3eea54be4c36b0b113d85c3d3d6b8532e4776b | /Installer/third_party/nbase/base/win32/path_util.cpp | 105d12483200388c85f2ad2c512a14968096bc58 | [] | no_license | wxz879526/Installer | 97ea9e24dc6d6dd851b0aa6b75861128644f3db5 | 693ac79c9d4813fdc995d05a462ad6408943559f | refs/heads/master | 2020-06-27T18:03:37.784419 | 2019-08-01T08:59:39 | 2019-08-01T08:59:39 | 200,014,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,362 | cpp | // Copyright (c) 2012, NetEase Inc. All rights reserved.
//
// wrt(guangguang)
// 2012/5/31
//
// utilities for path operation
#include "base/win32/path_util.h"
#if defined(OS_WIN)
#include <shlobj.h> // SHCreateDirectory
#include <shellapi.h> // SHFileOperation
#include "base/file/file_util.h"
//#include "base/log/log.h"
#include "base/win32/win_util.h"
namespace nbase
{
namespace win32
{
std::wstring GetModulePathName(HMODULE module_handle)
{
//DCHECK(IsModuleHandleValid(module_handle));
std::wstring mod_path;
mod_path.resize(MAX_PATH);
mod_path.resize(::GetModuleFileNameW(module_handle, &mod_path[0], (DWORD)mod_path.size()));
return mod_path;
}
std::wstring GetModuleDirectory(HMODULE module_handle)
{
//DCHECK(IsModuleHandleValid(module_handle));
std::wstring module_directory;
if (FilePathApartDirectory(GetModulePathName(module_handle), module_directory))
return module_directory;
return L"";
}
std::wstring GetModuleName(HMODULE module_handle)
{
//DCHECK(IsModuleHandleValid(module_handle));
std::wstring module_name;
if (FilePathApartFileName(GetModulePathName(module_handle), module_name))
return module_name;
return L"";
}
std::wstring GetCurrentModulePathName()
{
return GetModulePathName(GetCurrentModuleHandle());
}
std::wstring GetCurrentModuleDirectory()
{
return GetModuleDirectory(GetCurrentModuleHandle());
}
std::wstring GetCurrentModuleName()
{
return GetModuleName(GetCurrentModuleHandle());
}
std::wstring GetWindowsDir()
{
std::wstring windows_path;
windows_path.resize(MAX_PATH);
DWORD result = ::GetWindowsDirectory(&windows_path[0], MAX_PATH);
windows_path.resize(result);
return windows_path;
}
std::wstring GetSystemDir()
{
std::wstring system_path;
system_path.resize(MAX_PATH);
DWORD result = ::GetSystemDirectory(&system_path[0], MAX_PATH);
system_path.resize(result);
return system_path;
}
std::wstring GetTempDir()
{
std::wstring temp_path;
temp_path.resize(MAX_PATH);
DWORD result = ::GetTempPath(MAX_PATH, &temp_path[0]);
temp_path.resize(result);
return temp_path;
}
std::wstring GetLocalAppDataDir(HANDLE token /* = NULL */)
{
#if (NTDDI_VERSION < NTDDI_VISTA)
#ifndef KF_FLAG_CREATE
#define KF_FLAG_CREATE 0x00008000
#endif
#endif
std::wstring temp_path;
if (IsRunningOnVistaOrHigher())
{
typedef HRESULT (WINAPI *__SHGetKnownFolderPath)(REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*);
HMODULE moudle_handle = ::LoadLibraryW(L"shell32.dll");
if (moudle_handle != NULL)
{
__SHGetKnownFolderPath _SHGetKnownFolderPath =
reinterpret_cast<__SHGetKnownFolderPath>(::GetProcAddress(moudle_handle, "SHGetKnownFolderPath"));
if (_SHGetKnownFolderPath != NULL)
{
PWSTR result = NULL;
if (S_OK == _SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, token, &result))
{
temp_path = result;
::CoTaskMemFree(result);
}
}
::FreeLibrary(moudle_handle);
}
}
else
{
// On Windows XP, CSIDL_LOCAL_APPDATA represents "{user}\Local Settings\Application Data"
// while CSIDL_APPDATA represents "{user}\Application Data"
wchar_t buffer[MAX_PATH];
if (S_OK == ::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE, token, SHGFP_TYPE_CURRENT, buffer))
temp_path = buffer;
}
if (!temp_path.empty())
if (temp_path.back() != L'\\')
temp_path.push_back(L'\\');
return temp_path;
}
bool CreateDirectoryRecursively(const wchar_t *full_dir)
{
HRESULT result = ::SHCreateDirectory(NULL, full_dir);
if (result == ERROR_SUCCESS || result == ERROR_FILE_EXISTS || result == ERROR_ALREADY_EXISTS)
return true;
return false;
}
bool DeleteDirectoryRecursively(const wchar_t *full_dir)
{
DWORD attributes = ::GetFileAttributesW(full_dir);
if (attributes == INVALID_FILE_ATTRIBUTES) // not exists
return true;
if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) // not a file
return false;
SHFILEOPSTRUCTW file_op = {NULL,
FO_DELETE,
full_dir,
L"",
FOF_NOCONFIRMATION|FOF_NOERRORUI|FOF_SILENT,
FALSE,
0,
L""};
if (::SHFileOperation(&file_op) && !file_op.fAnyOperationsAborted)
return true;
return false;
}
} // namespace win32
} // namespace nbase
#endif // OS_WIN | [
"my-name@chromium.org"
] | my-name@chromium.org |
7af8a363b9de84c44e964fac8a04e1f3b81bbad6 | c879aa54fba94bea1d44d27b82f0bdf3e6c7df3e | /src/tree.h | 5650db3f476130a1407c1de35a86d83fe8ca6d96 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | pkurth/D3D12RendererOld | e211e0bb27a75982b1c79a42868f58a442a5aae5 | a35dca0ebd1b88417e5524aff0adfc96ee9df2a3 | refs/heads/master | 2022-04-18T09:07:13.680347 | 2020-03-14T16:10:30 | 2020-03-14T16:10:30 | 193,479,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | h | #pragma once
#include "buffer.h"
#include "root_signature.h"
#include "render_target.h"
#include "command_list.h"
#include "indirect_drawing.h"
struct tree_pipeline
{
void initialize(ComPtr<ID3D12Device2> device, dx_command_list* commandList, const dx_render_target& renderTarget, DXGI_FORMAT shadowMapFormat);
void render(dx_command_list* commandList,
D3D12_GPU_VIRTUAL_ADDRESS cameraCBAddress,
D3D12_GPU_VIRTUAL_ADDRESS sunCBAddress,
D3D12_GPU_VIRTUAL_ADDRESS spotLightCBAddress,
const indirect_descriptor_heap& descriptors);
void renderDepthOnly(dx_command_list* commandList, const render_camera& camera);
dx_mesh mesh;
std::vector<submesh_info> submeshes;
animation_skeleton skeleton;
ComPtr<ID3D12PipelineState> lightingPipelineState;
dx_root_signature lightingRootSignature;
ComPtr<ID3D12PipelineState> depthOnlyPipelineState;
dx_root_signature depthOnlyRootSignature;
};
| [
"philipp.kurth@fau.de"
] | philipp.kurth@fau.de |
a28a560ff307389dca21e7ffdc12b4bfcbacd6d8 | 812a6873a77606e783e77bd956b4bda51636828f | /screenn9000.cpp | f20d8f0fc95470641dc79822d9365e0b2fafab43 | [] | no_license | Madjita/GTS-Auto- | 0e714f076e26c678fb3e13a5d6da33704cb5422c | 7d5e77b78cc970cd451875524c48b559e56179aa | refs/heads/master | 2020-03-24T02:30:33.904039 | 2018-07-26T02:36:58 | 2018-07-26T02:36:58 | 142,378,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,808 | cpp | #include "screenn9000.h"
ScreenN9000::ScreenN9000()
{
this->moveToThread(new QThread());
connect(this->thread(),&QThread::started,this,&ScreenN9000::process_start);
this->thread()->start();
}
ScreenN9000::~ScreenN9000()
{
}
void ScreenN9000::process_start()
{
manager = new QNetworkAccessManager(this);
flagSizeLabel = false;
timer = new QTimer();
connect(timer,&QTimer::timeout,this,&ScreenN9000::getScreen);
connect(this,SIGNAL(timerStart()),timer,SLOT(start()));
connect(this,SIGNAL(timerStart(int)),timer,SLOT(start(int)));
connect(this,&ScreenN9000::timerStop,timer,&QTimer::stop);
pix = new QPixmap;
}
void ScreenN9000::replyFinished(QNetworkReply *reply)
{
if( reply->error() == QNetworkReply::NoError )
{
QByteArray dataHtml = reply->readAll();
pix->loadFromData(dataHtml);
emit imgN9000(pix);
}
else
{
// qDebug() << reply->errorString();
}
// Мы сами должны освободить память для reply
// Однако делать это через delete нельзя
reply->deleteLater();
}
void ScreenN9000::getScreen()
{
manager->get(QNetworkRequest(QUrl("http://"+n9000Ip+"/Agilent.SA.WebInstrument/Screen.png")));
}
void ScreenN9000::connectDevice(QString n9000 , QString gts)
{
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
emit timerStop();
n9000Ip = n9000;
emit timerStart(200);
}
void ScreenN9000::deviceDisconnect()
{
emit timerStop();
disconnect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
n9000Ip = "";
}
void ScreenN9000::imgN9000GetUpdate()
{
emit getScreen();
}
| [
"xok-s@yandex.ru"
] | xok-s@yandex.ru |
d3ddbb26af420b66e5de732936ecebf0b1be83e1 | aae875839120e4161623047e9950454bdef1c720 | /App5/App5/Generated Files/App.g.h | 840e3537a9b8355aa9da30a2f4f5d3886b661ab9 | [] | no_license | jle33/Directx11-Xaml-Project | 23f197a414473d6a9fbeb238abcd035a58b9b0e5 | 671239c94402fad16cf4a922d552faf8404c6c44 | refs/heads/master | 2021-01-10T09:50:32.378380 | 2015-10-01T20:44:48 | 2015-10-01T20:44:48 | 43,520,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | h | #pragma once
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
#include "XamlTypeInfo.g.h"
namespace App5
{
partial ref class App : public ::Windows::UI::Xaml::Application,
public ::Windows::UI::Xaml::Markup::IXamlMetadataProvider
{
public:
void InitializeComponent();
[Windows::Foundation::Metadata::DefaultOverload]
virtual ::Windows::UI::Xaml::Markup::IXamlType^ GetXamlType(::Windows::UI::Xaml::Interop::TypeName type);
virtual ::Windows::UI::Xaml::Markup::IXamlType^ GetXamlType(::Platform::String^ fullName);
virtual ::Platform::Array<::Windows::UI::Xaml::Markup::XmlnsDefinition>^ GetXmlnsDefinitions();
private:
::XamlTypeInfo::InfoProvider::XamlTypeInfoProvider^ _provider;
bool _contentLoaded;
};
}
| [
"jble33@gmail.com"
] | jble33@gmail.com |
d61b23e1161c594f9e4bbeefeb988a3d8ee7f2ae | 0add8e98654500d047d7a7f447245190ddae8b75 | /src/main.cpp | 2c2f6877bc530a51145d5d806b3d5381e99e2495 | [] | no_license | georges-chahine/dream-multi-matcher | 36c3a6ebf124d0082c85219cd4b87f06fa97163c | 8ad08a2ba0233a608ae0d889e773838da3dc2b2a | refs/heads/master | 2023-08-25T13:38:04.315994 | 2021-10-18T15:04:42 | 2021-10-18T15:04:42 | 322,437,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,000 | cpp | #include <rosbag/bag.h>
#include <stdlib.h>
#include <stdio.h>
#include "yaml-cpp/yaml.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <sys/types.h>
#include <time.h>
#include <sys/stat.h>
#include "IO/IO.h"
using namespace matcher;
using namespace Eigen;
template<typename M>
M load_csv (const std::string & path) {
std::ifstream indata;
indata.open(path);
std::string line;
std::vector<double> values;
uint rows = 0;
while (std::getline(indata, line)) {
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream, cell, ',')) {
values.push_back(std::stod(cell));
}
++rows;
}
return Map<const Matrix<typename M::Scalar, M::RowsAtCompileTime, M::ColsAtCompileTime, RowMajor>>(values.data(), rows, values.size()/rows);
}
void loopClosureFilter(std::vector<std::string> trajectories, std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> &XYZRGBL, std::vector<pcl::PointCloud<pcl::Normal>> &normals, Eigen::Matrix4d &prior){
double xIncrLc, yIncrLc;
MatrixXd newTrajectory = load_csv<MatrixXd>(trajectories[1]);
MatrixXd oldTrajectory = load_csv<MatrixXd>(trajectories[0]);
double xMaxNewTrajectory=newTrajectory(0,1);
double yMaxNewTrajectory=newTrajectory(0,2);
double xMaxOldTrajectory=oldTrajectory(0,1);
double yMaxOldTrajectory=oldTrajectory(0,2);
double xMinNewTrajectory=newTrajectory(0,1);
double yMinNewTrajectory=newTrajectory(0,2);
double xMinOldTrajectory=oldTrajectory(0,1);
double yMinOldTrajectory=oldTrajectory(0,2);
for (int j=1; j<newTrajectory.rows(); j++){
if (xMaxNewTrajectory<newTrajectory(j,1)){
xMaxNewTrajectory=newTrajectory(j,1);
}
if (yMaxNewTrajectory<newTrajectory(j,2)){
yMaxNewTrajectory=newTrajectory(j,2);
}
if (xMinNewTrajectory>newTrajectory(j,1)){
xMinNewTrajectory=newTrajectory(j,1);
}
if (yMinNewTrajectory>newTrajectory(j,2)){
yMinNewTrajectory=newTrajectory(j,2);
}
}
double oldXMean=oldTrajectory(0,1);
double oldYMean=oldTrajectory(0,2);
for (int j=1; j<oldTrajectory.rows(); j++){
if (xMaxOldTrajectory<oldTrajectory(j,1)){
xMaxOldTrajectory=oldTrajectory(j,1);
}
if (yMaxOldTrajectory<oldTrajectory(j,2)){
yMaxOldTrajectory=oldTrajectory(j,2);
}
if (xMinOldTrajectory>oldTrajectory(j,1)){
xMinOldTrajectory=oldTrajectory(j,1);
}
if (yMinOldTrajectory>oldTrajectory(j,2)){
yMinOldTrajectory=oldTrajectory(j,2);
}
oldXMean=oldTrajectory(j,1)+oldXMean;
oldYMean=oldTrajectory(j,2)+oldYMean;
}
oldXMean=oldXMean/oldTrajectory.rows()-oldTrajectory(0,1);
oldYMean=oldYMean/oldTrajectory.rows()-oldTrajectory(0,2);
float xIncr=oldXMean;
float yIncr=oldYMean;
xIncrLc=xIncr;yIncrLc=yIncr;
double xDiff=xMaxOldTrajectory-xMinOldTrajectory;
double yDiff=yMaxOldTrajectory-yMinOldTrajectory;
int trimTolerance=20;
unsigned int k=0;
pcl::PointCloud<pcl::PointXYZRGBL> pcTemp;
pcl::PointCloud<pcl::Normal> pcNrmlTmp;
std::cout<<"start here"<<std::endl;
while (true){ //lc
if (k>=XYZRGBL[0].points.size()){break;}
double x=XYZRGBL[0].points[k].x+oldTrajectory(0,1); double y=XYZRGBL[0].points[k].y+oldTrajectory(0,2);
if (xDiff>yDiff){
if ( (x+trimTolerance) <xMinOldTrajectory || (x+trimTolerance) <xMinNewTrajectory || (x-trimTolerance) > xMaxNewTrajectory || (x-trimTolerance) > xMaxOldTrajectory)
{
// std::cout<<"filtered!"<<std::endl;
// XYZRGBL[0].points.erase(XYZRGBL[0].points.begin() + k );
// normals[0].erase(normals[0].begin() + k );
}
else
{
pcl::PointXYZRGBL tmpPt= XYZRGBL[0].points[k];
pcl::Normal tmpNrml=normals[0][k];
pcTemp.push_back(tmpPt);
pcNrmlTmp.push_back(tmpNrml);
}
}
else
{
if ( (y+trimTolerance) <yMinOldTrajectory || (y+trimTolerance) <yMinNewTrajectory || (y-trimTolerance) > yMaxNewTrajectory || (y-trimTolerance) > yMaxOldTrajectory )
{
// std::cout<<"filtered!"<<std::endl;
// XYZRGBL[0].points.erase(XYZRGBL[0].points.begin() + k );
// normals[0].erase(normals[0].begin() + k );
}
else
{
pcl::PointXYZRGBL tmpPt= XYZRGBL[0].points[k];
pcl::Normal tmpNrml=normals[0][k];
pcTemp.push_back(tmpPt);
pcNrmlTmp.push_back(tmpNrml);
}
}
k++;
}
XYZRGBL[0]=pcTemp;
normals[0]=pcNrmlTmp;
pcl::PointCloud<pcl::PointXYZRGBL> pcTemp1;
pcl::PointCloud<pcl::Normal> pcNrmlTmp1;
std::cout<<"end here"<<std::endl;
k=0;
while (true){ //lc
if (k>=XYZRGBL[1].points.size()){break;}
double x=XYZRGBL[1].points[k].x+newTrajectory(0,1); double y=XYZRGBL[1].points[k].y+newTrajectory(0,2);
if (xDiff>yDiff){
if ( (x+trimTolerance) <xMinOldTrajectory || (x+trimTolerance) <xMinNewTrajectory || (x-trimTolerance) > xMaxNewTrajectory || (x-trimTolerance) > xMaxOldTrajectory)
{
// std::cout<<"filtered!"<<std::endl;
// XYZRGBL[0].points.erase(XYZRGBL[0].points.begin() + k );
// normals[0].erase(normals[0].begin() + k );
}
else
{
pcl::PointXYZRGBL tmpPt1= XYZRGBL[1].points[k];
pcl::Normal tmpNrml1=normals[1][k];
pcTemp1.push_back(tmpPt1);
pcNrmlTmp1.push_back(tmpNrml1);
}
}
else
{
if ( (y+trimTolerance) <yMinOldTrajectory || (y+trimTolerance) <yMinNewTrajectory || (y-trimTolerance) > yMaxNewTrajectory || (y-trimTolerance) > yMaxOldTrajectory )
{
// std::cout<<"filtered!"<<std::endl;
// XYZRGBL[0].points.erase(XYZRGBL[0].points.begin() + k );
// normals[0].erase(normals[0].begin() + k );
}
else
{
pcl::PointXYZRGBL tmpPt1= XYZRGBL[1].points[k];
pcl::Normal tmpNrml1=normals[1][k];
pcTemp1.push_back(tmpPt1);
pcNrmlTmp1.push_back(tmpNrml1);
}
}
k++;
}
XYZRGBL[1]=pcTemp1;
normals[1]=pcNrmlTmp1;
prior(0,3)=xIncrLc;prior(1,3)=yIncrLc;
}
void loadCloud(std::string pcdPath, std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> &XYZRGBL, std::vector<pcl::PointCloud<pcl::Normal>> &normals, double leafSize){
pcl::PointCloud<pcl::PointXYZRGBL>::Ptr pc2 (new pcl::PointCloud<pcl::PointXYZRGBL>);
if (pcl::io::loadPCDFile<pcl::PointXYZRGBL> (pcdPath, *pc2) == -1) //* load the file
{
PCL_ERROR ("Couldn't read file test_pcd.pcd \n");
//return (-1);
}
std::cout << "Loaded "
<< pc2->width * pc2->height
<< " data points from "<<pcdPath<< std::endl;
std::vector<int> indices;
// pcl::removeNaNFromPointCloud(*pc2, *pc2, indices);
pcl::VoxelGrid<pcl::PointXYZRGBL> sor;
sor.setInputCloud (pc2);
sor.setMinimumPointsNumberPerVoxel(2);
sor.setLeafSize (leafSize, leafSize, leafSize);
sor.filter (*pc2);
pcl::StatisticalOutlierRemoval<pcl::PointXYZRGBL> sor2;
sor2.setInputCloud (pc2);
sor2.setMeanK (5);
sor2.setStddevMulThresh (1.0);
sor2.filter (*pc2);
// std::vector<int> indices;
pcl::removeNaNFromPointCloud(*pc2, *pc2, indices);
pcl::NormalEstimationOMP<pcl::PointXYZRGBL, pcl::Normal> ne;
ne.setInputCloud (pc2);
pcl::search::KdTree<pcl::PointXYZRGBL>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGBL> ());
ne.setSearchMethod (tree);
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (0.2);
ne.compute (*cloud_normals);
normals.push_back(*cloud_normals);
XYZRGBL.push_back(*pc2);
pc2=NULL;
}
int main()
{
int dir;
YAML::Node config = YAML::LoadFile("../config.yaml");
std::string pathOut = config["pathOut"].as<std::string>();
std::string rMethod = config["mapRegistration"].as<std::string>();
std::string loopCloseKF = config["loopCloseKF"].as<std::string>();
std::string autoNameTemplate = config["autoNameTemplate"].as<std::string>();
std::string leafSize0 = config["voxelSize"].as<std::string>();
float leafSize=std::stod(leafSize0);
std::string icpConfigFilePath = config["icpConfig"].as<std::string>();
std::string icpConfigFilePathLoopClosure = config["icpConfigLoopClosure"].as<std::string>();
std::string inputFiltersConfigFilePath = config["icpInputFilters"].as<std::string>();
std::string mapPostFiltersConfigFilePath = config["icpPostFilters"].as<std::string>();
std::string rtkTopic="";
std::vector<std::string> sourceClouds = config["sourceClouds"].as<std::vector<std::string>>();
std::vector<std::string> sourceTrajectories = config["sourceTrajectories"].as<std::vector<std::string>>();
std::vector<std::string> autoMatchDir = config["autoMatchDir"].as<std::vector<std::string>>();
std::string autoMatchStr = config["autoMatch"].as<std::string>();
bool autoMatch=false;
Eigen::Matrix4d prior=Eigen::Matrix4d::Identity();
bool spatialAlignment=false;
if (autoMatchStr=="True" || autoMatchStr=="true")
{
autoMatch=true;
}
std::string loopCloseStr = config["autoLoopClose"].as<std::string>();
bool loopClose=false;
if (loopCloseStr=="True" || loopCloseStr=="true")
{
loopClose=true;
}
int mapNumber=sourceClouds.size();
int dirNumber=autoMatchDir.size();
std::vector<std::vector<std::string>> pcdFiles;
std::vector<std::vector<std::string>> csvFiles;
std::vector<std::vector<std::vector<unsigned int>>> matchIdx;
if (autoMatch){
for (int i=0; i<dirNumber; i++ )
{
int j=0;
std::vector<std::string> pcdFile;
std::vector<std::string> csvFile;
// if (loopClose){
// pcdFile.push_back(strPcdNameLc);
// csvFile.push_back(strCsvNameLc);
// }
while(true){
std::string strPcdName=autoMatchDir[i]+"/"+autoNameTemplate+std::to_string(j)+".pcd";
std::string strCsvName=autoMatchDir[i]+"/"+autoNameTemplate+std::to_string(j)+".csv";
std::ifstream fCsv(strCsvName.c_str());
std::ifstream fPcd(strPcdName.c_str());
if (!fPcd.good()||!fCsv.good())
{
/* if (loopClose){
// pcdFile.push_back(strPcdNameLc);
// csvFile.push_back(strCsvNameLc);
pcdFile.insert(pcdFile.begin() ,pcdFile.back() );
csvFile.insert(csvFile.begin() ,csvFile.back() );
}
*/
break;
}
// std::cout<<"string is \n"<<strPcdName<<std::endl;
pcdFile.push_back(strPcdName);
csvFile.push_back(strCsvName);
j++;
}
pcdFiles.push_back(pcdFile);
csvFiles.push_back(csvFile);
}
for (unsigned int i=0; i<(dirNumber-1); i++ ){
unsigned int tempIdx=i;
std::vector<std::vector<unsigned int>> matchIdx0;
while (true){
if (tempIdx+1>=dirNumber) break;
matchIdx0.push_back({i, tempIdx+1});
std::cout<<i<<","<<tempIdx+1<<std::endl;
tempIdx++;
}
matchIdx.push_back(matchIdx0);
}
}
/* std::string autoVerifyStr = config["autoVerify"].as<std::string>();
bool autoVerify=false;
if (autoVerifyStr=="True" || autoVerifyStr=="true")
{
autoVerify=true;
}
*/
std::string computeProbDynamicstr = config["icpComputeProbDynamic"].as<std::string>();
bool computeProbDynamic=false;
if (computeProbDynamicstr=="True" || computeProbDynamicstr=="true")
{
computeProbDynamic=true;
}
bool semantics=false;
std::string semanticsstr = config["semantics"].as<std::string>();
if (semanticsstr=="True" || semanticsstr=="true")
{
semantics=true;
}
//std::cout<<sourceBags.size()<<std::endl;
std::cout<<"Loading point clouds, voxelizing and satistical outlier filter..."<<std::endl;
if (autoMatch){
// std::vector<std::vector<pcl::PointCloud<pcl::PointXYZRGBL>>> XYZRGBLvec;
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> prevXYZRGBL;
std::vector<std::string> prevTrajectories;
std::vector<pcl::PointCloud<pcl::Normal>> prevNormals;
for (int k=0; k<pcdFiles[0].size();k++){
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> XYZRGBL;
std::vector<std::string> newTrajectories;
std::vector<pcl::PointCloud<pcl::Normal>> normals;
for (int ii=0; ii<pcdFiles.size(); ii++)
{
newTrajectories.push_back(csvFiles[ii][k]);
loadCloud(pcdFiles[ii][k],XYZRGBL,normals, leafSize) ;
}
//----------------------------------------------------temporal matching---------------------------------------------------------------------------//
spatialAlignment=false;
for (int i=0; i<matchIdx.size(); i++)
{
std::vector<std::vector<int>> matchLogIdx; // keyframe time period; keyframe timeperiod
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> XYZRGBL1;
std::vector<std::string> newTrajectories1;
std::vector<pcl::PointCloud<pcl::Normal>> normals1;
unsigned int k0=matchIdx[i][0][0];
XYZRGBL1.push_back(XYZRGBL[k0]);
normals1.push_back(normals[k0]);
newTrajectories1.push_back(newTrajectories[k0]);
matchLogIdx.push_back({k, i});
for (unsigned int j=0; j<matchIdx[i].size(); j++)
{
int k1=matchIdx[i][j][1];
matchLogIdx.push_back({k, k1});
XYZRGBL1.push_back(XYZRGBL[k1]);
newTrajectories1.push_back(newTrajectories[k1]);
normals1.push_back(normals[k1]);
}
std::string currentPath="";
//std::cout<<i<<std::endl;
int mapCounter=0;
//std::cout<<pathOut<<std::endl;
// std::ostringstream ss; ss<<(i);
currentPath=pathOut;
std::cout<<"matching in progress"<<std::endl;
dir=mkdir (currentPath.c_str(),S_IRWXU);
IO* Io =new IO();
Io ->readClouds(XYZRGBL1, normals1, newTrajectories1, matchLogIdx, spatialAlignment,autoMatch, currentPath, rMethod, mapCounter, semantics, leafSize, icpConfigFilePath, inputFiltersConfigFilePath, mapPostFiltersConfigFilePath, computeProbDynamic, false, prior);
delete Io;
}
//----------------------------------------------------spatial matching---------------------------------------------------------------------------//
int mapCounter=0;
if (k>0){
spatialAlignment=true;
for (unsigned int j=0; j<pcdFiles.size(); j++)
{
std::vector<std::vector<int>> matchLogIdx; // keyframe time period; keyframe timeperiod
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> XYZRGBL1;
std::vector<std::string> newTrajectories1;
std::vector<pcl::PointCloud<pcl::Normal>> normals1;
matchLogIdx.push_back({k-1, j});
matchLogIdx.push_back({k, j});
XYZRGBL1.push_back(prevXYZRGBL[j]);
newTrajectories1.push_back(prevTrajectories[j]);
normals1.push_back(prevNormals[j]);
XYZRGBL1.push_back(XYZRGBL[j]);
newTrajectories1.push_back(newTrajectories[j]);
normals1.push_back(normals[j]);
std::string currentPath="";
//std::cout<<i<<std::endl;
//std::cout<<pathOut<<std::endl;
// std::ostringstream ss; ss<<(i);
currentPath=pathOut;
//std::cout<<currentPath<<std::endl;
dir=mkdir (currentPath.c_str(),S_IRWXU);
IO* Io =new IO();
Io ->readClouds(XYZRGBL1, normals1, newTrajectories1, matchLogIdx, spatialAlignment,autoMatch, currentPath, rMethod, mapCounter, semantics, leafSize, icpConfigFilePath, inputFiltersConfigFilePath, mapPostFiltersConfigFilePath, computeProbDynamic,false, prior);
mapCounter++;
delete Io;
}
}
prevXYZRGBL=XYZRGBL;
prevTrajectories=newTrajectories;
prevNormals=normals;
}
/* ////////////////////LOOP CLOSURE////////////////////////////////////////////////////////////////////////////////////////////////////////// */
if (loopClose){
for (int i=0; i<dirNumber; i++ ) //alignment of loop closure KF with keyframe 0
{
int mapCounter=0;
std::string strPcdNameLc;
std::string strCsvNameLc;
strPcdNameLc=autoMatchDir[i]+"/"+loopCloseKF+".pcd";
strCsvNameLc=autoMatchDir[i]+"/"+loopCloseKF+".csv";
std::ifstream fCsv(strCsvNameLc.c_str());
std::ifstream fPcd(strPcdNameLc.c_str());
if (!fPcd.good()||!fCsv.good())
{
continue;
}
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> XYZRGBL;
std::vector<std::string> trajectories;
std::vector<pcl::PointCloud<pcl::Normal>> normals;
loadCloud(strPcdNameLc,XYZRGBL, normals, leafSize);
loadCloud(pcdFiles[i][0],XYZRGBL, normals, leafSize);
trajectories.push_back(strCsvNameLc);
trajectories.push_back(csvFiles[i][0]);
loopClosureFilter(trajectories, XYZRGBL, normals, prior);
std::vector<std::vector<int>> matchLogIdx; // keyframe time period; keyframe timeperiod
matchLogIdx.push_back({-1, i});
matchLogIdx.push_back({0, i});
std::string currentPath=pathOut;
dir=mkdir (currentPath.c_str(),S_IRWXU);
IO* Io =new IO();
Io ->readClouds(XYZRGBL, normals, trajectories, matchLogIdx, spatialAlignment,autoMatch, currentPath, rMethod, mapCounter, semantics, leafSize, icpConfigFilePathLoopClosure, inputFiltersConfigFilePath, mapPostFiltersConfigFilePath, computeProbDynamic,true, prior);
mapCounter++;
delete Io;
prior=Eigen::Matrix4d::Identity();
}
for (unsigned int i=0; i<dirNumber; i++ ) //alignment of loop closure KF with keyframe x at the end
{
bool success=false;
int mapCounter=0;
std::string strPcdNameLc;
std::string strCsvNameLc;
strPcdNameLc=autoMatchDir[i]+"/"+loopCloseKF+".pcd";
strCsvNameLc=autoMatchDir[i]+"/"+loopCloseKF+".csv";
std::ifstream fCsv(strCsvNameLc.c_str());
std::ifstream fPcd(strPcdNameLc.c_str());
unsigned int x;
double xClose, yClose, zClose, xClose0, yClose0, zClose0;
if (!fPcd.good()||!fCsv.good())
{
continue;
}
MatrixXd oldTrajectory = load_csv<MatrixXd>(strCsvNameLc);
double refTime=oldTrajectory(0,0);
for (unsigned int j=0; j<csvFiles[i].size(); j++){
MatrixXd newTrajectory = load_csv<MatrixXd>(csvFiles[i][j]);
for (unsigned int k=0; k<newTrajectory.rows();k++){
if (newTrajectory(k,0)==refTime){
x=j;
xClose=newTrajectory(k,1);
yClose=newTrajectory(k,2);
zClose=newTrajectory(k,3);
xClose0=newTrajectory(0,1);
yClose0=newTrajectory(0,2);
zClose0=newTrajectory(0,3);
success=true;
}
}
}
if (!success){
std::cout<<"couldn't find match for loop closure keyframe"<<std::endl;
continue;
}
prior(0,3)= -(xClose-xClose0);
prior(1,3)= -(yClose-yClose0);
prior(2,3)= -(zClose-zClose0);
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> XYZRGBL;
std::vector<std::string> trajectories;
std::vector<pcl::PointCloud<pcl::Normal>> normals;
loadCloud(strPcdNameLc,XYZRGBL, normals, leafSize);
loadCloud(pcdFiles[i][x],XYZRGBL, normals, leafSize);
trajectories.push_back(strCsvNameLc);
trajectories.push_back(csvFiles[i][x]);
std::vector<std::vector<int>> matchLogIdx; // keyframe time period; keyframe timeperiod
matchLogIdx.push_back({-1, i});
matchLogIdx.push_back({x, i});
std::string currentPath=pathOut;
dir=mkdir (currentPath.c_str(),S_IRWXU);
IO* Io =new IO();
Io ->readClouds(XYZRGBL, normals, trajectories, matchLogIdx, spatialAlignment,autoMatch, currentPath, rMethod, mapCounter, semantics, leafSize, icpConfigFilePathLoopClosure, inputFiltersConfigFilePath, mapPostFiltersConfigFilePath, computeProbDynamic,false, prior);
mapCounter++;
delete Io;
prior=Eigen::Matrix4d::Identity();
}
}
}
else {
std::vector<pcl::PointCloud<pcl::PointXYZRGBL>> XYZRGBL;
std::vector<pcl::PointCloud<pcl::Normal>> normals;
for (int i=0; i<mapNumber; i++)
{
loadCloud(sourceClouds[i],XYZRGBL,normals, leafSize) ;
}
std::string currentPath="";
//std::cout<<i<<std::endl;
int mapCounter=0;
//std::cout<<pathOut<<std::endl;
// std::ostringstream ss; ss<<(i);
currentPath=pathOut;
//std::cout<<currentPath<<std::endl;
dir=mkdir (currentPath.c_str(),S_IRWXU);
IO* Io =new IO();
std::vector<std::vector<int>> matchLogIdx;
Io ->readClouds(XYZRGBL, normals, sourceTrajectories, matchLogIdx, spatialAlignment, autoMatch, currentPath, rMethod, mapCounter, semantics, leafSize, icpConfigFilePath, inputFiltersConfigFilePath, mapPostFiltersConfigFilePath, computeProbDynamic, false, prior);
delete Io;
}
}
| [
"chahine.georges@gmail.com"
] | chahine.georges@gmail.com |
c3f0980f9fe087f6843367aca436e900b969ba06 | 6e782035b4d77099c590acc3e0e6c3b1444d62ed | /MyRainmeter/PropertiesWnd.cpp | a743f2239e4255837c50c9a18e34a6f741ac814e | [] | no_license | dream4java/MyRainmeterCPP | 2a091a22481353889c47d52e0e4edbeaef10acd7 | 3f2edf0e4a937b1a4abc15310ec945d337f15655 | refs/heads/master | 2020-04-27T23:25:20.939008 | 2013-03-14T05:49:43 | 2013-03-14T05:49:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,702 | cpp |
#include "stdafx.h"
#include "PropertiesWnd.h"
#include "Resource.h"
#include "MainFrm.h"
#include "MyRainmeter.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
// CResourceViewBar
CPropertiesWnd::CPropertiesWnd()
{
}
CPropertiesWnd::~CPropertiesWnd()
{
}
BEGIN_MESSAGE_MAP(CPropertiesWnd, CDockablePane)
ON_WM_CREATE()
ON_WM_SIZE()
ON_COMMAND(ID_EXPAND_ALL, OnExpandAllProperties)
ON_UPDATE_COMMAND_UI(ID_EXPAND_ALL, OnUpdateExpandAllProperties)
ON_COMMAND(ID_SORTPROPERTIES, OnSortProperties)
ON_UPDATE_COMMAND_UI(ID_SORTPROPERTIES, OnUpdateSortProperties)
ON_COMMAND(ID_PROPERTIES1, OnProperties1)
ON_UPDATE_COMMAND_UI(ID_PROPERTIES1, OnUpdateProperties1)
ON_COMMAND(ID_PROPERTIES2, OnProperties2)
ON_UPDATE_COMMAND_UI(ID_PROPERTIES2, OnUpdateProperties2)
ON_WM_SETFOCUS()
ON_WM_SETTINGCHANGE()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CResourceViewBar 消息处理程序
void CPropertiesWnd::AdjustLayout()
{
if (GetSafeHwnd() == NULL)
{
return;
}
CRect rectClient,rectCombo;
GetClientRect(rectClient);
m_wndObjectCombo.GetWindowRect(&rectCombo);
int cyCmb = rectCombo.Size().cy;
int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy;
m_wndObjectCombo.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), 200, SWP_NOACTIVATE | SWP_NOZORDER);
m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER);
m_wndPropList.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb + cyTlb, rectClient.Width(), rectClient.Height() -(cyCmb+cyTlb), SWP_NOACTIVATE | SWP_NOZORDER);
}
int CPropertiesWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rectDummy;
rectDummy.SetRectEmpty();
// 创建组合:
const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | WS_BORDER | CBS_SORT | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
if (!m_wndObjectCombo.Create(dwViewStyle, rectDummy, this, 1))
{
TRACE0("未能创建属性组合 \n");
return -1; // 未能创建
}
m_wndObjectCombo.AddString(_T("应用程序"));
m_wndObjectCombo.AddString(_T("属性窗口"));
m_wndObjectCombo.SetCurSel(0);
if (!m_wndPropList.Create(WS_VISIBLE | WS_CHILD, rectDummy, this, 2))
{
TRACE0("未能创建属性网格\n");
return -1; // 未能创建
}
InitPropList();
m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_PROPERTIES);
m_wndToolBar.LoadToolBar(IDR_PROPERTIES, 0, 0, TRUE /* 已锁定*/);
m_wndToolBar.CleanUpLockedImages();
m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_PROPERTIES_HC : IDR_PROPERTIES, 0, 0, TRUE /* 锁定*/);
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY);
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT));
m_wndToolBar.SetOwner(this);
// 所有命令将通过此控件路由,而不是通过主框架路由:
m_wndToolBar.SetRouteCommandsViaFrame(FALSE);
AdjustLayout();
return 0;
}
void CPropertiesWnd::OnSize(UINT nType, int cx, int cy)
{
CDockablePane::OnSize(nType, cx, cy);
AdjustLayout();
}
void CPropertiesWnd::OnExpandAllProperties()
{
m_wndPropList.ExpandAll();
}
void CPropertiesWnd::OnUpdateExpandAllProperties(CCmdUI* /* pCmdUI */)
{
}
void CPropertiesWnd::OnSortProperties()
{
m_wndPropList.SetAlphabeticMode(!m_wndPropList.IsAlphabeticMode());
}
void CPropertiesWnd::OnUpdateSortProperties(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_wndPropList.IsAlphabeticMode());
}
void CPropertiesWnd::OnProperties1()
{
// TODO: 在此处添加命令处理程序代码
}
void CPropertiesWnd::OnUpdateProperties1(CCmdUI* /*pCmdUI*/)
{
// TODO: 在此处添加命令更新 UI 处理程序代码
}
void CPropertiesWnd::OnProperties2()
{
// TODO: 在此处添加命令处理程序代码
}
void CPropertiesWnd::OnUpdateProperties2(CCmdUI* /*pCmdUI*/)
{
// TODO: 在此处添加命令更新 UI 处理程序代码
}
void CPropertiesWnd::InitPropList()
{
SetPropListFont();
m_wndPropList.EnableHeaderCtrl(FALSE);
m_wndPropList.EnableDescriptionArea();
m_wndPropList.SetVSDotNetLook();
m_wndPropList.MarkModifiedProperties();
CMFCPropertyGridProperty* pGroup1 = new CMFCPropertyGridProperty(_T("外观"));
pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("三维外观"), (_variant_t) false, _T("指定窗口的字体不使用粗体,并且控件将使用三维边框")));
CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("边框"), _T("对话框外框"), _T("其中之一:“无”、“细”、“可调整大小”或“对话框外框”"));
pProp->AddOption(_T("无"));
pProp->AddOption(_T("细"));
pProp->AddOption(_T("可调整大小"));
pProp->AddOption(_T("对话框外框"));
pProp->AllowEdit(FALSE);
pGroup1->AddSubItem(pProp);
pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("标题"), (_variant_t) _T("关于"), _T("指定窗口标题栏中显示的文本")));
m_wndPropList.AddProperty(pGroup1);
CMFCPropertyGridProperty* pSize = new CMFCPropertyGridProperty(_T("窗口大小"), 0, TRUE);
pProp = new CMFCPropertyGridProperty(_T("高度"), (_variant_t) 250l, _T("指定窗口的高度"));
pProp->EnableSpinControl(TRUE, 50, 300);
pSize->AddSubItem(pProp);
pProp = new CMFCPropertyGridProperty( _T("宽度"), (_variant_t) 150l, _T("指定窗口的宽度"));
pProp->EnableSpinControl(TRUE, 50, 200);
pSize->AddSubItem(pProp);
m_wndPropList.AddProperty(pSize);
CMFCPropertyGridProperty* pGroup2 = new CMFCPropertyGridProperty(_T("字体"));
LOGFONT lf;
CFont* font = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
font->GetLogFont(&lf);
lstrcpy(lf.lfFaceName, _T("宋体, Arial"));
pGroup2->AddSubItem(new CMFCPropertyGridFontProperty(_T("字体"), lf, CF_EFFECTS | CF_SCREENFONTS, _T("指定窗口的默认字体")));
pGroup2->AddSubItem(new CMFCPropertyGridProperty(_T("使用系统字体"), (_variant_t) true, _T("指定窗口使用“MS Shell Dlg”字体")));
m_wndPropList.AddProperty(pGroup2);
CMFCPropertyGridProperty* pGroup3 = new CMFCPropertyGridProperty(_T("杂项"));
pProp = new CMFCPropertyGridProperty(_T("(名称)"), _T("应用程序"));
pProp->Enable(FALSE);
pGroup3->AddSubItem(pProp);
CMFCPropertyGridColorProperty* pColorProp = new CMFCPropertyGridColorProperty(_T("窗口颜色"), RGB(210, 192, 254), NULL, _T("指定默认的窗口颜色"));
pColorProp->EnableOtherButton(_T("其他..."));
pColorProp->EnableAutomaticButton(_T("默认"), ::GetSysColor(COLOR_3DFACE));
pGroup3->AddSubItem(pColorProp);
static const TCHAR szFilter[] = _T("图标文件(*.ico)|*.ico|所有文件(*.*)|*.*||");
pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("图标"), TRUE, _T(""), _T("ico"), 0, szFilter, _T("指定窗口图标")));
pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("文件夹"), _T("c:\\")));
m_wndPropList.AddProperty(pGroup3);
CMFCPropertyGridProperty* pGroup4 = new CMFCPropertyGridProperty(_T("层次结构"));
CMFCPropertyGridProperty* pGroup41 = new CMFCPropertyGridProperty(_T("第一个子级"));
pGroup4->AddSubItem(pGroup41);
CMFCPropertyGridProperty* pGroup411 = new CMFCPropertyGridProperty(_T("第二个子级"));
pGroup41->AddSubItem(pGroup411);
pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("项 1"), (_variant_t) _T("值 1"), _T("此为说明")));
pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("项 2"), (_variant_t) _T("值 2"), _T("此为说明")));
pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("项 3"), (_variant_t) _T("值 3"), _T("此为说明")));
pGroup4->Expand(FALSE);
m_wndPropList.AddProperty(pGroup4);
}
void CPropertiesWnd::OnSetFocus(CWnd* pOldWnd)
{
CDockablePane::OnSetFocus(pOldWnd);
m_wndPropList.SetFocus();
}
void CPropertiesWnd::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
CDockablePane::OnSettingChange(uFlags, lpszSection);
SetPropListFont();
}
void CPropertiesWnd::SetPropListFont()
{
::DeleteObject(m_fntPropList.Detach());
LOGFONT lf;
afxGlobalData.fontRegular.GetLogFont(&lf);
NONCLIENTMETRICS info;
info.cbSize = sizeof(info);
afxGlobalData.GetNonClientMetrics(info);
lf.lfHeight = info.lfMenuFont.lfHeight;
lf.lfWeight = info.lfMenuFont.lfWeight;
lf.lfItalic = info.lfMenuFont.lfItalic;
m_fntPropList.CreateFontIndirect(&lf);
m_wndPropList.SetFont(&m_fntPropList);
m_wndObjectCombo.SetFont(&m_fntPropList);
}
| [
"lofei117@gmail.com"
] | lofei117@gmail.com |
4ff6aac9d5f41c7292f97f49d7702c1d0d39d89e | 32c10943c14b5e92bcd1d3f421e1539cf799725a | /XRays/LuaGUIInterface.h | 431b5861937a1b5202e4ed3873704aef746f7063 | [] | no_license | supercuglong/XRays | d25245bc6963ed34ba540433d3b165ad72737ef2 | c8b61dcb4cdb8d7156f065a3da9af6a2c9f9e4da | refs/heads/main | 2023-07-17T19:52:11.826768 | 2021-09-06T18:19:43 | 2021-09-06T18:19:43 | 403,798,898 | 2 | 4 | null | 2021-09-07T01:05:22 | 2021-09-07T01:05:20 | null | UTF-8 | C++ | false | false | 7,824 | h | #pragma once
#include <iostream>
#include <string>
#include <vector>
#include "Input.h"
#include "Utils.h"
#include "imgui.h"
/// Interface used by LUA scripts for creating UIs with imgui.
class LuaGUIInterface {
public:
void Begin(const char *name) { ImGui::Begin(name); }
void End() { ImGui::End(); }
bool Button(const char *text) { return ImGui::Button(text); }
bool ColorButton(const char *text, ImVec4 color) {
return ImGui::ColorButton(text, color);
}
bool Checkbox(const char *text, bool enabled) {
ImGui::Checkbox(text, &enabled);
return enabled;
}
void Text(const char *text) { ImGui::Text(text); }
void TextColored(const char *text, ImVec4 color) {
ImGui::TextColored(color, text);
}
void LabelText(const char *label, const char *text) {
ImGui::LabelText(label, text);
}
void LabelTextColored(const char *label, const char *text, ImVec4 color) {
ImGui::PushStyleColor(ImGuiCol_Text, color);
ImGui::LabelText(label, text);
ImGui::PopStyleColor();
}
ImVec4 ColorPicker(const char *label, ImVec4 color) {
ImGui::ColorPicker4(label, (float *)&color);
return color;
}
int DragInt5(const char *text, int i, int step = 1, int minVal = 0,
int maxVal = 0) {
ImGui::DragInt(text, &i, (float)step, minVal, maxVal);
return i;
}
int DragInt2(const char *text, int i) {
ImGui::DragInt(text, &i, 1.0, 0, 0);
return i;
}
//(float (LuaImguiInterface::*)(const char*, float)
float DragFloat2(const char *text, float i) {
ImGui::DragFloat(text, &i, 1, 0, 0);
return i;
}
float DragFloat5(const char *text, float i, float step = 1, float minVal = 0,
float maxVal = 0) {
ImGui::DragFloat(text, &i, step, minVal, maxVal);
return i;
}
float SliderFloat(const char *label, float val, float valMin, float valMax) {
ImGui::SliderFloat(label, &val, valMin, valMax);
return val;
}
float SliderInt(const char *label, int val, int valMin, int valMax) {
ImGui::SliderInt(label, &val, valMin, valMax);
return val;
}
void Separator() { ImGui::Separator(); }
bool CollapsingHeader(const char *text) {
return ImGui::CollapsingHeader(text);
}
bool TreeNode(const char *text) { return ImGui::TreeNode(text); }
void SetNextItemOpen() { ImGui::SetNextItemOpen(true, ImGuiCond_Once); }
void TreePop() { ImGui::TreePop(); }
void SameLine() { ImGui::SameLine(); }
void BeginGroup() { ImGui::BeginGroup(); }
void EndGroup() { ImGui::EndGroup(); }
int ListBox(const char *label, std::vector<std::string> items, int chosen) {
static std::vector<const char *> buffer;
buffer.clear();
for (auto &item : items)
buffer.push_back(item.c_str());
ImGui::ListBox(label, &chosen, buffer.data(), items.size(), items.size());
return chosen;
}
// Key selector stuff
void DrawButton(HKey key, HKey &clickedBtn, bool &wasClicked) {
if (ImGui::Button(HKeyNames[key])) {
clickedBtn = key;
wasClicked = true;
}
ImGui::SameLine();
}
int KeySelect(const char *label, int key) {
static int callNum = 0;
ImGui::PushID(label);
ImGui::BeginGroup();
if (ImGui::Button(HKeyNames[key])) {
ImGui::OpenPopup("Keys");
}
ImGui::SameLine();
ImGui::Text(label);
ImGui::EndGroup();
if (ImGui::BeginPopup("Keys")) {
HKey clickedBtn = HKey::NO_KEY;
bool wasClicked = false;
ImGui::BeginGroup();
DrawButton(HKey::ESC, clickedBtn, wasClicked);
DrawButton(HKey::F1, clickedBtn, wasClicked);
DrawButton(HKey::F2, clickedBtn, wasClicked);
DrawButton(HKey::F3, clickedBtn, wasClicked);
DrawButton(HKey::F4, clickedBtn, wasClicked);
DrawButton(HKey::F6, clickedBtn, wasClicked);
DrawButton(HKey::F6, clickedBtn, wasClicked);
DrawButton(HKey::F7, clickedBtn, wasClicked);
DrawButton(HKey::F8, clickedBtn, wasClicked);
DrawButton(HKey::F9, clickedBtn, wasClicked);
DrawButton(HKey::F10, clickedBtn, wasClicked);
ImGui::EndGroup();
ImGui::BeginGroup();
DrawButton(HKey::TILDE, clickedBtn, wasClicked);
DrawButton(HKey::N_1, clickedBtn, wasClicked);
DrawButton(HKey::N_2, clickedBtn, wasClicked);
DrawButton(HKey::N_3, clickedBtn, wasClicked);
DrawButton(HKey::N_4, clickedBtn, wasClicked);
DrawButton(HKey::N_5, clickedBtn, wasClicked);
DrawButton(HKey::N_6, clickedBtn, wasClicked);
DrawButton(HKey::N_7, clickedBtn, wasClicked);
DrawButton(HKey::N_8, clickedBtn, wasClicked);
DrawButton(HKey::N_9, clickedBtn, wasClicked);
DrawButton(HKey::N_0, clickedBtn, wasClicked);
DrawButton(HKey::MINUS, clickedBtn, wasClicked);
DrawButton(HKey::EQUAL, clickedBtn, wasClicked);
DrawButton(HKey::BS, clickedBtn, wasClicked);
ImGui::EndGroup();
ImGui::BeginGroup();
DrawButton(HKey::Tab, clickedBtn, wasClicked);
DrawButton(HKey::Q, clickedBtn, wasClicked);
DrawButton(HKey::W, clickedBtn, wasClicked);
DrawButton(HKey::E, clickedBtn, wasClicked);
DrawButton(HKey::R, clickedBtn, wasClicked);
DrawButton(HKey::T, clickedBtn, wasClicked);
DrawButton(HKey::Y, clickedBtn, wasClicked);
DrawButton(HKey::U, clickedBtn, wasClicked);
DrawButton(HKey::I, clickedBtn, wasClicked);
DrawButton(HKey::O, clickedBtn, wasClicked);
DrawButton(HKey::P, clickedBtn, wasClicked);
DrawButton(HKey::LBRACKET, clickedBtn, wasClicked);
DrawButton(HKey::RBRACKET, clickedBtn, wasClicked);
DrawButton(HKey::ENTER, clickedBtn, wasClicked);
ImGui::EndGroup();
ImGui::BeginGroup();
DrawButton(HKey::CAPS, clickedBtn, wasClicked);
DrawButton(HKey::A, clickedBtn, wasClicked);
DrawButton(HKey::S, clickedBtn, wasClicked);
DrawButton(HKey::D, clickedBtn, wasClicked);
DrawButton(HKey::F, clickedBtn, wasClicked);
DrawButton(HKey::G, clickedBtn, wasClicked);
DrawButton(HKey::H, clickedBtn, wasClicked);
DrawButton(HKey::J, clickedBtn, wasClicked);
DrawButton(HKey::K, clickedBtn, wasClicked);
DrawButton(HKey::L, clickedBtn, wasClicked);
DrawButton(HKey::SEMICOLON, clickedBtn, wasClicked);
DrawButton(HKey::SINGLE_QUOTE, clickedBtn, wasClicked);
DrawButton(HKey::BACKSLASH, clickedBtn, wasClicked);
DrawButton(HKey::NO_KEY, clickedBtn, wasClicked);
ImGui::EndGroup();
ImGui::BeginGroup();
DrawButton(HKey::LSHIFT, clickedBtn, wasClicked);
DrawButton(HKey::Z, clickedBtn, wasClicked);
DrawButton(HKey::X, clickedBtn, wasClicked);
DrawButton(HKey::C, clickedBtn, wasClicked);
DrawButton(HKey::V, clickedBtn, wasClicked);
DrawButton(HKey::B, clickedBtn, wasClicked);
DrawButton(HKey::N, clickedBtn, wasClicked);
DrawButton(HKey::M, clickedBtn, wasClicked);
DrawButton(HKey::COMMA, clickedBtn, wasClicked);
DrawButton(HKey::DOT, clickedBtn, wasClicked);
DrawButton(HKey::FRONTSLASH, clickedBtn, wasClicked);
DrawButton(HKey::RSHIFT, clickedBtn, wasClicked);
ImGui::EndGroup();
ImGui::BeginGroup();
DrawButton(HKey::CTRL, clickedBtn, wasClicked);
DrawButton(HKey::ALT, clickedBtn, wasClicked);
DrawButton(HKey::SPACE, clickedBtn, wasClicked);
DrawButton(HKey::HOME, clickedBtn, wasClicked);
DrawButton(HKey::INSERT, clickedBtn, wasClicked);
DrawButton(HKey::END, clickedBtn, wasClicked);
DrawButton(HKey::PAGE_DOWN, clickedBtn, wasClicked);
DrawButton(HKey::PAGE_UP, clickedBtn, wasClicked);
ImGui::EndGroup();
if (wasClicked) {
key = clickedBtn;
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::PopID();
return key;
}
}; | [
"lli@DESKTOP-S89EIDG"
] | lli@DESKTOP-S89EIDG |
0585d009ca34a264d9bf054c3f7afa5f801f31ad | 01bcef56ade123623725ca78d233ac8653a91ece | /public/engine/IEngineTrace.h | b9c6198f293ccf1904f271d3bf00ea94c3aa6362 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SwagSoftware/Kisak-Strike | 1085ba3c6003e622dac5ebc0c9424cb16ef58467 | 4c2fdc31432b4f5b911546c8c0d499a9cff68a85 | refs/heads/master | 2023-09-01T02:06:59.187775 | 2022-09-05T00:51:46 | 2022-09-05T00:51:46 | 266,676,410 | 921 | 123 | null | 2022-10-01T16:26:41 | 2020-05-25T03:41:35 | C++ | WINDOWS-1252 | C++ | false | false | 11,566 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef ENGINE_IENGINETRACE_H
#define ENGINE_IENGINETRACE_H
#ifdef _WIN32
#pragma once
#endif
#include "basehandle.h"
#include "utlvector.h" //need CUtlVector for IEngineTrace::GetBrushesIn*()
#include "mathlib/vector4d.h"
#include "bspflags.h"
class Vector;
class IHandleEntity;
struct Ray_t;
class CGameTrace;
typedef CGameTrace trace_t;
class ICollideable;
class QAngle;
class ITraceListData;
class CPhysCollide;
struct cplane_t;
struct virtualmeshlist_t;
struct AABB_t;
//-----------------------------------------------------------------------------
// The standard trace filter... NOTE: Most normal traces inherit from CTraceFilter!!!
//-----------------------------------------------------------------------------
enum TraceType_t
{
TRACE_EVERYTHING = 0,
TRACE_WORLD_ONLY, // NOTE: This does *not* test static props!!!
TRACE_ENTITIES_ONLY, // NOTE: This version will *not* test static props
TRACE_EVERYTHING_FILTER_PROPS, // NOTE: This version will pass the IHandleEntity for props through the filter, unlike all other filters
};
abstract_class ITraceFilter
{
public:
virtual bool ShouldHitEntity( IHandleEntity *pEntity, int contentsMask ) = 0;
virtual TraceType_t GetTraceType() const = 0;
};
struct OcclusionTestResults_t
{
VectorAligned vEndMin, vEndMax; // the bounding box enclosing the end of the occlusion test, to be used to extend the bounding box of an object shadow
};
//-----------------------------------------------------------------------------
// Classes are expected to inherit these + implement the ShouldHitEntity method
//-----------------------------------------------------------------------------
// This is the one most normal traces will inherit from
class CTraceFilter : public ITraceFilter
{
public:
virtual TraceType_t GetTraceType() const
{
return TRACE_EVERYTHING;
}
};
class CTraceFilterEntitiesOnly : public ITraceFilter
{
public:
virtual TraceType_t GetTraceType() const
{
return TRACE_ENTITIES_ONLY;
}
};
//-----------------------------------------------------------------------------
// Classes need not inherit from these
//-----------------------------------------------------------------------------
class CTraceFilterWorldOnly : public ITraceFilter
{
public:
bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )
{
return false;
}
virtual TraceType_t GetTraceType() const
{
return TRACE_WORLD_ONLY;
}
};
class CTraceFilterWorldAndPropsOnly : public ITraceFilter
{
public:
bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )
{
return false;
}
virtual TraceType_t GetTraceType() const
{
return TRACE_EVERYTHING;
}
};
class CTraceFilterHitAll : public CTraceFilter
{
public:
virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )
{
return true;
}
};
enum DebugTraceCounterBehavior_t
{
kTRACE_COUNTER_SET = 0,
kTRACE_COUNTER_INC,
};
//-----------------------------------------------------------------------------
// Enumeration interface for EnumerateLinkEntities
//-----------------------------------------------------------------------------
abstract_class IEntityEnumerator
{
public:
// This gets called with each handle
virtual bool EnumEntity( IHandleEntity *pHandleEntity ) = 0;
};
struct BrushSideInfo_t
{
cplane_t plane; // The plane of the brush side
unsigned short bevel; // Bevel plane?
unsigned short thin; // Thin?
};
//something we can easily create on the stack while easily maintaining our data release contract with IEngineTrace
class CBrushQuery
{
public:
CBrushQuery( void )
{
m_iCount = 0;
m_pBrushes = NULL;
m_iMaxBrushSides = 0;
m_pReleaseFunc = NULL;
m_pData = NULL;
}
~CBrushQuery( void )
{
ReleasePrivateData();
}
void ReleasePrivateData( void )
{
if( m_pReleaseFunc )
{
m_pReleaseFunc( this );
}
m_iCount = 0;
m_pBrushes = NULL;
m_iMaxBrushSides = 0;
m_pReleaseFunc = NULL;
m_pData = NULL;
}
inline int Count( void ) const { return m_iCount; }
inline uint32 *Base( void ) { return m_pBrushes; }
inline uint32 operator[]( int iIndex ) const { return m_pBrushes[iIndex]; }
inline uint32 GetBrushNumber( int iIndex ) const { return m_pBrushes[iIndex]; }
//maximum number of sides of any 1 brush in the query results
inline int MaxBrushSides( void ) const { return m_iMaxBrushSides; }
protected:
int m_iCount;
uint32 *m_pBrushes;
int m_iMaxBrushSides;
void (*m_pReleaseFunc)(CBrushQuery *); //release function is almost always in a different dll than calling code
void *m_pData;
};
//-----------------------------------------------------------------------------
// Interface the engine exposes to the game DLL
//-----------------------------------------------------------------------------
#define INTERFACEVERSION_ENGINETRACE_SERVER "EngineTraceServer004"
#define INTERFACEVERSION_ENGINETRACE_CLIENT "EngineTraceClient004"
abstract_class IEngineTrace
{
public:
// Returns the contents mask + entity at a particular world-space position
virtual int GetPointContents( const Vector &vecAbsPosition, int contentsMask = MASK_ALL, IHandleEntity** ppEntity = NULL ) = 0;
// Returns the contents mask of the world only @ the world-space position (static props are ignored)
virtual int GetPointContents_WorldOnly( const Vector &vecAbsPosition, int contentsMask = MASK_ALL ) = 0;
// Get the point contents, but only test the specific entity. This works
// on static props and brush models.
//
// If the entity isn't a static prop or a brush model, it returns CONTENTS_EMPTY and sets
// bFailed to true if bFailed is non-null.
virtual int GetPointContents_Collideable( ICollideable *pCollide, const Vector &vecAbsPosition ) = 0;
// Traces a ray against a particular entity
virtual void ClipRayToEntity( const Ray_t &ray, unsigned int fMask, IHandleEntity *pEnt, trace_t *pTrace ) = 0;
// Traces a ray against a particular entity
virtual void ClipRayToCollideable( const Ray_t &ray, unsigned int fMask, ICollideable *pCollide, trace_t *pTrace ) = 0;
// A version that simply accepts a ray (can work as a traceline or tracehull)
virtual void TraceRay( const Ray_t &ray, unsigned int fMask, ITraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
// A version that sets up the leaf and entity lists and allows you to pass those in for collision.
virtual void SetupLeafAndEntityListRay( const Ray_t &ray, ITraceListData *pTraceData ) = 0;
virtual void SetupLeafAndEntityListBox( const Vector &vecBoxMin, const Vector &vecBoxMax, ITraceListData *pTraceData ) = 0;
virtual void TraceRayAgainstLeafAndEntityList( const Ray_t &ray, ITraceListData *pTraceData, unsigned int fMask, ITraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
// A version that sweeps a collideable through the world
// abs start + abs end represents the collision origins you want to sweep the collideable through
// vecAngles represents the collision angles of the collideable during the sweep
virtual void SweepCollideable( ICollideable *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd,
const QAngle &vecAngles, unsigned int fMask, ITraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
// Enumerates over all entities along a ray
// If triggers == true, it enumerates all triggers along a ray
virtual void EnumerateEntities( const Ray_t &ray, bool triggers, IEntityEnumerator *pEnumerator ) = 0;
// Same thing, but enumerate entitys within a box
virtual void EnumerateEntities( const Vector &vecAbsMins, const Vector &vecAbsMaxs, IEntityEnumerator *pEnumerator ) = 0;
// Convert a handle entity to a collideable. Useful inside enumer
virtual ICollideable *GetCollideable( IHandleEntity *pEntity ) = 0;
// HACKHACK: Temp for performance measurments
virtual int GetStatByIndex( int index, bool bClear ) = 0;
//finds brushes in an AABB, prone to some false positives
virtual void GetBrushesInAABB( const Vector &vMins, const Vector &vMaxs, CBrushQuery &BrushQuery, int iContentsMask = 0xFFFFFFFF, int cmodelIndex = 0 ) = 0;
//Creates a CPhysCollide out of all displacements wholly or partially contained in the specified AABB
virtual CPhysCollide* GetCollidableFromDisplacementsInAABB( const Vector& vMins, const Vector& vMaxs ) = 0;
// gets the number of displacements in the world
virtual int GetNumDisplacements( ) = 0;
// gets a specific diplacement mesh
virtual void GetDisplacementMesh( int nIndex, virtualmeshlist_t *pMeshTriList ) = 0;
//retrieve brush planes and contents, returns zero if the brush doesn't exist,
//returns positive number of sides filled out if the array can hold them all, negative number of slots needed to hold info if the array is too small
virtual int GetBrushInfo( int iBrush, int &ContentsOut, BrushSideInfo_t *pBrushSideInfoOut, int iBrushSideInfoArraySize ) = 0;
virtual bool PointOutsideWorld( const Vector &ptTest ) = 0; //Tests a point to see if it's outside any playable area
// Walks bsp to find the leaf containing the specified point
virtual int GetLeafContainingPoint( const Vector &ptTest ) = 0;
virtual ITraceListData *AllocTraceListData() = 0;
virtual void FreeTraceListData(ITraceListData *) = 0;
/// Used only in debugging: get/set/clear/increment the trace debug counter. See comment below for details.
virtual int GetSetDebugTraceCounter( int value, DebugTraceCounterBehavior_t behavior ) = 0;
//Similar to GetCollidableFromDisplacementsInAABB(). But returns the intermediate mesh data instead of a collideable
virtual int GetMeshesFromDisplacementsInAABB( const Vector& vMins, const Vector& vMaxs, virtualmeshlist_t *pOutputMeshes, int iMaxOutputMeshes ) = 0;
virtual void GetBrushesInCollideable( ICollideable *pCollideable, CBrushQuery &BrushQuery ) = 0;
virtual bool IsFullyOccluded( int nOcclusionKey, const AABB_t &aabb1, const AABB_t &aabb2, const Vector &vShadow ) = 0;
virtual void SuspendOcclusionTests() = 0;
virtual void ResumeOcclusionTests() = 0;
class CAutoSuspendOcclusionTests
{
IEngineTrace *m_pEngineTrace;
public:
CAutoSuspendOcclusionTests( IEngineTrace *pEngineTrace ) : m_pEngineTrace( pEngineTrace ) { pEngineTrace->SuspendOcclusionTests(); }
~CAutoSuspendOcclusionTests() { m_pEngineTrace->ResumeOcclusionTests(); }
};
virtual void FlushOcclusionQueries() = 0;
};
/// IEngineTrace::GetSetDebugTraceCounter
/// SET to a negative number to disable. SET to a positive number to reset the counter; it'll tick down by
/// one for each trace, and break into the debugger on hitting zero. INC lets you add or subtract from the
/// counter. In each case it will return the value of the counter BEFORE you set or incremented it. INC 0
/// to query. This end-around approach is necessary for security: because only the engine knows when we
/// are in a trace, and only the server knows when we are in a think, data must somehow be shared between
/// them. Simply returning a pointer to an address inside the engine in a retail build is unacceptable,
/// and in the PC there is no way to distinguish between retail and non-retail builds at compile time
/// (there is no #define for it).
/// This may seem redundant with the VPROF_INCREMENT_COUNTER( "TraceRay" ), but it's not, because while
/// that's readable across DLLs, there's no way to trap on its exceeding a certain value, nor can we reset
/// it for each think.
#endif // ENGINE_IENGINETRACE_H
| [
"bbchallenger100@gmail.com"
] | bbchallenger100@gmail.com |
2c9387431c876dca9300845e1ef405d180669f5e | cad04bb71f3afd50c4df3b2f321cd378d3ad8cb9 | /OJ practices/PAT甲级真题练习/1061. Dating.cpp | 0cc869ac69d8a3b68784f7fa74e3b5bbe7249e6b | [] | no_license | SourDumplings/CodeSolutions | 9033de38005b1d90488e64ccbb99f91c7e7b71ec | 5f9eca3fe5701a8fca234343fde31cfcba94cf27 | refs/heads/master | 2023-08-16T17:23:34.977471 | 2023-08-07T13:14:47 | 2023-08-07T13:14:47 | 110,331,879 | 10 | 8 | null | 2023-06-14T22:25:16 | 2017-11-11T08:59:11 | C | UTF-8 | C++ | false | false | 1,497 | cpp | /*
@Date : 2018-02-02 14:19:26
@Author : 酸饺子 (changzheng300@foxmail.com)
@Link : https://github.com/SourDumplings
@Version : $Id$
*/
/*
https://www.patest.cn/contests/pat-a-practise/1061
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <array>
#include <cctype>
using namespace std;
const array<string, 7> dayName{{"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}};
int main(int argc, char const *argv[])
{
string s1, s2, s3, s4;
cin >> s1 >> s2 >> s3 >> s4;
int n1 = s1.length();
string day;
int hour;
int first_pos;
for (int i = 0; i != n1; ++i)
{
if ((s1[i] >= 'A' && s1[i] <= 'G') && (s1[i] == s2[i]))
{
day = dayName[s1[i] - 'A'];
first_pos = i;
break;
}
}
for (int i = first_pos + 1; i != n1; ++i)
{
if (s1[i] == s2[i])
{
if (isdigit(s1[i]))
{
hour = s1[i] - '0';
break;
}
else if (s1[i] >= 'A' && s1[i] <= 'N')
{
hour = s1[i] - 'A' + 10;
break;
}
}
}
int min;
int n3 = s3.length(), n4 = s4.length();
for (int i = 0; i != n3 && i != n4; ++i)
{
if (isalpha(s3[i]) && s3[i] == s4[i])
{
min = i;
break;
}
}
printf("%s %02d:%02d\n", day.c_str(), hour, min);
return 0;
}
| [
"changzheng300@foxmail.com"
] | changzheng300@foxmail.com |
5362fe19d86bc21c56ca0a121f62bb3262ffe17c | 1760901ad3ffb97b1c8629ad9261292f301c09e2 | /main.cpp | 9e752ca1fb3e9d932d6819c8b9d27ef07677c5e7 | [
"BSD-3-Clause"
] | permissive | ZhangJunQCC/CallStack-for-Windows-and-Linux | 4860771efdea2099b444080898caaec199ddcc70 | e8fb3c8adefc39710208db3e8519fe58255ffd3c | refs/heads/master | 2021-06-21T17:23:38.241062 | 2017-08-23T02:54:25 | 2017-08-23T02:54:25 | 94,791,773 | 8 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cpp | //
// Author: Jun Zhang
// mailto: zhangjunqcc@gmail.com
//
// To enable Callstack correctly return a function name, the codes
// have to be compiled with the following options:
//
// On Linux and Mac OS X:
// g++ -g -rdynamic
//
// On Windows, mingw:
// g++ -g
//
// On Windows, Microsoft Visual C++:
// cl.exe /DEBUG /Zi
//
// For link options, see the example Makefiles.
//
#include "CallStack.h"
#include <cstdio>
using namespace debug;
template<typename T>
void f4(T a)
{
vector<CallStack::CallInfo> cs;
CallStack::GetCalls(cs);
for(int i = 0; i < cs.size(); ++i)
{
printf("[%3d] %15p: %s in %s\n", cs.size()-i, cs[i].offset, cs[i].function.c_str(), cs[i].module.c_str());
}
}
class Foo {
public:
void f3(void) { double x = 1.; f4(x); }
};
void f2(void) { Foo f; f.f3(); }
void f1(void) { f2(); }
int main(int argc, char** argv)
{
f1();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
77029c6c75eacccda26748598d03623c587b64ee | be36a4a4a02e9bdf47c1d628589e538c3f26e26a | /BattleTank/Source/BattleTank/Public/SprungWheel.h | 8ed15492a966c9ad939562fa4559bebd5aac3f65 | [] | no_license | Murkjas/BattleTank | 2ca8a01c4a5b3780171e732ed008a4f664fe0b4f | 52b0a6b6c7bdf640ab973f7c1d3d4419d2f64a83 | refs/heads/master | 2020-04-01T14:34:56.241434 | 2019-02-01T19:14:25 | 2019-02-01T19:14:25 | 153,300,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Engine.h"
#include "SprungWheel.generated.h"
UCLASS()
class BATTLETANK_API ASprungWheel : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASprungWheel();
// Called every frame
virtual void Tick(float DeltaTime) override;
void AddDrivingForce(float ForceMagnitude);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
void SetupConstraint();
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
void ApplyForce();
// Components
UPROPERTY(VisibleAnywhere, Category = "Components")
USphereComponent* Wheel = nullptr;
UPROPERTY(VisibleAnywhere, Category = "Components")
UPhysicsConstraintComponent* MassWheelConstraint = nullptr;
UPROPERTY(VisibleAnywhere, Category = "Components")
USphereComponent* Axle = nullptr;
UPROPERTY(VisibleAnywhere, Category = "Components")
UPhysicsConstraintComponent* AxleWheelConstraint = nullptr;
float TotalForceMagnitudeThisFrame = 0;
};
| [
"markuskannisto@hotmail.com"
] | markuskannisto@hotmail.com |
b1ccb058810d2e383ead26bd3a9ace6708986974 | 8c5ca1bee5f581cebea051f181725698ef3e4e31 | /src/libtsduck/plugins/private/tstsmuxCore.cpp | 21a46fa1466bbf08406dbad310a61834c02907a3 | [
"BSD-2-Clause"
] | permissive | vtns/tsduck | 1f914c799fcd3e758fbea144cbd7a14f95e17f00 | 2a7c923ef054d8f42fd4428efe905b033574f78f | refs/heads/master | 2023-08-28T08:11:02.430223 | 2021-10-29T23:28:47 | 2021-10-29T23:28:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,111 | cpp | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// 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.
//
// 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 "tstsmuxCore.h"
#include "tsMonotonic.h"
#include "tsFatal.h"
#include "tsAlgorithm.h"
#include "tsBinaryTable.h"
#include "tsCADescriptor.h"
#include "tsTDT.h"
#include "tsTOT.h"
#include "tsEIT.h"
//----------------------------------------------------------------------------
// Constructor and destructor.
//----------------------------------------------------------------------------
ts::tsmux::Core::Core(const MuxerArgs& opt, const PluginEventHandlerRegistry& handlers, Report& log) :
_handlers(handlers),
_log(log),
_opt(opt),
_duck(&log),
_terminate(false),
_bitrate(0),
_output_packets(0),
_time_input_index(opt.timeInputIndex),
_inputs(_opt.inputs.size(), nullptr),
_output(_opt, handlers, _log),
_terminated_inputs(),
_pat_pzer(_duck, PID_PAT, CyclingPacketizer::StuffingPolicy::ALWAYS),
_cat_pzer(_duck, PID_CAT, CyclingPacketizer::StuffingPolicy::ALWAYS),
_nit_pzer(_duck, PID_NIT, CyclingPacketizer::StuffingPolicy::ALWAYS),
_sdt_bat_pzer(_duck, PID_SDT, CyclingPacketizer::StuffingPolicy::ALWAYS),
_eit_pzer(_duck, PID_EIT, this),
_output_pat(),
_output_cat(),
_output_sdt(),
_output_nit(),
_max_eits(128), // hard-coded for now
_eits(),
_pid_origin(),
_service_origin()
{
// Preset common default options.
_duck.restoreArgs(_opt.duckArgs);
// Load all input plugins, analyze their options.
for (size_t i = 0; i < _opt.inputs.size(); ++i) {
_inputs[i] = new Input(*this, i);
CheckNonNull(_inputs[i]);
}
}
ts::tsmux::Core::~Core()
{
// Wait for termination of all threads.
waitForTermination();
// Deallocate all input plugins.
for (size_t i = 0; i < _inputs.size(); ++i) {
delete _inputs[i];
}
_inputs.clear();
}
//----------------------------------------------------------------------------
// Start the tsmux processing.
//----------------------------------------------------------------------------
bool ts::tsmux::Core::start()
{
// Initialize the output plugin.
if (!_output.plugin()->getOptions() || !_output.plugin()->start()) {
return false;
}
// Make sure that we have an output bitrate.
const BitRate br = _output.plugin()->getBitrate();
if (br != 0) {
// The output plugin reports an output bitrate, always use this one.
_bitrate = br;
if (_opt.outputBitRate == 0) {
_log.verbose(u"output bitrate is %'d b/s, as reported by output plugin", {br});
}
else if (_opt.outputBitRate != br) {
_log.warning(u"output bitrate is %'d b/s, as reported by output plugin, overrides %'d b/s from command line", {br, _opt.outputBitRate});
}
}
else if (_opt.outputBitRate == 0) {
_log.error(u"no output bitrate specified and none reported by output plugin");
_output.plugin()->stop();
return false;
}
else {
_bitrate = _opt.outputBitRate;
}
// Get all plugin command line options and start them
// (start the plugins but do not start the plugin executor threads).
for (size_t i = 0; i < _inputs.size(); ++i) {
if (!_inputs[i]->init()) {
// Error, close previous plugins.
for (size_t prev = 0; prev < i; ++prev) {
_inputs[prev]->uninit();
}
_output.plugin()->stop();
return false;
}
}
// Now that all plugins are open, start all executor threads.
bool success = _output.start();
for (size_t i = 0; success && i < _inputs.size(); ++i) {
success = _inputs[i]->start();
}
// Now start the Core internal thread, the one that does the multiplexing.
success = success && Thread::start();
if (!success) {
stop();
}
return success;
}
//----------------------------------------------------------------------------
// Stop the tsmux processing.
//----------------------------------------------------------------------------
void ts::tsmux::Core::stop()
{
// Request termination of all plugin executor threads.
_output.terminate();
for (size_t i = 0; i < _inputs.size(); ++i) {
_inputs[i]->terminate();
}
// Stop our internal thread. We only set the terminate flag, actual termination
// will occur at the next muxing iteration.
_terminate = true;
}
//----------------------------------------------------------------------------
// Wait for completion of all plugins.
//----------------------------------------------------------------------------
void ts::tsmux::Core::waitForTermination()
{
// Wait for output termination.
_output.waitForTermination();
// Wait for all input termination.
for (size_t i = 0; i < _inputs.size(); ++i) {
_inputs[i]->waitForTermination();
}
// Wait for our internal thread.
Thread::waitForTermination();
}
//----------------------------------------------------------------------------
// Invoked in the context of the core thread.
//----------------------------------------------------------------------------
void ts::tsmux::Core::main()
{
_log.debug(u"core thread started");
// Reinitialize PID and service tracking.
_pid_origin.clear();
_service_origin.clear();
// Reinitialize output PSI/SI. At the beginning, we do not send these empty tables
// into their packetizer. When the first table of a given type is encountered in
// an input stream, it will be merged into the corresponding output table and will
// be sent to the packetizer. Thus, if a table such as a CAT is not present in any
// input, it won't be present in output either.
_output_pat.clear();
_output_pat.ts_id = _opt.outputTSId;
_output_pat.nit_pid = PID_NIT;
_output_cat.clear();
_output_nit.clear();
_output_nit.network_id = _opt.outputNetwId;
_output_sdt.clear();
_output_sdt.ts_id = _opt.outputTSId;
_output_sdt.onetw_id = _opt.outputNetwId;
_eits.clear();
// Reset packetizers for output PSI/SI.
_pat_pzer.reset();
_cat_pzer.reset();
_nit_pzer.reset();
_sdt_bat_pzer.reset();
_eit_pzer.reset();
// Insertion interval for signalization.
const PacketCounter pat_interval = (_opt.outputBitRate / _opt.patBitRate).toInt();
const PacketCounter cat_interval = (_opt.outputBitRate / _opt.catBitRate).toInt();
const PacketCounter nit_interval = (_opt.outputBitRate / _opt.nitBitRate).toInt();
const PacketCounter sdt_interval = (_opt.outputBitRate / _opt.sdtBitRate).toInt();
// Reset signalization insertion.
PacketCounter next_pat_packet = 0;
PacketCounter next_cat_packet = 0;
PacketCounter next_nit_packet = 0;
PacketCounter next_sdt_packet = 0;
// Insertion is cadenced using a monotonic clock.
const Monotonic start(true);
Monotonic clock(start);
// The unit of Monotonic operations is the nanosecond, the command line option is in microseconds.
const NanoSecond cadence = _opt.cadence * NanoSecPerMicroSec;
// Keep track of terminated input plugins.
_terminated_inputs.clear();
// Next input plugin to read from.
size_t input_index = 0;
// Reset output packet counter.
_output_packets = 0;
TSPacket pkt;
TSPacketMetadata pkt_data;
// Loop until we are instructed to stop. Each iteration is a muxing period at the defined cadence.
while (!_terminate) {
// End of next time interval.
clock += cadence;
// Number of packets which should have been sent by the end of the time interval.
const PacketCounter expected_packets = (((clock - start) * _bitrate) / (NanoSecPerSec * PKT_SIZE_BITS)).toInt();
// Number of packets to send by the end of the time interval.
PacketCounter packet_count = expected_packets < _output_packets ? 0 : expected_packets - _output_packets;
// Loop on packets to send during this time interval.
while (!_terminate && packet_count > 0) {
pkt_data.reset();
// This section selects packets to insert. Initially, the insertion strategy was very basic.
// To improve the muxing method, rework this section.
if (_output_packets >= next_pat_packet && _pat_pzer.getNextPacket(pkt)) {
// Got a PAT packet.
next_pat_packet += pat_interval;
}
else if (_output_packets >= next_cat_packet && _cat_pzer.getNextPacket(pkt)) {
// Got a CAT packet.
next_cat_packet += cat_interval;
}
else if (_output_packets >= next_nit_packet && _nit_pzer.getNextPacket(pkt)) {
// Got a NIT packet.
next_nit_packet += nit_interval;
}
else if (_output_packets >= next_sdt_packet && _sdt_bat_pzer.getNextPacket(pkt)) {
// Got an SDT packet.
next_sdt_packet += sdt_interval;
}
else if (getInputPacket(input_index, pkt, pkt_data)) {
// Got a packet from an input plugin.
}
else if (_eit_pzer.getNextPacket(pkt)) {
// Got an EIT packet. Note that EIT are muxed, not cycled. So, they are inserted when available.
}
else {
// Nothing is available, insert a null packet.
pkt = NullPacket;
pkt_data.setNullified(true);
}
// Output that packet.
if (!_output.send(&pkt, &pkt_data, 1)) {
_log.error(u"output plugin terminated on error, aborting");
_terminate = true;
}
else {
_output_packets++;
packet_count--;
}
}
// Wait until next muxing period.
if (!_terminate) {
clock.wait();
}
}
// Make sure all plugins, input and output, terminates.
// It termination was externally triggerd, all plugins are already terminating.
// But if all inputs have naturally terminated, we must terminate the output thread.
// Or if the output thread terminated on error, we must terminate all input threads.
stop();
_log.debug(u"core thread terminated");
}
//----------------------------------------------------------------------------
// Get a packet from plugin at given index.
//----------------------------------------------------------------------------
bool ts::tsmux::Core::getInputPacket(size_t& input_index, TSPacket& pkt, TSPacketMetadata& pkt_data)
{
bool success = false;
size_t plugin_count = 0;
do {
// Try to get a packet from current plugin.
success = _inputs[input_index]->getPacket(pkt, pkt_data);
// Keep track of terminated input plugins.
if (!success && _inputs[input_index]->isTerminated()) {
_terminated_inputs.insert(input_index);
if (_terminated_inputs.size() >= _inputs.size()) {
// All input plugins are now terminated. Request global termination.
_terminate = true;
}
}
// Point to next plugin.
input_index = (input_index + 1) % _inputs.size();
} while (!_terminate && !success && ++plugin_count < _inputs.size());
return success;
}
//----------------------------------------------------------------------------
// Try to extract a UTC time from a TDT or TOT in one TS packet.
//----------------------------------------------------------------------------
bool ts::tsmux::Core::getUTC(Time& utc, const TSPacket& pkt)
{
if (pkt.getPUSI()) {
// This packet contains the start of a section.
const uint8_t* pl = pkt.getPayload();
size_t pl_size = pkt.getPayloadSize();
if (pl_size > 0) {
// Get the pointer field.
const uint8_t pf = pl[0];
if (pl_size >= 1 + pf + MIN_SHORT_SECTION_SIZE) {
// A section can fit. Get address and remaining size.
pl += 1 + pf;
pl_size -= 1 + pf;
// Get section size.
const size_t sect_size = 3 + (GetUInt16(pl + 1) & 0x0FFF);
if (pl_size >= sect_size) {
// A complete section is here, make it a binary table.
BinaryTable table;
table.addSection(SectionPtr(new Section(pl, sect_size)));
// Try to interpret it as a TDT or TOT.
TDT tdt(_duck, table);
if (tdt.isValid()) {
utc = tdt.utc_time;
return true;
}
TOT tot(_duck, table);
if (tot.isValid()) {
utc = tot.utc_time;
return true;
}
}
}
}
}
return false; // no time found
}
//----------------------------------------------------------------------------
// Implementation of SectionProviderInterface (for output EIT provision).
//----------------------------------------------------------------------------
bool ts::tsmux::Core::doStuffing()
{
// Never do stuffing, always pack EIT's.
return false;
}
void ts::tsmux::Core::provideSection(SectionCounter counter, SectionPtr& section)
{
if (_eits.empty()) {
// No EIT section to provide.
section.clear();
}
else {
// Remove one EIT section from the queue for insertion.
section = _eits.front();
_eits.pop_front();
}
}
//----------------------------------------------------------------------------
// Description of an input stream.
//----------------------------------------------------------------------------
ts::tsmux::Core::Input::Input(Core& core, size_t index) :
_core(core),
_plugin_index(index),
_terminated(false),
_got_ts_id(false),
_ts_id(0),
_input(_core._opt, core._handlers, index, _core._log),
_demux(_core._duck, this, nullptr),
_eit_demux(_core._duck, nullptr, this),
_pcr_merger(_core._duck),
_nit(),
_next_insertion(0),
_next_packet(),
_next_metadata(),
_pid_clocks()
{
// Filter all global PSI/SI for merging in output PSI.
_demux.addPID(PID_PAT);
_demux.addPID(PID_CAT);
if (_core._opt.nitScope != TableScope::NONE) {
_demux.addPID(PID_NIT);
}
if (_core._opt.sdtScope != TableScope::NONE) {
_demux.addPID(PID_SDT);
}
// Filter EIT sections one by one if the output stream shall contain EIT's.
if (_core._opt.eitScope != TableScope::NONE) {
_eit_demux.addPID(PID_EIT);
}
// Always reset PCR progression when moving ahead of PTS or DTS.
_pcr_merger.setResetBackwards(true);
// The NIT is valid only when waiting to be merged.
_nit.invalidate();
}
//----------------------------------------------------------------------------
// Get one input packet. Return false when none is immediately available.
//----------------------------------------------------------------------------
bool ts::tsmux::Core::Input::getPacket(TSPacket& pkt, TSPacketMetadata& pkt_data)
{
// If there is a waiting packet, either return that packet or nothing.
if (_next_insertion > 0) {
if (_next_insertion <= _core._output_packets) {
// It is now time to return that packet.
_core._log.debug(u"input #%d, PID 0x%X (%<d), output packet %'d, restarting insertion", {_plugin_index, _next_packet.getPID(), _core._output_packets});
_next_insertion = 0;
pkt = _next_packet;
pkt_data = _next_metadata;
adjustPCR(pkt);
return true;
}
else {
// Not yet time to release a packet from that input stream.
return false;
}
}
// Get one packet from the input executor thread, non-blocking.
size_t ret_count = 0;
_terminated = _terminated || !_input.getPackets(&pkt, &pkt_data, 1, ret_count, false);
if (_terminated || ret_count == 0) {
return false;
}
const PID pid = pkt.getPID();
// Feed the two PSI/SI demux.
_demux.feedPacket(pkt);
_eit_demux.feedPacket(pkt);
// If this is TDT/TOT PID, check if we need to pass it.
if (pid == PID_TDT && _core._time_input_index == NPOS) {
// Time PID not yet selected. If we find a time here, we will use that plugin.
Time utc;
if (_core.getUTC(utc, pkt)) {
// From now on, we will use that input plugin as time reference.
_core._time_input_index = _plugin_index;
_core._log.verbose(u"using input #%d as TDT/TOT reference", {_plugin_index});
}
}
// If the packet contains a PCR, check if it is time to insert it in the output.
// PCR packets are inserted at the same (or similar) PCR interval as in the orginal stream.
if (pkt.hasPCR()) {
const auto clock = _pid_clocks.find(pid);
if (clock != _pid_clocks.end()) {
const uint64_t packet_pcr = pkt.getPCR();
if (packet_pcr < clock->second.pcr_value && !WrapUpPCR(clock->second.pcr_value, packet_pcr)) {
const uint64_t back = DiffPCR(packet_pcr, clock->second.pcr_value);
_core._log.verbose(u"input #%d, PID 0x%X (%<d), late packet by PCR %'d, %'s ms", {_plugin_index, pid, back, (back * MilliSecPerSec) / SYSTEM_CLOCK_FREQ});
}
else {
// Compute current PCR for previous packet in the output TS.
assert(_core._output_packets > clock->second.pcr_packet);
const uint64_t output_pcr = NextPCR(clock->second.pcr_value, _core._output_packets - clock->second.pcr_packet - 1, _core._bitrate);
// Compute difference between packet's PCR and current output PCR.
// If they differ by more than one second, we consider that there was a clock leap and
// we just let the packet pass without PCR adjustment. If the difference is less than
// one second, we consider that the PCR progression is valid and we synchronize on it.
if (AbsDiffPCR(packet_pcr, output_pcr) < SYSTEM_CLOCK_FREQ) {
// Compute the theoretical position of the packet in the output stream.
const PacketCounter target_packet = clock->second.pcr_packet + PacketDistanceFromPCR(_core._bitrate, DiffPCR(clock->second.pcr_value, packet_pcr));
if (target_packet > _core._output_packets) {
// This packet will be inserted later.
_core._log.debug(u"input #%d, PID 0x%X (%<d), output packet %'d, delay packet by %'d packets", {_plugin_index, pid, _core._output_packets, target_packet - _core._output_packets});
_next_insertion = target_packet;
_next_packet = pkt;
_next_metadata = pkt_data;
return false;
}
}
}
}
}
// Adjust and remember PCR values and position.
adjustPCR(pkt);
// Don't return packets from predefined PID's, they are separately regenerated.
return pid > PID_DVB_LAST || (pid == PID_TDT && _core._time_input_index == _plugin_index);
}
//----------------------------------------------------------------------------
// Adjust the PCR of a packet before insertion.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::adjustPCR(TSPacket& pkt)
{
// Adjust PCR in the packet, assuming it will be the next one to be inserted in the output.
_pcr_merger.processPacket(pkt, _core._output_packets, _core._bitrate);
// Remember PCR insertion point (with adjusted PCR value).
if (pkt.hasPCR()) {
PIDClock& clock(_pid_clocks[pkt.getPID()]);
clock.pcr_value = pkt.getPCR();
clock.pcr_packet = _core._output_packets;
}
}
//----------------------------------------------------------------------------
// Receive a PSI/SI table from an input stream.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::handleTable(SectionDemux& demux, const BinaryTable& table)
{
switch (table.tableId()) {
case TID_PAT: {
const PAT pat(_core._duck, table);
if (pat.isValid() && table.sourcePID() == PID_PAT) {
handlePAT(pat);
}
break;
}
case TID_CAT: {
const CAT cat(_core._duck, table);
if (cat.isValid() && table.sourcePID() == PID_CAT) {
handleCAT(cat);
}
break;
}
case TID_NIT_ACT: {
if (_core._opt.nitScope != TableScope::NONE && table.sourcePID() == PID_NIT) {
// Process the NIT only when the current TS id is known.
_nit.deserialize(_core._duck, table);
if (_nit.isValid() && _got_ts_id) {
handleNIT(_nit);
_nit.invalidate();
}
}
break;
}
case TID_NIT_OTH: {
if (_core._opt.nitScope == TableScope::ALL && table.sourcePID() == PID_NIT) {
// This is a NIT-Other. It must be reinserted without modification in the NIT PID.
_core._nit_pzer.removeSections(table.tableId(), table.tableIdExtension());
_core._nit_pzer.addTable(table);
}
break;
}
case TID_SDT_ACT: {
if (_core._opt.sdtScope != TableScope::NONE && table.sourcePID() == PID_SDT) {
const SDT sdt(_core._duck, table);
if (sdt.isValid()) {
handleSDT(sdt);
}
}
break;
}
case TID_SDT_OTH: {
if (_core._opt.sdtScope == TableScope::ALL && table.sourcePID() == PID_SDT) {
// This is an SDT-Other. It must be reinserted without modification in the SDT/BAT PID.
_core._sdt_bat_pzer.removeSections(table.tableId(), table.tableIdExtension());
_core._sdt_bat_pzer.addTable(table);
}
break;
}
default: {
break;
}
}
}
//----------------------------------------------------------------------------
// Receive a PAT from an input stream.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::handlePAT(const PAT& pat)
{
bool modified = false;
// Input TS id is now known.
_ts_id = pat.ts_id;
_got_ts_id = true;
// Now that the TS id is known, we can process a waiting NIT.
if (_nit.isValid()) {
handleNIT(_nit);
_nit.invalidate();
}
// Add all services from input PAT into output PAT.
for (auto it = pat.pmts.begin(); it != pat.pmts.end(); ++it) {
// Origin of the service.
const uint16_t service_id = it->first;
Origin& origin(_core._service_origin[service_id]);
if (!Contains(_core._output_pat.pmts, service_id)) {
// New service found.
_core._log.verbose(u"adding service 0x%X (%<d) from input #%d in PAT", {service_id, _plugin_index});
_core._output_pat.pmts[service_id] = it->second;
origin.plugin_index = _plugin_index;
modified = true;
}
else if (origin.plugin_index == _plugin_index) {
// Already found in same input, maybe same PMT PID, modify if not the same.
modified = it->second != _core._output_pat.pmts[service_id];
_core._output_pat.pmts[service_id] = it->second;
}
else if (!_core._opt.ignoreConflicts) {
_core._log.error(u"service conflict, service 0x%X (%<d) exists in input #%d and #%d, aborting", {service_id, origin.plugin_index, _plugin_index});
_core.stop();
return;
}
else if (!origin.conflict_detected) {
// Conflicts are ignored, this conflict is detected for the first time.
origin.conflict_detected = true;
_core._log.warning(u"service conflict, service 0x%X (%<d) exists in input #%d and #%d, ignoring", {service_id, origin.plugin_index, _plugin_index});
}
}
// Check if previous services from this input have disappeared.
for (auto it = _core._output_pat.pmts.begin(); it != _core._output_pat.pmts.end(); ) {
const uint16_t service_id = it->first;
if (_core._service_origin[service_id].plugin_index == _plugin_index && !Contains(pat.pmts, service_id)) {
// This service was in the output PAT and identified as coming from this input plugin.
// However, it is no longer in the PAT of this input.
_core._log.verbose(u"service 0x%X (%<d) disappeared from input #%d, removing from PAT", {service_id, _plugin_index});
it = _core._output_pat.pmts.erase(it);
modified = true;
}
else {
++it;
}
}
// If the output PAT was modified, increment its version and replace it in the packetizer.
if (modified) {
_core._output_pat.version = (_core._output_pat.version + 1) & SVERSION_MASK;
_core._pat_pzer.removeSections(TID_PAT);
_core._pat_pzer.addTable(_core._duck, _core._output_pat);
}
}
//----------------------------------------------------------------------------
// Receive a CAT from an input stream.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::handleCAT(const CAT& cat)
{
bool modified = false;
// Add all CA descriptors from input CAT into output CAT.
for (size_t index = cat.descs.search(DID_CA); index < cat.descs.count(); index = cat.descs.search(DID_CA, index + 1)) {
const CADescriptor ca(_core._duck, *cat.descs[index]);
if (ca.isValid()) {
// Origin of the corresponding EMM PID.
Origin& origin(_core._pid_origin[ca.ca_pid]);
// Check if the same EMM PID already exists in the output CAT.
const size_t output_index = CADescriptor::SearchByPID(_core._output_cat.descs, ca.ca_pid);
if (output_index >= _core._output_cat.descs.count()) {
// Not found in output CAT, this is a new EMM PID.
_core._log.verbose(u"adding EMM PID 0x%X (%<d) from input #%d in CAT", {ca.ca_pid, _plugin_index});
_core._output_cat.descs.add(cat.descs[index]);
origin.plugin_index = _plugin_index;
modified = true;
}
else if (origin.plugin_index == _plugin_index) {
// Already found in same input, maybe same CA desc, modify if not the same.
modified = *cat.descs[index] != *_core._output_cat.descs[output_index];
if (modified) {
_core._output_cat.descs.removeByIndex(output_index);
_core._output_cat.descs.add(cat.descs[index]);
}
}
else if (!_core._opt.ignoreConflicts) {
_core._log.error(u"EMM PID conflict, PID 0x%X (%<d) exists in input #%d and #%d, aborting", {ca.ca_pid, origin.plugin_index, _plugin_index});
_core.stop();
return;
}
else if (!origin.conflict_detected) {
// Conflicts are ignored, this conflict is detected for the first time.
origin.conflict_detected = true;
_core._log.warning(u"EMM PID conflict, PID 0x%X (%<d) exists in input #%d and #%d, ignoring", {ca.ca_pid, origin.plugin_index, _plugin_index});
}
}
}
// We do not try to eliminate previous CA descriptors from same input but no longer referenced.
// We could do it in the future.
// If the output CAT was modified, increment its version and replace it in the packetizer.
if (modified) {
_core._output_cat.version = (_core._output_cat.version + 1) & SVERSION_MASK;
_core._cat_pzer.removeSections(TID_CAT);
_core._cat_pzer.addTable(_core._duck, _core._output_cat);
}
}
//----------------------------------------------------------------------------
// Receive a NIT from an input stream.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::handleNIT(const NIT& nit)
{
bool modified = false;
// Merge initial descriptors.
_core._output_nit.descs.merge(_core._duck, nit.descs);
// Loop on all transport streams in the input NIT.
for (auto it = nit.transports.begin(); it != nit.transports.end(); ++it) {
const uint16_t tsid = it->first.transport_stream_id;
if (tsid == _ts_id) {
// This is the description of the input transport stream.
// Map it to the description of the output transport stream.
NIT::Transport& ts(_core._output_nit.transports[TransportStreamId(_core._opt.outputTSId, _core._opt.outputNetwId)]);
ts.descs.merge(_core._duck, it->second.descs);
modified = true;
}
else if (tsid != _core._opt.outputTSId) {
// This is the description of a transport stream which does not conflict
// with the description of the output transport stream.
NIT::Transport& ts(_core._output_nit.transports[TransportStreamId(tsid, _core._opt.outputNetwId)]);
ts.descs.merge(_core._duck, it->second.descs);
modified = true;
}
}
// If the output NIT was modified, increment its version and replace it in the packetizer.
if (modified) {
_core._output_nit.version = (_core._output_nit.version + 1) & SVERSION_MASK;
_core._nit_pzer.removeSections(TID_NIT_ACT);
_core._nit_pzer.addTable(_core._duck, _core._output_nit);
}
}
//----------------------------------------------------------------------------
// Receive an SDT from an input stream.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::handleSDT(const SDT& sdt)
{
bool modified = false;
// Add all services from input SDT into output SDT.
for (auto it = sdt.services.begin(); it != sdt.services.end(); ++it) {
// Origin of the service.
const uint16_t service_id = it->first;
Origin& origin(_core._service_origin[service_id]);
if (!Contains(_core._output_sdt.services, service_id)) {
// New service found.
_core._log.verbose(u"adding service 0x%X (%<d) from input #%d in SDT", {service_id, _plugin_index});
_core._output_sdt.services[service_id] = it->second;
origin.plugin_index = _plugin_index;
modified = true;
}
else if (origin.plugin_index == _plugin_index) {
// Already found in same input, maybe same service description but modify anywat.
_core._output_sdt.services[service_id] = it->second;
modified = true;
}
else if (!_core._opt.ignoreConflicts) {
_core._log.error(u"service conflict, service 0x%X (%<d) exists in input #%d and #%d, aborting", {service_id, origin.plugin_index, _plugin_index});
_core.stop();
return;
}
else if (!origin.conflict_detected) {
// Conflicts are ignored, this conflict is detected for the first time.
origin.conflict_detected = true;
_core._log.warning(u"service conflict, service 0x%X (%<d) exists in input #%d and #%d, ignoring", {service_id, origin.plugin_index, _plugin_index});
}
}
// Check if previous services from this input have disappeared.
for (auto it = _core._output_sdt.services.begin(); it != _core._output_sdt.services.end(); ) {
const uint16_t service_id = it->first;
if (_core._service_origin[service_id].plugin_index == _plugin_index && !Contains(sdt.services, service_id)) {
// This service was in the output SDT and identified as coming from this input plugin.
// However, it is no longer in the SDT of this input.
_core._log.verbose(u"service 0x%X (%<d) disappeared from input #%d, removing from SDT", {service_id, _plugin_index});
it = _core._output_sdt.services.erase(it);
modified = true;
}
else {
++it;
}
}
// If the output SDT was modified, increment its version and replace it in the packetizer.
if (modified) {
_core._output_sdt.version = (_core._output_sdt.version + 1) & SVERSION_MASK;
_core._sdt_bat_pzer.removeSections(TID_SDT_ACT);
_core._sdt_bat_pzer.addTable(_core._duck, _core._output_sdt);
}
}
//----------------------------------------------------------------------------
// Receive an EIT section from an input stream.
//----------------------------------------------------------------------------
void ts::tsmux::Core::Input::handleSection(SectionDemux& demux, const Section& section)
{
const TID tid = section.tableId();
const bool is_eit = EIT::IsEIT(tid) && section.sourcePID() == PID_EIT;
const bool is_actual = EIT::IsActual(tid);
if (is_eit && _core._opt.eitScope != TableScope::NONE && (is_actual || _core._opt.eitScope == TableScope::ALL)) {
// Create a copy of the EIT section object (shared section data).
const SectionPtr sp(new Section(section, ShareMode::SHARE));
CheckNonNull(sp.pointer());
// If this is an EIT-Actual, patch the EIT with output TS id.
if (is_actual && sp->payloadSize() >= 4) {
sp->setUInt16(0, _core._opt.outputTSId, false);
sp->setUInt16(2, _core._opt.outputNetwId, true);
}
// Enqueue the EIT section.
_core._eits.push_back(sp);
// Check that there is no accumulation of late EIT's.
if (_core._eits.size() > _core._max_eits) {
_core._log.warning(u"too many input EIT, not enough space in output EIT PID, dropping some EIT sections");
// Drop oldest EIT's.
while (_core._eits.size() > _core._max_eits) {
_core._eits.pop_front();
}
}
}
}
| [
"thierry@lelegard.fr"
] | thierry@lelegard.fr |
cb215a02f766a990744316e8101612792c45b57d | 91bb8082c01d7b1aafd4e66a03b544f52696a224 | /Discrete/kvs.cpp | ca1f9074c17b1155927ac572ab677df8b2764611 | [] | no_license | SabbirPulok/C--Programming | fe114eaf65e854819107eb4a5ca790ec4f4169d6 | 057995957ecc8e42091f659659a640658250aa68 | refs/heads/main | 2022-12-30T15:24:28.006129 | 2020-10-20T15:36:55 | 2020-10-20T15:36:55 | 305,754,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | cpp | #include<bits/stdc++.h>
using namespace std;
#define MAXN 1025
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x)
}
vector<int>tree[MAXN];
vector<int>centroidTree[MAXN];
bool centroidMarked[MAXN;
void addEdge(int u, int v)
{
tree[u].push_back(v);
tree[v].push_back(u);
}
void DFS(int src, bool visited[],int substree_size[], int* n)
{
visited[src]= true;
*n += 1;
subtree_size[src]=1;
vector<int>::iterator it;
for(it=tree[src].begin();it!=tree[src])
}
int main()
{
}
| [
"sabbir.pulak@gmail.com"
] | sabbir.pulak@gmail.com |
682c4f926a9831e21ac7821fd4765f28f834c637 | cc0405f2f3612e4060991947967d5db50346e053 | /image_resample/image_resample.cpp | 4e9daa4ab816b6bd51015d5508adc7dec9a55664 | [
"Unlicense"
] | permissive | fungosforks/reenigne | eee719fe09986a763b0839ad765215497a2b6ca4 | 1ae8c8cc969e720d00fea41857b47197ba3b834c | refs/heads/master | 2020-12-14T18:34:15.571253 | 2015-04-10T14:35:08 | 2015-04-10T14:35:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,981 | cpp | #include "alfe/main.h"
#include "alfe/file.h"
#include "alfe/colour_space.h"
#include <stdio.h>
#include "alfe/bitmap.h"
#include "alfe/bitmap_png.h"
#include "alfe/config_file.h"
#include "alfe/minimum_maximum.h"
class Program : public ProgramBase
{
public:
void run()
{
if (_arguments.count() == 1) {
printf("Usage: image_resample <config file path>\n");
return;
}
ConfigFile config;
List<StructuredType::Member> vectorMembers;
vectorMembers.add(StructuredType::Member(String("x"), Type::integer));
vectorMembers.add(StructuredType::Member(String("y"), Type::integer));
StructuredType vectorType(String("Vector"), vectorMembers);
config.addType(vectorType);
config.addOption("inputPicture", Type::string);
config.addOption("outputSize", vectorType);
config.addOption("subpixels", Type::boolean);
config.addOption("tripleResolution", Type::boolean);
config.addOption("outputPicture", Type::string);
config.load(_arguments[1]);
PNGFileFormat png;
Bitmap<SRGB> input =
png.load(File(config.get<String>("inputPicture")));
//input.save(RawFileFormat(Vector(0, 0)), File("../../input.raw"));
Bitmap<Vector3<float> > linearInput(input.size());
input.convert(linearInput, ConvertSRGBToLinear());
Array<Any> sizeArray = config.get<List<Any> >("outputSize");
Vector size(sizeArray[0].value<int>(), sizeArray[1].value<int>());
Bitmap<Vector3<float> > linearOutput(size);
if (config.get<bool>("subpixels"))
linearInput.subPixelResample(linearOutput,
config.get<bool>("tripleResolution"));
else
linearInput.resample(linearOutput);
Bitmap<SRGB> output(linearOutput.size());
linearOutput.convert(output, ConvertLinearToSRGB());
output.save(png, File(config.get<String>("outputPicture")));
}
private:
class ConvertSRGBToLinear
{
public:
ConvertSRGBToLinear() : _c(ColourSpace::rgb()) { }
Vector3<float> convert(SRGB c)
{
//return Vector3<float>(pow(c.x/255.0, 1/2.2), pow(c.y/255.0, 1/2.2), pow(c.z/255.0, 1/2.2));
return Vector3Cast<float>(_c.fromSrgb(c));
}
private:
ColourSpace _c;
};
class ConvertLinearToSRGB
{
public:
ConvertLinearToSRGB() : _c(ColourSpace::rgb()) { }
SRGB convert(Vector3<float> c)
{
return _c.toSrgb24(c);
//return SRGB(
// static_cast<Byte>(clamp(0, static_cast<int>(pow(static_cast<double>(c.x), 2.2)*255.0), 255)),
// static_cast<Byte>(clamp(0, static_cast<int>(pow(static_cast<double>(c.y), 2.2)*255.0), 255)),
// static_cast<Byte>(clamp(0, static_cast<int>(pow(static_cast<double>(c.z), 2.2)*255.0), 255)));
}
private:
ColourSpace _c;
};
};
| [
"andrew@reenigne.org"
] | andrew@reenigne.org |
6f9d1b6210a3d573017a0f0dd354ca120981ab16 | d186edadb6ee1a74a8c63936aef633a36a7c0763 | /Task3/Task3/Richest.cpp | 466fa7dc6ca72ba1c3cb2f7464ed70361bfd26c2 | [] | no_license | Dimentr01/Task___3 | ca3ffe2decef7d31b0a1fee8238101bd352e86c1 | 6dc5237652e242ecef0d3c5e545d7bcf723a96ee | refs/heads/master | 2022-07-03T05:28:40.915892 | 2020-05-06T11:17:42 | 2020-05-06T11:17:42 | 261,724,707 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 395 | cpp | #include <iostream>
#include "Robber.h"
#include "Helper.h"
void Richest(robbers Robber[], int &lifes)
{
int k = 0;
int richest = Robber[0].wealth;
for (int i = 0; i < lifes; i++)
if ((Robber[i].wealth > richest) and (Robber[i].life == 1))
{
richest = Robber[i].wealth;
k = i;
}
PrintRobber(Robber[k]);
std::cout << "Богач найден" << std::endl << std::endl;
}
| [
"dima.zaharcev@mail.ru"
] | dima.zaharcev@mail.ru |
6aa04634cd47b8767d7e6b29dc2160cfdad345e1 | 61f308cf7c285d581aaa663fe4d108acfaf64cf1 | /p3/src/org/cracs/stheno/services/rpc/RPCTestObjectClient.cpp | a3eaf5f52b6a1d10142794c1625b698e354056b4 | [
"Apache-2.0"
] | permissive | rolandomar/stheno | d382352be3cf8b6001e761e32a526df709a06fe3 | 6b41f56f25be1e7d56c8be4973203bf943e4f041 | refs/heads/master | 2016-09-01T22:30:36.873669 | 2012-12-06T18:42:52 | 2012-12-06T18:42:52 | 6,522,876 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | cpp | /*
* Copyright 2012 Rolando Martins, CRACS & INESC-TEC, DCC/FCUP
*
* 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.
*
*/
/*
* File: RPCTestObjectClient.cpp
* Author: rmartins
*
* Created on January 22, 2011, 8:20 PM
*/
#include "RPCTestObjectClient.h"
RPCTestObjectClient::RPCTestObjectClient(RPCServiceClient* rpcRPCServiceClient):
m_rpcRPCServiceClient(rpcRPCServiceClient),m_oid(new UUID("BFDD340C31ECDD49CD7E694AF4AFF426")),m_counter(0)
{
}
RPCTestObjectClient::~RPCTestObjectClient() {
}
| [
"rolando.martins@gmail.com"
] | rolando.martins@gmail.com |
0fe258aa013df0804c54a1116dc9ea236d4ffa99 | 6e4a96db328ae318af1c42435083076cbac594c5 | /openframeworks/addon/ofxCv/ofxCv/RunningBackground.h | 1dba8d71d2d91f9e3f78430b5889e53540ab5dac | [] | no_license | echa/libopenframeworks | 03c74498fe6c895c8530d435743296cc9dd65efa | 075bf0060137839b71b0e284d90948a02ba3e3c5 | refs/heads/master | 2021-01-19T05:01:20.437181 | 2013-03-14T15:10:04 | 2013-03-14T15:10:04 | 6,373,233 | 4 | 0 | null | 2013-06-12T21:21:52 | 2012-10-24T16:04:24 | C++ | UTF-8 | C++ | false | false | 2,685 | h | /*
this class is designed to handle the common task of detecting foreground
objects in a complex scene by subtracting a known background. a good summary
of different background subtraction techniques is available at:
http://www-staff.it.uts.edu.au/~massimo/BackgroundSubtractionReview-Piccardi.pdf
this class only implements the running average technique. this technique is
also described in the opencv 2 cookbook in chapter 10, under "extracting the
foreground objects in video". the example ignores foreground pixels during
accumulation. this class uses all pixels by default, but can be set to ignore
foreground pixels by calling setIgnoreForeground(true).
learningRate determines how quickly the background is learned. a smaller value
means the background takes longer to learn. default the learningRate is .0001
and you can use setLearningRate() to change this.
guessing a learningRate can be hard, because it's related to the threshold and
your camera framerate. setLearningTime() will let you set the learningRate
in terms of frames. larger values meaning the background takes longer to learn.
a learning time of 900 means a 30 fps camera would take 30 seconds before
a foreground object could leave a "shadow", or "trace" in the background
that appears as foreground after thresholding. in practice, it will only take
this amount of time exactly when the background is completely black and the
foreground is completely white. most of the time it will take longer than
learningTime, so it's safe to under-shoot.
to do:
- use hsb space, or sb space for differencing (like ContourFinder)
*/
#pragma once
#include "ofxCv/Utilities.h"
namespace ofxCv {
class RunningBackground {
public:
enum DifferenceMode {ABSDIFF, BRIGHTER, DARKER};
RunningBackground();
template <class F, class T>
void update(F& frame, T& thresholded) {
ofxCv::imitate(thresholded, frame, CV_8UC1);
cv::Mat frameMat = toCv(frame);
cv::Mat thresholdedMat = toCv(thresholded);
update(frameMat, thresholdedMat);
}
void update(cv::Mat frame, cv::Mat& thresholded);
cv::Mat& getBackground();
cv::Mat& getForeground();
float getPresence() const;
void setThresholdValue(unsigned int thresholdValue);
void setLearningRate(double learningRate);
void setLearningTime(double learningTime);
void setIgnoreForeground(bool ignoreForeground);
void setDifferenceMode(DifferenceMode differenceMode);
void reset();
protected:
cv::Mat accumulator, background, foreground, foregroundGray;
double learningRate, learningTime;
unsigned int thresholdValue;
bool useLearningTime, needToReset, ignoreForeground;
DifferenceMode differenceMode;
};
}
| [
"micuat@aim.com"
] | micuat@aim.com |
acb9426e55be05dca103436e2c2ca3de86e9c04b | d173ec70e3c5fe7f5c4d7a2b7fdf90736c3853c1 | /UVA/11057 Solution.cpp | aa372a0ff4da9b2e283205440ef4615b164c8254 | [] | no_license | thaherkhan/Online_Judge | c4122d659b874f1a343afdcfb5e2f18f820dc866 | 2de9cba9534cb6bc98ecbed2a576df3e8474e58c | refs/heads/main | 2023-02-27T00:52:00.902164 | 2021-01-23T21:18:48 | 2021-01-23T21:18:48 | 332,282,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
ll a[100000];
int main()
{
ll n,d1,d2;
while(cin>>n)
{
ll mx=0,mn=0;
d2=100000000;
for(ll i=0; i<n; i++)
cin>>a[i];
ll q;
cin>>q;
for(ll i=0; i<n; i++)
{
for(ll j=i+1; j<n; j++)
{
if(a[i]+a[j]==q)
{
d1=abs(a[i]-a[j]);
if(d1<d2)
{
d2=d1;
mx=max(a[i],a[j]);
mn=min(a[i],a[j]);
}
}
}
}
cout<<"Peter should buy books whose prices are "<<mn<<" and "<<mx<<"."<<endl<<endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
35554ccd6a80f9f278462368a607ca436403daf3 | 3d9c6163656436abed072a7b56534ecae1ca2f66 | /Sources/x10/xla_tensor/ops/binary_cross_entropy.h | 9b9397b6e462658e1c938f0c4746c8cdf67cec81 | [
"Apache-2.0"
] | permissive | kongzii/swift-apis | 5c807e12e443bf032cbf78f8cbbe0d75fed14082 | cd2236fb51c20d3c9bbf1b37524cf9bc2ed04ce6 | refs/heads/master | 2020-11-28T20:17:45.644349 | 2020-10-05T18:00:51 | 2020-10-05T18:00:51 | 220,660,173 | 0 | 0 | Apache-2.0 | 2019-11-09T15:14:09 | 2019-11-09T15:14:08 | null | UTF-8 | C++ | false | false | 1,358 | h | /*
* Copyright 2020 TensorFlow Authors
*
* 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.
*/
#pragma once
#include "absl/types/optional.h"
#include "tensorflow/compiler/tf2xla/xla_tensor/ir.h"
#include "tensorflow/compiler/tf2xla/xla_tensor/reduction.h"
namespace swift_xla {
namespace ir {
namespace ops {
class BinaryCrossEntropy : public Node {
public:
BinaryCrossEntropy(const Value& logits, const Value& labels,
const absl::optional<Value>& weight,
ReductionMode reduction);
std::string ToString() const override;
NodePtr Clone(OpList operands) const override;
XlaOpVector Lower(LoweringContext* loctx) const override;
ReductionMode reduction() const { return reduction_; }
private:
ReductionMode reduction_;
};
} // namespace ops
} // namespace ir
} // namespace swift_xla
| [
"noreply@github.com"
] | noreply@github.com |
fd651ea1881c95f6b329207a1916195ec28f9696 | 3fd4598f5617cefb3c60ec79371ff6dbaa2d0105 | /src/track.cc | 24975b33847b80e11e75dae6c3e83d92a92235fb | [] | no_license | lteris/videotrackingdemo | 3a0c0632b92967744723049af9c7a42b6830f975 | 10b534126af5681569936221fd2409c541ab54d0 | refs/heads/master | 2021-01-13T01:26:27.801940 | 2009-06-15T16:07:47 | 2009-06-15T16:07:47 | 40,610,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,284 | cc | #include "track.h"
using namespace track;
#define KWD_BUFFER_IN "BUFFER_IN"
#define KWD_BUFFER_OUT "BUFFER_OUT"
#define KWD_QUALITY_OUT "JPEG_QUALITY_OUT"
#define KWD_BUFFER_DETECTION "BUFFER_DETECTION"
#define KWD_QUALITY_DETECTION "JPEG_QUALITY_DETECTION"
#define KWD_DISPLAY_DETECTION "DISPLAY_DETECTION"
#define KWD_TARGET "GNGT_TARGET"
#define KWD_AGE "GNGT_EDGE_AGE"
#define KWD_LEARNING_RATES "GNGT_LEARNING_RATES"
#define KWD_VARIANCE "GNGT_MAX_VARIANCE"
#define KWD_LENGTH "GNGT_MAX_LENGTH"
#define KWD_EPOCHS "GNGT_EPOCHS_PER_FRAME"
#define KWD_PEN_THICKNESS "PEN_THICKNESS"
#define KWD_MORPH "MORPHOMATH"
/*-----------------------------------------------------------------------------------------*/
/* define the global vars in track:: */
/*-----------------------------------------------------------------------------------------*/
std::string track::param_buffer_in_hostname;
std::string track::param_buffer_in_resource;
std::string track::param_buffer_in_entity;
int track::param_buffer_in_port;
bool track::param_buffer_in_jpg;
std::string track::param_buffer_out_hostname;
std::string track::param_buffer_out_resource;
std::string track::param_buffer_out_entity;
int track::param_buffer_out_port;
bool track::param_buffer_out_jpg;
int track::param_out_jpeg_quality;
std::string track::param_buffer_detection_hostname;
std::string track::param_buffer_detection_resource;
std::string track::param_buffer_detection_entity;
int track::param_buffer_detection_port;
bool track::param_buffer_detection_jpg;
int track::param_detection_jpeg_quality;
bool track::param_display_detection;
double track::param_gngt_target;
double track::param_gngt_first_learning_rate;
double track::param_gngt_second_learning_rate;
int track::param_gngt_edge_age_max;
double track::param_gngt_variance_max;
double track::param_gngt_length_max;
int track::param_nb_epochs_per_frame;
int track::param_pen_thickness;
bool track::param_morph;
int track::param_morph_radius;
ServerConnection* track::serverConn;
/*-----------------------------------------------------------------------------------------*/
/* set default parameters */
/*-----------------------------------------------------------------------------------------*/
void track::ParameterParser::loadDefaultParameters() {
param_buffer_in_hostname = "localhost";
param_buffer_in_resource = "JPEG-RESOURCE";
param_buffer_in_entity = "video-buf";
param_buffer_in_port = 20000;
param_buffer_in_jpg = true;
param_buffer_out_hostname = "localhost";
param_buffer_out_resource = "JPEG-RESOURCE";
param_buffer_out_entity = "display-buf1";
param_buffer_out_port = 20000;
param_buffer_out_jpg = true;
param_out_jpeg_quality = 70;
param_buffer_detection_hostname = "localhost";
param_buffer_detection_resource = "JPEG-RESOURCE";
param_buffer_detection_entity = "display-buf2";
param_buffer_detection_port = 20000;
param_buffer_detection_jpg = true;
param_detection_jpeg_quality = 70;
param_display_detection = false;
param_gngt_target = 30;
param_gngt_first_learning_rate = .05;
param_gngt_second_learning_rate = .005;
param_gngt_edge_age_max = 20;
param_gngt_variance_max = 50;
param_gngt_length_max = 20;
param_nb_epochs_per_frame = 10;
param_pen_thickness = 3;
param_morph = false;
param_morph_radius = 3;
}
track::ParameterParser::ParameterParser(void) {
loadDefaultParameters();
serverConn = new ServerConnection();
}
/*-----------------------------------------------------------------------------------------*/
/* get the parameters from the input file */
/*-----------------------------------------------------------------------------------------*/
track::ParameterParser::ParameterParser(const std::string& filename) {
std::ifstream file;
std::string comment;
std::string kwd;
std::string mode;
char first;
loadDefaultParameters();
file.open(filename.c_str());
if (!file) {
std::cerr << "Cannot open file \"" << filename
<< "\" for loading configuration." << std::endl;
::exit(1);
}
file >> std::ws;
file.get(first);
while (!file.eof()) {
file.putback(first);
if (first == '#')
std::getline(file, comment, '\n');
else {
file >> kwd;
if (kwd == KWD_BUFFER_IN) {
file >> param_buffer_in_hostname >> param_buffer_in_port
>> param_buffer_in_resource >> param_buffer_in_entity
>> mode;
param_buffer_in_jpg = true || mode == "jpg" || mode == "jpeg"
|| mode == "JPG" || mode == "JPEG";
} else if (kwd == KWD_BUFFER_OUT) {
file >> param_buffer_out_hostname >> param_buffer_out_port
>> param_buffer_out_resource >> param_buffer_out_entity
>> mode;
param_buffer_out_jpg = true || mode == "jpg" || mode == "jpeg"
|| mode == "JPG" || mode == "JPEG";
} else if (kwd == KWD_QUALITY_OUT)
file >> param_out_jpeg_quality;
else if (kwd == KWD_BUFFER_DETECTION) {
file >> param_buffer_detection_hostname
>> param_buffer_detection_port
>> param_buffer_detection_resource
>> param_buffer_detection_entity >> mode;
param_buffer_detection_jpg = true || mode == "jpg" || mode
== "jpeg" || mode == "JPG" || mode == "JPEG";
} else if (kwd == KWD_QUALITY_DETECTION)
file >> param_detection_jpeg_quality;
else if (kwd == KWD_DISPLAY_DETECTION)
param_display_detection = true;
else if (kwd == KWD_TARGET)
file >> param_gngt_target;
else if (kwd == KWD_AGE)
file >> param_gngt_edge_age_max;
else if (kwd == KWD_LEARNING_RATES)
file >> param_gngt_first_learning_rate
>> param_gngt_second_learning_rate;
else if (kwd == KWD_VARIANCE)
file >> param_gngt_variance_max;
else if (kwd == KWD_LENGTH)
file >> param_gngt_length_max;
else if (kwd == KWD_EPOCHS)
file >> param_nb_epochs_per_frame;
else if (kwd == KWD_PEN_THICKNESS) {
file >> param_pen_thickness;
}
else if (kwd == KWD_MORPH) {
param_morph = true;
file >> param_morph_radius;
} else {
std::cerr << "Warning : Keyword \"" << kwd
<< "\" is ignored, line skipped." << std::endl;
std::getline(file, comment, '\n');
}
}
file >> std::ws;
file.get(first);
}
file.close();
serverConn = new ServerConnection();
}
/*-----------------------------------------------------------------------------------------*/
/* save current parameters to file */
/*-----------------------------------------------------------------------------------------*/
void track::ParameterParser::saveParameters(const std::string& filename) {
std::ofstream file;
file.open(filename.c_str());
if (!file) {
std::cerr << "Cannot open file \"" << filename
<< "\" for saving configuration." << std::endl;
::exit(1);
}
file << "######################################" << std::endl
<< "# #" << std::endl
<< "# Parameters for gngt-video tracking #" << std::endl
<< "# #" << std::endl
<< "######################################" << std::endl
<< std::endl
<< "# Input and output. Order is host, port, resource, entity, mode (JPEG | IMG)."
<< std::endl << KWD_BUFFER_IN << ' ' << param_buffer_in_hostname
<< ' ' << param_buffer_in_port << ' ' << param_buffer_in_resource
<< ' ' << param_buffer_in_entity << ' ' << Mode(param_buffer_in_jpg) << std::endl << KWD_BUFFER_OUT << ' '
<< param_buffer_out_hostname << ' ' << param_buffer_out_port << ' '
<< param_buffer_out_resource << ' ' << param_buffer_out_entity
<< ' ' << Mode(param_buffer_out_jpg) << std::endl << std::endl
<< "# Idf output is compressed, this is its Jpeg quality (1--100)."
<< std::endl << KWD_QUALITY_OUT << ' ' << param_out_jpeg_quality
<< std::endl << std::endl
<< "# Comment out the following to disable the sending"
<< std::endl << "# of object detection result to server."
<< std::endl;
if (!param_display_detection)
file << "# ";
file << KWD_DISPLAY_DETECTION << std::endl
<< "# If enabled, this describe the sending of detection to the server."
<< std::endl << KWD_BUFFER_DETECTION << ' '
<< param_buffer_detection_hostname << ' '
<< param_buffer_detection_port << ' '
<< param_buffer_detection_resource << ' '
<< param_buffer_detection_entity << ' ' << Mode(
param_buffer_detection_jpg) << std::endl << KWD_QUALITY_DETECTION
<< ' ' << param_detection_jpeg_quality << std::endl << std::endl
<< "# GNG-T Parameters : target, maximum edge age," << std::endl
<< "# winner and second learning rates." << std::endl << KWD_TARGET
<< ' ' << param_gngt_target << std::endl << KWD_AGE << ' '
<< param_gngt_edge_age_max << std::endl << KWD_LEARNING_RATES
<< ' ' << param_gngt_first_learning_rate << ' '
<< param_gngt_second_learning_rate << std::endl
<< "# Number of GNG-T epochs per frame (a supplementary one will be actually used)."
<< std::endl << KWD_EPOCHS << ' ' << param_nb_epochs_per_frame
<< std::endl << "# Maximal variance for a non noisy node."
<< std::endl << KWD_VARIANCE << ' ' << param_gngt_variance_max
<< std::endl << "# Maximal edge length inside a polygon."
<< std::endl << KWD_LENGTH << ' ' << param_gngt_length_max
<< std::endl << std::endl << "# Drawing paremeters" << std::endl
<< KWD_PEN_THICKNESS << ' ' << param_pen_thickness << std::endl
<< std::endl
<< "# Uncomment the following line to enable morpho-matematical"
<< std::endl << "# detection cleaning. Number is the mask radius."
<< std::endl;
if (!param_morph)
file << "# ";
file << KWD_MORPH << ' ' << param_morph_radius << std::endl << std::endl
<< std::endl;
file.close();
}
/*-----------------------------------------------------------------------------------------*/
/* connect to server using the parameters in the track namespace */
/*-----------------------------------------------------------------------------------------*/
track::ServerConnection::ServerConnection() {
this->jpgClientDetection = NULL;
this->jpgClientIn = NULL;
this->jpgClientOut = NULL;
this->rawClientDetection = NULL;
this->rawClientIn = NULL;
this->rawClientOut = NULL;
std::cout << " --> " << param_buffer_in_entity << '('
<< param_buffer_in_resource << ")@" << param_buffer_in_hostname
<< ':' << param_buffer_in_port << std::endl;
if (param_buffer_in_jpg) {
jpgClientIn = new bkbd::Repository<bkbd::JPEG>::Client(
param_buffer_in_resource);
if (!jpgClientIn->Connect(param_buffer_in_hostname,
param_buffer_in_port)) {
std::cerr << "Cannot connect to \"" << param_buffer_in_resource
<< "\"@" << param_buffer_in_hostname << ':'
<< param_buffer_in_port << std::endl;
::exit(1);
}
} else {
rawClientIn = new bkbd::Repository<bkbd::Image>::Client(
param_buffer_in_resource);
if (!rawClientIn->Connect(param_buffer_in_hostname,
param_buffer_in_port)) {
std::cerr << "Cannot connect to \"" << param_buffer_in_resource
<< "\"@" << param_buffer_in_hostname << ':'
<< param_buffer_in_port << std::endl;
::exit(1);
}
}
std::cout << " <-- " << param_buffer_out_entity << '('
<< param_buffer_out_resource << ")@" << param_buffer_out_hostname
<< ':' << param_buffer_out_port << std::endl;
if (param_buffer_out_jpg) {
jpgClientOut = new bkbd::Repository<bkbd::JPEG>::Client(
param_buffer_out_resource);
if (!jpgClientOut->Connect(param_buffer_out_hostname,
param_buffer_out_port)) {
std::cerr << "Cannot connect to \"" << param_buffer_out_resource
<< "\"@" << param_buffer_out_hostname << ':'
<< param_buffer_out_port << std::endl;
::exit(1);
}
} else {
rawClientOut = new bkbd::Repository<bkbd::Image>::Client(
param_buffer_out_resource);
if (!rawClientOut->Connect(param_buffer_out_hostname,
param_buffer_out_port)) {
std::cerr << "Cannot connect to \"" << param_buffer_out_resource
<< "\"@" << param_buffer_out_hostname << ':'
<< param_buffer_out_port << std::endl;
::exit(1);
}
}
if (param_display_detection) {
std::cout << " <-- " << param_buffer_detection_entity << '('
<< param_buffer_detection_resource << ")@"
<< param_buffer_detection_hostname << ':'
<< param_buffer_detection_port << std::endl;
if (param_buffer_detection_jpg) {
jpgClientDetection = new bkbd::Repository<bkbd::JPEG>::Client(
param_buffer_detection_resource);
if (!jpgClientDetection->Connect(param_buffer_detection_hostname,
param_buffer_detection_port)) {
std::cerr << "Cannot connect to \""
<< param_buffer_detection_resource << "\"@"
<< param_buffer_detection_hostname << ':'
<< param_buffer_detection_port << std::endl;
::exit(1);
}
} else {
rawClientDetection = new bkbd::Repository<bkbd::Image>::Client(
param_buffer_detection_resource);
if (!rawClientDetection->Connect(param_buffer_detection_hostname,
param_buffer_detection_port)) {
std::cerr << "Cannot connect to \""
<< param_buffer_detection_resource << "\"@"
<< param_buffer_detection_hostname << ':'
<< param_buffer_detection_port << std::endl;
::exit(1);
}
}
} else
std::cout << " <-- detection display disabled." << std::endl;
}
track::ServerConnection::~ServerConnection() {
//TODO close connection
}
/*-----------------------------------------------------------------------------------------*/
/* retrieve an image from the server */
/*-----------------------------------------------------------------------------------------*/
void track::ServerConnection::getImage(bkbd::Image* frame) {
int w, h, d;
frame->setAllocationPolicy(bkbd::Image::AllocateAutomatic);
if (param_buffer_in_jpg) {
jpgClientIn->get(param_buffer_in_entity, inJpegBuf, timestamp);
decompressor.setInputStream(inJpegBuf.ijpeg());
decompressor.Flush();
decompressor.readHeader(w, h, d);
frame->resize(w, h, (bkbd::Image::Depth) d);
decompressor.readImage(frame->data);
} else
rawClientIn->get(param_buffer_in_entity, *frame, timestamp);
}
/*-----------------------------------------------------------------------------------------*/
/* post image to the server */
/*-----------------------------------------------------------------------------------------*/
void track::ServerConnection::postImg(ImageRGB24& outFrame) {
dest.setAllocationPolicy(bkbd::Image::AllocateNone,
(unsigned char*) (&(*outFrame.begin())));
dest.resize(outFrame._dimension[0], outFrame._dimension[1],
bkbd::Image::RGB24);
if (param_buffer_out_jpg) {
compressor.setOutputStream(outJpegBuf.ojpeg());
compressor.writeImage(dest.width, dest.height, (int) (dest.depth),
dest.data, param_out_jpeg_quality);
jpgClientOut->post(param_buffer_out_entity, outJpegBuf);
} else {
rawClientOut->post(param_buffer_out_entity, dest);
}
}
void track::ServerConnection::postImg(ImageBool& outFrame) {
unsigned char* buf = (unsigned char*) (&(*outFrame.begin()));
for (int i = 0; i < outFrame.size(); i++) {
if (buf[i] == true) {
buf[i] = 0xff;
}
}
dest.setAllocationPolicy(bkbd::Image::AllocateNone,
(unsigned char*) (&(*outFrame.begin())));
dest.resize(outFrame._dimension[0], outFrame._dimension[1],
bkbd::Image::Gray);
dest.data = (unsigned char*) (&(*outFrame.begin()));
if (param_buffer_out_jpg) {
compressor.setOutputStream(outJpegBuf.ojpeg());
compressor.writeImage(dest.width, dest.height, (int) (dest.depth),
dest.data, param_out_jpeg_quality);
jpgClientOut->post(param_buffer_out_entity, outJpegBuf);
} else {
rawClientOut->post(param_buffer_out_entity, dest);
}
}
/*-----------------------------------------------------------------------------------------*/
/* retrieve images from the server */
/*-----------------------------------------------------------------------------------------*/
void track::ImageFeeder_RGB24::operator ()(void* dummy, ImageRGB24*& outFrame) {
track::serverConn->getImage(&buffer);
outFrame->resize(mirage::img::Coordinate(buffer.width, buffer.height),
(mirage::colorspace::RGB_24*) (buffer.data));
}
/*-----------------------------------------------------------------------------------------*/
/* post images to the server */
/*-----------------------------------------------------------------------------------------*/
void track::ImagePoster::operator ()(ImageRGB24* image, void* dummy) {
track::serverConn->postImg(*image);
}
void track::ImagePoster::operator ()(ImageBool* image, void* dummy) {
track::serverConn->postImg(*image);
}
/*-----------------------------------------------------------------------------------------*/
/* obtain grayscale image from bkbd::Image */
/*-----------------------------------------------------------------------------------------*/
void track::ForeGround::convert2Gray(ImageRGB24* inFrame) {
buffer.resize(inFrame->_dimension);
mirage::algo::UnaryOp<ImageRGB24, ImageGRAY8,
mirage::colorspace::RGBToGray<ImageRGB24::value_type,
ImageGray8::value_type> >(*inFrame, buffer);
}
void track::ForeGround::getForeground(ImageBool*& outFrame) {
if (firstImg) {
algo.initForegroundDetection(buffer);
firstImg = false;
}
algo.SigmaDeltaModified(buffer);
algo.getMask(*outFrame);
}
/*-----------------------------------------------------------------------------------------*/
/* get contour from the foreground image */
/*-----------------------------------------------------------------------------------------*/
void track::Morpho_Contour::getContour(ImageBool& outFrame) {
ImageBool::pixel_type pix1, pix2, pix_end;
ImageBool::point_type pos, dimension, offset;
// std::cout<<&buffer << " "<<&outFrame<<" "<<&(*(buffer.begin()))<<" "<< &(*(outFrame.begin()))<< "\n";
outFrame.resize(buffer._dimension);
for (pix1 = buffer.begin(), pix_end = buffer.end(), pix2
= outFrame.begin(); pix1 != pix_end; ++pix1, ++pix2) {
if (*pix1) {
pos = !pix2 + offset(1, 0);
if(!(*pix2 = !(buffer(pos)))) {
pos = !pix2 + offset(0, 1);
if(!(*pix2 = !(buffer(pos)))) {
pos = !pix2 + offset(0, -1);
if(!(*pix2 = !(buffer(pos)))){
pos = !pix2 + offset(-1, 0);
*pix2 = !(buffer(pos));
}
}
}
} else {
*pix2 = false;
}
}
}
void track::Morpho_Contour::morphoMath(ImageBool* inFrame) {
ImageBool::pixel_type pix1, pix2, pix_end;
ImageBool::point_type pos, offset;
bool n, s, e, w;
buffer.resize(inFrame->_dimension);
if (!param_morph) {
for (pix1 = inFrame->begin(), pix_end = inFrame->end(), pix2
= buffer.begin(); pix1 != pix_end; ++pix1, ++pix2) {
if (*pix1) {
pos = !pix2 + offset(1, 0);
w = !((*inFrame)(pos));
pos = !pix2 + offset(-1, 0);
e = !((*inFrame)(pos));
pos = !pix2 + offset(0, 1);
s = !((*inFrame)(pos));
pos = !pix2 + offset(0, -1);
n = !((*inFrame)(pos));
*pix2 = !((n && s) || (e && w));
} else {
*pix2 = false;
}
}
} else {
mirage::morph::Format<ImageBool, ImageBool, 0>::Opening(*inFrame,
element, buffer);
}
}
/*-----------------------------------------------------------------------------------------*/
/* apply gngt on the contour */
/*-----------------------------------------------------------------------------------------*/
void track::GNGT_Draw::feedGNGT(ImageBool& contour) {
ImageBool::pixel_type pix, pix_end;
std::vector<Input>::iterator iter, iter_end;
Input example;
int epoch;
// Getting examples
examples.clear();
for (pix = contour.begin(), pix_end = contour.end(); pix != pix_end; ++pix)
if (*pix) {
example[0] = (!pix)[0];
example[1] = (!pix)[1];
examples.push_back(example);
}
for (epoch = 0; epoch < param_nb_epochs_per_frame; ++epoch) {
iter_end = examples.end();
iter = examples.begin();
std::random_shuffle(iter, iter_end);
algo.OpenEpoch(true);
for (; iter != iter_end; ++iter)
algo.Submit(*iter);
algo.CloseEpoch();
}
iter_end = examples.end();
iter = examples.begin();
std::random_shuffle(iter, iter_end);
algo.OpenEpoch(false);
for (; iter != iter_end; ++iter)
algo.Submit(*iter);
algo.CloseEpoch();
}
void track::GNGT_Draw::labelize() {
GNG_T::Edges::iterator edge_iter, edge_end;
GNG_T::Nodes::iterator node_iter, node_end;
GNG_T::Node *n;
GNG_T::Edge *e;
double length_max;
length_max = param_gngt_length_max * param_gngt_length_max;
for (edge_iter = algo.edges.begin(), edge_end = algo.edges.end(); edge_iter
!= edge_end; ++edge_iter) {
e = *edge_iter;
labelizer.SetValidity(e, Input::d2(e->n1->value.w, e->n2->value.w)
< length_max);
}
for (node_iter = algo.nodes.begin(), node_end = algo.nodes.end(); node_iter
!= node_end; ++node_iter) {
n = *node_iter;
labelizer.SetValidity(n, n->value.e / n->value.n
< param_gngt_variance_max);
}
labelizer.Process(algo);
}
/*-----------------------------------------------------------------------------------------*/
/* draw the graph over the original image */
/*-----------------------------------------------------------------------------------------*/
mirage::colorspace::RGB_24 track::GNGT_Draw::getRandomColor() {
mirage::colorspace::RGB_24 res;
res._red = (mirage::colorspace::RGB_24::value_type) (256.0 * (rand()
/ (RAND_MAX + 1.0)));
res._green = (mirage::colorspace::RGB_24::value_type) (256.0 * (rand()
/ (RAND_MAX + 1.0)));
res._blue = (mirage::colorspace::RGB_24::value_type) (256.0 * (rand()
/ (RAND_MAX + 1.0)));
return res;
}
/* initialize colors */
track::GNGT_Draw::GNGT_Draw() {
pen[0] = pen[1] = param_pen_thickness;
half_pen = pen / 2;
colors[0]._red = 255;
colors[0]._green = 95;
colors[0]._blue = 95;
colors[1]._red = 0;
colors[1]._green = 0;
colors[1]._blue = 255;
colors[2]._red = 0;
colors[2]._green = 255;
colors[2]._blue = 0;
colors[3]._red = 0;
colors[3]._green = 255;
colors[3]._blue = 255;
colors[4]._red = 190;
colors[4]._green = 190;
colors[4]._blue = 255;
colors[5]._red = 255;
colors[5]._green = 0;
colors[5]._blue = 255;
colors[6]._red = 255;
colors[6]._green = 190;
colors[6]._blue = 0;
colors[7]._red = 190;
colors[7]._green = 255;
colors[7]._blue = 0;
colors[8]._red = 255;
colors[8]._green = 190;
colors[8]._blue = 190;
}
void track::GNGT_Draw::draw(ImageRGB24*& result, ImageRGB24& original) {
vq::Labelizer<GNG_T>::Labeling::iterator label_iter, label_end;
vq::Labelizer<GNG_T>::ConnectedComponent* component;
vq::Labelizer<GNG_T>::ConnectedComponent::Edges::iterator edge_iter,
edge_end;
int label;
mirage::img::Line<ImageRGB24> line;
mirage::img::Line<ImageRGB24>::pixel_type lpix, lpix_end;
mirage::img::Coordinate A, B;
GNG_T::Node *n1, *n2;
mirage::colorspace::RGB_24 paint;
mirage::img::Coordinate img_origin, img_size;
result->resize(original._dimension);
*result = original;
mirage::SubFrame<ImageRGB24> dot(*result, pen, pen); // silly pen args
line << (*result);
for (label_iter = labelizer.labeling.begin(), label_end
= labelizer.labeling.end(); label_iter != label_end; ++label_iter) {
label = label_iter->first;
component = label_iter->second;
if (colors.count(label) == 0)
colors[label] = getRandomColor();
paint = colors[label];
for (edge_iter = component->edges.begin(), edge_end
= component->edges.end(); edge_iter != edge_end; ++edge_iter) {
n1 = (*edge_iter)->n1;
n2 = (*edge_iter)->n2;
A((int) (n1->value.w[0] + .5), (int) (n1->value.w[1] + .5));
B((int) (n2->value.w[0] + .5), (int) (n2->value.w[1] + .5));
if ((A[0] != B[0]) || (A[1] != B[1])) {
line(A, B, false, false);
for (lpix = line.begin(), lpix_end = line.end(); lpix
!= lpix_end; ++lpix) {
dot.resize(!lpix - half_pen, pen);
dot = paint;
}
}
}
}
}
| [
"liviu.teris@01713dfc-2fe9-11de-ba44-d58fe8a9ce33"
] | liviu.teris@01713dfc-2fe9-11de-ba44-d58fe8a9ce33 |
fe0a14c022a7840106dffc0073688a341afa8408 | d537cd2fa2e5f77a645f881e01108ea1c9d89e19 | /Game.h | 0ff7fe14f6e6a8726ff9854699ccfce4a8f90703 | [] | no_license | MarcBerneman/Tower-Defense | 10b73a93d22464ee451e97264933078e97f2bdd1 | a8725117a533ecf6ea3c9496e1c4c73323120707 | refs/heads/master | 2020-03-17T23:41:17.121568 | 2018-06-01T01:19:58 | 2018-06-01T01:19:58 | 134,055,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | h | #ifndef GAME_H
#define GAME_H
#include "Enemy.h"
#include <QGraphicsView>
#include <QMouseEvent>
#include "TowerButton.h"
#include "Grid.h"
#include "Inventory.h"
#include "GameHandler.h"
#include "pushButton.h"
#include "Tower.h"
//default values
const int SCREENWIDTH = 800;
const int SCREENHEIGHT = 600;
const int MENUWIDTH = 250;
const int ENEMYTIMER = 10;
const int PROJECTILE_TIMER = 10;
class Game : public QGraphicsView
{
Q_OBJECT
public:
Game();
GameHandler * handler; // handles the rounds, waves, reset, ...
QGraphicsScene * scene;
myPixmapItem * cursor;
QList<Enemy *> ground_enemies;
QList<Enemy *> air_enemies;
QVector<QPointF> ground_path;
QVector<QPointF> air_path;
QVector<Tower *> towers; // to keep track of the towers on the map
Inventory * inventory;
Grid * grid;
TowerButton * build_mode; // selling or building a tower
void start_game();
void setCursor(QString image);
void clearCursor();
QPoint mapToGridRectItem(QPoint pos); // map from view to grid coordinates
// getters
TowerButton *getSellButton() const;
pushButton *getNextWaveButton() const;
pushButton *getNewGameButton() const;
private:
QVector<QPointF> getPath(QString filename); // get path from textfile
pushButton * nextWaveButton;
pushButton * newGameButton;
TowerButton * sellButton;
private slots:
void enemy_killed(Enemy *e);
void enemy_reached_end(Enemy *e);
protected:
void mouseMoveEvent(QMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
};
#endif // GAME_H
| [
"marcus.berneman@gmail.com"
] | marcus.berneman@gmail.com |
cabe2a22a194f64970c7d02d4d0194cb9042a39e | 227762382eabdf753466e218c9b0361d3a1c3b41 | /source/services/posix_service/process.cpp | 315b22e1dce2bd124c259499a3530ecaffddc7f0 | [
"ISC"
] | permissive | aejsmith/kiwi | c9b6835b933c87cd6a099d053cce0db12432f93c | c4a2af6680fcaeb866b52de674fd05fa45740484 | refs/heads/main | 2023-08-16T18:29:25.257616 | 2023-08-09T19:09:42 | 2023-08-09T19:09:42 | 13,698,734 | 17 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 29,198 | cpp | /*
* Copyright (C) 2009-2023 Alex Smith
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, 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.
*/
/**
* @file
* @brief POSIX process class.
*/
#include "posix_service.h"
#include "process_group.h"
#include "process.h"
#include "session.h"
#include <core/log.h>
#include <core/service.h>
#include <core/time.h>
#include <kernel/condition.h>
#include <kernel/file.h>
#include <kernel/process.h>
#include <kernel/status.h>
#include <kernel/time.h>
#include <kiwi/core/token_setter.h>
#include <services/posix_service.h>
#include <services/terminal_service.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
/** Internal signal disposition values. */
enum {
kSignalDisposition_Default = POSIX_SIGNAL_DISPOSITION_DEFAULT,
kSignalDisposition_Ignore = POSIX_SIGNAL_DISPOSITION_IGNORE,
kSignalDisposition_Handler = POSIX_SIGNAL_DISPOSITION_HANDLER,
kSignalDisposition_Terminate = 3,
kSignalDisposition_CoreDump,
kSignalDisposition_Stop,
kSignalDisposition_Continue,
};
Process::Process(Kiwi::Core::Connection connection, Kiwi::Core::Handle handle, pid_t pid) :
m_connection (std::move(connection)),
m_handle (std::move(handle)),
m_id (pid),
m_signalsPending (0),
m_signalMask (0)
{
debug_log("connection received from PID %" PRId32, m_id);
m_deathEvent = g_posixService.eventLoop().addEvent(
m_handle, PROCESS_EVENT_DEATH, 0,
[this] (const object_event_t &) { handleDeathEvent(); });
initConnection();
}
Process::~Process() {}
void Process::initConnection() {
handle_t connHandle = m_connection.handle();
m_hangupEvent = g_posixService.eventLoop().addEvent(
connHandle, CONNECTION_EVENT_HANGUP, 0,
[this] (const object_event_t &) { handleHangupEvent(); });
m_messageEvent = g_posixService.eventLoop().addEvent(
connHandle, CONNECTION_EVENT_MESSAGE, 0,
[this] (const object_event_t &) { handleMessageEvent(); });
}
void Process::reconnect(Kiwi::Core::Connection connection) {
if (m_connection.isValid()) {
if (m_connection.isActive()) {
core_log(CORE_LOG_NOTICE, "ignoring connection from already connected process %" PRId32, m_id);
return;
}
m_connection.close();
}
debug_log("PID %" PRId32 " reconnected", m_id);
m_connection = std::move(connection);
initConnection();
}
void Process::handleDeathEvent() {
debug_log("PID %" PRId32 " died", m_id);
/* This destroys the Process, don't access this after. */
g_posixService.removeProcess(this);
}
void Process::handleHangupEvent() {
debug_log("PID %" PRId32 " hung up connection", m_id);
m_connection.close();
m_hangupEvent.remove();
m_messageEvent.remove();
/* We treat a hangup without the process dying as an exec(). */
status_t ret = kern_process_status(m_handle, nullptr, nullptr);
if (ret == STATUS_STILL_RUNNING) {
/* Across exec, we retain the signal mask, ignored signals, and any
* pending signals. Signals with handlers are reset to their default
* action. */
for (int num = 0; num < NSIG; num++) {
SignalState &signal = m_signals[num];
signal.flags = 0;
if (signal.disposition == kSignalDisposition_Handler)
signal.disposition = kSignalDisposition_Default;
}
updateSignals();
} else {
/* We should handle the death event after and destroy the process. */
}
}
void Process::handleMessageEvent() {
Kiwi::Core::Message message;
status_t ret = m_connection.receive(0, message);
if (ret != STATUS_SUCCESS)
return;
assert(message.type() == Kiwi::Core::Message::kRequest);
Kiwi::Core::Message reply;
uint32_t id = message.id();
switch (id) {
case POSIX_REQUEST_GET_SIGNAL_CONDITION: reply = handleGetSignalCondition(message); break;
case POSIX_REQUEST_GET_PENDING_SIGNAL: reply = handleGetPendingSignal(message); break;
case POSIX_REQUEST_SET_SIGNAL_ACTION: reply = handleSetSignalAction(message); break;
case POSIX_REQUEST_SET_SIGNAL_MASK: reply = handleSetSignalMask(message); break;
case POSIX_REQUEST_KILL: reply = handleKill(message); break;
case POSIX_REQUEST_ALARM: reply = handleAlarm(message); break;
case POSIX_REQUEST_GETPGID: reply = handleGetpgid(message); break;
case POSIX_REQUEST_SETPGID: reply = handleSetpgid(message); break;
case POSIX_REQUEST_GETSID: reply = handleGetsid(message); break;
case POSIX_REQUEST_SETSID: reply = handleSetsid(message); break;
case POSIX_REQUEST_GET_PGRP_SESSION: reply = handleGetPgrpSession(message); break;
case POSIX_REQUEST_SET_SESSION_TERMINAL: reply = handleSetSessionTerminal(message); break;
case POSIX_REQUEST_GET_TERMINAL: reply = handleGetTerminal(message); break;
default:
core_log(
CORE_LOG_NOTICE, "received unrecognised message type %" PRId32 " from client %" PRId32,
id, m_id);
break;
}
if (reply.isValid()) {
ret = m_connection.reply(reply);
if (ret != STATUS_SUCCESS)
core_log(CORE_LOG_WARN, "failed to send reply: %" PRId32, ret);
}
}
static inline bool createReply(Kiwi::Core::Message &reply, const Kiwi::Core::Message &request, size_t size) {
if (!reply.createReply(request, size)) {
core_log(CORE_LOG_WARN, "failed to allocate reply message");
return false;
}
return true;
}
Kiwi::Core::Message Process::handleGetSignalCondition(Kiwi::Core::Message &request) {
status_t ret;
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_get_signal_condition_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_get_signal_condition_t>();
replyData->err = 0;
if (!m_signalCondition.isValid()) {
ret = kern_condition_create(m_signalCondition.attach());
if (ret != STATUS_SUCCESS) {
core_log(CORE_LOG_WARN, "failed to create signal condition: %" PRId32, ret);
replyData->err = ENOMEM;
return reply;
}
}
reply.attachHandle(m_signalCondition);
return reply;
}
Kiwi::Core::Message Process::handleGetPendingSignal(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_get_pending_signal_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_get_pending_signal_t>();
uint32_t deliverable = signalsDeliverable();
if (deliverable) {
int32_t num = __builtin_ffs(deliverable) - 1;
SignalState &signal = m_signals[num];
/* If it's still deliverable here, it should be using a handler.
* Ignored signals should not ever be set in pending, and default
* signals should be handled as soon as they made deliverable. */
assert(signal.disposition == kSignalDisposition_Handler);
memcpy(&replyData->info, &m_signals[num].info, sizeof(replyData->info));
m_signalsPending &= ~(1 << num);
} else {
replyData->info.si_signo = 0;
}
/* This will update the signal condition state . */
updateSignals();
return reply;
}
Kiwi::Core::Message Process::handleSetSignalAction(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_set_signal_action_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_set_signal_action_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_set_signal_action_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_set_signal_action_t>();
if (requestData->num < 1 || requestData->num >= NSIG) {
replyData->err = EINVAL;
return reply;
}
switch (requestData->disposition) {
case kSignalDisposition_Default:
break;
case kSignalDisposition_Ignore:
case kSignalDisposition_Handler:
/* It is not allowed to set these to non-default action. */
if (requestData->num == SIGKILL || requestData->num == SIGSTOP) {
replyData->err = EINVAL;
return reply;
}
break;
default:
replyData->err = EINVAL;
return reply;
}
SignalState &signal = m_signals[requestData->num];
signal.disposition = requestData->disposition;
signal.flags = requestData->flags;
/* If it was pending but now ignored, remove it. */
if (signal.disposition == kSignalDisposition_Ignore) {
m_signalsPending &= ~(1 << requestData->num);
updateSignals();
}
replyData->err = 0;
return reply;
}
Kiwi::Core::Message Process::handleSetSignalMask(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_set_signal_mask_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_set_signal_mask_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_set_signal_mask_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_set_signal_mask_t>();
/* Attempts to mask SIGKILL or SIGSTOP are silently ignored. */
uint32_t mask = requestData->mask;
mask &= (1 << NSIG) - 1;
mask &= ~(1 << SIGKILL);
mask &= ~(1 << SIGSTOP);
if (mask != m_signalMask) {
m_signalMask = mask;
updateSignals();
}
replyData->err = 0;
return reply;
}
/**
* Perform the default action for a signal. Note that this requires privileged
* access to the process, and the service should be running with sufficient
* privilege (PRIV_PROCESS_ADMIN) for this, so it is not necessary to call with
* the sending thread's security context.
*/
static void defaultSignal(handle_t process, int32_t num) {
status_t ret;
uint32_t disposition;
switch (num) {
case SIGHUP:
case SIGINT:
case SIGKILL:
case SIGPIPE:
case SIGALRM:
case SIGTERM:
case SIGUSR1:
case SIGUSR2:
disposition = kSignalDisposition_Terminate;
break;
case SIGQUIT:
case SIGILL:
case SIGTRAP:
case SIGABRT:
case SIGBUS:
case SIGFPE:
case SIGSEGV:
disposition = kSignalDisposition_CoreDump;
break;
case SIGSTOP:
case SIGTSTP:
case SIGTTIN:
case SIGTTOU:
disposition = kSignalDisposition_Stop;
break;
case SIGCONT:
disposition = kSignalDisposition_Continue;
break;
case SIGCHLD:
case SIGURG:
case SIGWINCH:
disposition = kSignalDisposition_Ignore;
break;
default:
core_log(CORE_LOG_ERROR, "unhandled signal %" PRId32, num);
disposition = kSignalDisposition_Ignore;
break;
}
switch (disposition) {
case kSignalDisposition_Terminate:
case kSignalDisposition_CoreDump:
// TODO: Core dump.
ret = kern_process_kill(process, (__POSIX_KILLED_STATUS << 16) | num);
if (ret != STATUS_SUCCESS)
core_log(CORE_LOG_ERROR, "failed to kill process: %" PRId32, ret);
break;
case kSignalDisposition_Stop:
case kSignalDisposition_Continue:
// TODO: Stop/continue.
core_log(CORE_LOG_ERROR, "TODO: signal stop/continue");
break;
default:
/* Ignore. */
break;
}
}
/** Get the set of deliverable signals (pending and unmasked). */
uint32_t Process::signalsDeliverable() const {
return m_signalsPending & ~m_signalMask;
}
/**
* Called when signal state is changed such that we should re-test if we can
* deliver any signals.
*/
void Process::updateSignals() {
bool needHandler = false;
uint32_t deliverable = signalsDeliverable();
while (deliverable) {
int32_t num = __builtin_ffs(deliverable) - 1;
deliverable &= ~(1 << num);
SignalState &signal = m_signals[num];
/* These should not be in the pending set. */
assert(signal.disposition != kSignalDisposition_Ignore);
if (signal.disposition == kSignalDisposition_Default) {
defaultSignal(m_handle, num);
m_signalsPending &= ~(1 << num);
} else if (signal.disposition == kSignalDisposition_Handler) {
/* Removed from pending set by GET_PENDING_SIGNAL. */
needHandler = true;
}
}
if (m_signalCondition.isValid()) {
status_t ret = kern_condition_set(m_signalCondition, needHandler);
if (ret != STATUS_SUCCESS)
core_log(CORE_LOG_ERROR, "failed to set signal condition for PID %" PRId32 ": %" PRId32, m_id, ret);
}
}
void Process::sendSignal(int32_t num, const Process *sender, const security_context_t *senderSecurity) {
SignalState &signal = m_signals[num];
/* Only need to do something if it's not ignored, and not already pending. */
if (signal.disposition != kSignalDisposition_Ignore &&
!(m_signalsPending & (1 << num)))
{
memset(&signal.info, 0, sizeof(signal.info));
signal.info.si_signo = num;
signal.info.si_pid = (sender) ? sender->m_id : 0;
signal.info.si_uid = (sender) ? senderSecurity->uid : 0;
m_signalsPending |= (1 << num);
updateSignals();
}
}
Kiwi::Core::Message Process::handleKill(Kiwi::Core::Message &request) {
status_t ret;
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_kill_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_kill_t>();
replyData->err = 0;
const security_context_t *security = request.security();
if (request.size() != sizeof(posix_request_kill_t) || !security) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_kill_t>();
debug_log("kill(%" PRId32 ", %" PRId32 ") from PID %" PRId32, requestData->pid, requestData->num, m_id);
if (requestData->num < 1 || requestData->num >= NSIG) {
replyData->err = EINVAL;
return reply;
}
auto killProcess = [&] (handle_t handle, pid_t pid) -> bool {
/* Check if we have sufficient privilege to signal the process. The
* kernel's privileged access definition matches the requirement of
* POSIX so use that. */
// TODO: What about saved-setuid?
if (pid != m_id) {
Kiwi::Core::TokenSetter token;
ret = token.set(security);
if (ret != STATUS_SUCCESS) {
core_log(CORE_LOG_WARN, "failed to set security context: %" PRId32, ret);
return false;
}
ret = kern_process_access(handle);
if (ret != STATUS_SUCCESS)
return false;
}
Process *process = g_posixService.findProcess(pid);
if (process) {
process->sendSignal(requestData->num, this, security);
} else {
/* If the process is not known, it has not connected to the service and
* therefore should be treated as having default signal state. */
defaultSignal(handle, requestData->num);
}
return true;
};
if (requestData->pid <= 0) {
/* Killing a process group. */
ProcessGroup *group = nullptr;
if (requestData->pid == 0) {
/* Process group of caller. */
group = g_posixService.findProcessGroupForProcess(m_handle);
} else if (requestData->pid == -1) {
/* Every process for which the calling process has permission to
* send signals, except for process 1 (init). This is currently
* unimplemented. */
replyData->err = ENOSYS;
return reply;
} else {
group = g_posixService.findProcessGroup(-requestData->pid);
if (!group) {
replyData->err = ESRCH;
return reply;
}
}
size_t failed = 0;
size_t succeeded = 0;
group->forEachProcess([&] (handle_t handle, pid_t pid) {
debug_log("kill %d in group %d", pid, group->id());
if (killProcess(handle, pid)) {
succeeded++;
} else {
failed++;
}
});
if (succeeded > 0) {
replyData->err = 0;
} else if (failed > 0) {
replyData->err = EPERM;
} else {
replyData->err = ESRCH;
}
} else {
/* Killing an individual process. */
Kiwi::Core::Handle openedHandle;
handle_t handle;
replyData->err = g_posixService.getProcessHandle(requestData->pid, openedHandle, handle);
if (replyData->err != 0)
return reply;
replyData->err = (killProcess(handle, requestData->pid)) ? 0 : EPERM;
}
return reply;
}
void Process::handleAlarmEvent() {
/* Clear the fired state. */
kern_timer_stop(m_alarmTimer, nullptr);
sendSignal(SIGALRM, nullptr, nullptr);
m_alarmEvent.remove();
m_alarmTimer.close();
}
Kiwi::Core::Message Process::handleAlarm(Kiwi::Core::Message &request) {
status_t ret;
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_alarm_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_alarm_t>();
replyData->err = 0;
replyData->remaining = 0;
if (request.size() != sizeof(posix_request_alarm_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_alarm_t>();
if (m_alarmTimer.isValid()) {
nstime_t remaining = 0;
kern_timer_stop(m_alarmTimer, &remaining);
replyData->remaining = core_nsecs_to_secs(remaining);
}
if (requestData->seconds > 0) {
if (!m_alarmTimer.isValid()) {
ret = kern_timer_create(TIMER_ONESHOT, m_alarmTimer.attach());
if (ret != STATUS_SUCCESS) {
core_log(CORE_LOG_WARN, "failed to create alarm timer: %" PRId32, ret);
replyData->err = EAGAIN;
return reply;
}
m_alarmEvent = g_posixService.eventLoop().addEvent(
m_alarmTimer, TIMER_EVENT, 0,
[this] (const object_event_t &) { handleAlarmEvent(); });
}
nstime_t nsecs = core_secs_to_nsecs(requestData->seconds);
ret = kern_timer_start(m_alarmTimer, nsecs, TIMER_ONESHOT);
if (ret != STATUS_SUCCESS) {
core_log(CORE_LOG_WARN, "failed to start alarm timer: %" PRId32, ret);
replyData->err = EAGAIN;
return reply;
}
} else {
m_alarmEvent.remove();
m_alarmTimer.close();
}
return reply;
}
Kiwi::Core::Message Process::handleGetpgid(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_getpgid_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_getpgid_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_getpgid_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_getpgid_t>();
if (requestData->pid < 0) {
replyData->err = EINVAL;
return reply;
}
pid_t pid = (requestData->pid != 0) ? requestData->pid : m_id;
Kiwi::Core::Handle openedHandle;
handle_t handle;
replyData->err = g_posixService.getProcessHandle(pid, openedHandle, handle);
if (replyData->err != 0)
return reply;
ProcessGroup *group = g_posixService.findProcessGroupForProcess(handle);
replyData->pgid = group->id();
return reply;
}
Kiwi::Core::Message Process::handleSetpgid(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_setpgid_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_setpgid_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_setpgid_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_setpgid_t>();
if (requestData->pid < 0 || requestData->pgid < 0) {
replyData->err = EINVAL;
return reply;
}
pid_t pid = (requestData->pid != 0) ? requestData->pid : m_id;
Kiwi::Core::Handle openedHandle;
handle_t handle;
replyData->err = g_posixService.getProcessHandle(pid, openedHandle, handle);
if (replyData->err != 0)
return reply;
if (pid != m_id) {
// TODO: Allow changing other processes. This is only allowed if the
// target process is a child of the caller and has not execve()'d yet.
// We don't currently have the capability to track this.
// This must also reject children in a different session to the caller.
replyData->err = ENOSYS;
return reply;
}
/* New group must be in the same session as the *calling* process. A process
* can only change the group of child processes in the same session as it,
* so the calling and target process sessions are the same. */
ProcessGroup *currentGroup = g_posixService.findProcessGroupForProcess(handle);
if (currentGroup->session()->id() == pid) {
replyData->err = EPERM;
return reply;
}
pid_t pgid = (requestData->pgid != 0) ? requestData->pgid : pid;
if (pgid != currentGroup->id()) {
ProcessGroup *newGroup = g_posixService.findProcessGroup(pgid);
if (newGroup) {
if (newGroup->session() != currentGroup->session()) {
replyData->err = EPERM;
return reply;
}
newGroup->addProcess(handle);
} else if (pgid == pid) {
newGroup = g_posixService.createProcessGroup(pgid, currentGroup->session(), handle);
if (!newGroup) {
replyData->err = EAGAIN;
return reply;
}
} else {
replyData->err = EPERM;
return reply;
}
currentGroup->removeProcess(handle);
}
return reply;
}
Kiwi::Core::Message Process::handleGetsid(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_getsid_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_getsid_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_getsid_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_getsid_t>();
pid_t pid = (requestData->pid != 0) ? requestData->pid : m_id;
Kiwi::Core::Handle openedHandle;
handle_t handle;
replyData->err = g_posixService.getProcessHandle(pid, openedHandle, handle);
if (replyData->err != 0)
return reply;
ProcessGroup *group = g_posixService.findProcessGroupForProcess(handle);
replyData->sid = group->session()->id();
return reply;
}
Kiwi::Core::Message Process::handleSetsid(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_setsid_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_setsid_t>();
replyData->err = 0;
if (request.size() != 0) {
replyData->err = EINVAL;
return reply;
}
/* Not allowed to create a new session if there's a group with our ID. */
if (g_posixService.findProcessGroup(m_id)) {
replyData->err = EPERM;
return reply;
}
ProcessGroup *currentGroup = g_posixService.findProcessGroupForProcess(m_handle);
Session *session = g_posixService.createSession(m_id);
ProcessGroup *newGroup = g_posixService.createProcessGroup(m_id, session, m_handle);
if (!newGroup) {
/* Group destructor will have destroyed the session. */
replyData->err = EAGAIN;
return reply;
}
currentGroup->removeProcess(m_handle);
replyData->sid = m_id;
return reply;
}
Kiwi::Core::Message Process::handleGetPgrpSession(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_get_pgrp_session_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_get_pgrp_session_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_get_pgrp_session_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_get_pgrp_session_t>();
ProcessGroup *group = g_posixService.findProcessGroup(requestData->pgid);
if (!group) {
replyData->err = ESRCH;
return reply;
}
replyData->sid = group->session()->id();
return reply;
}
bool Process::isTerminalService() {
status_t ret;
/* Only look this up when we need to know, it'd be a waste of time to
* check this each time a process connects. */
if (!m_isTerminalService.has_value()) {
m_isTerminalService = false;
Kiwi::Core::Handle service;
ret = core_service_get_process(TERMINAL_SERVICE_NAME, service.attach());
if (ret == STATUS_SUCCESS) {
process_id_t id;
ret = kern_process_id(service, &id);
if (ret == STATUS_SUCCESS)
m_isTerminalService = id == m_id;
}
}
return *m_isTerminalService;
}
Kiwi::Core::Message Process::handleSetSessionTerminal(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_set_session_terminal_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_set_session_terminal_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_set_session_terminal_t)) {
replyData->err = EINVAL;
return reply;
}
/* This interface is for use by terminal_service only. */
if (!isTerminalService()) {
replyData->err = EPERM;
return reply;
}
auto requestData = request.data<posix_request_set_session_terminal_t>();
/* Native processes shouldn't be trying to set a controlling terminal. */
if (requestData->sid == kDefaultProcessGroupId) {
replyData->err = EINVAL;
return reply;
}
Session *session = g_posixService.findSession(requestData->sid);
if (!session) {
replyData->err = ESRCH;
return reply;
}
session->setTerminal(request.detachHandle());
return reply;
}
Kiwi::Core::Message Process::handleGetTerminal(Kiwi::Core::Message &request) {
Kiwi::Core::Message reply;
if (!createReply(reply, request, sizeof(posix_reply_get_terminal_t)))
return Kiwi::Core::Message();
auto replyData = reply.data<posix_reply_get_terminal_t>();
replyData->err = 0;
if (request.size() != sizeof(posix_request_get_terminal_t)) {
replyData->err = EINVAL;
return reply;
}
auto requestData = request.data<posix_request_get_terminal_t>();
replyData->err = ENXIO;
ProcessGroup *group = g_posixService.findProcessGroupForProcess(m_handle);
if (group) {
Session *session = group->session();
if (session->terminal().isValid()) {
Kiwi::Core::Handle handle;
status_t ret = kern_file_reopen(session->terminal(), requestData->access, requestData->flags, handle.attach());
if (ret != STATUS_SUCCESS) {
replyData->err = EAGAIN;
} else {
replyData->err = 0;
reply.attachHandle(std::move(handle));
}
}
}
return reply;
}
| [
"alex@alex-smith.me.uk"
] | alex@alex-smith.me.uk |
b7550ee5797c802a786113e27302309ad6240a70 | c6f4fe2766815616b37beccf07db82c0da27e6c1 | /SimpleMaterial.h | f50fe9ee3b226d2a89b4ee96ff3a9b27d84044df | [] | no_license | fragoulis/gpm-sem1-spacegame | c600f300046c054f7ab3cbf7193ccaad1503ca09 | 85bdfb5b62e2964588f41d03a295b2431ff9689f | refs/heads/master | 2023-06-09T03:43:53.175249 | 2007-12-13T03:03:30 | 2007-12-13T03:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,061 | h | #pragma once
#include "Material.h"
#include "Color.h"
namespace tlib
{
class OCSimpleMaterial : public IOCMaterial
{
private:
// Ambient color
Color m_Ambient;
// Diffuse color
Color m_Diffuse;
// Emission color
Color m_Emission;
// Specular color
Color m_Specular;
// Specular shininess
float m_fShininess;
public:
/**
* Constructors
*/
OCSimpleMaterial();
/**
* Destructor
*/
virtual ~OCSimpleMaterial() {}
/**
* Returns the unique component ID
*/
const string componentID() const {
return string("simplematerial");
}
/**
* Applies the material
*/
virtual void apply() const;
/**
* Accessor methods for diffuse, ambient and emission
*/
const Color& getAmbient() const { return m_Ambient; }
Color& getAmbient() { return m_Ambient; }
const Color& getDiffuse() const { return m_Diffuse; }
Color& getDiffuse() { return m_Diffuse; }
const Color& getEmission() const { return m_Emission; }
Color& getEmission() { return m_Emission; }
const Color& getSpecualar() const { return m_Specular; }
Color& getSpecualar() { return m_Specular; }
float getShininess() const { return m_fShininess; }
/**
* Assignment methods for diffuse, ambient and emission
*/
void setAmbient( const Color &ambient ) { m_Ambient = ambient; }
void setDiffuse( const Color &diffuse ) { m_Diffuse = diffuse; }
void setEmission( const Color &emission ) { m_Emission = emission; }
void setSpecular( const Color &specular ) { m_Specular = specular; }
void setShininess( float fShininess ) { m_fShininess = fShininess; }
}; // end of OCSimpleMaterial class
} // end of namespace tlib | [
"john.fragkoulis@201bd241-053d-0410-948a-418211174e54"
] | john.fragkoulis@201bd241-053d-0410-948a-418211174e54 |
812651e19dd7f6a17114a1a71d342f2d10f2be27 | 775bf78d7c6dbfcda37366a140d6dcd7900b414f | /pracs/p2/code/representation.cpp | dd6ef578562094d18ac7373a209f2a0559db0891 | [] | no_license | JorgeReus/GeneticAlgorithms | 95ff86ef14da26d3cedbb4ab8861b48822845184 | d4e242e644156ea2d2b19fb27b8c1e8c74203590 | refs/heads/master | 2020-03-26T07:01:23.120368 | 2018-11-15T02:55:31 | 2018-11-15T02:55:31 | 144,632,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,663 | cpp | #include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <locale>
#include <string>
#include <sstream>
#include<iomanip>
#include <bits/stdc++.h>
using namespace std;
const int num_alelo = 10;
void binary_representation() {
int individual[num_alelo];
cout << "\n[";
for (int i = 0; i < num_alelo; i++) {
individual[i] = (rand() % 2);
if (i + 1 == num_alelo) {
cout << individual[i] << "]\n\n";
} else {
cout << individual[i] << ", ";
}
}
}
int xor_c(int a, int b) { return (a == b) ? 0 : 1; }
void gray_representation()
{
int binary[num_alelo];
int gray[num_alelo];
cout << "\n[";
for (int i = 0; i < num_alelo; i++) {
int value = (rand() % 2);
binary[i] = value;
if (i + 1 == num_alelo) {
cout << value << "] => ";
} else {
cout << value << ", ";
}
}
gray[0] = binary[0];
cout << "[";
for (int i = 1; i < num_alelo; i++) {
int value = xor_c(binary[i - 1], binary[i]);
gray[i] = value;
}
for (int i = 0; i < num_alelo; i++) {
if (i + 1 == num_alelo) {
cout << gray[i] << "]\n";
} else {
cout << gray[i] << ", ";
}
}
}
float random_float(float a, float b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
void real_representation() {
float individual[num_alelo];
cout << "\n[";
for (int i = 0; i < num_alelo; i++) {
float value = random_float(1, 10);
individual[i] = value;
if (i + 1 == num_alelo) {
cout << value << "]\n";
} else {
cout << value << ", ";
}
}
}
void integer_representation() {
int individual[num_alelo];
cout << "\n[";
for (int i = 0; i < num_alelo; i++) {
int value = random() % 10;
individual[i] = value;
if (i + 1 == num_alelo) {
cout << value << "]\n";
} else {
cout << value << ", ";
}
}
}
int main(int argc, char *argv[])
{
srand(time(0));
int option = 0;
while(option != 5) {
cout << "Ingrese la opción: " << endl << " 1: Representación Binaria" <<
endl << " 2: Representación Gray" << endl << " 3: Representación real" <<
endl << " 4: Representación entera" << endl << " 5: Salir" << endl;
scanf("%d", &option);
switch(option) {
case 1:
cout << "Representación Binaria" << endl;
binary_representation();
break;
case 2:
cout << "Representación Gray" << endl;
gray_representation();
break;
case 3:
cout << "Representación Real" << endl;
real_representation();
break;
case 4:
cout << "Representación Entera" << endl;
integer_representation();
break;
default:
break;
}
fflush(stdin);
}
return 0;
}
| [
"j-g1996@live.com"
] | j-g1996@live.com |
ecd4a5c3302a41546317b55aba13c43242218971 | 01fb392944ce8f5a731e7e35ff299b162b9d09a4 | /DronengineOG/src/DronengineOG/ObjectHandler.h | 7ea1c94b6bde5810ab1d3f6fa9bed0b0cda4acfd | [] | no_license | PromZona/DronengineOG | c4ed977f2ff84247adb848a9ab5d221f285c2e17 | 96841ab240e3323cc9624bf926ffa0b57f04e4ef | refs/heads/master | 2022-10-21T11:36:56.226432 | 2020-06-09T13:18:15 | 2020-06-09T13:18:15 | 194,309,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | h | #pragma once
#include "Core.h"
#include "Object.h"
namespace DronengineOG
{
class ObjectHandler
{
public:
ObjectHandler();
~ObjectHandler();
static void Update();
static void AddObject(Object* obj);
static void DeleteObject(Object* obj);
private:
static std::vector<DronengineOG::Object*> ObjectsCollection;
};
} | [
"promzona17112000@mail.ru"
] | promzona17112000@mail.ru |
da0737353896a0b5925ec4ac35bb38581447be11 | 29f87adb9d8413e90b364179fe98f95242819d38 | /UMLEditor/PropertyContainer.cpp | 4ac721ff0ad0b158c2552a7555b2330d321238b6 | [
"Unlicense"
] | permissive | pmachapman/Tulip | d05f069c2ec11b900711c1be5a12e0dbe1bb40e1 | 2123145132faff5e0d606af8626007d8e9ffe3a3 | refs/heads/master | 2023-01-29T10:19:01.249474 | 2023-01-17T06:09:23 | 2023-01-17T06:09:23 | 130,920,566 | 0 | 1 | Unlicense | 2023-09-05T19:06:38 | 2018-04-24T22:28:13 | C++ | UTF-8 | C++ | false | false | 10,934 | cpp | /* ==========================================================================
Class : CPropertyContainer
Author : Johan Rosengren, Abstrakt Mekanik AB
Date : 06/06/04
Purpose : "CPropertyContainer" is a container for property objects.
Description : The class contains a "CObArray" holding "CProperty"
instances, as well as access functions for them.
Usage : The class manages memory.
========================================================================
Changes : 8/7 2004 Added SetPropertyValue
========================================================================*/
#include "stdafx.h"
#include "PropertyContainer.h"
#include "../DiagramEditor/Tokenizer.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Construction/destruction
CPropertyContainer::CPropertyContainer()
/* ============================================================
Function : CPropertyContainer::CPropertyContainer
Description : Constructor
Access : Public
Return : void
Parameters : none
Usage :
============================================================*/
{
}
CPropertyContainer::~CPropertyContainer()
/* ============================================================
Function : CPropertyContainer::~CPropertyContainer
Description : Destructor
Access : Public
Return : void
Parameters : none
Usage : Deletes assocuated memory as well.
============================================================*/
{
RemoveAll();
}
void CPropertyContainer::Copy(CPropertyContainer& properties)
/* ============================================================
Function : CPropertyContainer::Copy
Description : Copies the contents from "properties" to
this container.
Access : Public
Return : void
Parameters : CPropertyContainer& properties - Container to copy from.
Usage : Call to copy the properties from another
container into thsi one.
============================================================*/
{
RemoveAll();
INT_PTR max = properties.GetSize();
for (INT_PTR t = 0; t < max; t++)
Add(new CProperty(properties.GetAt(t)));
}
// Implementation
INT_PTR CPropertyContainer::GetSize() const
/* ============================================================
Function : CPropertyContainer::GetSize
Description : Gets the number of properties in the container.
Access : Public
Return : int - Number of properties.
Parameters : none
Usage : Call to get the number of properties in the
container.
============================================================*/
{
return m_properties.GetSize();
}
CProperty* CPropertyContainer::GetAt(INT_PTR index) const
/* ============================================================
Function : CPropertyContainer::GetAt
Description : Gets the object at "index".
Access : Public
Return : CProperty* - The object, or "NULL" if out of bounds.
Parameters : int index - Index to get object from.
Usage : Call to get a specific property from the
container.
============================================================*/
{
CProperty* result = NULL;
if (index < GetSize())
result = static_cast<CProperty*>(m_properties[index]);
return result;
}
void CPropertyContainer::RemoveAt(INT_PTR index)
/* ============================================================
Function : CPropertyContainer::RemoveAt
Description : Removes the property at "index"
Access : Public
Return : void
Parameters : int index - Index to remove property from.
Usage : Call to remove a property at a specific
index. Memory will also be deleted.
============================================================*/
{
if (index > -1 && index < GetSize())
{
delete GetAt(index);
m_properties.RemoveAt(index);
}
}
void CPropertyContainer::RemoveAll()
/* ============================================================
Function : CPropertyContainer::RemoveAll
Description : Removes all objects from the container.
Access : Public
Return : void
Parameters : none
Usage : Call to clear the container. Memory will
also be deleted.
============================================================*/
{
while (GetSize())
RemoveAt(0);
}
void CPropertyContainer::Add(CProperty* property)
/* ============================================================
Function : CPropertyContainer::Add
Description : Adds "property" to the container.
Access : Public
Return : void
Parameters : CProperty* property - Property to add.
Usage : Call to add a property to a container. The
container takes ownership of the object.
============================================================*/
{
CProperty* oldproperty = FindProperty(property->key);
if (oldproperty)
{
if (property->value != oldproperty->value)
oldproperty->value = property->value;
delete property;
}
else
m_properties.Add(property);
}
void CPropertyContainer::Add(const CString& tag, const CString& val)
/* ============================================================
Function : CPropertyContainer::Add
Description : Create and add a property to the container.
Access : Public
Return : void
Parameters : const CString& tag - Tag of the property
const CString& val - Value of the tag
Usage : Call to a add a property to the container.
============================================================*/
{
CProperty* property = new CProperty(tag, val);
Add(property);
}
CString CPropertyContainer::GetString(int format) const
/* ============================================================
Function : CPropertyContainer::GetString
Description : Gets a string representation of this
object in the format "format".
Access : Public
Return : CString - Result
Parameters : int format - Format
Usage : "format" can be one of:
"STRING_FORMAT_SAVE" For saving to file
"STRING_FORMAT_CPP" cpp-file format
"STRING_FORMAT_UML" UML-format
"STRING_FORMAT_H" h-file format
"STRING_FORMAT_HTML" HTML-format
"STRING_FORMAT_H_CTOR" ctor in a header
============================================================*/
{
CString output;
INT_PTR max = GetSize();
if (max)
{
switch (format)
{
case STRING_FORMAT_SAVE:
{
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
output += property->GetString(format);
if (t < max - 1)
output += _T("#");
}
}
break;
case STRING_FORMAT_CPP:
{
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
output += property->GetString(format);
if (t < max - 1)
output += _T(", ");
}
}
break;
case STRING_FORMAT_UML:
{
output = _T("{ ");
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
output += property->GetString(format);
if (t < max - 1)
output += _T(", ");
}
output += _T(" }");
}
break;
case STRING_FORMAT_HTML:
{
output = _T("{ ");
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
output += property->GetString(STRING_FORMAT_UML);
if (t < max - 1)
output += _T("<br>");
}
output += _T(" }");
}
break;
}
}
return output;
}
void CPropertyContainer::FromString(const CString& str)
/* ============================================================
Function : CPropertyContainer::FromString
Description : Creates properties from a string
representation and adds them to the
container.
Access : Public
Return : void
Parameters : const CString& str - New operation, or "NULL" if "str"
is not a valid representation of
properties
Usage : Call from load-functions
============================================================*/
{
CTokenizer tok(str, _T("#"));
INT_PTR max = tok.GetSize();
for (INT_PTR t = 0; t < max; t++)
{
CString propval;
tok.GetAt(t, propval);
CProperty* prop = CProperty::FromString(propval);
if (prop)
Add(prop);
}
}
CString CPropertyContainer::GetPropertyValue(const CString& tag) const
/* ============================================================
Function : CString CPropertyContainer::GetPropertyValue
Description : Gets the value for the property "tag"
Access : Public
Return : CString - Result
Parameters : const CString& tag - Tag to get the value for.
Usage : Returns the value of the tag, or "true" if
the tag has no value. Empty if the tag doesn't
exist.
============================================================*/
{
CString result;
INT_PTR max = GetSize();
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
if (property->key == tag)
{
result = property->value;
if (result.IsEmpty())
result = _T("true");
}
}
return result;
}
CProperty* CPropertyContainer::FindProperty(const CString& tag)
/* ============================================================
Function : CPropertyContainer::FindProperty
Description : Returns a pointer to the property having
"tag".
Access : Public
Return : CProperty* - Resulting property, or
"NULL" if it doesn't exist.
Parameters : const CString& tag - Tag to find.
Usage : Call to get a pointer to the property with
the tag "tag", if it exists.
============================================================*/
{
CProperty* result = NULL;
INT_PTR max = GetSize();
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
if (property->key == tag)
result = property;
}
return result;
}
void CPropertyContainer::RemoveProperty(const CString& tag)
/* ============================================================
Function : CPropertyContainer::RemoveProperty
Description : Removes the property with the tag "tag".
Access : Public
Return : void
Parameters : const CString& tag - Tag of property to
remove.
Usage : Call to remove a specific tag.
============================================================*/
{
INT_PTR max = GetSize();
for (INT_PTR t = 0; t < max; t++)
{
CProperty* property = GetAt(t);
if (property->key == tag)
{
RemoveAt(t);
t = max;
}
}
}
void CPropertyContainer::SetPropertyValue(const CString& tag, const CString& value)
/* ============================================================
Function : CPropertyContainer::SetPropertyValue
Description : Sets the value of "tag" to "value"
Access :
Return : void
Parameters : const CString& tag - Tag of property to set.
const CString& value - New value
Usage : Call to set the value of the property with
the tag "tag". If the property does not
exist, it will be created.
============================================================*/
{
CProperty* property = FindProperty(tag);
if (property == NULL)
{
property = new CProperty(tag, value);
Add(property);
}
else
{
property->value = value;
}
}
| [
"peter@conglomo.co.nz"
] | peter@conglomo.co.nz |
ef354a6ae03849fbc569bd22cbcbfec9aa56ecc9 | 868e8628acaa0bf276134f9cc3ced379679eab10 | /firstCrude2D/we123/h2/0.171/p | 1ccfcadcc83b381b86f5fdb0afa39f06f338a5d3 | [] | no_license | stigmn/droplet | 921af6851f88c0acf8b1cd84f5e2903f1d0cb87a | 1649ceb0a9ce5abb243fb77569211558c2f0dc96 | refs/heads/master | 2020-04-04T20:08:37.912624 | 2015-11-25T11:20:32 | 2015-11-25T11:20:32 | 45,102,907 | 0 | 0 | null | 2015-10-28T09:46:30 | 2015-10-28T09:46:29 | null | UTF-8 | C++ | false | false | 66,050 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.4.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.171";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
6500
(
35.4471
41.0227
41.4703
43.5399
52.416
86.5484
196.608
193.618
-19.8463
-63.2763
53.1603
17.8438
10.6835
9.3272
-8.11703
-6.31287
-7.66226
-9.15339
-13.0454
-7.39781
-3.74541
-2.97617
-2.95086
-2.69679
-1.95473
-1.13741
-0.500254
-0.254842
-0.152497
-0.183046
-0.146465
0.0797448
0.162824
0.0938491
0.0678105
0.0859236
0.0865111
0.0744716
0.0618794
0.0703753
0.111143
0.129382
0.124122
0.0809551
0.0779729
0.0798587
0.0804973
0.0751504
0.0571904
0.0441426
33.5765
39.1872
39.5881
41.591
50.6116
86.3447
196.062
184.768
-20.7112
-29.0429
100.241
17.9183
12.5517
9.27739
-7.27737
-4.63199
-7.68073
-9.24665
-13.4079
-7.30145
-3.55484
-3.0089
-2.9445
-2.73685
-1.98211
-1.14495
-0.527725
-0.265196
-0.145115
-0.177662
-0.169196
0.0684936
0.165378
0.0851092
0.0621442
0.0688812
0.0929794
0.0647834
0.0543655
0.0625448
0.0671894
0.0752622
0.0792864
0.0802712
0.0741158
0.0841414
0.0751082
0.0728336
0.0532023
0.0441991
31.6993
37.4291
37.7949
39.6912
48.6266
84.0381
199.481
181.581
-21.5327
-37.1238
61.8511
17.9927
13.7342
9.10621
-6.70745
-7.38972
-7.5037
-9.432
-13.4455
-7.6838
-2.76649
-2.31013
-2.93679
-2.82039
-1.96498
-0.795322
-0.443898
-0.278794
-0.113495
-0.170231
-0.219618
0.0283074
0.172018
0.0701379
0.0557203
0.0645517
0.0761787
0.0662953
0.050099
0.0484948
0.0564025
0.0720965
0.0863367
0.0783334
0.0713545
0.0683521
0.0648443
0.0605073
0.050342
0.0380746
29.8994
35.7982
36.1168
37.825
46.7019
81.2895
202.988
171.812
-22.0836
12.4052
81.2165
17.6441
9.10576
9.05836
-10.236
-6.7097
-7.43046
-10.0406
-13.2612
-8.48554
-3.0474
-2.70366
-2.91833
-2.92781
-2.04432
-1.0204
-0.388249
-0.298627
-0.092666
-0.195112
-0.271022
0.073744
0.289938
0.0710851
0.0646371
0.0716438
0.0697979
0.0548878
0.0431093
0.0415239
0.0503194
0.0669457
0.0759693
0.0744652
0.0644713
0.0672066
0.0639116
0.0567623
0.0429145
0.0256698
28.189
34.3096
34.581
36.0394
44.8388
78.8751
214.804
177.372
-24.0107
-51.7781
76.727
17.3173
21.3651
9.52051
3.2677
-6.37066
-7.09212
-10.6069
-13.6031
-8.7641
-3.98219
-2.69939
-2.889
-3.04426
-2.10622
-1.01058
-0.346227
-0.315639
-0.0753429
-0.190577
-0.135925
0.0541878
0.429266
0.0698175
0.0660321
0.0713396
0.0730565
0.0515258
0.0344634
0.0324519
0.0434522
0.0666225
0.161417
0.112834
0.068376
0.0645042
0.0600426
0.0499615
0.0314782
0.0109274
26.5619
32.9329
32.9097
34.3639
43.4825
76.3238
221.187
179.524
-28.834
104.279
122.708
31.3538
20.7619
-0.370324
-7.35786
-6.61641
-6.24823
-11.0243
-10.9748
-6.75753
-4.11102
-2.39529
-2.87427
-3.15807
-2.15075
-1.00204
0.119982
-0.324041
-0.0825428
-0.168277
0.58059
0.0519842
0.386328
0.0449858
0.0607655
0.0738713
0.0760141
0.0489117
0.0254467
0.0207963
0.0273483
0.0734004
0.172847
0.177014
0.067426
0.0617515
0.0539005
0.0410245
0.0184637
-0.00385832
25.0162
31.6609
31.6011
42.8995
44.3246
73.7856
228.529
179.9
-33.0676
82.1018
74.6068
18.0321
20.7173
-0.112723
-7.86957
-6.13938
-5.63492
-12.4248
-11.8348
-6.5351
-3.19395
-2.47712
-2.85064
-3.2503
-2.19582
-1.02169
0.146274
-0.373527
-0.101562
-0.116775
-0.251162
-0.0690894
0.341073
-0.049745
0.0563069
0.0824309
0.0813401
0.0460339
0.0141505
0.00425881
-0.00844751
0.0108306
0.233944
0.158361
0.0510614
0.0519033
0.0452971
0.0310179
0.00523571
-0.0176294
23.5544
30.4869
30.5313
40.7975
31.6528
71.2927
230.723
181.993
-40.0649
85.1711
76.4453
29.2921
20.9691
-0.00214486
-6.81957
-4.9364
-4.41548
-14.6283
-13.5161
-7.02945
-3.15361
-2.54142
-2.85004
-3.29985
-2.24368
-1.05726
0.324306
-0.269928
-0.0574548
-0.0941099
-0.163663
0.0572244
0.28193
-0.148123
0.0683804
0.100408
0.0875373
0.0430785
0.00135806
-0.0170513
-0.0641013
0.104045
0.189414
0.196699
0.28424
0.0449175
0.0376748
0.021974
-0.00681416
-0.0311222
22.1771
29.4171
32.1534
39.3545
37.3391
68.634
235.841
185.416
25.0829
83.4383
64.2366
23.7878
19.134
-0.0805203
-7.12033
-5.02519
14.6215
-16.6921
-16.3246
28.4496
-1.97267
-2.31463
-2.86419
-3.31196
-1.70464
-1.26694
1.23022
2.81253
0.0838805
-0.0659046
-0.148082
0.0401959
0.170335
-0.147127
0.0762845
0.118624
0.0921487
0.040085
-0.0112292
-0.0399013
-0.0925935
0.0052438
0.849101
0.208223
0.159555
0.05588
0.0375027
0.0156404
-0.0171986
-0.0433253
20.8831
28.4088
32.1538
39.8121
36.0541
72.8724
241.351
186.87
9.16597
22.574
126.392
23.6343
19.9548
-0.245919
-7.57112
-5.08858
-2.13972
-18.4223
12.2371
18.9159
-1.84613
-2.34725
-2.89166
-3.31021
-1.11763
-1.49246
2.52101
1.24595
0.303613
-0.0472516
-0.242692
-0.00122519
0.259525
-0.120963
-0.160599
0.137715
0.0946204
0.037489
-0.0220495
-0.0617081
-0.125571
0.0224824
4.08367
0.200896
0.266254
0.0710322
0.0379489
0.00917795
-0.0272177
-0.0542144
19.6704
27.465
25.8287
38.3817
32.5203
66.0992
246.751
187.335
1.0652
118.423
60.6167
24.1486
21.5456
-0.462933
10.0772
-5.77323
9.46767
-19.7475
6.38945
14.7267
-0.863439
-2.42816
-2.90776
-3.22981
-1.95091
-1.66949
-1.99947
0.134928
0.217039
-0.048022
-0.245529
-0.0683094
0.372419
-0.12087
-0.140158
0.242345
0.0993643
0.0359711
-0.0314197
-0.0751554
-0.190606
0.0708915
5.57875
0.131327
0.298208
0.0564995
0.0258414
-0.00124139
-0.0381838
-0.0637257
18.5354
27.045
24.9974
41.4777
45.3482
79.8163
252.011
185.891
147.524
18.8141
62.3264
30.6956
21.653
-0.778838
8.02699
-3.87204
-0.324958
17.725
3.69068
14.2282
-1.59563
-1.08338
-2.91052
-3.17348
-2.59681
-1.91575
-1.7163
0.112393
0.14937
-0.0219968
-0.248027
-0.0754509
0.413526
-0.15421
-0.320405
0.31535
0.106191
0.035339
-0.0411547
-0.115302
-0.119194
0.135188
6.95363
0.440665
0.263285
0.00306804
-0.00763954
-0.0175873
-0.0501439
-0.0721379
17.4763
26.2761
24.2302
36.4821
42.9554
59.9541
257.471
191.501
70.1481
18.767
63.4206
31.0187
40.2664
-1.4318
7.52351
-3.56071
0.44468
19.0662
22.6269
8.11591
-1.15314
-1.28723
-2.9272
-3.23651
-2.61219
-2.09282
-1.62709
1.59985e-05
0.120663
2.36188
-0.252475
-0.0799947
0.433999
-0.196203
-0.549986
0.389681
0.114982
0.0345753
-0.0466064
-0.137524
-0.130912
-0.161764
6.69583
0.173182
0.203543
-0.0702995
-0.0591261
-0.0380144
-0.0626177
-0.0791654
16.4894
25.6502
22.4317
36.1401
42.4377
57.9387
262.966
192.889
72.2213
42.817
65.8504
31.2594
24.4728
6.10536
7.52168
-4.12575
3.2595
17.8348
17.2983
7.93495
5.51045
0.00668985
-2.94392
-3.26885
-1.96509
-2.33224
-1.55003
-0.104781
0.0145896
0.132505
-0.144173
-0.0784028
0.436956
-0.363813
-0.726666
0.477539
0.1119
0.0321549
-0.0515011
-0.139152
-0.156832
-0.457526
6.35796
4.29702
0.117461
-0.141438
-0.106913
-0.0584719
-0.0747515
-0.0850306
20.4911
25.083
21.7724
35.2652
41.5749
55.954
268.105
193.154
94.7034
42.7605
67.7469
32.1514
24.5307
5.17094
7.90601
-4.78698
7.54705
16.439
16.0055
33.5581
3.61638
-0.851598
-2.8188
-3.1842
-2.06037
-2.30876
-1.40417
0.00631942
1.21517
0.286458
-0.201529
-0.0931929
0.436503
1.26168
-0.953836
0.647076
0.0837558
0.0260372
-0.05336
-0.216147
-0.161881
-0.134615
6.55924
4.37896
-0.1085
-0.219993
-0.149685
-0.0767798
-0.0856879
-0.0900052
15.931
21.1613
23.2001
34.4267
43.5142
24.693
273.39
181.568
60.2078
40.4567
69.8654
31.7841
11.8307
4.56722
7.96496
-5.10298
11.7284
14.9527
14.5401
2.50272
2.25811
4.10668
-2.91718
-3.13969
-1.95963
-2.38832
-1.49333
-0.11269
-0.440328
-1.60286
-0.0506264
0.122318
0.399359
1.089
-1.12264
1.01404
0.0125926
0.0111536
-0.0309795
-0.096193
-0.158008
0.549731
6.3431
4.54236
0.500578
-0.266239
-0.189326
-0.0920865
-0.0948856
-0.0941644
15.1572
20.6748
21.388
33.6788
43.6139
74.2917
279.002
619.507
55.4076
34.2833
116.23
32.6186
11.7679
4.94415
7.83954
6.10644
1.07372
13.3823
12.9628
3.09698
2.22278
1.41066
-3.02559
-3.12296
-1.7248
-2.48559
-1.34128
-0.205883
-0.468779
-1.40647
0.210739
-0.130004
0.32885
0.747606
-1.20343
1.36261
-0.0680259
0.065538
-0.0135049
-0.171926
-0.154154
0.785369
6.30257
4.80476
1.19002
-0.245762
-0.213657
-0.1013
-0.102164
-0.0979314
14.4436
20.2276
20.8663
33.0031
39.934
89.5587
500.398
497.495
-34.2624
222.759
54.5162
34.9017
10.8863
4.93514
7.83959
6.23454
2.41011
11.5406
11.1807
3.50099
2.45602
0.317833
-3.33808
-3.11037
-1.18976
2.02121
-1.31651
-0.303343
-0.395611
-1.26966
-1.69371
-0.0912257
0.26357
1.14506
-1.43637
1.72544
1.34947
-0.0186589
-0.0053471
0.103718
-0.136246
0.66191
6.43744
4.84824
0.69795
-0.173702
-0.202648
-0.104349
-0.10776
-0.102171
13.7835
19.8091
20.3796
32.4585
39.5851
101.815
401.86
753.786
-31.1224
206.158
64.0813
0.301794
2.04411
4.88287
7.84247
4.28733
3.08854
10.3707
9.1747
4.17312
2.56629
8.2513
15.395
-3.10599
-1.12017
4.13697
-1.24412
0.361787
-0.423131
-1.17025
-1.60282
-0.0705451
0.207051
1.18958
0.755006
1.95496
0.215916
0.0237032
-0.00717332
-0.0799108
-0.145932
0.748595
6.52506
4.80625
0.704144
-0.144125
-0.177899
-0.105804
-0.111973
-0.107253
13.1702
19.4196
19.9189
32.0427
39.2402
91.924
489.101
691.402
-29.8492
95.139
76.4469
1.05626
1.77155
4.4166
6.5737
3.92624
2.57416
9.14107
7.15137
4.96309
2.61113
8.00096
2.67914
-2.82628
-1.55156
-0.532534
-1.1842
-0.0481272
-0.471549
-1.11729
-1.46976
0.0096486
0.209437
1.84812
0.91192
2.92151
0.12947
-0.0124467
-0.0146438
-0.0551579
-0.16368
1.01886
6.50796
4.74092
0.507289
-0.131018
-0.160127
-0.10831
-0.115092
-0.112428
0.0380512
0.032983
0.0282959
0.0219909
0.0113005
-0.0051057
-0.0294592
-0.0655996
-0.105447
-0.184551
4.7895
37.6044
57.8843
60.3155
53.6401
44.9492
3.45399
1.22781
0.740614
0.653373
0.452299
0.567667
0.282566
-1.28763
-2.95709
-3.21855
-3.87405
-4.25869
-4.60619
-5.22212
-5.6594
-6.6684
-6.93379
-9.12327
-12.8511
-19.2952
-18.1539
-21.7633
-27.9614
-82.5139
-45.2526
-283.6
-220.609
-178.868
-50.8545
0.737872
23.7665
22.9231
35.3351
26.0066
0.0356612
0.0281148
0.0218329
0.01725
0.00753527
-0.00869509
-0.0303304
-0.0657633
-0.113199
-0.226746
18.9381
58.708
71.2282
65.3149
51.0555
39.6077
19.4439
0.765962
0.706495
0.643854
0.43275
1.06538
0.49724
-0.918301
-1.94748
-3.1903
-4.14304
-4.58569
-4.63459
-4.83019
-5.28333
-6.17618
-6.43616
-8.5123
-12.8896
-19.4226
-17.8935
-23.0043
-27.9639
-83.5503
-42.3091
-289.486
-185.023
-172.003
-51.8288
-0.843641
21.9469
21.0038
33.504
24.1449
0.0259157
0.0161232
0.00970621
0.00428668
-0.00597229
-0.0204967
-0.0380153
-0.0554205
-0.0682238
0.466394
43.6208
72.277
71.4932
62.6107
55.7774
57.3818
42.261
3.90843
0.704169
0.660436
0.43638
1.285
0.647981
-0.58873
-1.99541
-3.12945
-4.1729
-4.44314
-4.6397
-5.41537
-6.15783
-7.12537
-7.3128
-8.28368
-12.9608
-19.4254
-18.2909
-22.9659
-27.3812
-96.1186
-28.8816
-301.953
-231.484
-175.611
-53.5873
-2.15349
20.3513
19.2093
31.8051
22.3177
0.013334
0.00588222
-5.58878e-05
-0.00618715
-0.0162568
-0.0291584
-0.0430634
-0.0604253
-0.0667865
0.316034
33.8287
70.0553
69.6789
60.1884
54.2572
57.5559
52.7738
5.81488
0.714308
0.665303
0.393388
1.15346
0.707587
-0.44744
-1.24103
-3.32492
-4.09758
-4.66823
-4.96949
-5.47209
-6.17021
-7.18143
-7.28204
-8.23834
-13.0722
-19.4462
-19.1851
-22.8281
-30.346
-114.334
-28.9512
-310.511
-227.836
-177.226
-55.24
-3.16998
19.3499
17.698
30.2499
20.5863
-0.000340741
-0.0091438
-0.0138992
-0.0177993
-0.0241228
-0.036723
-0.0486129
-0.0644461
-0.0693422
0.235436
42.0624
63.7844
64.1411
58.016
52.6033
55.686
59.3344
6.5273
0.718063
0.670083
0.288066
1.19538
0.817112
0.337768
-1.90741
-3.18187
-4.09184
-4.67664
-4.97665
-5.51792
-6.18685
-7.25623
-7.19187
-7.80886
4.18056
-19.7612
-18.9482
-22.7773
-29.3418
-140.74
-18.2145
-306.797
-176.232
-188.321
-56.597
-3.32283
18.0846
16.1268
28.8306
18.9483
-0.0158374
-0.0234547
-0.0250914
-0.0294414
-0.035625
-0.0446006
-0.0539349
-0.0653451
-0.0711193
-0.0149782
31.6308
56.1535
59.7457
57.3819
52.8259
55.4066
59.8705
9.16691
0.698142
0.647367
0.182313
1.49202
0.797706
0.432455
-1.48609
-2.64264
-4.08192
-4.80798
-4.9757
-5.54955
-6.21762
-7.31265
-7.19096
2.64799
-2.16161
-20.4296
-19.4495
-22.9613
-28.3825
-157.436
-19.4251
-313.248
-215.69
-162.357
-39.1133
-4.44735
16.9308
14.6605
27.521
17.3966
-0.0327955
-0.0364381
-0.0357092
-0.0387949
-0.0426269
-0.050528
-0.0591733
-0.0696828
-0.0808625
-0.0952922
32.3512
52.3359
57.6354
57.0867
53.0798
54.979
62.1016
6.41956
0.698676
0.610255
0.0217245
1.35723
0.579698
0.748221
-1.20723
-2.07189
-4.19522
-4.94598
-4.95965
-5.54695
-6.22086
-7.42008
-7.42111
-8.3088
-2.05335
-20.8561
-20.933
-22.8505
-30.0809
-146.47
-3.78434
-323.215
-220.111
-168.884
-40.5735
-4.91692
21.4856
13.3191
26.3721
15.9288
-0.0457259
-0.048084
-0.0444762
-0.0471493
-0.0491538
-0.0562927
-0.0631468
-0.0719078
-0.0952005
-0.147855
16.3232
51.2035
57.0517
56.6123
53.4056
54.5322
64.5872
3.20611
0.716079
0.556542
-0.125959
0.561929
0.464179
1.97117
-1.1553
-1.38138
0.0587573
-5.24948
-4.936
-5.51426
-6.21597
-7.56956
-7.15319
-8.19139
-2.07386
-21.7408
-20.1243
-23.1035
-31.3065
-148.779
-37.4782
-337.929
-212.454
-108.479
-20.1862
0.0803512
20.5802
12.0948
25.2658
14.5432
-0.057439
-0.0588325
-0.0516004
-0.0551967
-0.055348
-0.0607173
-0.0687072
-0.0793289
-0.110641
-0.138363
6.50082
47.7055
55.9539
55.5854
53.2739
53.5769
64.1263
2.52794
0.744444
0.381516
-0.321667
0.222042
0.610599
-0.0452161
-0.965563
-0.669199
0.498901
3.57659
-1.08392
-5.47525
-6.23893
-7.83697
-6.40984
-8.20405
-3.38711
-14.454
-20.5429
-7.92567
-33.5712
-192.641
-27.8422
-26.4744
-162.853
-94.433
-35.2466
-4.36964
19.7672
11.8108
24.218
13.238
-0.0683196
-0.0697582
-0.0570081
-0.0626746
-0.0607272
-0.0647301
-0.0709823
-0.0845681
-0.113996
-0.138501
2.51944
36.5796
54.1224
54.0034
52.5729
52.0598
59.3583
-0.924303
0.80324
-0.154751
-0.236632
0.0999213
0.612766
4.84241
-0.807614
0.785012
2.05873
-1.46605
-3.50146
-5.45958
0.666114
-1.79914
-5.5987
-8.28599
1.32961
-17.8301
-21.1136
-15.136
-36.8164
-148.368
-24.2683
-243.165
-347.873
156.831
16.4549
-5.41866
19.3966
10.7521
40.1991
12.3067
-0.0782686
-0.0821811
-0.0587571
-0.0699896
-0.0666809
-0.0676212
-0.0715529
-0.0819395
-0.110391
-0.146808
0.970501
29.1412
52.9011
52.5391
51.511
50.0215
52.7409
-1.85944
0.873071
0.727826
-0.0657793
0.239462
0.54504
3.76765
-0.768532
-0.00296282
3.59758
-1.28738
-3.41096
-5.3341
-2.76167
-3.97427
-4.93187
-6.20935
-3.44802
-19.5839
-2.29285
-9.25287
-36.2981
-168.458
-20.3267
-255.133
171.459
67.7667
30.7728
-6.60129
18.725
9.31266
29.9753
11.0641
-0.0862445
-0.0867536
-0.0370497
-0.0793247
-0.0730229
-0.0697747
-0.0705985
-0.07839
-0.111759
-0.108622
2.43682
17.2171
51.9281
51.3375
50.3161
48.0086
33.4194
0.838881
0.928498
-0.123356
0.12628
0.251442
0.559413
3.61151
-0.758916
0.116008
-0.696556
-1.30281
-3.32885
-2.97333
-2.73778
4.95112
-4.35401
-6.06356
-3.22212
-1.37323
-3.17361
-10.8671
-38.3447
-152.126
-16.888
-253.334
-65.1994
76.3672
-2.26614
-7.04201
17.5057
33.4895
29.241
9.91297
-0.0915335
-0.0725327
0.0448489
-0.0815349
-0.0795939
-0.0709769
-0.0689863
-0.0786127
-0.108519
-0.0941333
2.4399
9.98116
47.093
50.388
49.13
45.7595
18.5751
0.8314
0.955275
0.35482
0.308907
0.199447
0.432324
4.58149
7.69094
0.135354
-0.952125
-1.36564
-3.25625
-2.72902
-2.68324
1.90615
-3.73678
-3.83574
-3.08852
-11.8909
-2.28297
-10.1242
-63.7965
-151.992
-12.2291
-257.213
-60.7476
88.0952
94.3356
-6.59381
16.9057
28.3975
28.785
8.94078
-0.0963397
-0.0767576
0.0428169
-0.0449981
-0.082689
-0.0714881
-0.0671925
-0.0786148
-0.100508
-0.112493
0.879264
14.8755
38.3402
50.1098
48.4279
43.7533
4.06309
0.848216
0.980067
0.333796
0.363043
-0.0271121
0.399257
4.37806
3.42464
0.150683
0.161836
-1.4201
-3.19849
-2.56335
-2.6492
1.69545
-3.20822
-3.88884
-2.96688
22.1167
15.1845
68.0169
-64.0115
-155.894
-2.78063
-261.598
-42.9313
97.0697
72.0958
5.89687
25.1154
27.654
28.1741
8.02551
-0.10088
-0.0719457
0.0141785
-0.0460289
-0.0801496
-0.0730099
-0.0658548
-0.0768793
-0.094477
-0.117098
-0.278145
15.3864
30.4158
50.3815
48.6166
42.7379
0.401067
0.88666
1.0231
0.51181
0.165088
-0.101152
0.039066
4.73574
3.70822
0.230985
1.24957
3.5646
-3.1715
-2.43273
-2.60282
0.761388
-2.76435
-3.66221
31.7882
6.96008
26.9019
7.06637
45.2452
-161.297
11.8679
-265.372
-39.51
103.11
72.3871
-16.6183
19.6827
27.0147
27.6256
28.6807
-0.100936
-0.0831666
0.181504
-0.0205963
-0.0795629
-0.0768455
-0.0654418
-0.0751934
-0.0906202
-0.110317
-0.221335
0.519936
26.9936
47.4599
49.5911
37.8391
3.21455
0.858989
1.07147
0.151283
0.093774
-0.113258
-0.0517028
5.32758
3.52519
0.0249105
3.62453
0.603463
-3.13419
-2.36623
-2.57136
0.0624792
-2.48098
-4.39672
3.54615
6.58669
35.348
7.43097
51.7646
125.261
12.7579
-268.488
-38.3981
132.69
72.1092
-16.6854
19.2782
26.4638
27.2393
21.8546
-0.100884
-0.0690818
0.214491
-0.0935197
-0.0862633
-0.081975
-0.0660498
-0.0754298
-0.0908631
-0.0942656
-0.00685168
-4.43933
21.9338
40.182
50.2739
30.2951
3.78956
0.853325
1.12253
0.0149948
0.0676214
-0.117534
-0.127175
6.62338
2.82738
-0.0292976
0.448054
2.75365
-3.0919
-2.30682
-2.63906
-0.207304
-2.35617
-4.4409
3.8034
6.69979
32.6773
5.56178
47.8691
99.43
19.805
-272.695
-33.1832
137.318
37.9997
-15.8205
18.8615
25.9481
26.8273
21.1798
-0.103773
-0.0936206
0.188919
-0.0597258
-0.095261
-0.0873638
-0.0673899
-0.0776769
-0.0950107
-0.0702159
-0.0508852
-1.7102
13.3291
33.5021
45.9159
20.9515
3.02854
0.76147
1.11128
-0.106049
0.043618
-0.105723
-0.504398
4.64592
2.54646
0.238794
0.280731
0.153493
-2.34063
-2.2504
-2.49714
-0.315912
-2.20163
6.53337
3.95534
6.77793
35.0561
8.20146
45.7721
80.016
8.2814
-281.353
-26.9088
142.52
93.6596
-16.3025
16.2246
25.503
26.4456
20.7391
-0.110129
-0.116662
0.173363
0.0084418
-0.101379
-0.0886775
-0.067544
-0.080919
-0.103458
-0.0554779
-0.0804865
-0.160256
-1.09447
27.142
43.6435
7.05358
1.23172
1.58546
1.32918
-0.1832
0.00853652
-0.130041
4.54173
5.52269
2.541
1.26531
0.136374
0.248001
-2.70303
-2.18947
-2.31993
-0.366913
-2.12537
0.271624
3.97193
6.38647
36.945
119.284
54.3568
185.551
-16.523
819.265
-21.2645
148.158
-4.62665
33.2622
21.2029
25.0309
26.0428
20.1924
-0.117543
-0.114178
0.166594
0.0465932
-0.103088
-0.0937988
-0.05177
-0.082995
-0.109156
-0.0691
-0.0338018
-0.185135
0.898998
11.5942
34.0395
1.82268
-0.0284092
0.210849
1.31846
-0.221339
-0.019011
-0.139542
1.12807
6.49881
2.49899
-0.924627
0.0673303
0.0648263
-2.41198
-2.14871
-2.43631
-0.30248
-2.08046
0.343489
4.02486
6.18204
26.4024
126.148
52.226
169.764
-10.7025
323.072
-15.4637
186.829
-4.72436
5.22956
17.5875
24.6177
25.6978
19.648
11.6777
18.4844
18.8501
29.4052
39.9787
101.928
-49.5907
2.90652
-27.5108
70.9153
10.7056
1.31376
1.64262
4.3464
7.185
3.24296
2.7556
7.98272
6.14436
4.9461
2.45354
6.43181
3.31254
-2.89934
-3.46245
-0.659807
-1.09302
-0.326448
-0.515282
-0.959549
-1.28452
0.532751
0.303029
0.196964
0.460592
-2.876
-0.151667
0.00184228
-0.0404744
-0.0968986
-0.173022
0.798458
6.3625
4.61944
0.228734
-0.11402
-0.129146
-0.117175
-0.12197
-0.124372
9.59797
16.8918
29.2623
27.0002
28.442
60.4022
-33.7554
-0.955459
-28.5306
39.445
82.5225
1.55343
1.46425
4.03492
3.80354
1.24768
6.68951
7.53435
5.78335
2.64297
4.93671
6.18726
-2.87286
-1.05225
-2.24323
-0.664038
-0.803199
-0.467878
-0.553822
-0.870819
-1.11776
-1.44964
-0.73895
-0.174153
0.274913
-1.33877
-0.3796
-0.0801514
-0.0818111
-0.116557
-0.146965
-0.083166
6.37321
3.11941
-0.0337408
-0.14184
-0.136675
-0.131327
-0.134246
-0.135288
7.47034
15.4262
19.4087
25.2159
27.0427
56.1245
-19.1614
-2.23308
13.0507
11.9777
-5.91294
1.40258
1.28792
3.71717
3.23674
8.02527
4.87503
7.05711
5.42095
3.71437
4.3933
4.97167
-1.47139
6.64786
-1.19082
-0.625094
-0.74764
-0.486824
-0.58212
-0.841039
-1.12267
-1.31093
-1.4821
-0.859427
0.00742589
-0.482723
-0.405244
-0.178174
-0.13407
-0.14361
-0.15633
-0.149552
5.79028
0.226904
-0.136398
-0.15089
-0.149643
-0.144275
-0.145934
-0.147163
12.9047
13.7274
17.5315
22.0748
24.8417
46.71
-11.2607
-1.44708
5.08018
4.23088
-4.86528
1.55955
1.24163
3.38623
3.08966
5.90834
5.00079
6.28691
4.82889
4.95178
3.5263
2.5157
-0.649863
-0.994062
-0.59326
-0.526049
-0.619609
-0.515568
-0.612701
-0.81999
-1.06383
-1.25435
-1.24701
-1.28199
-0.189654
-0.250574
-0.402718
-0.247915
-0.164298
-0.157076
-0.170674
-0.161296
0.692755
-0.0616614
-0.150349
-0.14797
-0.152888
-0.152826
-0.157756
-0.162586
10.1386
8.95426
15.485
19.0775
22.2924
38.2784
-7.35565
0.787825
5.19986
3.71804
-4.59395
1.63956
1.2121
2.48605
2.93068
3.71758
4.9862
5.16875
5.69676
4.36682
3.66744
1.53936
-0.0163259
-0.463741
-0.504609
-0.57491
-0.515065
-0.537387
-0.648398
-0.816321
-1.03187
-1.21136
-1.16903
-1.52236
-0.313854
-0.158654
-0.341837
-0.314522
-0.235058
-0.215949
-0.189555
-0.153323
-0.0999329
-0.11921
-0.152476
-0.149952
-0.155404
-0.160773
-0.167518
-0.17426
7.76614
7.13272
13.1767
15.9452
19.4698
33.9925
-1.17922
1.43256
9.53177
1.06087
-4.8407
1.82531
1.14586
2.42123
2.78217
2.35066
2.02411
3.82862
2.81285
4.6236
3.54037
0.86072
-0.300008
-0.204546
-0.47467
-0.463163
-0.422952
-0.547739
-0.70016
-0.830875
-1.01692
-1.19369
-1.20767
-1.41986
-0.353434
-0.123334
-0.394524
-0.366213
-0.270623
-0.232742
-0.216742
-0.169876
-0.139471
-0.150037
-0.155012
-0.157681
-0.164617
-0.172472
-0.181762
-0.188628
6.39394
5.66595
9.82203
11.9789
16.6528
29.3004
0.594026
1.27995
7.38854
-3.87146
-4.11998
4.13287
1.10107
2.37259
2.67059
2.27044
1.98708
1.51482
3.78357
4.97472
2.98003
0.166682
-0.100871
-0.092482
-0.522371
-0.314246
-0.463076
-0.544792
-0.661624
-0.807598
-0.999632
-1.19906
-1.3157
-1.17628
-0.366812
-0.138586
-0.504895
-0.398791
-0.301414
-0.258106
-0.215949
-0.186777
-0.188121
-0.176934
-0.175294
-0.176826
-0.183153
-0.191343
-0.199719
-0.206833
3.86601
3.81015
7.62512
9.51425
13.4337
23.9043
3.82638
1.22254
5.45492
-2.99428
-1.76243
-0.025251
1.11705
2.30369
2.54497
2.21831
1.97539
1.99356
4.59871
3.34121
2.85274
-0.673534
-0.233269
-0.0154214
-0.476819
-0.490812
-0.331369
-0.227133
-0.721835
-0.818919
-0.980543
-1.2141
-1.52657
-1.03735
-0.350103
-0.418455
-0.529295
-0.419574
-0.327353
-0.28566
-0.232567
-0.21237
-0.215161
-0.204814
-0.201878
-0.202638
-0.206092
-0.210648
-0.215014
-0.223888
1.2824
1.99074
3.96906
5.79752
9.8206
17.5843
8.86087
1.30744
5.92544
-2.13434
-0.247996
0.0592402
1.11587
2.27676
2.44402
2.1522
1.9898
2.05107
13.7871
4.99208
2.68649
-0.574191
-0.170194
-0.435696
-0.46669
-0.225144
-0.185255
-0.661994
-0.70814
-0.792062
-0.952316
-1.19962
-1.56623
-1.10024
-0.240122
-0.529774
-0.528798
-0.430586
-0.353314
-0.311149
-0.267123
-0.253593
-0.254036
-0.234475
-0.234653
-0.230556
-0.229192
-0.233066
-0.234698
-0.237917
0.0547895
0.829449
1.65032
1.24965
4.58676
13.3548
14.7856
1.17715
4.43903
-1.41929
0.351239
0.108313
1.08787
2.23533
2.37828
2.10965
1.98396
2.02198
3.98257
5.7944
1.98737
-0.495477
-0.1435
-0.309797
-0.477578
-0.600166
-0.547909
-0.611913
-0.688246
-0.76278
-0.894826
-1.10746
-1.44246
-1.44359
-0.832566
-0.601626
-0.536567
-0.442393
-0.374062
-0.338427
-0.313987
-0.291628
-0.276479
-0.271357
-0.199497
-0.189662
-0.233641
-0.25543
-0.25544
-0.257541
-0.0151739
0.178094
0.249357
0.0724125
0.529107
1.97408
2.25474
0.307256
3.5056
-0.7488
-0.145718
0.12774
0.897098
2.28638
2.23569
2.0333
1.98078
2.06439
2.88219
4.42929
1.80264
-0.428107
-0.162728
-0.301597
-0.450835
-0.491713
-0.406794
-0.640737
-0.683471
-0.735326
-0.838623
-1.01378
-1.22762
-1.16884
-0.848576
-0.633891
-0.54048
-0.456134
-0.396869
-0.361464
-0.33726
-0.317423
-0.304422
-0.24462
-0.230163
-0.219832
-0.219649
-0.264653
-0.270392
-0.271887
-0.021695
-0.0181934
-0.0520297
-0.00632024
-0.105736
-0.0675941
-0.538198
1.41955
2.12175
-0.230566
0.0254926
0.172645
0.949599
2.1464
2.19562
1.95815
1.99072
2.13012
2.89621
1.1323
1.51414
-0.300244
-0.154777
-0.303839
-0.438429
-0.425009
-0.536102
-0.589046
-0.675957
-0.712033
-0.787525
-0.904286
-1.00619
-0.943213
-0.764911
-0.623587
-0.53564
-0.466899
-0.417207
-0.383849
-0.359673
-0.341071
-0.32786
-0.291339
-0.253197
-0.238032
-0.239694
-0.289874
-0.290975
-0.290418
-0.0254352
-0.0202321
-0.054336
-0.0110169
-0.110995
-0.0844823
-0.472726
-0.140111
0.286242
0.244467
0.592321
0.221869
0.835247
1.90667
1.98918
1.87534
1.97334
2.154
2.87464
0.340545
0.987803
-0.274255
-0.165099
-0.329334
-0.441985
-0.372083
-0.388372
-0.618638
-0.649825
-0.684789
-0.738612
-0.810399
-0.847751
-0.793438
-0.682094
-0.591929
-0.525256
-0.472239
-0.43138
-0.401139
-0.378304
-0.360611
-0.345628
-0.339307
-0.315549
-0.302214
-0.313757
-0.317035
-0.312373
-0.30943
-0.0315339
-0.0262379
-0.0616607
-0.0230794
-0.117471
-0.091243
-0.435931
-0.250768
0.194433
0.666341
0.413405
0.24936
0.74897
1.65345
2.09914
1.79059
1.93039
2.10852
2.80346
1.49697
0.637089
-0.137633
-0.238311
-0.399767
-0.482522
-0.327886
-0.368186
-0.593209
-0.620332
-0.655388
-0.694611
-0.737574
-0.753883
-0.705473
-0.627843
-0.563072
-0.512872
-0.472206
-0.439189
-0.413005
-0.392376
-0.375521
-0.362596
-0.35375
-0.346236
-0.340689
-0.33562
-0.330347
-0.32736
-0.324832
-0.033209
-0.0272214
-0.0653759
-0.0236118
-0.123633
-0.095901
-0.410639
-0.215125
0.194864
0.218838
0.282165
0.260827
0.637535
1.3989
2.06702
1.70783
1.89047
2.07997
2.73711
2.07502
0.197895
0.0112342
-0.51327
-0.178371
-0.586459
-0.361551
-0.351237
-0.569209
-0.590816
-0.625241
-0.655025
-0.688788
-0.693805
-0.651417
-0.588968
-0.536704
-0.499184
-0.468617
-0.442455
-0.420428
-0.402147
-0.387119
-0.375351
-0.36595
-0.358785
-0.353086
-0.347801
-0.34282
-0.338326
-0.334445
-0.0417563
-0.016835
-0.0668413
-0.0210096
-0.129766
-0.100243
-0.377728
-0.209617
0.176378
0.13723
0.116771
0.268875
0.442068
1.11646
1.26236
1.64942
1.87288
2.0294
2.32056
2.36161
0.27436
0.0849685
-0.34286
-0.0846416
-0.0907625
-0.245571
-0.250062
-0.547577
-0.560616
-0.599066
-0.620493
-0.645493
-0.658173
-0.591909
-0.555456
-0.510025
-0.48588
-0.463748
-0.443202
-0.424829
-0.408867
-0.395451
-0.384611
-0.375962
-0.369124
-0.363525
-0.358417
-0.353453
-0.349139
-0.340762
-0.0468626
-0.0585273
-0.0723903
-0.063847
-0.136577
-0.105199
-0.352571
-0.218219
0.0484227
0.128212
0.130695
0.266517
0.417837
0.855865
1.01499
1.56536
1.86612
1.99767
2.12688
2.50988
0.316422
-0.00361379
-0.319652
-0.405035
-0.458325
-0.146414
-0.170113
-0.535461
-0.533505
-0.56997
-0.588801
-0.608326
-0.576055
-0.411313
-0.39708
-0.47585
-0.475279
-0.459845
-0.443541
-0.427975
-0.413887
-0.401694
-0.391454
-0.383392
-0.376977
-0.37136
-0.365895
-0.360424
-0.354245
-0.324428
-0.05206
-0.0646746
-0.077961
-0.0689975
-0.1416
-0.109394
-0.331544
-0.213546
0.0143378
0.108651
0.137605
0.267012
0.422255
0.789905
0.97733
1.42343
1.67621
2.63978
3.54256
2.43908
-0.00265394
0.0368416
-0.310585
-0.363565
-0.380394
-0.171224
-0.351784
-0.514255
-0.515295
-0.546206
-0.558549
-0.574385
-0.431561
-0.386174
-0.365812
-0.38214
-0.473392
-0.462867
-0.447164
-0.432662
-0.419632
-0.407914
-0.397596
-0.388785
-0.383912
-0.379876
-0.375084
-0.370625
-0.369077
-0.340954
-0.0575444
-0.0694019
-0.0837977
-0.0742322
-0.147711
-0.110956
-0.310074
-0.207857
-0.0111459
0.0521958
0.133715
0.261654
0.415718
0.770172
0.888918
1.3526
1.02295
0.878885
3.01247
3.13719
0.446025
-0.0312059
-0.274858
-0.334029
-0.347567
-0.325244
-0.436921
-0.486928
-0.495811
-0.519247
-0.530916
-0.539435
-0.47989
-0.402977
-0.37627
-0.365062
-0.486061
-0.474584
-0.455787
-0.440872
-0.4291
-0.41509
-0.400522
-0.386267
-0.385125
-0.386176
-0.386435
-0.378269
-0.379163
-0.378148
-0.0632177
-0.074891
-0.0887385
-0.0803038
-0.149518
-0.112611
-0.288226
-0.190587
-0.0444031
0.179239
0.124547
0.241507
0.387566
0.627873
0.80102
1.24045
0.79509
0.0550182
2.22971
2.81563
0.803922
-0.0729643
-0.225887
-0.319854
-0.342418
-0.371759
-0.418816
-0.456404
-0.475304
-0.494954
-0.50653
-0.512502
-0.505422
-0.451486
-0.372464
-0.404673
-0.506423
-0.486333
-0.465097
-0.451481
-0.42598
-0.338242
-0.262183
-0.273321
-0.249421
-0.23122
-0.2978
-0.366532
-0.374122
-0.369482
-0.0690727
-0.0797943
-0.0926432
-0.085592
-0.15009
-0.114814
-0.265904
-0.177234
-0.097782
-0.0684889
0.110656
0.547279
0.517361
0.692071
0.699712
1.4033
0.481283
-0.165422
0.248283
1.02605
0.247014
-0.0237993
-0.20969
-0.303307
-0.328309
-0.360293
-0.398721
-0.432691
-0.455803
-0.474363
-0.486272
-0.492756
-0.494339
-0.492791
-0.500422
-0.504833
-0.508
-0.482332
-0.460802
-0.445519
-0.386312
-0.280572
-0.25875
-0.258175
-0.254489
-0.264199
-0.27275
-0.337616
-0.364609
-0.36756
-0.0750554
-0.0847139
-0.096824
-0.0913608
-0.149971
-0.117504
-0.248513
-0.180072
-0.112292
-0.0786252
0.0949836
0.259613
0.347551
0.32754
0.555849
1.32776
0.10103
-0.186415
-0.288531
-0.0461681
0.100047
-0.118298
-0.231619
-0.300934
-0.320626
-0.350268
-0.382796
-0.414226
-0.437914
-0.456607
-0.469209
-0.476287
-0.480206
-0.481817
-0.486194
-0.487161
-0.478434
-0.462548
-0.448062
-0.438634
-0.403936
-0.294462
-0.25202
-0.266868
-0.266616
-0.266298
-0.321643
-0.381881
-0.387986
-0.383685
-0.0811566
-0.0897203
-0.101016
-0.0971614
-0.149577
-0.120497
-0.233163
-0.153195
-0.110995
-0.0666098
0.145169
0.266647
0.300325
0.332492
0.435814
0.745474
0.0115214
-0.174225
-0.201867
-0.0700248
-0.0387471
-0.167881
-0.243044
-0.302163
-0.306576
-0.339598
-0.369886
-0.399031
-0.421785
-0.440594
-0.453979
-0.462916
-0.466597
-0.467986
-0.469421
-0.466291
-0.456644
-0.44467
-0.435163
-0.429022
-0.424987
-0.410313
-0.38921
-0.387162
-0.395494
-0.381621
-0.413019
-0.407663
-0.398581
-0.391698
-0.0873699
-0.0948764
-0.105344
-0.102973
-0.149245
-0.123382
-0.218017
-0.162915
-0.1064
-0.0577128
0.154666
0.249717
0.286475
0.281265
0.305929
0.414525
0.07421
-0.114595
-0.143114
-0.101864
-0.0907312
-0.158804
-0.230483
-0.267101
-0.307023
-0.330342
-0.359591
-0.385748
-0.406594
-0.425577
-0.441045
-0.450541
-0.454351
-0.454182
-0.453021
-0.446087
-0.438995
-0.428658
-0.418946
-0.410901
-0.400816
-0.382822
-0.371941
-0.367383
-0.371767
-0.376676
-0.376159
-0.376157
-0.375649
-0.374973
-0.093694
-0.100202
-0.109859
-0.108866
-0.149342
-0.126004
-0.204659
-0.15842
-0.102583
-0.0570456
0.143684
0.233216
0.257554
0.231635
0.239413
0.425931
-0.00804989
-0.109037
-0.122255
-0.117188
-0.128261
-0.166955
-0.219175
-0.281402
-0.2961
-0.323218
-0.344159
-0.37125
-0.392225
-0.411736
-0.426642
-0.429837
-0.439313
-0.439781
-0.436439
-0.431309
-0.42378
-0.417422
-0.411867
-0.406903
-0.408742
-0.306528
-0.381014
-0.362692
-0.363085
-0.361622
-0.362246
-0.362048
-0.362295
-0.363216
-0.100141
-0.105772
-0.11461
-0.114846
-0.149919
-0.129695
-0.191034
-0.154972
-0.104216
-0.0591169
0.104669
0.223741
0.235437
0.192257
0.147009
0.192953
0.17676
-0.112665
-0.118115
-0.130963
-0.153527
-0.194257
-0.240186
-0.271362
-0.293269
-0.307794
-0.330827
-0.356754
-0.37131
-0.394232
-0.404307
-0.412222
-0.415199
-0.419538
-0.416849
-0.412568
-0.406834
-0.401311
-0.395211
-0.350017
-0.320335
-0.310596
-0.322722
-0.338511
-0.349076
-0.344005
-0.354466
-0.349042
-0.348745
-0.34886
-0.106744
-0.111576
-0.119675
-0.120923
-0.1509
-0.133454
-0.178958
-0.149143
-0.104237
-0.0631652
0.151182
0.19872
0.191193
0.161654
0.0965465
0.0436165
-0.0383867
-0.10896
-0.119969
-0.139569
-0.165051
-0.199476
-0.23485
-0.260974
-0.28326
-0.298594
-0.316587
-0.340178
-0.352281
-0.370875
-0.377065
-0.386466
-0.394199
-0.396012
-0.39591
-0.395073
-0.391511
-0.389044
-0.379857
-0.314195
-0.30067
-0.307922
-0.312575
-0.315156
-0.336623
-0.30959
-0.275045
-0.292832
-0.326788
-0.338235
-0.113536
-0.117651
-0.12506
-0.127093
-0.152256
-0.137311
-0.170414
-0.145782
-0.109623
-0.0706568
0.0350601
0.182176
0.205563
0.137296
0.0717724
0.0169874
-0.0607259
-0.103807
-0.122381
-0.145723
-0.17104
-0.200437
-0.229367
-0.253396
-0.273947
-0.291335
-0.306282
-0.32158
-0.33348
-0.34768
-0.352167
-0.362758
-0.367426
-0.372371
-0.374953
-0.378718
-0.385066
-0.386762
-0.395198
-0.38129
-0.371117
-0.366599
-0.373677
-0.377409
-0.366086
-0.344318
-0.348001
-0.341706
-0.366432
-0.363721
-0.120549
-0.124018
-0.130824
-0.133369
-0.154082
-0.141678
-0.16755
-0.144611
-0.115711
-0.0806096
0.0118576
0.186107
0.158768
0.112767
0.0462548
-0.00365137
-0.063841
-0.103576
-0.126398
-0.15071
-0.175249
-0.200908
-0.225395
-0.246757
-0.265018
-0.280563
-0.294013
-0.30371
-0.314932
-0.323023
-0.330697
-0.337448
-0.34346
-0.349507
-0.353977
-0.359652
-0.365659
-0.371175
-0.37401
-0.37399
-0.370511
-0.365592
-0.361869
-0.357782
-0.355201
-0.353931
-0.354415
-0.35322
-0.351107
-0.349287
-0.127818
-0.130695
-0.136986
-0.139766
-0.156474
-0.146482
-0.164021
-0.145501
-0.126596
-0.106864
0.0556443
-0.0219724
0.0273587
0.0705773
0.0165364
-0.0260305
-0.0713677
-0.107262
-0.13154
-0.155453
-0.178504
-0.201241
-0.222483
-0.241296
-0.257485
-0.271138
-0.282595
-0.292046
-0.298284
-0.306541
-0.31241
-0.318756
-0.325298
-0.331606
-0.33805
-0.343659
-0.348282
-0.351834
-0.353974
-0.354541
-0.353389
-0.349856
-0.347301
-0.346389
-0.340575
-0.344594
-0.342342
-0.341543
-0.340651
-0.339853
-0.135371
-0.137703
-0.143547
-0.146321
-0.159497
-0.151659
-0.162836
-0.148207
-0.137311
-0.126863
0.195443
-0.0336731
0.027434
0.0862251
-0.00880657
-0.0479837
-0.0827305
-0.113894
-0.13766
-0.160239
-0.181503
-0.201784
-0.220468
-0.237087
-0.251477
-0.263661
-0.273856
-0.282354
-0.289276
-0.294887
-0.301578
-0.307058
-0.312935
-0.318572
-0.321859
-0.322461
-0.332985
-0.33519
-0.337754
-0.338752
-0.339297
-0.337965
-0.337399
-0.336817
-0.335329
-0.3347
-0.334435
-0.334653
-0.334484
-0.333215
-0.143155
-0.145049
-0.150489
-0.153091
-0.163221
-0.157199
-0.163367
-0.151869
-0.138581
-0.136176
-0.016776
-0.05213
-0.0366489
0.0652007
-0.0285459
-0.0683531
-0.0960505
-0.122616
-0.144698
-0.165408
-0.184745
-0.20282
-0.219341
-0.23406
-0.246878
-0.257833
-0.267104
-0.274984
-0.281785
-0.287755
-0.293193
-0.298296
-0.303205
-0.306277
-0.309288
-0.313328
-0.317531
-0.321873
-0.325735
-0.327107
-0.327992
-0.32849
-0.3287
-0.328813
-0.328778
-0.328643
-0.326401
-0.325461
-0.327562
-0.327483
-0.151195
-0.15276
-0.157815
-0.160131
-0.167698
-0.163162
-0.165561
-0.156381
-0.14181
-0.142149
-0.0947316
-0.0730804
-0.0665571
0.0353014
-0.0558261
-0.0874345
-0.110341
-0.132794
-0.15258
-0.171131
-0.188458
-0.204531
-0.219173
-0.232238
-0.243683
-0.253566
-0.262038
-0.269326
-0.275688
-0.281341
-0.286481
-0.291279
-0.295729
-0.298789
-0.300122
-0.30332
-0.30698
-0.312049
-0.315966
-0.317751
-0.319127
-0.320228
-0.321138
-0.321899
-0.322561
-0.323193
-0.323731
-0.321596
-0.322734
-0.324256
-0.159624
-0.160885
-0.165544
-0.167497
-0.172973
-0.169601
-0.169295
-0.161865
-0.147627
-0.142823
-0.108159
-0.0990286
-0.0910038
0.0243316
-0.0479293
-0.110653
-0.127958
-0.144865
-0.161393
-0.177548
-0.19286
-0.207103
-0.220071
-0.231681
-0.241924
-0.250869
-0.258651
-0.265442
-0.271439
-0.276828
-0.28177
-0.286389
-0.290717
-0.294694
-0.297898
-0.29951
-0.30348
-0.307137
-0.309164
-0.310701
-0.312023
-0.313165
-0.31417
-0.315061
-0.315856
-0.316566
-0.317189
-0.31769
-0.318048
-0.318317
-0.168483
-0.169459
-0.173703
-0.175252
-0.179089
-0.176539
-0.174494
-0.168312
-0.155299
-0.148479
-0.124126
-0.11787
-0.113627
-0.0267384
-0.0957634
-0.126905
-0.142397
-0.156127
-0.170379
-0.184575
-0.198048
-0.210625
-0.222092
-0.232401
-0.241565
-0.249658
-0.256792
-0.263104
-0.268738
-0.273823
-0.278468
-0.282749
-0.2867
-0.290321
-0.293627
-0.296557
-0.298948
-0.301023
-0.302824
-0.304372
-0.305734
-0.306928
-0.307982
-0.308915
-0.309741
-0.310474
-0.311119
-0.311669
-0.312124
-0.312504
-0.177804
-0.178514
-0.182327
-0.183469
-0.186069
-0.184025
-0.181184
-0.175458
-0.164782
-0.158181
-0.140499
-0.138978
-0.145081
-0.13111
-0.135566
-0.13624
-0.153654
-0.166888
-0.179755
-0.19239
-0.204262
-0.215272
-0.225328
-0.234414
-0.242554
-0.249812
-0.256276
-0.262049
-0.26723
-0.27191
-0.276159
-0.280025
-0.28354
-0.286724
-0.289591
-0.292122
-0.294296
-0.296186
-0.297856
-0.299333
-0.300644
-0.301805
-0.302831
-0.303736
-0.304531
-0.305227
-0.305832
-0.306354
-0.306802
-0.307183
-0.18762
-0.188075
-0.191453
-0.192224
-0.193919
-0.192176
-0.18903
-0.184043
-0.175221
-0.16942
-0.156006
-0.154332
-0.154495
-0.154171
-0.1612
-0.162556
-0.169711
-0.181225
-0.190781
-0.201261
-0.210844
-0.221087
-0.22971
-0.237605
-0.244746
-0.251168
-0.256929
-0.262104
-0.266763
-0.27097
-0.274776
-0.278219
-0.281327
-0.284122
-0.286624
-0.288847
-0.290811
-0.292545
-0.294078
-0.295434
-0.296632
-0.29769
-0.298621
-0.299438
-0.300152
-0.300773
-0.301308
-0.301767
-0.302158
-0.302485
-0.197894
-0.198235
-0.201128
-0.201586
-0.202633
-0.201046
-0.198047
-0.193788
-0.186675
-0.182021
-0.173233
-0.173553
-0.173741
-0.183145
-0.135738
-0.14619
-0.176113
-0.19166
-0.201654
-0.210337
-0.21893
-0.227648
-0.235122
-0.241931
-0.248113
-0.253692
-0.258716
-0.263245
-0.267331
-0.271024
-0.274361
-0.277375
-0.280092
-0.282535
-0.284723
-0.286677
-0.288416
-0.289962
-0.291332
-0.292545
-0.293616
-0.294558
-0.295385
-0.296106
-0.296733
-0.297273
-0.297736
-0.298127
-0.298453
-0.298722
-0.208718
-0.208944
-0.211391
-0.211614
-0.212211
-0.210776
-0.20809
-0.204527
-0.198994
-0.195516
-0.189565
-0.190788
-0.190339
-0.201671
-0.177132
-0.148395
-0.163416
-0.203732
-0.212348
-0.220699
-0.227508
-0.234928
-0.241188
-0.247034
-0.252326
-0.25709
-0.261374
-0.265244
-0.268745
-0.271917
-0.274788
-0.277386
-0.279731
-0.281843
-0.283741
-0.285441
-0.286959
-0.288311
-0.289512
-0.290574
-0.29151
-0.292332
-0.29305
-0.293672
-0.294208
-0.294666
-0.295051
-0.295372
-0.295634
-0.295843
-0.220099
-0.220247
-0.222287
-0.222353
-0.222651
-0.221387
-0.219095
-0.216209
-0.212032
-0.209499
-0.205225
-0.206999
-0.206136
-0.212577
-0.216922
-0.152866
-0.156559
-0.210677
-0.22114
-0.230869
-0.237316
-0.244074
-0.249262
-0.253589
-0.257916
-0.261789
-0.265259
-0.268404
-0.271266
-0.273877
-0.276258
-0.278425
-0.280394
-0.282179
-0.283794
-0.28525
-0.28656
-0.287736
-0.288788
-0.289726
-0.29056
-0.291299
-0.29195
-0.292521
-0.293018
-0.293448
-0.293815
-0.294127
-0.294386
-0.294598
-0.232064
-0.232183
-0.233871
-0.233831
-0.233952
-0.232883
-0.231022
-0.228793
-0.225744
-0.224029
-0.221437
-0.223057
-0.223548
-0.227172
-0.230685
-0.189601
-0.165459
-0.231706
-0.23911
-0.242498
-0.246577
-0.25092
-0.255066
-0.260031
-0.264021
-0.266952
-0.269479
-0.27187
-0.274122
-0.27622
-0.278161
-0.279948
-0.281586
-0.283083
-0.284448
-0.285689
-0.286815
-0.287834
-0.288755
-0.289586
-0.290332
-0.291002
-0.291601
-0.292135
-0.292609
-0.293027
-0.293394
-0.293714
-0.293991
-0.294229
-0.244658
-0.244803
-0.246179
-0.246069
-0.246127
-0.245262
-0.243834
-0.242221
-0.240072
-0.238984
-0.237493
-0.238875
-0.239912
-0.243341
-0.248822
-0.258231
-0.260043
-0.261801
-0.244581
-0.254836
-0.260585
-0.268332
-0.267872
-0.270538
-0.27143
-0.273515
-0.274983
-0.276616
-0.278228
-0.279775
-0.281238
-0.28261
-0.283888
-0.285073
-0.286171
-0.287187
-0.288127
-0.288997
-0.289802
-0.290549
-0.291242
-0.291886
-0.292486
-0.293046
-0.29357
-0.29406
-0.29452
-0.294952
-0.295359
-0.295742
-0.257934
-0.258157
-0.259237
-0.259087
-0.259197
-0.258514
-0.257513
-0.256432
-0.255047
-0.254475
-0.25358
-0.254798
-0.255947
-0.258605
-0.26223
-0.268764
-0.270073
-0.270019
-0.273953
-0.269276
-0.261681
-0.269525
-0.278112
-0.255365
-0.250835
-0.266967
-0.279647
-0.280119
-0.281776
-0.282919
-0.284107
-0.285191
-0.286198
-0.287135
-0.288011
-0.288832
-0.289606
-0.290338
-0.291033
-0.291698
-0.292335
-0.292948
-0.29354
-0.294114
-0.294671
-0.295214
-0.295743
-0.29626
-0.296764
-0.297257
-0.271954
-0.272293
-0.273091
-0.272973
-0.273093
-0.272624
-0.272054
-0.271395
-0.270612
-0.270406
-0.269895
-0.270589
-0.271211
-0.272762
-0.273794
-0.276853
-0.275725
-0.280477
-0.282896
-0.300481
-0.218135
-0.247525
-0.267579
-0.267424
-0.269783
-0.285861
-0.286798
-0.286963
-0.287453
-0.287966
-0.288538
-0.289101
-0.289652
-0.290184
-0.290697
-0.291191
-0.291669
-0.29213
-0.292577
-0.29301
-0.29343
-0.293838
-0.294235
-0.294622
-0.294998
-0.295365
-0.295722
-0.29607
-0.296408
-0.296737
-0.286807
-0.287277
-0.287796
-0.287706
-0.287854
-0.287576
-0.287461
-0.287181
-0.287004
-0.286918
-0.286934
-0.287262
-0.287829
-0.28872
-0.289875
-0.29174
-0.293131
-0.298072
-0.302085
-0.317047
-0.320182
-0.293
-0.296287
-0.294018
-0.295219
-0.294355
-0.293779
-0.293602
-0.293483
-0.293386
-0.293331
-0.293315
-0.293334
-0.293383
-0.293454
-0.29354
-0.293638
-0.293743
-0.293852
-0.293965
-0.294079
-0.294193
-0.294306
-0.294418
-0.294528
-0.294636
-0.29474
-0.294841
-0.294939
-0.295033
-0.132903
-0.125831
0.154667
0.0959686
-0.0991978
-0.0991729
-0.110503
-0.0881812
-0.117997
-0.0839222
-0.174521
-0.163289
0.202566
-0.325264
1.18027
0.275281
-0.585372
-0.429679
-1.3281
-0.327997
-0.098246
-0.158677
0.423956
-2.6587
-0.994396
-0.85704
-0.545758
-0.420696
-2.39624
-3.08955
-2.43967
-0.389127
-1.94724
0.240785
4.24977
5.55605
7.44274
-5.26773
49.0948
155.788
21.5853
270.011
17.8002
-75.233
-5.14998
4.54779
16.7402
23.6154
23.9644
18.3348
-0.1369
-0.127723
0.149119
0.045801
-0.105573
-0.111533
-0.123357
-0.139576
-0.124785
-0.114129
-0.308371
-0.22497
-0.606072
-0.449178
0.130153
0.0370315
-0.655185
-0.540508
-1.04693
-0.442517
-0.203941
-0.191535
0.235824
-1.4245
-1.22118
-1.00618
-0.452833
-0.731616
-3.66222
-2.95518
-2.24532
-0.511384
-1.74965
-0.370988
4.26902
4.21477
8.52499
-5.74347
93.3228
115.762
-23.4727
181.557
16.8916
-64.7827
-6.15122
4.24151
15.4753
22.2045
17.2565
16.3738
-0.149388
-0.158469
0.149653
-0.0704941
-0.11866
-0.125935
-0.137573
-0.153946
-0.0995889
-0.0792458
-0.267263
-0.134382
-0.313301
-0.409186
-0.197297
-0.631074
-0.674768
-0.603985
-0.919391
-0.489919
-0.252413
-0.276177
-0.4004
-1.93676
-1.36959
-0.843004
-0.449473
-0.780115
-1.76404
-2.15004
-1.96756
-0.586208
-1.58451
-0.52902
3.35353
5.66265
-3.98668
-0.199436
-0.29303
55.6561
-12.2606
94.9915
-11.4624
-45.9208
4.46972
3.70239
14.2128
20.3812
15.7271
14.4034
-0.16849
-0.177233
0.205455
-0.132335
-0.140366
-0.144137
-0.152341
-0.157404
-0.161822
-0.135435
-0.264383
-0.300516
-0.348317
-0.135021
-0.13553
-0.569361
-0.557999
-0.635196
-0.831702
-0.512328
-0.318586
-0.168669
-0.426249
-0.944771
-1.3064
-0.967805
-0.362938
-0.708359
-1.40042
-2.77217
-1.91201
-0.640069
-1.46308
1.70678
3.12089
2.83599
-1.01624
-1.33618
-0.663373
31.7134
-7.40449
2.3359
50.126
-25.5198
2.33098
3.29198
12.8598
17.0642
14.1098
17.3592
-0.17652
-0.171825
0.13143
-0.162404
-0.168707
-0.169577
-0.172153
-0.162991
-0.175983
-0.187673
-0.256389
-0.297825
-0.387785
-0.375048
-0.414437
-0.554226
-0.612022
-0.657011
-0.754482
-0.514004
-0.393245
-0.210692
-0.486993
-1.30016
-1.13433
-0.808812
-0.3064
-0.0686291
-1.84616
-0.779863
-1.89654
-0.479308
-1.42582
-0.352484
2.85873
1.63339
-0.53634
-1.14057
-0.966011
39.7531
-4.60985
6.56396
-8.83107
-12.9206
0.854918
2.5636
11.4304
15.6176
12.404
13.1057
-0.191853
-0.192843
-0.160345
-0.156352
-0.203159
-0.201825
-0.200251
-0.191908
-0.202472
-0.187611
-0.278295
-0.313605
-0.360224
-0.391538
-0.420273
-0.518966
-0.525323
-0.488047
-0.527676
-0.436274
0.0544375
-0.199148
-0.50828
-0.92776
-0.828253
-0.563175
-0.298737
-0.0650183
-1.59775
-1.78746
-1.66286
-0.882113
-1.46152
0.251816
4.2355
1.41323
-0.217498
-0.760766
-0.58054
20.0126
-2.5075
4.94217
9.54289
-4.3541
-3.92874
0.947881
9.92804
11.8012
10.6117
11.0715
-0.213107
-0.2175
-0.220771
-0.217165
-0.226738
-0.224473
-0.219874
-0.214744
-0.207377
-0.212568
-0.288513
-0.317749
-0.348209
-0.386176
-0.433218
-0.47471
-0.457018
-0.611749
-0.565187
-0.466255
-0.538293
-0.432879
-0.634595
-0.847651
-0.960155
0.184045
-0.0911511
-0.119515
-1.09165
-0.713803
-1.27667
-0.645482
0.0231881
0.706485
0.860266
1.05252
-0.116338
-0.562514
0.369178
13.2373
-0.921366
3.94353
7.62951
-0.058755
-2.22348
0.0910156
8.32521
10.7558
8.72708
8.83948
-0.229998
-0.234753
-0.238818
-0.240912
-0.240118
-0.23898
-0.237843
-0.211393
-0.215367
-0.233742
-0.272905
-0.332113
-0.359221
-0.399847
-0.45209
-0.567082
-0.637658
-0.601353
-0.519369
-0.51623
-0.584236
-0.555746
-0.598424
-0.760875
-0.52343
0.189681
-0.12986
1.75677
-0.888561
-0.361568
-0.964728
-0.496476
-0.553519
-0.94548
0.431373
0.784382
-0.111246
-0.469243
0.489046
11.454
-1.13861
3.32727
1.41753
0.975279
6.29231
-0.569157
6.28859
8.55968
6.89074
4.00453
-0.243493
-0.247326
-0.249341
-0.249266
-0.246975
-0.244695
-0.244312
-0.204149
-0.217415
-0.237542
-0.256916
-0.341349
-0.367397
-0.41014
-0.448101
-0.50196
-0.447171
-0.542114
-0.502991
-0.5142
-0.571507
-0.565939
-0.610679
-0.721292
-0.897036
-0.404119
-0.339776
-0.778741
-0.794912
-0.775511
-0.723669
-0.227494
-0.476757
-0.309988
0.534849
2.81386
-0.16317
-0.404707
0.048776
10.285
2.9596
3.04717
0.854372
1.02161
1.91011
1.02232
3.92795
6.1515
4.98271
1.88378
-0.25851
-0.259468
-0.259599
-0.259396
-0.25643
-0.254996
-0.254656
-0.210896
-0.220329
-0.244136
-0.255826
-0.339934
-0.355407
-0.427927
-0.468795
-0.413501
-0.43296
-0.55477
-0.494891
-0.511112
-0.558859
-0.576426
-0.632127
-0.74903
-0.855258
-0.716186
-0.589623
-0.752158
-0.765643
-0.729298
-0.502382
-0.307802
-0.433404
-0.338692
0.556046
0.942453
-0.174453
-0.346866
0.266976
8.87908
13.1654
2.9876
0.850408
0.972018
1.13729
-0.42997
2.37214
3.53166
3.00607
0.561556
-0.273442
-0.274534
-0.273294
-0.273321
-0.272187
-0.274236
-0.275783
-0.212974
-0.225168
-0.27221
-0.310899
-0.346153
-0.364833
-0.442619
-0.326097
-0.400225
-0.453508
-0.521831
-0.486088
-0.506852
-0.548708
-0.5849
-0.638604
-0.710221
-0.788871
-0.641492
-0.590623
-0.712512
-0.726719
-0.719377
-0.648577
-0.415548
-0.442754
-0.261291
0.161799
0.282364
-0.190239
-0.286094
0.282011
5.90349
-0.429796
2.44962
0.819818
0.984442
-0.371543
-3.73859
1.34164
1.0996
0.726792
0.0895855
-0.290605
-0.291012
-0.290846
-0.291162
-0.292646
-0.299382
-0.309053
-0.25237
-0.207108
-0.317863
-0.336189
-0.353255
-0.383061
-0.432008
-0.358139
-0.374812
-0.423909
-0.472572
-0.482731
-0.51029
-0.542909
-0.589128
-0.637139
-0.679022
-0.734015
-0.663855
-0.61841
-0.700168
-0.695984
-0.696112
-0.62559
-0.430887
-0.471528
-0.42259
-0.199425
0.13148
-0.165299
-0.240807
-0.350816
5.38589
4.50653
2.28188
0.821959
0.980378
0.0680663
-3.71585
1.07292
0.397002
-0.149336
-0.0420063
-0.308335
-0.30817
-0.308082
-0.30766
-0.308196
-0.312979
-0.318959
-0.324333
-0.333136
-0.338929
-0.349595
-0.364242
-0.385589
-0.416478
-0.423378
-0.380609
-0.40528
-0.456133
-0.4424
-0.517288
-0.540011
-0.592687
-0.610066
-0.654404
-0.695841
-0.662948
-0.599174
-0.627621
-0.670604
-0.67351
-0.618521
-0.555312
-0.460642
-0.375175
-0.194743
0.00666578
-0.252323
-0.257569
-0.349622
3.20603
-0.868763
1.87227
0.816918
0.935093
0.146404
-0.168793
0.978165
0.235625
-0.0379333
-0.0432738
-0.324385
-0.326051
-0.327949
-0.324313
-0.319607
-0.317976
-0.319506
-0.32345
-0.327612
-0.337993
-0.353485
-0.373271
-0.385303
-0.404006
-0.418763
-0.412404
-0.419894
-0.471836
-0.403896
-0.510866
-0.535621
-0.593676
-0.583583
-0.642923
-0.671197
-0.667885
-0.669882
-0.656536
-0.644538
-0.651789
-0.6147
-0.535665
-0.447025
-0.35038
-0.208469
-0.0598846
-0.0319755
-0.043519
-0.353959
1.12154
-0.380253
1.32949
0.773022
0.846564
0.156011
0.184544
0.243921
0.108108
-0.0368914
-0.0454476
-0.33139
-0.334898
-0.294064
-0.300621
-0.331195
-0.328692
-0.325429
-0.329473
-0.337904
-0.330994
-0.365344
-0.378443
-0.389526
-0.404299
-0.424672
-0.420597
-0.461888
-0.528604
-0.358526
-0.514442
-0.536642
-0.576519
-0.594257
-0.642569
-0.66239
-0.662108
-0.6555
-0.641904
-0.609161
-0.633231
-0.58742
-0.516974
-0.428331
-0.339222
-0.227471
-0.0982129
-0.0953304
-0.224839
-0.357477
0.843519
0.737263
1.1953
0.722977
0.78788
0.157838
0.115232
0.169857
0.085594
-0.0409518
-0.046342
-0.321011
-0.312471
-0.298358
-0.295202
-0.329776
-0.33471
-0.328901
-0.335637
-0.330114
-0.335817
-0.372678
-0.38263
-0.393572
-0.406475
-0.421738
-0.42124
-0.445701
-0.485191
-0.293271
-0.516221
-0.532904
-0.575524
-0.603974
-0.637371
-0.658388
-0.657595
-0.643958
-0.625725
-0.612243
-0.570159
-0.563469
-0.490571
-0.40764
-0.333183
-0.240945
-0.128038
-0.118407
-0.183743
-0.336137
-0.484807
1.44891
1.20387
0.696368
0.742324
0.164734
0.100945
0.147979
0.0789085
-0.0423959
-0.0472878
-0.318
-0.318168
-0.314361
-0.317105
-0.339531
-0.342012
-0.335576
-0.34531
-0.334483
-0.345742
-0.374598
-0.384217
-0.394516
-0.405768
-0.415776
-0.414587
-0.42551
-0.449079
-0.382098
-0.500369
-0.518791
-0.563781
-0.599894
-0.634137
-0.654008
-0.651194
-0.632511
-0.609751
-0.585922
-0.550311
-0.449083
-0.462896
-0.388274
-0.325563
-0.254686
-0.141365
-0.105614
-0.174733
-0.314699
-0.652135
2.34594
1.1276
0.666292
0.700698
0.180382
0.116385
0.142871
0.0620967
-0.0428561
-0.0481548
-0.293346
-0.3464
-0.350663
-0.348304
-0.350466
-0.346522
-0.34677
-0.349703
-0.342968
-0.367072
-0.375945
-0.384215
-0.39314
-0.403002
-0.410829
-0.408528
-0.408911
-0.429392
-0.398013
-0.480231
-0.528173
-0.562004
-0.595911
-0.629795
-0.647761
-0.6425
-0.620069
-0.59405
-0.568641
-0.547797
-0.541284
-0.458252
-0.393213
-0.317958
-0.254636
-0.169825
-0.233363
-0.236737
-0.319747
-0.162606
2.66978
1.04919
0.621689
0.651699
0.190186
0.104124
0.0893622
0.056095
-0.0422153
-0.049317
-0.375388
-0.371521
-0.364731
-0.360199
-0.357342
-0.355153
-0.355065
-0.350257
-0.347967
-0.376902
-0.37887
-0.383899
-0.390306
-0.398243
-0.406981
-0.411056
-0.41421
-0.408405
-0.320555
-0.459611
-0.402505
-0.557729
-0.591519
-0.621391
-0.637366
-0.630188
-0.605699
-0.578034
-0.552434
-0.531134
-0.514435
-0.449536
-0.391528
-0.313458
-0.259961
-0.173291
-0.206423
-0.221211
-0.35604
-0.0494808
3.19338
0.972824
0.563892
0.595324
0.192971
0.114441
0.0850688
0.0420966
-0.0418277
-0.0510114
-0.366701
-0.36616
-0.365583
-0.365138
-0.364621
-0.365027
-0.358996
-0.354183
-0.364131
-0.372388
-0.377923
-0.383955
-0.390395
-0.398198
-0.410603
-0.425539
-0.418385
-0.411676
-0.430946
-0.395106
-0.416386
-0.534951
-0.58593
-0.608718
-0.622455
-0.613466
-0.588799
-0.561103
-0.535919
-0.514033
-0.490815
-0.436814
-0.381711
-0.31187
-0.263672
-0.197644
-0.198123
-0.220249
-0.362929
-0.149872
2.74679
0.899204
0.5106
0.545685
0.193357
0.120791
0.0802682
0.0366915
-0.0421615
-0.0533841
-0.368035
-0.368641
-0.369034
-0.369365
-0.369618
-0.368815
-0.34823
-0.350746
-0.370968
-0.374581
-0.379738
-0.384858
-0.39081
-0.398353
-0.406051
-0.293402
-0.226695
-0.273365
-0.313216
-0.327637
-0.37741
-0.442973
-0.466892
-0.599054
-0.604697
-0.592622
-0.568838
-0.542285
-0.518863
-0.496311
-0.469905
-0.423633
-0.372487
-0.311182
-0.2657
-0.215527
-0.194771
-0.204495
-0.332895
-0.347568
2.22635
0.709286
0.45974
0.50482
0.190254
0.123865
0.0750056
0.0311793
-0.0432467
-0.0564114
-0.380066
-0.377742
-0.376254
-0.375369
-0.374648
-0.371175
-0.372656
-0.371672
-0.377103
-0.379271
-0.382417
-0.386546
-0.39075
-0.397024
-0.404296
-0.30443
-0.243844
-0.3519
-0.430343
-0.434508
-0.380109
-0.393224
-0.500726
-0.582315
-0.57883
-0.566916
-0.546091
-0.523413
-0.500875
-0.478271
-0.450891
-0.410284
-0.363826
-0.310775
-0.266154
-0.224416
-0.19182
-0.189899
-0.305842
-0.342417
2.74671
0.631074
0.40553
0.456301
0.184205
0.123917
0.0691512
0.0254412
-0.0449373
-0.0600175
-0.38611
-0.382227
-0.379613
-0.377354
-0.375283
-0.376615
-0.376404
-0.376829
-0.378217
-0.380435
-0.382859
-0.386519
-0.389868
-0.395289
-0.399653
-0.403222
-0.400319
-0.399991
-0.391052
-0.383745
-0.402815
-0.404245
-0.539213
-0.54998
-0.544972
-0.536014
-0.521008
-0.502415
-0.48215
-0.46021
-0.433125
-0.397029
-0.35542
-0.309064
-0.264647
-0.230431
-0.188588
-0.173679
-0.288476
-0.370135
1.82294
0.529475
0.362972
0.410298
0.175682
0.121074
0.0626541
0.0194229
-0.0472272
-0.0641545
-0.374424
-0.374032
-0.37381
-0.373689
-0.37386
-0.374351
-0.375128
-0.376079
-0.377431
-0.378441
-0.380732
-0.382767
-0.385747
-0.388308
-0.389944
-0.393191
-0.391405
-0.388013
-0.381895
-0.371484
-0.379565
-0.42131
-0.482169
-0.501445
-0.505245
-0.503754
-0.495388
-0.481042
-0.463193
-0.442391
-0.416253
-0.380752
-0.346209
-0.305472
-0.263043
-0.231308
-0.199736
-0.166711
-0.25587
-0.254575
0.842014
0.399182
0.314814
0.362508
0.165375
0.115916
0.0554659
0.0130374
-0.0501304
-0.0688
-0.364016
-0.364994
-0.366077
-0.367256
-0.368524
-0.369862
-0.37122
-0.372652
-0.374144
-0.375639
-0.377234
-0.378854
-0.381036
-0.382467
-0.384308
-0.387126
-0.386608
-0.387044
-0.379499
-0.374643
-0.381993
-0.390562
-0.437538
-0.461551
-0.472151
-0.475406
-0.471229
-0.460398
-0.444636
-0.425144
-0.400025
-0.360043
-0.322722
-0.300577
-0.261144
-0.230874
-0.195197
-0.164422
-0.213271
-0.117851
0.21963
0.294747
0.281087
0.318022
0.153845
0.108408
0.0474047
0.0063289
-0.0536925
-0.0739476
-0.353823
-0.357322
-0.35897
-0.360299
-0.362185
-0.364416
-0.36595
-0.367446
-0.36899
-0.370483
-0.371981
-0.373565
-0.375292
-0.377181
-0.379048
-0.381382
-0.384602
-0.377424
-0.33239
-0.324539
-0.32634
-0.366003
-0.431816
-0.440471
-0.447777
-0.451778
-0.449838
-0.44128
-0.427034
-0.408788
-0.384533
-0.345975
-0.312906
-0.294546
-0.258836
-0.230133
-0.191243
-0.160246
-0.170632
-0.0979049
0.191533
0.241989
0.248728
0.275427
0.140692
0.0986143
0.0385903
-0.000902724
-0.0578693
-0.0796061
-0.345961
-0.348574
-0.353577
-0.354685
-0.355723
-0.358056
-0.358441
-0.35995
-0.361654
-0.363302
-0.365005
-0.366723
-0.368572
-0.370675
-0.372945
-0.373693
-0.377383
-0.361743
-0.314672
-0.308826
-0.314839
-0.371182
-0.413279
-0.419726
-0.426825
-0.431848
-0.431266
-0.424017
-0.410654
-0.39323
-0.369062
-0.333106
-0.315466
-0.288573
-0.256386
-0.227538
-0.193371
-0.157609
-0.138266
-0.0561961
0.17208
0.19635
0.215375
0.234575
0.125716
0.0868193
0.0291259
-0.00891188
-0.0626653
-0.08579
-0.360582
-0.359747
-0.35785
-0.352176
-0.353083
-0.352244
-0.350421
-0.350763
-0.353661
-0.355143
-0.357084
-0.358751
-0.361181
-0.363663
-0.365329
-0.369229
-0.371191
-0.378359
-0.362559
-0.365263
-0.372647
-0.38621
-0.394387
-0.400672
-0.40833
-0.415095
-0.415556
-0.408919
-0.395761
-0.378546
-0.357028
-0.321108
-0.308477
-0.283135
-0.253174
-0.224504
-0.19043
-0.15346
-0.119406
-0.0429151
0.138791
0.155426
0.181896
0.195573
0.10891
0.0732175
0.0188903
-0.0177073
-0.0680539
-0.0924871
-0.347933
-0.346944
-0.346308
-0.345275
-0.343708
-0.343417
-0.342016
-0.34166
-0.342294
-0.343422
-0.344484
-0.34657
-0.350466
-0.352957
-0.353986
-0.355829
-0.359089
-0.360796
-0.362845
-0.365534
-0.366008
-0.369299
-0.374512
-0.381582
-0.39272
-0.403074
-0.403869
-0.396778
-0.382971
-0.365151
-0.344806
-0.312323
-0.301765
-0.277716
-0.249704
-0.221431
-0.187663
-0.150295
-0.108644
-0.0375428
0.104748
0.119036
0.148745
0.158442
0.0904169
0.0580177
0.00780549
-0.0273084
-0.0742782
-0.0994652
-0.339359
-0.338508
-0.336855
-0.339404
-0.336115
-0.336698
-0.338178
-0.336844
-0.337139
-0.339761
-0.3413
-0.342376
-0.343521
-0.344152
-0.346288
-0.34685
-0.348316
-0.349528
-0.349783
-0.350125
-0.349973
-0.350866
-0.354359
-0.362108
-0.381635
-0.39791
-0.397058
-0.387936
-0.372473
-0.353731
-0.33457
-0.306567
-0.294557
-0.272236
-0.2462
-0.218742
-0.185938
-0.14889
-0.104936
-0.0412298
0.071315
0.0855358
0.116498
0.123114
0.0705202
0.0414306
-0.00418341
-0.0377218
-0.0812932
-0.106866
-0.335621
-0.334933
-0.334602
-0.33444
-0.334391
-0.334668
-0.334818
-0.334264
-0.334809
-0.335306
-0.335869
-0.33657
-0.337217
-0.337846
-0.338688
-0.339605
-0.340192
-0.340114
-0.339339
-0.338021
-0.336253
-0.333747
-0.33345
-0.337985
-0.333822
-0.327875
-0.361761
-0.379324
-0.357042
-0.342547
-0.323198
-0.304908
-0.287703
-0.267063
-0.243011
-0.216674
-0.18538
-0.149423
-0.106283
-0.0499113
0.0389536
0.0549088
0.0845074
0.0894491
0.0495101
0.023668
-0.0171229
-0.0489332
-0.0891273
-0.114743
-0.327049
-0.330606
-0.329691
-0.328158
-0.33018
-0.330372
-0.330493
-0.330526
-0.330624
-0.330874
-0.331197
-0.331551
-0.33192
-0.332311
-0.332776
-0.333218
-0.333418
-0.33311
-0.332072
-0.330121
-0.327031
-0.322417
-0.317323
-0.247021
-0.176648
-0.157623
-0.201856
-0.341169
-0.337649
-0.326656
-0.312559
-0.297218
-0.281207
-0.262473
-0.24035
-0.215426
-0.18603
-0.151879
-0.111356
-0.0618619
0.00839481
0.026065
0.0533988
0.0574386
0.0276489
0.00493635
-0.0310486
-0.0609114
-0.097805
-0.123129
-0.324179
-0.324562
-0.324912
-0.325013
-0.325351
-0.325393
-0.32552
-0.325698
-0.325924
-0.32614
-0.326405
-0.326718
-0.327075
-0.327482
-0.327943
-0.328416
-0.32883
-0.329099
-0.329171
-0.329195
-0.330063
-0.33184
-0.286437
-0.151162
-0.145826
-0.126658
-0.117757
-0.248177
-0.322215
-0.314455
-0.303082
-0.290114
-0.275655
-0.258655
-0.23843
-0.215145
-0.187894
-0.156128
-0.119114
-0.0758919
-0.020156
-0.00130118
0.0231479
0.0269996
0.00515502
-0.0145747
-0.0459512
-0.073639
-0.107344
-0.132045
-0.318639
-0.318904
-0.319181
-0.319441
-0.319689
-0.319927
-0.320165
-0.320413
-0.320681
-0.32098
-0.321322
-0.321717
-0.322181
-0.322733
-0.323401
-0.324225
-0.325273
-0.326678
-0.328705
-0.331889
-0.337562
-0.348124
-0.305676
-0.16183
-0.153884
-0.135041
-0.15786
-0.284748
-0.311418
-0.3049
-0.295033
-0.283963
-0.271209
-0.255778
-0.237387
-0.215918
-0.190981
-0.161964
-0.128784
-0.0912688
-0.0468138
-0.0274939
-0.00612349
-0.00207451
-0.0177951
-0.0347031
-0.0617856
-0.0870999
-0.117758
-0.14151
-0.312838
-0.313157
-0.313471
-0.313776
-0.314068
-0.314354
-0.31464
-0.314931
-0.315231
-0.315551
-0.315903
-0.316303
-0.316771
-0.317339
-0.318052
-0.318982
-0.320246
-0.322043
-0.324756
-0.329054
-0.3366
-0.348951
-0.358214
-0.331614
-0.211634
-0.239239
-0.295327
-0.305922
-0.299009
-0.294781
-0.287614
-0.278671
-0.26777
-0.253892
-0.237311
-0.217796
-0.195269
-0.169168
-0.139836
-0.107506
-0.0718176
-0.0527359
-0.0343439
-0.0299899
-0.0410611
-0.0553211
-0.0784901
-0.101292
-0.129034
-0.151538
-0.307514
-0.307824
-0.308121
-0.308407
-0.30868
-0.308942
-0.309194
-0.309435
-0.309669
-0.3099
-0.310132
-0.310374
-0.310637
-0.310941
-0.311312
-0.311797
-0.312459
-0.31342
-0.314869
-0.317081
-0.32067
-0.326208
-0.334147
-0.334963
-0.329868
-0.315912
-0.299355
-0.303262
-0.29474
-0.28929
-0.282798
-0.274983
-0.265502
-0.253122
-0.238323
-0.220814
-0.200717
-0.177561
-0.151951
-0.12425
-0.0954324
-0.0771923
-0.0615343
-0.0569209
-0.0645296
-0.0763372
-0.0959932
-0.116222
-0.141138
-0.162139
-0.302767
-0.303025
-0.303267
-0.30349
-0.303693
-0.303872
-0.304024
-0.304145
-0.30423
-0.304275
-0.304274
-0.304222
-0.304112
-0.303938
-0.303697
-0.303389
-0.303025
-0.302609
-0.302209
-0.301917
-0.301961
-0.302673
-0.304515
-0.305578
-0.30617
-0.302293
-0.294612
-0.292442
-0.290083
-0.286438
-0.280824
-0.273839
-0.264886
-0.253689
-0.240567
-0.225033
-0.207259
-0.186999
-0.164893
-0.141308
-0.117912
-0.101006
-0.0877675
-0.0830353
-0.0881135
-0.0976943
-0.114218
-0.131889
-0.154038
-0.173319
-0.298946
-0.299144
-0.29932
-0.29947
-0.29959
-0.299674
-0.299713
-0.299699
-0.299621
-0.299465
-0.299216
-0.298854
-0.298356
-0.297694
-0.296838
-0.295756
-0.294414
-0.292775
-0.290827
-0.288727
-0.28704
-0.286073
-0.285085
-0.283637
-0.282927
-0.282472
-0.281589
-0.283953
-0.286246
-0.286578
-0.283482
-0.277434
-0.266938
-0.255954
-0.244197
-0.230419
-0.214913
-0.197377
-0.178499
-0.158593
-0.139465
-0.124339
-0.113172
-0.108475
-0.111758
-0.119362
-0.133088
-0.148295
-0.167702
-0.185086
-0.296011
-0.296153
-0.29627
-0.296358
-0.296409
-0.296415
-0.296366
-0.296249
-0.296049
-0.295748
-0.295324
-0.294752
-0.294004
-0.293052
-0.291876
-0.290486
-0.288895
-0.286996
-0.284552
-0.281514
-0.278781
-0.277198
-0.274489
-0.270312
-0.268677
-0.269561
-0.268038
-0.27768
-0.272638
-0.286834
-0.286116
-0.283446
-0.270808
-0.259962
-0.249188
-0.236915
-0.223601
-0.208587
-0.192661
-0.176051
-0.160351
-0.147306
-0.137884
-0.13339
-0.135457
-0.141334
-0.152584
-0.165406
-0.182105
-0.19745
-0.294773
-0.294926
-0.29506
-0.295168
-0.295243
-0.295276
-0.295254
-0.29516
-0.294974
-0.294667
-0.294201
-0.293524
-0.292564
-0.291216
-0.289318
-0.286643
-0.282938
-0.277901
-0.271058
-0.264067
-0.262387
-0.265566
-0.266014
-0.262004
-0.264887
-0.243243
-0.205612
-0.173371
-0.152729
-0.193944
-0.229367
-0.277611
-0.273951
-0.263929
-0.255003
-0.244128
-0.233238
-0.22051
-0.207298
-0.193657
-0.180874
-0.169941
-0.162094
-0.15791
-0.159261
-0.163625
-0.172681
-0.183223
-0.197239
-0.210427
-0.294439
-0.29464
-0.294836
-0.295024
-0.295201
-0.295361
-0.295498
-0.295603
-0.295667
-0.295677
-0.29562
-0.295489
-0.295288
-0.295038
-0.294855
-0.295304
-0.297607
-0.302097
-0.306562
-0.262465
-0.169646
-0.148446
-0.146653
-0.189446
-0.175746
-0.155285
-0.143127
-0.193999
-0.233089
-0.235429
-0.21076
-0.274843
-0.279448
-0.267901
-0.261308
-0.252381
-0.243287
-0.233012
-0.222368
-0.211434
-0.201249
-0.19237
-0.186011
-0.182382
-0.183112
-0.186247
-0.193362
-0.201759
-0.213115
-0.22404
-0.296117
-0.296511
-0.296945
-0.297425
-0.297961
-0.298566
-0.299256
-0.300056
-0.300999
-0.302131
-0.303525
-0.305291
-0.307613
-0.310819
-0.315531
-0.323074
-0.335632
-0.354697
-0.380881
-0.34719
-0.299398
-0.288085
-0.341917
-0.308015
-0.311307
-0.310886
-0.308763
-0.300266
-0.292731
-0.293042
-0.293569
-0.282114
-0.284823
-0.27653
-0.269177
-0.261663
-0.254202
-0.246132
-0.237881
-0.229457
-0.221655
-0.21476
-0.209829
-0.206846
-0.207181
-0.20934
-0.214679
-0.221046
-0.229771
-0.238325
-0.297755
-0.298294
-0.298901
-0.299591
-0.30038
-0.301292
-0.302354
-0.303607
-0.305103
-0.306916
-0.309151
-0.311966
-0.315599
-0.320476
-0.327301
-0.3374
-0.352856
-0.374881
-0.401017
-0.398739
-0.382098
-0.357312
-0.336041
-0.325247
-0.317134
-0.312783
-0.308821
-0.303942
-0.298533
-0.296845
-0.294057
-0.290222
-0.284758
-0.280364
-0.275852
-0.270883
-0.265549
-0.259759
-0.253848
-0.247823
-0.242272
-0.237309
-0.233773
-0.231518
-0.231637
-0.233005
-0.236711
-0.24114
-0.247255
-0.253329
-0.297068
-0.297425
-0.297824
-0.298271
-0.298776
-0.299346
-0.299995
-0.300736
-0.301586
-0.302567
-0.303707
-0.305042
-0.306618
-0.308495
-0.310753
-0.313502
-0.316889
-0.321041
-0.325741
-0.330125
-0.332295
-0.326414
-0.31795
-0.311938
-0.30854
-0.306705
-0.304069
-0.301664
-0.299383
-0.297557
-0.295618
-0.293113
-0.290035
-0.287139
-0.284144
-0.280944
-0.27759
-0.274001
-0.270369
-0.26668
-0.263308
-0.260256
-0.25811
-0.256655
-0.25669
-0.257401
-0.25958
-0.262128
-0.265636
-0.269117
-0.295126
-0.295226
-0.295336
-0.295456
-0.295589
-0.295735
-0.295895
-0.296069
-0.29626
-0.296467
-0.296691
-0.296933
-0.297194
-0.29747
-0.297751
-0.298012
-0.298199
-0.298266
-0.298079
-0.297518
-0.296292
-0.294695
-0.294915
-0.297076
-0.299589
-0.301382
-0.302396
-0.302556
-0.301867
-0.300883
-0.299539
-0.297867
-0.296069
-0.294494
-0.293043
-0.291634
-0.290281
-0.288903
-0.287568
-0.286219
-0.285032
-0.283906
-0.283187
-0.282591
-0.282641
-0.282768
-0.283484
-0.284166
-0.285038
-0.285786
)
;
boundaryField
{
leftWall
{
type calculated;
value nonuniform List<scalar>
20
(
35.4471
33.5765
31.6993
29.8994
28.189
26.5619
25.0162
23.5544
22.1771
20.8831
19.6704
18.5354
17.4763
16.4894
20.4911
15.931
15.1572
14.4436
13.7835
13.1702
)
;
}
rightWall
{
type calculated;
value nonuniform List<scalar>
20
(
26.0066
24.1449
22.3177
20.5863
18.9483
17.3966
15.9288
14.5432
13.238
12.3067
11.0641
9.91297
8.94078
8.02551
28.6807
21.8546
21.1798
20.7391
20.1924
19.648
)
;
}
lowerWall
{
type calculated;
value nonuniform List<scalar>
100
(
36.4116
41.9733
42.407
44.4543
53.2359
87.0478
195.805
186.722
-20.2243
-63.0392
53.0442
17.4955
10.7244
9.32278
-8.14207
-6.39257
-7.70942
-9.13058
-13.1244
-7.52623
-3.92189
-3.05567
-2.94988
-2.69618
-1.95385
-1.13642
-0.499278
-0.256015
-0.151648
-0.182398
-0.146808
0.0804574
0.163946
0.0966613
0.0685092
0.0658738
0.0810476
0.0660223
0.0664727
0.0683083
0.0686794
0.0953964
0.0643525
0.0792762
0.0814501
0.072489
0.0734736
0.0561662
0.0471809
0.0451187
0.0390274
0.0339592
0.0292703
0.0224466
0.0115673
-0.00484624
-0.0290894
-0.0651757
-0.104444
-0.183575
-2.1579
-2.43262
28.2994
44.7284
35.1311
8.15507
-18.9733
1.23011
0.74159
0.647755
0.455802
0.543289
0.239575
-1.33379
-3.03561
-3.22853
-3.87307
-4.25772
-4.59953
-5.23322
-5.66232
-6.66448
-6.93119
-9.12198
-12.8497
-19.2894
-18.1364
-21.9579
-30.9267
-82.5402
-44.9957
-283.455
-224.276
-179.181
-50.2196
1.644
24.6494
23.859
36.3039
26.9796
)
;
}
atmosphere
{
type calculated;
value nonuniform List<scalar>
190
(
-20.3304
-21.9143
-23.2254
-24.4497
-26.2706
-29.039
-31.1922
-33.3595
-33.3622
-8.7809
-0.0582562
-0.0434253
-0.0462526
-0.0495118
-0.0536492
-0.0559352
-0.0591576
-0.0628286
-0.0666969
-0.0707736
-0.0750537
-0.0795792
-0.0843419
-0.0893664
-0.0946607
-0.10024
-0.106118
-0.112313
-0.11884
-0.125718
-0.132965
-0.140606
-0.148663
-0.157149
-0.166089
-0.175509
-0.185438
-0.195905
-0.206938
-0.218567
-0.230814
-0.243705
-0.257268
-0.271541
-0.286575
-0.294501
-0.295056
-0.295426
-0.295327
-0.295502
-0.295285
-0.295441
-0.295262
-0.295369
-0.295282
-0.295374
-0.295408
-0.295544
-0.295774
-0.295772
-0.296276
-0.294833
-0.2943
-0.2943
-0.337644
-0.347921
-0.544881
-0.355513
-0.29433
-0.294304
-0.294303
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.2943
-0.294312
-0.295779
-0.298873
-0.301684
-0.30389
-0.305338
-0.3055
-0.304508
-0.303691
-0.302417
-0.300806
-0.299134
-0.298096
-0.297448
-0.296991
-0.296717
-0.296487
-0.296346
-0.29618
-0.296112
-0.29595
-0.295968
-0.295811
-0.2959
-0.295745
-0.295759
-0.295509
-0.295095
-0.294405
-20.3257
-21.8868
-23.5534
-24.9708
-26.9432
-29.1004
-31.1619
-33.0828
-27.2217
-18.4051
-5.26316
-0.0443105
-0.0470126
-0.0500188
-0.0532071
-0.0561461
-0.0593006
-0.0628153
-0.0666833
-0.0707656
-0.0750594
-0.0795734
-0.0843418
-0.0893663
-0.0946607
-0.10024
-0.106118
-0.112314
-0.118886
-0.125826
-0.133122
-0.140792
-0.148857
-0.157343
-0.166276
-0.175685
-0.185602
-0.196056
-0.207073
-0.218681
-0.230901
-0.243763
-0.257302
-0.271558
-0.286578
)
;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"stig.m.nilsen@gmail.com"
] | stig.m.nilsen@gmail.com | |
16bb8895895d27c7cf333f6b2b4a84c76bb80d73 | 43eb4b71987a11905dfacfd684c20247f171b689 | /solution/51/solution.cpp | af5809ead95976937b2a28717851f09938ace47c | [] | no_license | youjiajia/learn-leetcode | a44cd994df1f103cd284e561ac82580739dcdeaa | f87b018f7abcdc6e7ae7532810688f9a9d8cbb41 | refs/heads/master | 2021-09-14T23:39:26.459338 | 2018-05-22T12:11:13 | 2018-05-22T12:11:13 | 104,706,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,725 | cpp | #include <stdio.h>
#include <vector>
#include <string>
class Solution {
public:
std::vector<std::vector<std::string> > solveNQueens(int n) {
std::vector<std::vector<std::string> > result;
std::vector<std::string> item;
std::vector<std::string> nowboard;
for(int i=0;i< n;i++){
std::string s;
for(int x=0;x< n;x++){
s += '.';
}
nowboard.push_back(s);
item.push_back(s);
}
complateNQueue(0, item, result, nowboard);
return result;
}
void updateboard(std::vector<std::string>& nowboard, int x, int y){
nowboard[x][y] = '1';
static const int markx[] = {0, 0, 1, 1, 1, -1, -1, -1};
static const int marky[] = {-1, 1, 0, -1, 1, 0, -1, 1};
for(int i=0;i<nowboard.size();i++){
for(int j=0;j<8;j++){
int newx = x + markx[j]*i;
int newy = y + marky[j]*i;
if(newx>=0&&newx<nowboard.size()&&newy>=0&&newy<nowboard.size())nowboard[newx][newy]='1';
}
}
}
void complateNQueue(int x, std::vector<std::string>& item, std::vector<std::vector<std::string> >& result, std::vector<std::string>& nowboard){
if(x== nowboard.size()){result.push_back(item);return;}
for(int y=0;y<nowboard.size();y++){
if(nowboard[x][y]=='1')continue;
std::vector<std::string> copyboard = nowboard;
item[x][y] = 'Q';
updateboard(nowboard, x, y);
complateNQueue(x+1, item, result, nowboard);
nowboard = copyboard;
item[x][y]='.';
}
}
};
int main(){
Solution s;
s.solveNQueens(1);
} | [
"jasonyou.info@gmail.com"
] | jasonyou.info@gmail.com |
be210ce6c548480833db72b5eae46332812e261b | 1891b5adfbcb3ac1d2507e0b458f8fda274d72a8 | /TP1/Source/SoftDesignTraining/SDTCollectible.h | c1758d90ffeddca3a4c78992e0123d79fa908e24 | [] | no_license | anthonysarkis/LOG8235-AgentJeux | e56eee30fe0b7373aa9a55373d5364c451fb7611 | 0787ac796fec05cd7ba476778907273018fc2e6c | refs/heads/master | 2023-04-05T16:58:14.413542 | 2021-04-18T16:29:03 | 2021-04-18T16:29:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/StaticMeshActor.h"
#include "SDTCollectible.generated.h"
/**
*
*/
UCLASS()
class SOFTDESIGNTRAINING_API ASDTCollectible : public AStaticMeshActor
{
GENERATED_BODY()
public:
ASDTCollectible();
void Collect();
void OnCooldownDone();
bool IsOnCooldown();
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = AI)
float m_CollectCooldownDuration = 10.f;
protected:
FTimerHandle m_CollectCooldownTimer;
USoundBase* Sound;
UParticleSystem* Particles;
};
| [
"savoiepe@gmail.com"
] | savoiepe@gmail.com |
5947e51017bd37de7968456c4f71ee9973ff024a | a465a2b5acccb364d67ca1dfacf07f82cb19b642 | /chrome/browser/enterprise/connectors/file_system/box_uploader.cc | e398792b3dee98a30b4ce66cd11f5b7cbbd460de | [
"BSD-3-Clause"
] | permissive | emlxy/chromium | f80e7aa71ee54db72e4bb1fc4cd7bded8a373634 | d9d451fd95061797352d015879b4d7099efdb2a6 | refs/heads/master | 2023-06-17T12:21:00.785160 | 2021-07-23T06:39:49 | 2021-07-23T06:39:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,300 | cc | // Copyright 2021 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/enterprise/connectors/file_system/box_uploader.h"
#include "base/files/file_util.h"
#include "base/i18n/time_formatting.h"
#include "base/i18n/unicodestring.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/enterprise/connectors/connectors_prefs.h"
#include "chrome/browser/enterprise/connectors/file_system/box_api_call_flow.h"
#include "chrome/browser/enterprise/connectors/file_system/box_api_call_response.h"
#include "chrome/browser/enterprise/connectors/file_system/box_upload_file_chunks_handler.h"
#include "chrome/browser/enterprise/connectors/file_system/rename_handler.h"
#include "components/download/public/common/download_interrupt_reasons_utils.h"
#include "components/prefs/pref_service.h"
#include "net/http/http_status_code.h"
#include "third_party/icu/source/common/unicode/utypes.h"
#include "third_party/icu/source/i18n/unicode/calendar.h"
namespace {
constexpr auto kFileSuccess = base::File::Error::FILE_OK;
base::File::Error DeleteIfExists(base::FilePath path) {
DCHECK(!path.empty());
if (!base::PathExists(path)) {
// If the file is deleted by some other thread, how can we be sure what we
// read and uploaded was correct?! So report as error. Otherwise, it is
// considered successful to
// attempt to delete a file that does not exist by base::DeleteFile().
return base::File::Error::FILE_ERROR_NOT_FOUND;
}
return base::DeleteFile(path) ? kFileSuccess : base::File::GetLastFileError();
}
using download::ConvertFileErrorToInterruptReason;
using download::ConvertNetErrorToInterruptReason;
using download::DownloadInterruptReasonToString;
constexpr auto kSuccess = download::DOWNLOAD_INTERRUPT_REASON_NONE;
constexpr auto kBoxUnknownError =
download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
const char kBoxErrorMessageFormat[] = "%d %s"; // 404 "not_found"
const char kBoxMoreMessageFormat[] = "Request ID %s"; // <request_id>
} // namespace
namespace enterprise_connectors {
const char kUniquifierUmaLabel[] = "Enterprise.FileSystem.Uniquifier";
////////////////////////////////////////////////////////////////////////////////
// BoxUploader
////////////////////////////////////////////////////////////////////////////////
// static
const FileSystemServiceProvider BoxUploader::kServiceProvider = BOX;
// static
std::unique_ptr<BoxUploader> BoxUploader::Create(
download::DownloadItem* download_item) {
if (static_cast<size_t>(download_item->GetTotalBytes()) <
BoxApiCallFlow::kChunkFileUploadMinSize) {
return std::make_unique<BoxDirectUploader>(download_item);
} else {
return std::make_unique<BoxChunkedUploader>(download_item);
}
}
// Box API reference:
// https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors
BoxUploader::InterruptReason
BoxUploader::ConvertToInterruptReasonOrErrorMessage(BoxApiCallResponse response,
BoxInfo& reroute_info) {
const auto code = response.net_or_http_code;
DCHECK_NE(code, 0);
if (code < 0) { // net::Error's
return ConvertNetErrorToInterruptReason(
static_cast<net::Error>(code),
download::DOWNLOAD_INTERRUPT_FROM_NETWORK);
}
// Otherwise it's HTTP errors, and we just display error message from Box.
// Unless it's authentication errors, which are already handled in
// EnsureSuccess().
reroute_info.set_error_message(base::StringPrintf(
kBoxErrorMessageFormat, code, response.box_error_code.c_str()));
reroute_info.set_additional_message(base::StringPrintf(
kBoxMoreMessageFormat, response.box_request_id.c_str()));
return kBoxUnknownError;
}
BoxUploader::BoxUploader(download::DownloadItem* download_item)
: local_file_path_(
// State would be COMPLETE iff it was already uploaded and had its
// local file deleted successfully.
(download_item->GetState() == download::DownloadItem::COMPLETE)
? base::FilePath()
: download_item->GetFullPath()),
target_file_name_(download_item->GetTargetFilePath().BaseName()),
download_start_time_(download_item->GetStartTime()),
uniquifier_(0) {
bool is_completed =
download_item->GetState() == download::DownloadItem::COMPLETE;
const auto& reroute_info = download_item->GetRerouteInfo();
if (reroute_info.IsInitialized()) {
// If |reroute_info| is initialized, that means it was loaded from
// databases, because the item was previously uploaded, or in the middle of
// uploading. Therefore, as long as the state is consistent with file_id and
// URL, |reroute_info| is valid.
DCHECK_EQ(reroute_info.service_provider(), kServiceProvider);
DCHECK_EQ(is_completed, reroute_info.box().has_file_id());
reroute_info_ = reroute_info;
DCHECK_EQ(is_completed, GetUploadedFileUrl().is_valid());
// TODO(https://crbug.com/1213761) If |is_completed| == false, load info to
// resume upload from where it left off.
} else {
// If |reroute_info| is not initialized, that means the item is either a new
// download to be uploaded now, or the previous upload attempt didn't go
// very far to have any information to recover from, therefore we start the
// upload workflow from scratch.
DCHECK(!is_completed) << download_item->GetState();
reroute_info_.set_service_provider(kServiceProvider);
reroute_info_.mutable_box(); // Set upload to BoxInfo.
}
}
BoxUploader::~BoxUploader() {
for (auto& observer : observers_)
observer.OnDestruction();
// TODO(https://crbug.com/1213761) May need to TerminateTask() to resume
// later.
}
void BoxUploader::Init(
base::RepeatingCallback<void(void)> authen_retry_callback,
ProgressUpdateCallback progress_update_cb,
UploadCompleteCallback upload_complete_cb,
PrefService* prefs) {
DCHECK(reroute_info().file_id().empty());
prefs_ = prefs;
authentication_retry_callback_ = std::move(authen_retry_callback);
progress_update_cb_ = std::move(progress_update_cb);
upload_complete_cb_ = std::move(upload_complete_cb);
SetCurrentApiCall(GetFolderId().empty() ? MakeFindUpstreamFolderApiCall()
: MakePreflightCheckApiCall());
}
void BoxUploader::TryTask(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const std::string& access_token) {
url_loader_factory_ = std::move(url_loader_factory);
access_token_ = access_token;
TryCurrentApiCall();
}
void BoxUploader::TryCurrentApiCall() {
DCHECK(authentication_retry_callback_);
DCHECK(upload_complete_cb_);
DCHECK(current_api_call_);
StartCurrentApiCall();
}
void BoxUploader::TerminateTask(InterruptReason reason) {
current_api_call_.reset(nullptr);
// TODO(https://crbug.com/1213761) May need to resume upload later.
OnApiCallFlowFailure(reason);
}
bool BoxUploader::EnsureSuccess(BoxApiCallResponse response) {
if (response.success) {
return true;
}
if (response.net_or_http_code == net::HTTP_UNAUTHORIZED) {
// Authentication failure, so we need to redo authenticaction.
authentication_retry_callback_.Run();
} else {
// Unexpected error. Clean up, then notify failure to download thread.
OnApiCallFlowFailure(response);
}
return false;
}
void BoxUploader::StartCurrentApiCall() {
current_api_call_->Start(url_loader_factory_, access_token_);
}
void BoxUploader::StartUpload() {
LogUniquifierCountToUma();
SendProgressUpdate();
SetCurrentApiCall(MakeFileUploadApiCall());
for (auto& observer : observers_)
observer.OnUploadStart();
TryCurrentApiCall();
}
void BoxUploader::OnFileError(base::File::Error error) {
LOG(ERROR) << base::File::ErrorToString(error);
const auto reason = ConvertFileErrorToInterruptReason(error);
OnApiCallFlowFailure(reason);
}
void BoxUploader::OnApiCallFlowFailure(BoxApiCallResponse response) {
const auto reason =
ConvertToInterruptReasonOrErrorMessage(response, reroute_info());
DLOG(ERROR) << "Request with id \"" << response.box_request_id
<< "\" failed with status " << response.net_or_http_code
<< " error \"" << response.box_error_code << "\" reason "
<< DownloadInterruptReasonToString(reason);
OnApiCallFlowFailure(reason);
}
void BoxUploader::OnApiCallFlowFailure(InterruptReason reason) {
OnApiCallFlowDone(reason, {});
}
void BoxUploader::OnApiCallFlowDone(InterruptReason reason,
std::string file_id) {
for (auto& observer : observers_)
observer.OnUploadDone(reason == kSuccess);
if (reason != kSuccess) {
LOG(ERROR) << "Upload failed: " << DownloadInterruptReasonToString(reason);
// TODO(https://crbug.com/1165972): on upload failure, decide whether to
// queue up the file to retry later, or also delete as usual. At this stage,
// for trusted testers (TT), deleting as usual for now. Need to determine
// how to communicate the failure/error to user.
} else {
DCHECK(reroute_info().file_id().empty());
DCHECK(!file_id.empty());
reroute_info().set_file_id(file_id);
}
SendProgressUpdate();
PostDeleteFileTask(reason);
}
void BoxUploader::NotifyResult(InterruptReason reason) {
std::move(upload_complete_cb_).Run(reason, GetUploadFileName());
}
void BoxUploader::SendProgressUpdate() const {
progress_update_cb_.Run(ProgressUpdate{GetUploadFileName(), reroute_info_});
}
void BoxUploader::OnFindUpstreamFolderResponse(BoxApiCallResponse response,
const std::string& folder_id) {
if (!EnsureSuccess(response)) {
SetCurrentApiCall(MakeFindUpstreamFolderApiCall());
return;
}
if (folder_id.empty()) {
// Advance to create a new default download folder.
SetCurrentApiCall(MakeCreateUpstreamFolderApiCall());
} else {
SetFolderId(folder_id);
// Advance to preflight check.
SetCurrentApiCall(MakePreflightCheckApiCall());
}
TryCurrentApiCall();
}
void BoxUploader::OnCreateUpstreamFolderResponse(BoxApiCallResponse response,
const std::string& folder_id) {
if (!EnsureSuccess(response)) {
SetCurrentApiCall(MakeCreateUpstreamFolderApiCall());
return;
}
CHECK_EQ(folder_id.empty(), false);
SetFolderId(folder_id);
// Advance to preflight check.
SetCurrentApiCall(MakePreflightCheckApiCall());
TryCurrentApiCall();
}
void BoxUploader::LogUniquifierCountToUma() {
base::UmaHistogramSparse(kUniquifierUmaLabel, uniquifier_);
}
void BoxUploader::OnPreflightCheckResponse(BoxApiCallResponse response) {
if (response.success) {
CHECK_EQ(response.net_or_http_code, net::HTTP_OK);
StartUpload();
return;
}
switch (response.net_or_http_code) {
case net::HTTP_UNAUTHORIZED:
// Authentication failure, we need to reauth and redo the preflight check.
SetCurrentApiCall(MakePreflightCheckApiCall());
authentication_retry_callback_.Run();
break;
case net::HTTP_NOT_FOUND:
// Probably because folder id has changed or been deleted. Restart
// from the beginning.
SetFolderId(std::string());
SetCurrentApiCall(MakeFindUpstreamFolderApiCall());
TryCurrentApiCall();
break;
case net::HTTP_CONFLICT:
if (uniquifier_ < UploadAttemptCount::kMaxRenamedWithSuffix) {
++uniquifier_;
} else if (uniquifier_ == UploadAttemptCount::kMaxRenamedWithSuffix) {
uniquifier_ = UploadAttemptCount::kTimestampBasedName;
} else {
uniquifier_ = UploadAttemptCount::kAbandonedUpload;
}
if (uniquifier_ < UploadAttemptCount::kAbandonedUpload) {
SetCurrentApiCall(MakePreflightCheckApiCall());
TryCurrentApiCall();
break;
}
DLOG(WARNING) << "Box upload failed for file " << target_file_name_;
LogUniquifierCountToUma();
FALLTHROUGH; // Also OnOnApiCallFlowFailure() to surface this to user.
default:
// Unexpected error. Notify failure to download thread.
OnApiCallFlowFailure(response);
}
}
std::unique_ptr<OAuth2ApiCallFlow> BoxUploader::MakePreflightCheckApiCall() {
return std::make_unique<BoxPreflightCheckApiCallFlow>(
base::BindOnce(&BoxUploader::OnPreflightCheckResponse,
weak_factory_.GetWeakPtr()),
GetUploadFileName(), folder_id_);
}
std::unique_ptr<OAuth2ApiCallFlow>
BoxUploader::MakeFindUpstreamFolderApiCall() {
return std::make_unique<BoxFindUpstreamFolderApiCallFlow>(base::BindOnce(
&BoxUploader::OnFindUpstreamFolderResponse, weak_factory_.GetWeakPtr()));
}
std::unique_ptr<OAuth2ApiCallFlow>
BoxUploader::MakeCreateUpstreamFolderApiCall() {
return std::make_unique<BoxCreateUpstreamFolderApiCallFlow>(
base::BindOnce(&BoxUploader::OnCreateUpstreamFolderResponse,
weak_factory_.GetWeakPtr()));
}
// Getters & Setters ///////////////////////////////////////////////////////////
GURL BoxUploader::GetUploadedFileUrl() const {
return BoxApiCallFlow::MakeUrlToShowFile(reroute_info().file_id());
}
GURL BoxUploader::GetDestinationFolderUrl() const {
return BoxApiCallFlow::MakeUrlToShowFolder(GetFolderId());
}
const base::FilePath BoxUploader::GetLocalFilePath() const {
return local_file_path_;
}
const base::FilePath BoxUploader::GetUploadFileName() const {
if (uniquifier_ == UploadAttemptCount::kNotRenamed) {
return target_file_name_;
} else if (uniquifier_ <= UploadAttemptCount::kMaxRenamedWithSuffix) {
return target_file_name_.InsertBeforeExtensionASCII(
base::StringPrintf(" (%d)", uniquifier_));
} else if (uniquifier_ == UploadAttemptCount::kTimestampBasedName) {
// Generate an ISO8601 compliant local timestamp suffix that avoids
// reserved characters that are forbidden on some OSes like Windows.
base::Time::Exploded exploded;
download_start_time_.LocalExplode(&exploded);
// Instead of using the raw_offset, use the offset in effect now.
// For instance, US Pacific Time, the offset shown will be -7 in summer
// while it'll be -8 in winter. Time zone information appended to the format
// generated by CreateUniqueFilename in
// components/download/internal/common/download_path_reservation_tracker.cc
int raw_offset, dst_offset;
UDate now = icu::Calendar::getNow();
std::unique_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault());
UErrorCode status = U_ZERO_ERROR;
zone.get()->getOffset(now, false, raw_offset, dst_offset, status);
DCHECK(U_SUCCESS(status));
int offset = raw_offset + dst_offset;
// |offset| is in msec.
int minute_offset = offset / 60000;
int hour_offset = minute_offset / 60;
int min_remainder = std::abs(minute_offset) % 60;
// Some timezones have a non-integral hour offset. So, we need to use hh:mm
// form.
std::string suffix = base::StringPrintf(
" - %04d-%02d-%02dT%02d%02d%02d.%03d UTC%+dh%02d", exploded.year,
exploded.month, exploded.day_of_month, exploded.hour, exploded.minute,
exploded.second, exploded.millisecond, hour_offset, min_remainder);
return target_file_name_.InsertBeforeExtensionASCII(suffix);
} else {
DCHECK_EQ(uniquifier_, UploadAttemptCount::kAbandonedUpload);
return target_file_name_.InsertBeforeExtensionASCII(".abandoned");
}
}
const std::string BoxUploader::GetFolderId() {
if (folder_id_.empty() && prefs_) {
folder_id_ = prefs_->GetString(kFileSystemUploadFolderIdPref);
}
// TODO(https://crbug.com/1215847) Update to make API call to find folder id
// if has file id.
return folder_id_;
}
const std::string BoxUploader::GetFolderId() const {
return folder_id_;
}
void BoxUploader::SetFolderId(std::string folder_id) {
folder_id_ = folder_id;
prefs_->SetString(kFileSystemUploadFolderIdPref, folder_id);
}
void BoxUploader::SetCurrentApiCall(
std::unique_ptr<OAuth2ApiCallFlow> api_call) {
current_api_call_ = std::move(api_call);
}
// File Delete /////////////////////////////////////////////////////////////////
void BoxUploader::PostDeleteFileTask(InterruptReason upload_reason) {
auto delete_file_task = base::BindOnce(&DeleteIfExists, GetLocalFilePath());
auto delete_file_reply = base::BindOnce(
&BoxUploader::OnFileDeleted, weak_factory_.GetWeakPtr(), upload_reason);
for (auto& observer : observers_)
observer.OnFileDeletionStart();
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
std::move(delete_file_task), std::move(delete_file_reply));
}
void BoxUploader::OnFileDeleted(InterruptReason upload_reason,
base::File::Error delete_status) {
auto final_reason = upload_reason;
if (upload_reason == kSuccess &&
delete_status != base::File::Error::FILE_OK) {
final_reason = ConvertFileErrorToInterruptReason(delete_status);
DLOG(ERROR) << "Failed to delete local temp file " << GetLocalFilePath()
<< "; possible reason: "
<< base::File::ErrorToString(delete_status);
}
NotifyResult(final_reason);
for (auto& observer : observers_)
observer.OnFileDeletionDone(delete_status == base::File::Error::FILE_OK);
}
// Helper methods for tests ////////////////////////////////////////////////////
std::string BoxUploader::GetFolderIdForTesting() const {
return folder_id_;
}
void BoxUploader::NotifyOAuth2ErrorForTesting() {
authentication_retry_callback_.Run();
}
void BoxUploader::SetUploadApiCallFlowDoneForTesting(InterruptReason reason,
std::string file_id) {
OnApiCallFlowDone(reason, file_id);
}
////////////////////////////////////////////////////////////////////////////////
// BoxDirectUploader
////////////////////////////////////////////////////////////////////////////////
BoxDirectUploader::BoxDirectUploader(download::DownloadItem* download_item)
: BoxUploader(download_item) {}
BoxDirectUploader::~BoxDirectUploader() = default;
std::unique_ptr<OAuth2ApiCallFlow> BoxDirectUploader::MakeFileUploadApiCall() {
return std::make_unique<BoxWholeFileUploadApiCallFlow>(
base::BindOnce(&BoxDirectUploader::OnWholeFileUploadResponse,
weak_factory_.GetWeakPtr()),
GetFolderId(), GetUploadFileName(), GetLocalFilePath());
}
void BoxDirectUploader::OnWholeFileUploadResponse(BoxApiCallResponse response,
const std::string& file_id) {
if (!response.net_or_http_code) {
OnFileError(base::File::Error::FILE_ERROR_IO);
return;
}
if (!EnsureSuccess(response)) {
SetCurrentApiCall(MakeFileUploadApiCall());
return;
}
// Report upload success back to the download thread.
OnApiCallFlowDone(kSuccess, file_id);
}
////////////////////////////////////////////////////////////////////////////////
// BoxChunkedUploader
////////////////////////////////////////////////////////////////////////////////
BoxChunkedUploader::BoxChunkedUploader(download::DownloadItem* download_item)
: BoxUploader(download_item), file_size_(download_item->GetTotalBytes()) {}
BoxChunkedUploader::~BoxChunkedUploader() = default;
std::unique_ptr<OAuth2ApiCallFlow> BoxChunkedUploader::MakeFileUploadApiCall() {
return MakeCreateUploadSessionApiCall();
}
std::unique_ptr<OAuth2ApiCallFlow>
BoxChunkedUploader::MakeCreateUploadSessionApiCall() {
return std::make_unique<BoxCreateUploadSessionApiCallFlow>(
base::BindOnce(&BoxChunkedUploader::OnCreateUploadSessionResponse,
weak_factory_.GetWeakPtr()),
GetFolderId(), file_size_, GetUploadFileName());
}
std::unique_ptr<OAuth2ApiCallFlow>
BoxChunkedUploader::MakePartFileUploadApiCall() {
return std::make_unique<BoxPartFileUploadApiCallFlow>(
base::BindOnce(&BoxChunkedUploader::OnPartFileUploadResponse,
weak_factory_.GetWeakPtr()),
session_endpoints_.FindPath("upload_part")->GetString(),
curr_part_.content, curr_part_.byte_from, curr_part_.byte_to, file_size_);
}
std::unique_ptr<OAuth2ApiCallFlow>
BoxChunkedUploader::MakeCommitUploadSessionApiCall() {
return std::make_unique<BoxCommitUploadSessionApiCallFlow>(
base::BindOnce(&BoxChunkedUploader::OnCommitUploadSessionResponse,
weak_factory_.GetWeakPtr()),
session_endpoints_.FindPath("commit")->GetString(), uploaded_parts_,
sha1_digest_);
}
std::unique_ptr<OAuth2ApiCallFlow>
BoxChunkedUploader::MakeAbortUploadSessionApiCall(InterruptReason reason) {
return std::make_unique<BoxAbortUploadSessionApiCallFlow>(
base::BindOnce(&BoxChunkedUploader::OnAbortUploadSessionResponse,
weak_factory_.GetWeakPtr(), reason),
session_endpoints_.FindPath("abort")->GetString());
}
void BoxChunkedUploader::OnCreateUploadSessionResponse(
BoxApiCallResponse response,
base::Value session_endpoints,
size_t part_size) {
if (!EnsureSuccess(response)) {
if (response.net_or_http_code == net::HTTP_NOT_FOUND) {
// Folder not found: clear locally stored folder id.
LOG(ERROR) << "Folder id = " << GetFolderId() << " not found; clearing";
// TODO(https://crbug.com/1190396): May be removed with Preflight Check?
SetFolderId(std::string());
}
SetCurrentApiCall(MakeCreateUploadSessionApiCall());
return;
}
session_endpoints_ = std::move(session_endpoints);
chunks_handler_ = std::make_unique<FileChunksHandler>(GetLocalFilePath(),
file_size_, part_size);
chunks_handler_->StartReading(
base::BindRepeating(&BoxChunkedUploader::OnFileChunkRead,
weak_factory_.GetWeakPtr()),
base::BindOnce(&BoxChunkedUploader::OnFileCompletelyUploaded,
weak_factory_.GetWeakPtr()));
}
void BoxChunkedUploader::OnFileChunkRead(PartInfo part_info) {
if (part_info.content.empty()) {
OnFileError(part_info.error);
return;
}
// Advance to upload the file part.
curr_part_ = std::move(part_info);
SetCurrentApiCall(MakePartFileUploadApiCall());
TryCurrentApiCall();
}
void BoxChunkedUploader::OnPartFileUploadResponse(BoxApiCallResponse response,
base::Value part_info) {
if (!EnsureSuccess(response)) {
if (response.net_or_http_code == net::HTTP_UNAUTHORIZED) {
// Setup current_api_call_ to retry upload the file part.
SetCurrentApiCall(MakePartFileUploadApiCall());
} // else don't overwrite, since OnApiCallFlowFailure() was triggered in
// EnsureSuccess() and abortion is in-progress.
return;
}
uploaded_parts_.Append(std::move(part_info));
chunks_handler_->ContinueToReadChunk(uploaded_parts_.GetList().size() + 1);
}
void BoxChunkedUploader::OnFileCompletelyUploaded(
const std::string& sha1_digest) {
DCHECK(sha1_digest.size());
sha1_digest_ = sha1_digest;
SetCurrentApiCall(MakeCommitUploadSessionApiCall());
TryCurrentApiCall();
}
void BoxChunkedUploader::OnCommitUploadSessionResponse(
BoxApiCallResponse response,
base::TimeDelta retry_after,
const std::string& file_id) {
if (!EnsureSuccess(response)) {
if (response.net_or_http_code == net::HTTP_UNAUTHORIZED) {
SetCurrentApiCall(MakeCommitUploadSessionApiCall());
}
return;
}
if (response.net_or_http_code == net::HTTP_ACCEPTED) {
base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&BoxChunkedUploader::OnFileCompletelyUploaded,
weak_factory_.GetWeakPtr(), sha1_digest_),
retry_after);
} else {
OnApiCallFlowDone(kSuccess, file_id);
}
}
void BoxChunkedUploader::OnAbortUploadSessionResponse(
InterruptReason reason,
BoxApiCallResponse response) {
session_endpoints_.DictClear(); // Clear dict here to avoid infinite retry.
if (EnsureSuccess(response)) {
OnApiCallFlowFailure(reason);
} else {
// OnApiCallFlowFailure() already triggered in EnsureSuccess().
LOG(ERROR) << "Unexpected response after aborting upload session for "
<< GetUploadFileName() << " after upload failure "
<< DownloadInterruptReasonToString(reason);
}
}
void BoxChunkedUploader::OnApiCallFlowFailure(InterruptReason reason) {
// Dict would've been cleared if aborted already; otherwise, try abort.
if (session_endpoints_.is_dict() && !session_endpoints_.DictEmpty()) {
chunks_handler_.reset();
SetCurrentApiCall(MakeAbortUploadSessionApiCall(reason));
TryCurrentApiCall();
} else {
BoxUploader::OnApiCallFlowFailure(reason);
}
}
// BoxUploader::TestObserver
BoxUploader::TestObserver::TestObserver(FileSystemRenameHandler* rename_handler)
: uploader_(
FileSystemRenameHandler::TestObserver::GetBoxUploader(rename_handler)
->weak_factory_.GetWeakPtr()) {
uploader_->observers_.AddObserver(this);
}
BoxUploader::TestObserver::~TestObserver() {
uploader_->observers_.RemoveObserver(this);
}
void BoxUploader::TestObserver::OnUploadStart() {
upload_status_ = Status::kInProgress;
if (stop_waiting_for_upload_to_start_)
std::move(stop_waiting_for_upload_to_start_).Run();
}
void BoxUploader::TestObserver::OnUploadDone(bool succeeded) {
upload_status_ = succeeded ? Status::kSucceeded : Status::kFailed;
if (stop_waiting_for_upload_to_complete_)
std::move(stop_waiting_for_upload_to_complete_).Run();
}
void BoxUploader::TestObserver::OnFileDeletionStart() {
tmp_file_deletion_status_ = Status::kInProgress;
}
void BoxUploader::TestObserver::OnFileDeletionDone(bool succeeded) {
tmp_file_deletion_status_ = succeeded ? Status::kSucceeded : Status::kFailed;
if (stop_waiting_for_deletion_to_complete_)
std::move(stop_waiting_for_deletion_to_complete_).Run();
}
void BoxUploader::TestObserver::OnDestruction() {
uploader_.reset();
}
void BoxUploader::TestObserver::WaitForUploadStart() {
if (upload_status_ == Status::kInProgress)
return;
base::RunLoop run_loop;
stop_waiting_for_upload_to_start_ = run_loop.QuitClosure();
run_loop.Run();
}
bool BoxUploader::TestObserver::WaitForUploadCompletion() {
if (upload_status_ == Status::kSucceeded || upload_status_ == Status::kFailed)
return true;
base::RunLoop run_loop;
stop_waiting_for_upload_to_complete_ = run_loop.QuitClosure();
run_loop.Run();
return upload_status_ == Status::kSucceeded;
}
bool BoxUploader::TestObserver::WaitForTmpFileDeletion() {
if ((tmp_file_deletion_status_ == Status::kSucceeded) ||
(tmp_file_deletion_status_ == Status::kFailed))
return true;
base::RunLoop run_loop;
stop_waiting_for_deletion_to_complete_ = run_loop.QuitClosure();
run_loop.Run();
return tmp_file_deletion_status_ == Status::kSucceeded;
}
GURL BoxUploader::TestObserver::GetFileUrl() {
return uploader_->GetUploadedFileUrl();
}
} // namespace enterprise_connectors
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
5ac60ca2dd2e2904a9664345ae827869693b1ef6 | e879e725a8eefed6fb0cb70d489f90d650247c50 | /firmware/library/utility/macros.hpp | cfc79e9ff462c4ac6f0067ac64cef01c000eef7f | [
"Apache-2.0"
] | permissive | znic1967/Khalils-Kids | 8137b196b77681504b393f770a107b6b494f59b9 | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | refs/heads/master | 2020-05-18T11:00:09.968602 | 2019-05-10T00:42:16 | 2019-05-10T00:42:16 | 184,365,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,133 | hpp | /// @ingroup SJSU-Dev2
/// @defgroup Macros Utility Macros
/// @brief This module is meant for general purpose macros that can be used
/// across the SJSU-Dev2 environment.
/// @{
#pragma once
#include "config.hpp"
// SJ2_SECTION will place a variable or function within a given section of the
// executable. It uses both attribute "section" and "used". Section attribute
// places variable/function into that section and "used" labels the symbol as
// used to ensure that the compiler does remove this symbol at link time.
#if defined(__APPLE__)
#define SJ2_SECTION(section_name) \
__attribute__((used, section("__TEXT," section_name)))
#else
#define SJ2_SECTION(section_name) __attribute__((used, section(section_name)))
#endif
/// DO NOT USE this macro directly. Use the C++17 attribute [[maybe_unused]]
/// instead.
/// _SJ2_USED will use void casting as a means to convince the compiler that the
/// variable has been used in the software, to remove compiler warnings about
/// unused variables.
/// NOTE: this will not stop the compiler from optimizing this variable out.
#define _SJ2_USED(variable) ((void)variable)
/// SJ2_VARIADIC_USED can suppress unused parameter warnings within macros when
/// supplied with __VA_ARGS__.
inline void UsedVariadicFunction(...) {}
#define SJ2_VARIADIC_USED(...) \
if (false) \
{ \
UsedVariadicFunction(__VA_ARGS__); \
}
/// These macros are used to stringify define values. For example:
///
/// #define VALUE true
/// #define STRING "value = " STRINGIFY(s) => "value = true"
///
#define SJ2_STRINGIFY(s) SJ2_STRINGIFY2(s)
#define SJ2_STRINGIFY2(s) #s
/// SJ2_PACKED give a specified type a packed attribute
#define SJ2_PACKED(type) type [[gnu::packed]]
/// Set a function as a "weak" function. This means that if there is another
/// declaration of this exact function somewhere else in the software, the
/// non-weak function will be used instead of the weak function.
#define SJ2_WEAK(function) [[gnu::weak]] function
// __attribute__((weak, alias(#f), no_instrument_function)) // NOLINT
/// @}
| [
"zackary.k.nicholson@gmail.com"
] | zackary.k.nicholson@gmail.com |
3b4e5a92b471ef28750d60cfdc7294defac7160d | a1d328963c3b3dfc01b272beb4eaa879b0c566f3 | /Program 2/bigint.h | cf78d2d4edaac4e1c8d2bb1618c0675a6069a995 | [] | no_license | mdgreenh/CMPS-109 | 7438acacd86a61e0c07c2efc3e5e26a80589a76b | 4064fd938d7dc4c4656ef22b61860c3afe39217d | refs/heads/master | 2020-12-25T23:36:13.788072 | 2015-12-10T23:28:25 | 2015-12-10T23:28:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,274 | h | // $Id: bigint.h,v 1.16 2014-07-02 20:01:17-07 - - $
//Programmers:
//Alex Vincent - avincent@ucsc.edu
//Nader Sleem - nsleem@ucsc.edu
#ifndef __BIGINT_H__
#define __BIGINT_H__
#include <exception>
#include <iostream>
#include <utility>
#include <memory>
#include <vector>
using namespace std;
#include "debug.h"
class bigint;
using stackpair = pair <bigint,bigint>;
using quot_rem = pair<bigint,bigint>;
bigint operator+ (const bigint& left, const bigint& right);
//
// Define class bigint
//
class bigint {
friend ostream &operator<< (ostream &, const bigint &);
private:
long long_value {};
void initialize(const string& s);
//BigInt Structure//
using digit_t = unsigned char;
using bigvalue_t = vector<digit_t>;
bool negative = false;
bigvalue_t big_value;
using quot_rem = pair<bigint,bigint>;
using unumber = unsigned long;
friend quot_rem divide (const bigint&, const bigint&);
//Arithmetic functions
bigint multiply_by_2 (bigint&);
friend void divide_by_2 (unumber&);
void do_bigadd(const bigvalue_t&, const bigvalue_t&,
bigvalue_t&) const;
void do_bigsub(const bigvalue_t&, const bigvalue_t&,
bigvalue_t&) const;
//Clean and compare functions
void clean_negative_zero();
int compare (const bigint &that) const;
int absolute_compare(const bigint &that) const;
void clean_zeroes(bigvalue_t &bigvalue) const;
public:
//
// Ensure synthesized members are genrated.
//
bigint() = default;
bigint (const bigint&) = default;
bigint (bigint&&) = default;
bigint& operator= (const bigint&) = default;
bigint& operator= (bigint&&) = default;
~bigint() = default;
//
// Extra ctors to make bigints.
//
bigint (const long);
bigint (const string&);
//
// Basic add/sub operators.
//
friend bigint operator+ (const bigint&, const bigint&);
friend bigint operator- (const bigint&, const bigint&);
friend bigint operator+ (const bigint&);
friend bigint operator- (const bigint&);
long to_long() const;
//
// Extended operators implemented with add/sub.
//
friend bigint operator* (bigint&, bigint&);
friend bigint operator/ (const bigint&, const bigint&);
friend bigint operator% (const bigint&, const bigint&);
//
// Comparison operators.
//
friend bool operator== (const bigint&, const bigint&);
friend bool operator< (const bigint&, const bigint&);
};
//
// The rest of the operators do not need to be friends.
// Make the comparisons inline for efficiency.
//
bigint pow (const bigint& base, const bigint& exponent);
inline bool operator!= (const bigint &left, const bigint &right) {
return not (left == right);
}
inline bool operator> (const bigint &left, const bigint &right) {
return right < left;
}
inline bool operator<= (const bigint &left, const bigint &right) {
return not (right < left);
}
inline bool operator>= (const bigint &left, const bigint &right) {
return not (left < right);
}
#endif
| [
"alexraymondvincent@gmail.com"
] | alexraymondvincent@gmail.com |
634127446bfc0b264b14feb3adc699e3bad55810 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/shell/ext/netplwiz/netplace.cpp | dc265a27e7c83d7e48b1362b791ae1c4eb320a9f | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 20,269 | cpp | #include "stdafx.h"
#include "netplace.h"
#include "msdasc.h"
#pragma hdrstop
CNetworkPlace::CNetworkPlace() :
_pidl(NULL), _fSupportWebFolders(FALSE), _fIsWebFolder(FALSE), _fDeleteWebFolder(FALSE)
{
_szTarget[0] = TEXT('\0');
_szName[0] = TEXT('\0');
_szDescription[0] = TEXT('\0');
}
// destructor - clean up our state
CNetworkPlace::~CNetworkPlace()
{
_InvalidateCache();
}
void CNetworkPlace::_InvalidateCache()
{
// web folders will create a shortcut to objects if we go through its binding
// process, therefore when we attempt to invalidate our cache we should
// clean up our mess.
//
// if the user has commited the change then we can/will keep the shortcut
// around, otherwise we call the delete verb on it.
if (_fIsWebFolder && _fDeleteWebFolder && _pidl)
{
IShellFolder *psf;
LPCITEMIDLIST pidlLast;
HRESULT hr = SHBindToIDListParent(_pidl, IID_PPV_ARG(IShellFolder, &psf), &pidlLast);
if (SUCCEEDED(hr))
{
IContextMenu *pcm;
hr = psf->GetUIObjectOf(NULL, 1, &pidlLast, IID_X_PPV_ARG(IContextMenu, NULL, &pcm));
if (SUCCEEDED(hr))
{
CMINVOKECOMMANDINFO ici = {0};
ici.cbSize = sizeof (ici);
ici.fMask = CMIC_MASK_FLAG_NO_UI;
ici.lpVerb = "Delete";
ici.nShow = SW_SHOWNORMAL;
hr = pcm->InvokeCommand(&ici);
pcm->Release();
}
psf->Release();
}
}
// now clean up the rest of our state.
ILFree(_pidl);
_pidl = NULL;
_szTarget[0] = TEXT('\0');
_szName[0] = TEXT('\0');
_szDescription[0] = TEXT('\0');
_fIsWebFolder = FALSE;
_fDeleteWebFolder = FALSE;
}
HRESULT CNetworkPlace::SetTarget(HWND hwnd, LPCWSTR pszTarget, DWORD dwFlags)
{
_InvalidateCache();
HRESULT hr = S_OK;
if (pszTarget)
{
// set our state accordingly
_fSupportWebFolders = (dwFlags & NPTF_ALLOWWEBFOLDERS) != 0;
// copy the URL and prepare for parsing
StrCpyN(_szTarget, pszTarget, ARRAYSIZE(_szTarget));
INT cchTarget = lstrlen(_szTarget)-1;
if ((_szTarget[cchTarget] == L'\\') || (_szTarget[cchTarget] == '/'))
{
_szTarget[cchTarget] = TEXT('\0');
}
if (dwFlags & NPTF_VALIDATE)
{
// connecting to a server root or local path is not supported
if (PathIsUNCServer(_szTarget) || PathGetDriveNumber(_szTarget) != -1)
{
hr = E_INVALIDARG;
}
else
{
// check the policy to see if we are setting this.
if (PathIsUNC(_szTarget) && SHRestricted(REST_NONETCONNECTDISCONNECT))
{
hr = E_INVALIDARG;
}
else
{
hr = _IDListFromTarget(hwnd);
}
}
if (FAILED(hr))
{
if (hwnd && !(dwFlags & NPTF_SILENT))
{
::DisplayFormatMessage(hwnd,
IDS_ANP_CAPTION,
PathIsUNCServer(_szTarget) ? IDS_PUB_ONLYSERVER:IDS_CANTFINDFOLDER,
MB_OK|MB_ICONERROR);
}
_InvalidateCache();
}
}
}
return hr;
}
HRESULT CNetworkPlace::SetName(HWND hwnd, LPCWSTR pszName)
{
HRESULT hr = S_OK;
if (!_fIsWebFolder)
{
// check to see if we are going to overwrite an existing place, if we
// are then display a prompt and let the user choose. if they answer
// yes, then have at it!
TCHAR szPath[MAX_PATH];
if (hwnd && _IsPlaceTaken(pszName, szPath))
{
if (IDNO == ::DisplayFormatMessage(hwnd,
IDS_ANP_CAPTION , IDS_FRIENDLYNAMEINUSE,
MB_YESNO|MB_ICONQUESTION,
pszName))
{
hr = E_FAIL;
}
}
}
// if we succeed the above then lets use the new name.
if (SUCCEEDED(hr))
StrCpyN(_szName, pszName, ARRAYSIZE(_szName));
return hr;
}
HRESULT CNetworkPlace::SetDescription(LPCWSTR pszDescription)
{
StrCpyN(_szDescription, pszDescription, ARRAYSIZE(_szDescription));
return S_OK;
}
// recompute the URL based on the new user/password information that
// we were just given.
HRESULT CNetworkPlace::SetLoginInfo(LPCWSTR pszUser, LPCWSTR pszPassword)
{
TCHAR szServer[INTERNET_MAX_HOST_NAME_LENGTH + 1];
TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH + 1];
TCHAR szExtraInfo[MAX_PATH + 1]; // Includes Port Number and download type (ASCII, Binary, Detect)
URL_COMPONENTS urlComps = {0};
urlComps.dwStructSize = sizeof(urlComps);
urlComps.lpszHostName = szServer;
urlComps.dwHostNameLength = ARRAYSIZE(szServer);
urlComps.lpszUrlPath = szUrlPath;
urlComps.dwUrlPathLength = ARRAYSIZE(szUrlPath);
urlComps.lpszExtraInfo = szExtraInfo;
urlComps.dwExtraInfoLength = ARRAYSIZE(szExtraInfo);
// WARNING - the ICU_DECODE/ICU_ESCAPE is a lossy roundtrip - ZekeL - 26-MAR-2001
// many escaped characters are not correctly identified and re-escaped.
// any characters that are reserved for URL parsing purposes
// will be interpreted as their parsing char (ie '/').
BOOL fResult = InternetCrackUrl(_szTarget, 0, 0, &urlComps);
if (fResult)
{
urlComps.lpszUserName = (LPTSTR) pszUser;
urlComps.dwUserNameLength = (pszUser ? lstrlen(pszUser) : 0);
urlComps.lpszPassword = (LPTSTR) pszPassword;
urlComps.dwPasswordLength = (pszPassword ? lstrlen(pszPassword) : 0);
DWORD cchSize = ARRAYSIZE(_szTarget);
fResult = InternetCreateUrl(&urlComps, (ICU_ESCAPE | ICU_USERNAME), _szTarget, &cchSize);
// if we have a cached IDList then lets ensure that we clear it up
// so that we rebind and the FTP namespace gets a crack at it.
if (fResult && _pidl)
{
ILFree(_pidl);
_pidl = NULL;
}
}
return fResult ? S_OK : HRESULT_FROM_WIN32(GetLastError());
}
HRESULT CNetworkPlace::GetIDList(HWND hwnd, LPITEMIDLIST *ppidl)
{
HRESULT hr = _IDListFromTarget(hwnd);
if (SUCCEEDED(hr))
{
hr = SHILClone(_pidl, ppidl);
}
return hr;
}
HRESULT CNetworkPlace::GetObject(HWND hwnd, REFIID riid, void **ppv)
{
HRESULT hr = _IDListFromTarget(hwnd);
if (SUCCEEDED(hr))
{
hr = SHBindToObject(NULL, riid, _pidl, ppv);
}
return hr;
}
HRESULT CNetworkPlace::GetName(LPWSTR pszBuffer, int cchBuffer)
{
HRESULT hr = _IDListFromTarget(NULL);
if (SUCCEEDED(hr))
{
StrCpyN(pszBuffer, _szName, cchBuffer);
hr = S_OK;
}
return hr;
}
// check to see if we are going to overwrite a network place
BOOL CNetworkPlace::_IsPlaceTaken(LPCTSTR pszName, LPTSTR pszPath)
{
BOOL fOverwriting = FALSE;
SHGetSpecialFolderPath(NULL, pszPath, CSIDL_NETHOOD, TRUE);
PathCombine(pszPath, pszPath, pszName);
IShellFolder *psf;
HRESULT hr = SHGetDesktopFolder(&psf);
if (SUCCEEDED(hr))
{
LPITEMIDLIST pidl;
if (SUCCEEDED(psf->ParseDisplayName(NULL, NULL, pszPath, NULL, &pidl, NULL)))
{
// we think we are going to overwrite an existing net place, so lets
// check first to see if the place which is there is not actually
// pointing at our new target. if its is then we can just
// ignore all of this.
TCHAR szTarget[INTERNET_MAX_URL_LENGTH];
hr = _GetTargetPath(pidl, szTarget, ARRAYSIZE(szTarget));
if (FAILED(hr) || (0 != StrCmpI(szTarget, _szTarget)))
{
fOverwriting = TRUE;
}
ILFree(pidl);
}
psf->Release();
}
return fOverwriting;
}
// handle creating the web folders IDLIST for this item. we check with the
// rosebud binder to find out if this scheme is supported, if so then
// we attempt to have the Web Folders code crack the URL
static const BYTE c_pidlWebFolders[] =
{
0x14,0x00,0x1F,0x0F,0xE0,0x4F,0xD0,0x20,
0xEA,0x3A,0x69,0x10,0xA2,0xD8,0x08,0x00,
0x2B,0x30,0x30,0x9D,0x14,0x00,0x2E,0x00,
0x00,0xDF,0xEA,0xBD,0x65,0xC2,0xD0,0x11,
0xBC,0xED,0x00,0xA0,0xC9,0x0A,0xB5,0x0F,
0x00,0x00
};
HRESULT CNetworkPlace::_TryWebFolders(HWND hwnd)
{
// lets see if Rosebud can handle this scheme item by checking the
// scheme and seeing if the rosebud binder can handle it.
TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH + 1];
DWORD cchScheme = ARRAYSIZE(szScheme);
HRESULT hr = UrlGetPart(_szTarget, szScheme, &cchScheme, URL_PART_SCHEME, 0);
if (SUCCEEDED(hr))
{
IRegisterProvider *prp;
hr = CoCreateInstance(CLSID_RootBinder, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARG(IRegisterProvider, &prp));
if (SUCCEEDED(hr))
{
// let the web folders code have a go at creating a link to this storage,
// the IDLIST we generate points to the folder inside My Computer (hidden)
CLSID clsidOut;
hr = prp->GetURLMapping(szScheme, 0, &clsidOut);
if (hr == S_OK)
{
IShellFolder *psf;
hr = SHBindToObject(NULL, IID_IShellFolder, (LPCITEMIDLIST)c_pidlWebFolders, (void**)&psf);
if (SUCCEEDED(hr))
{
IBindCtx *pbc;
hr = CreateBindCtx(NULL, &pbc);
if (SUCCEEDED(hr))
{
BIND_OPTS bo = {sizeof(bo), 0, STGM_CREATE};
hr = pbc->SetBindOptions(&bo);
if (SUCCEEDED(hr))
{
// we need to pase NULL hWnd to this so that Web Folders doesn't display any
// UI, in particular its ever so useful NULL error message box... mumble mumble
LPITEMIDLIST pidl;
hr = psf->ParseDisplayName(NULL, pbc, _szTarget, NULL, &pidl, NULL);
if (SUCCEEDED(hr))
{
ASSERT(!_pidl);
hr = SHILCombine((LPCITEMIDLIST)c_pidlWebFolders, pidl, &_pidl);
ILFree(pidl);
_fDeleteWebFolder = TRUE; // we now have the magic web folders link (clean it up)
}
}
pbc->Release();
}
psf->Release();
}
}
else
{
hr = E_FAIL;
}
prp->Release();
}
}
return hr;
}
// dereference a link and get the target path
HRESULT CNetworkPlace::_GetTargetPath(LPCITEMIDLIST pidl, LPTSTR pszPath, int cchPath)
{
LPITEMIDLIST pidlTarget;
HRESULT hr = SHGetTargetFolderIDList(pidl, &pidlTarget);
if (SUCCEEDED(hr))
{
SHGetNameAndFlags(pidlTarget, SHGDN_FORPARSING, pszPath, cchPath, NULL);
ILFree(pidlTarget);
}
return hr;
}
// create an IDLIST for the target that we have, this code attempts to parse the name and
// then set our state for the item. if we fail to parse then we attempt to have Web Folders
// look at it - this most common scenario for this will be the DAV RDR failing because
// the server isn't a DAV store, so instead we try Web Folders to handle WEC etc.
HRESULT CNetworkPlace::_IDListFromTarget(HWND hwnd)
{
HRESULT hr = S_OK;
if (!_pidl)
{
if (_szTarget[0])
{
_fIsWebFolder = FALSE; // not a web folder
BINDCTX_PARAM rgParams[] =
{
{ STR_PARSE_PREFER_FOLDER_BROWSING, NULL},
{ L"BUT NOT WEBFOLDERS", NULL},
};
IBindCtx *pbc;
hr = BindCtx_RegisterObjectParams(NULL, rgParams, ARRAYSIZE(rgParams), &pbc);
if (SUCCEEDED(hr))
{
IBindCtx *pbcWindow;
hr = BindCtx_RegisterUIWindow(pbc, hwnd, &pbcWindow);
if (SUCCEEDED(hr))
{
SFGAOF sfgao;
hr = SHParseDisplayName(_szTarget, pbcWindow, &_pidl, SFGAO_FOLDER, &sfgao);
// if we parsed something that turns out to not
// be a folder, we want to throw it away
if (SUCCEEDED(hr) && !(sfgao & SFGAO_FOLDER))
{
ILFree(_pidl);
_pidl = 0;
hr = E_FAIL;
}
// if that failed, its is a HTTP/HTTPS and we have web folders support then lets try
// and fall back to the old behaviour.
if (FAILED(hr) && _fSupportWebFolders)
{
DWORD scheme = GetUrlScheme(_szTarget);
if (scheme == URL_SCHEME_HTTP || scheme == URL_SCHEME_HTTPS)
{
switch (hr)
{
#if 0
case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND):
case HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND):
case HRESULT_FROM_WIN32(ERROR_BAD_NET_NAME):
case HRESULT_FROM_WIN32(ERROR_BAD_NETPATH):
#endif
case HRESULT_FROM_WIN32(ERROR_CANCELLED):
break;
default:
{
hr = _TryWebFolders(hwnd);
if (SUCCEEDED(hr))
{
_fIsWebFolder = TRUE;
}
}
}
}
}
if (SUCCEEDED(hr))
{
// given that we may have translated the name above for the parse
// to work, lets read back the name we used into our _szTarget.
SHGetNameAndFlags(_pidl, SHGDN_FORPARSING, _szTarget, ARRAYSIZE(_szTarget), NULL);
}
pbcWindow->Release();
}
// compute the place name for the location we have hit, this includes reusing
// any places we have already created.
if (SUCCEEDED(hr) && !_szName[0])
{
SHGetNameAndFlags(_pidl, SHGDN_NORMAL, _szName, ARRAYSIZE(_szName), NULL);
TCHAR szPath[MAX_PATH];
if (!_fIsWebFolder && _IsPlaceTaken(_szName, szPath))
{
PathYetAnotherMakeUniqueName(szPath, szPath, NULL, NULL);
StrCpyN(_szName, PathFindFileName(szPath), ARRAYSIZE(_szName)); // update our state
}
}
pbc->Release();
}
}
else
{
hr = E_FAIL;
}
}
return hr;
}
// handle creating the network place shortcut
HRESULT CNetworkPlace::CreatePlace(HWND hwnd, BOOL fOpen)
{
HRESULT hr = _IDListFromTarget(hwnd);
if (SUCCEEDED(hr))
{
// web folders already have their links created, therefore we can ignore this
// whole process for them, and instead fall back to just executing their link.
//
// for regular folders though we must attempt to find a unique name and create
// the link, or if the link already exists that we can use then just open it.
if (!_fIsWebFolder)
{
IShellLink *psl;
hr = CoCreateInstance(CLSID_FolderShortcut, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARG(IShellLink, &psl));
if (SUCCEEDED(hr))
{
hr = psl->SetIDList(_pidl);
if (SUCCEEDED(hr))
hr = psl->SetDescription(_szDescription[0] ? _szDescription:_szTarget);
if (SUCCEEDED(hr))
{
IPersistFile *ppf;
hr = psl->QueryInterface(IID_PPV_ARG(IPersistFile, &ppf));
if (SUCCEEDED(hr))
{
// get the name to the shortcut, we assume that this is unique
TCHAR szPath[MAX_PATH];
SHGetSpecialFolderPath(NULL, szPath, CSIDL_NETHOOD, TRUE);
PathCombine(szPath, szPath, _szName);
hr = ppf->Save(szPath, TRUE);
ppf->Release();
}
}
psl->Release();
}
}
else
{
// this is the web folder case, so we now need to set the display
// name for this guy. note that we don't have any control over
// the description text we are going to be seeing.
IShellFolder *psf;
LPCITEMIDLIST pidlLast;
hr = SHBindToIDListParent(_pidl, IID_PPV_ARG(IShellFolder, &psf), &pidlLast);
if (SUCCEEDED(hr))
{
LPITEMIDLIST pidlNew;
hr = psf->SetNameOf(hwnd, pidlLast, _szName, SHGDN_INFOLDER, &pidlNew);
if (SUCCEEDED(hr))
{
_fDeleteWebFolder = FALSE;
//Web folders will return S_FALSE with bogus pidlNew if _szName is the same as the current name
if (S_OK == hr)
{
ILFree(_pidl);
hr = SHILCombine((LPCITEMIDLIST)c_pidlWebFolders, pidlNew, &_pidl);
}
}
psf->Release();
}
}
// now open the target if thats what they asked for
if (SUCCEEDED(hr) && fOpen)
{
LPITEMIDLIST pidlNetPlaces;
hr = SHGetSpecialFolderLocation(hwnd, CSIDL_NETWORK, &pidlNetPlaces);
if (SUCCEEDED(hr))
{
IShellFolder *psf;
hr = SHBindToObject(NULL, IID_X_PPV_ARG(IShellFolder, pidlNetPlaces, &psf));
if (SUCCEEDED(hr))
{
LPITEMIDLIST pidl;
hr = psf->ParseDisplayName(hwnd, NULL, _szName, NULL, &pidl, NULL);
if (SUCCEEDED(hr))
{
LPITEMIDLIST pidlToOpen;
hr = SHILCombine(pidlNetPlaces, pidl, &pidlToOpen);
if (SUCCEEDED(hr))
{
BrowseToPidl(pidlToOpen);
ILFree(pidlToOpen);
}
ILFree(pidl);
}
psf->Release();
}
ILFree(pidlNetPlaces);
}
}
}
return hr;
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
d01c9a23bdd8a7bbd5f01531af3345dbcc26aa52 | b91a37992ec3c2c8084d85e268aa84f6e855ed80 | /src/pwm/pwm.cpp | 9de8b8c465a4dcaa173f502f2bfbdc35e3fb9ba6 | [] | no_license | USA-RedDragon/pwm-usb-serial-arduino | e7a0076f379626353d224af745248139be7a9ec5 | 2ab4aee075cd67ded0680112bc34876dea7f5c62 | refs/heads/main | 2023-06-23T20:23:24.539749 | 2021-07-28T08:44:40 | 2021-07-28T08:44:40 | 389,062,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | cpp | #include <Arduino.h>
#include "pins.h"
#include "pwm.h"
void pwmSetup(Configuration configuration) {
pinMode(PIN_PWM_USB0, OUTPUT);
pinMode(PIN_PWM_USB1, OUTPUT);
pwmWrite(PIN_PWM_USB0, configuration.usb0Restore);
pwmWrite(PIN_PWM_USB1, configuration.usb1Restore);
}
void pwmWrite(int pin, PowerState powerState) {
if (powerState.power) {
analogWrite(pin, powerState.dutyCycle);
}
} | [
"jacob@mcswain.dev"
] | jacob@mcswain.dev |
961c05443743c13aa098f2d730d727efcbd06d47 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_old_hunk_3070.cpp | 483df43e60faec05910c5fa95daafd4ddfcbc731 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | if (git_config_rename_section(buf.buf, buf2.buf) < 1)
return error(_("Could not rename config section '%s' to '%s'"),
buf.buf, buf2.buf);
strbuf_reset(&buf);
strbuf_addf(&buf, "remote.%s.fetch", rename.new);
if (git_config_set_multivar(buf.buf, NULL, NULL, 1))
return error(_("Could not remove config section '%s'"), buf.buf);
strbuf_addf(&old_remote_context, ":refs/remotes/%s/", rename.old);
for (i = 0; i < oldremote->fetch_refspec_nr; i++) {
char *ptr;
strbuf_reset(&buf2);
strbuf_addstr(&buf2, oldremote->fetch_refspec[i]);
| [
"993273596@qq.com"
] | 993273596@qq.com |
110199dff267e406031cc3350fd1381da1e97ec8 | 90db83e7fb4d95400e62fa2ce48bd371754987e0 | /src/chrome/browser/chromeos/crosapi/account_manager_ash.cc | c74ee21f8012e37abbea89becf5231da8b503d03 | [
"BSD-3-Clause"
] | permissive | FinalProjectNEG/NEG-Browser | 5bf10eb1fb8b414313d5d4be6b5af863c4175223 | 66c824bc649affa8f09e7b1dc9d3db38a3f0dfeb | refs/heads/main | 2023-05-09T05:40:37.994363 | 2021-06-06T14:07:21 | 2021-06-06T14:07:21 | 335,742,507 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,891 | cc | // Copyright 2020 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/chromeos/crosapi/account_manager_ash.h"
#include <utility>
#include "base/callback.h"
#include "base/notreached.h"
#include "chromeos/components/account_manager/account_manager.h"
#include "mojo/public/cpp/bindings/remote.h"
namespace crosapi {
AccountManagerAsh::AccountManagerAsh(
chromeos::AccountManager* account_manager,
mojo::PendingReceiver<mojom::AccountManager> receiver)
: account_manager_(account_manager), receiver_(this, std::move(receiver)) {
DCHECK(account_manager_);
account_manager_->AddObserver(this);
}
AccountManagerAsh::~AccountManagerAsh() {
account_manager_->RemoveObserver(this);
}
void AccountManagerAsh::IsInitialized(IsInitializedCallback callback) {
std::move(callback).Run(account_manager_->IsInitialized());
}
void AccountManagerAsh::AddObserver(AddObserverCallback callback) {
mojo::Remote<mojom::AccountManagerObserver> remote;
auto receiver = remote.BindNewPipeAndPassReceiver();
observers_.Add(std::move(remote));
std::move(callback).Run(std::move(receiver));
}
void AccountManagerAsh::OnTokenUpserted(
const chromeos::AccountManager::Account& account) {
for (auto& observer : observers_)
observer->OnTokenUpserted(ToMojoAccount(account));
}
void AccountManagerAsh::OnAccountRemoved(
const chromeos::AccountManager::Account& account) {
for (auto& observer : observers_)
observer->OnAccountRemoved(ToMojoAccount(account));
}
// static
chromeos::AccountManager::Account AccountManagerAsh::FromMojoAccount(
const mojom::AccountPtr& mojom_account) {
chromeos::AccountManager::Account account;
account.key.id = mojom_account->key->id;
account.key.account_type =
FromMojoAccountType(mojom_account->key->account_type);
account.raw_email = mojom_account->raw_email;
return account;
}
// static
mojom::AccountPtr AccountManagerAsh::ToMojoAccount(
const chromeos::AccountManager::Account& account) {
mojom::AccountPtr mojom_account = mojom::Account::New();
mojom_account->key = mojom::AccountKey::New();
mojom_account->key->id = account.key.id;
mojom_account->key->account_type =
ToMojoAccountType(account.key.account_type);
mojom_account->raw_email = account.raw_email;
return mojom_account;
}
// static
chromeos::account_manager::AccountType AccountManagerAsh::FromMojoAccountType(
const mojom::AccountType& account_type) {
switch (account_type) {
case mojom::AccountType::kUnspecified:
return chromeos::account_manager::AccountType::ACCOUNT_TYPE_UNSPECIFIED;
case mojom::AccountType::kGaia:
return chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA;
case mojom::AccountType::kActiveDirectory:
return chromeos::account_manager::AccountType::
ACCOUNT_TYPE_ACTIVE_DIRECTORY;
default:
// Ash does not know about this new account type. Don't consider this as
// as error to preserve forwards compatibility with lacros.
LOG(WARNING) << "Unknown account type: " << account_type;
return chromeos::account_manager::AccountType::ACCOUNT_TYPE_UNSPECIFIED;
}
}
// static
mojom::AccountType AccountManagerAsh::ToMojoAccountType(
const chromeos::account_manager::AccountType& account_type) {
switch (account_type) {
case chromeos::account_manager::AccountType::ACCOUNT_TYPE_UNSPECIFIED:
return mojom::AccountType::kUnspecified;
case chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA:
return mojom::AccountType::kGaia;
case chromeos::account_manager::AccountType::ACCOUNT_TYPE_ACTIVE_DIRECTORY:
return mojom::AccountType::kActiveDirectory;
}
}
void AccountManagerAsh::FlushMojoForTesting() {
observers_.FlushForTesting();
}
} // namespace crosapi
| [
"sapirsa3@ac.sce.ac.il"
] | sapirsa3@ac.sce.ac.il |
f7d5854a925d8547dd2e204c471b19a1b85708db | 88ff0f4227d8f2004df52205cde54f568256597a | /task_1_3_15.cpp | 51644bf41053595f7d9582377b6e2296af4d33fa | [] | no_license | AlterFritz88/intro_to_prog_c_plus_plus | 6f5322ff6d2ce17ab5252db62cb774fcfb075598 | d83b15bbfad2252a041a560487b2dcc5c6b39c16 | refs/heads/master | 2020-06-13T04:39:24.602066 | 2019-07-16T10:18:53 | 2019-07-16T10:18:53 | 194,537,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 240 | cpp | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int d4 = n / 1000;
int d3 = n / 100 % 10;
int d2 = n / 10 % 10;
int d1 = n % 10;
cout << ((d4*10 + d3) - (d1*10 + d2)) + 1;
return 0;
}
| [
"burdin009@gmail.com"
] | burdin009@gmail.com |
bdab6f22630a5d572fee5f46c7903092fbec7e03 | 783b32575866ea565b92bf2c91addf03387aee64 | /screenDischarging.h | 826273fd16510bbaa6b267b159bea82099eb018a | [] | no_license | mean00/batteryTester2 | e43bf288f4e82c1096ea9b525772089e697525c7 | 622b261bd3d3da445e454dc6ead65c8cd1270fa8 | refs/heads/master | 2021-06-23T22:46:42.829405 | 2020-10-29T06:35:50 | 2020-10-29T06:35:50 | 131,689,825 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,937 | h | /***************************************************
Battery Tester
* GPL v2
* (c) mean 2018 fixounet@free.fr
****************************************************/
#pragma once
#include "screenBase.h"
#include "screenFinished.h"
#include "ad_timer.h"
#define AVERAGING_SAMPLE_COUNT 10
#define AVERAGING_SAMPLE_PERIOD 100 // 100 ms
#define ANIMATION_MAX 4
class dischargingScreen : public batScreen
{
public:
enum VOLTAGE_RANGE
{
RANGE_HIGH=0,
RANGE_MED=1,
RANGE_LOW=2
};
dischargingScreen( batConfig *c, int currentV);
void draw();
virtual batScreen *process(); // return NULL if the current screen stays the same
protected:
bool evaluateTargetAmp();
int computeGateCommand(int amp);
void updateInfo();
bool resetAverage();
bool processEvents();
int gateCommand;
int originalGateCommand;
batScreen *goToEnd(EndOfChargeCause cause);
bool computeAverage(int mV,int mA,int &avgV, int &avgA);
bool adjustGateVoltage(int avgA,int avgV);
void updateTargetCurrent();
bool LeftOrRigh(int leftRight);
void animate();
int sampleIndex;
int samplema[AVERAGING_SAMPLE_COUNT];
int samplemv[AVERAGING_SAMPLE_COUNT];
bool paused;
VOLTAGE_RANGE range;
int resyncing;
int animation;
Timer timer;
Timer smallTimer,debounceTimer;
Timer animateTimer;
Timer tuneTimer;
int iconColor;
}; | [
"fixounet@free.fr"
] | fixounet@free.fr |
ff019a4e0eff826a4370d875916a69d690048821 | 294a64de6f841e9436875d9bd6eab9b1dd1ad528 | /project3/http_server.cpp | 28beb913f356a4870f0fa32fe1c3bda745eafa73 | [] | no_license | stevenchiu30801/NCTU-Network-Programming-Grad | 968fad98a2c7f12d81fbfcc898570c2d143e675d | 9143cafc61156f3c11ed40eecd978faabbc64e2d | refs/heads/master | 2020-04-01T09:13:05.668232 | 2018-12-28T06:11:29 | 2018-12-28T06:11:29 | 153,065,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,922 | cpp | #include <array>
#include <boost/asio.hpp>
#include <cstdlib>
#include <iostream>
#include <regex>
#include <signal.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_SHELL_SESSION 5
using namespace boost::asio;
using namespace std;
io_service global_io_service;
void sigchld_handler(int signo) {
waitpid(-1, NULL, 0);
return;
}
class Session : public enable_shared_from_this<Session> {
private:
enum { max_length = 1024 };
ip::tcp::socket _socket;
array<char, max_length> _buffer;
string server_addr, server_port, remote_addr, remote_port;
/* REQUEST_METHOD. REQUEST_URI, SCRIPT_NAME, QUERY_STRING, SERVER_PROTOCOL, HTTP_HOST */
string method, uri, script, query, protocol, host;
public:
Session(ip::tcp::socket socket)
: _socket(move(socket)) {}
void start() { do_read(); }
private:
void do_read() {
auto self(shared_from_this());
_socket.async_read_some(
buffer(_buffer, max_length),
[this, self](boost::system::error_code ec, std::size_t bytes_transferred) {
if (!ec) {
server_addr = _socket.local_endpoint().address().to_string();
server_port = std::to_string(_socket.local_endpoint().port());
remote_addr = _socket.remote_endpoint().address().to_string();
remote_port = std::to_string(_socket.remote_endpoint().port());
do_parse(_buffer.data());
do_response();
}
});
}
void do_parse(string data) {
stringstream ss_request_line(data);
string keys;
ss_request_line >> method;
ss_request_line >> uri;
ss_request_line >> protocol;
ss_request_line >> keys;
ss_request_line >> host;
regex uri_regex("\\?");
smatch uri_match;
regex_search(uri, uri_match, uri_regex);
if (uri_match.empty() == false) {
script = uri_match.prefix().str();
query = uri_match.suffix().str();
}
else {
script = uri;
query.clear();
}
}
void do_response() {
struct stat buffer;
if (stat(script.substr(1).c_str(), &buffer) != 0) {
string response = "HTTP/1.1 404 Not Found\n";
write(_socket, boost::asio::buffer(response, response.length()));
return;
}
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork error");
exit(1);
}
else if (pid == 0) {
/* child process */
/* set http environment variable */
setenv("REQUEST_METHOD", method.c_str(), 1);
setenv("REQUEST_URI", uri.c_str(), 1);
setenv("QUERY_STRING", query.c_str(), 1);
setenv("SERVER_PROTOCOL", protocol.c_str(), 1);
setenv("HTTP_HOST", host.c_str(), 1);
setenv("SERVER_ADDR", server_addr.c_str(), 1);
setenv("SERVER_PORT", server_port.c_str(), 1);
setenv("REMOTE_ADDR", remote_addr.c_str(), 1);
setenv("REMOTE_PORT", remote_port.c_str(), 1);
char *argv[] = {NULL};
int sockfd = _socket.native_handle();
dup2(sockfd, STDIN_FILENO);
dup2(sockfd, STDOUT_FILENO);
cout << "HTTP/1.1 200 OK" << endl;
execv(script.substr(1).c_str(), argv);
}
else {
/* parent process */
waitpid(pid, NULL, 0);
}
}
};
class Server {
private:
ip::tcp::acceptor _acceptor;
ip::tcp::socket _socket;
public:
Server(short port)
: _acceptor(global_io_service, ip::tcp::endpoint(ip::tcp::v4(), port)),
_socket(global_io_service)
{
do_accept();
}
private:
void do_accept() {
_acceptor.async_accept(_socket, [this](boost::system::error_code ec) {
if (!ec)
make_shared<Session>(move(_socket))->start();
do_accept();
});
}
};
int main(int argc, char* argv[]) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <port>\n";
return 1;
}
signal(SIGCHLD, sigchld_handler);
try {
short port = atoi(argv[1]);
Server s(port);
global_io_service.run();
} catch (exception& e) {
cerr << "Exception: " << e.what() << endl;
}
return 0;
}
| [
"steven30801@gmail.com"
] | steven30801@gmail.com |
89fe5a937d9d8f1db95f07bcb63b6d588f332a0e | 8a041a113f02ac0574e1529a699c1e5ffd336613 | /Algorithm/Sorting/Counting Sort part 2.cpp | 7e9a137fd01d685477bd993720a6cf48342f70f2 | [] | no_license | UtkarshSharma26/HackerRank | f155436f48cc059024bfbac2e2c34517cac8fa4a | 44b156d7abc903f9e364e04cd6a50fdf66b0b5ca | refs/heads/master | 2020-03-24T13:11:27.625149 | 2019-10-13T07:19:15 | 2019-10-13T07:19:15 | 142,737,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
long long arr[1000000] ={0},i,j,k,x,n;
cin>>n;
for(i=0;i<n;i++){
cin>>x;
arr[x]++;
}
i=0;
while(n>0){
while(arr[i]>0){
cout<<i<<" ";
n--;
arr[i]--;
}
i++;
}
cout<<endl;
return 0;
} | [
"utkarsh.sharma26@hotmail.com"
] | utkarsh.sharma26@hotmail.com |
7dfcc7ae80590eaa4608c1022f552f7ce2f55e85 | 3b411f613131e8cc2380aa72b5513909422afe8d | /16.cpp | d4cc1a86e520cc8c9f436e6651787b94a28346dd | [] | no_license | ajaybhakuni85/college-project | 3b34ae1d863a7ec93f673641542cd5bf27c537a1 | 1fa48b07a7688bfd0a961509a048a6a1beabdae8 | refs/heads/main | 2023-06-30T07:07:36.283159 | 2021-07-30T16:29:35 | 2021-07-30T16:29:35 | 391,127,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | #include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *start=NULL;
void createLinkedList(int data){
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->next=NULL;
if(start==NULL){
start=temp;
}
else{
struct node *last=start;
while(last->next!=NULL){
last=last->next;
}
last->next=temp;
}
}
void display(){
struct node *temp=start;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void odd(){
struct node *odd=start;
int i=1;
while(odd!=NULL){
if(i%2!=0) printf("%d ",odd->data);
i++;
odd=odd->next;
}
printf("\n");
}
void even(){
struct node *odd=start;
int i=1;
while(odd!=NULL){
if(i%2==0) printf("%d ",odd->data);
i++;
odd=odd->next;
}
printf("\n");
}
int main(){
int n,element;
printf("enter size of linked list :");
scanf("%d",&n);
printf("enter elements :");
while(n--){
scanf("%d",&element);
createLinkedList(element);
}
printf("P is : \n");
display();
printf("Q is : \n");
odd();
printf("R is : \n");
even();
}
| [
"noreply@github.com"
] | noreply@github.com |
46cf17fb50142091af9cb61fe125b2ac7c310676 | efd81d18412b52596d8f47e5c17b1e1c31d530d5 | /motor.cpp | 75bbe8e8f14e17eb2963d5cb937d6769519d3372 | [] | no_license | gary600/meche-project2 | 0d21a5c7015bae947b1123e4038da455781cef52 | f169d91d38bc9ce70d9e56272103494c38642908 | refs/heads/master | 2023-09-03T13:14:47.239813 | 2021-11-12T17:00:28 | 2021-11-12T17:00:28 | 421,631,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | cpp | ///////////////////////////////////////////
// `motor.cpp`: Motor control functions. //
///////////////////////////////////////////
#include "motor.hpp"
#include <Arduino.h>
#include "pins.hpp"
// Helper function: Sets the speed of 1 side of the robot.
void _motor_speed(int speed_pin, int dir_pin, float motor_speed) {
// Clamp to range -1 to 1 to prevent overflow
motor_speed = motor_speed > 1.0 ? 1.0 : motor_speed;
motor_speed = motor_speed < -1.0 ? -1.0 : motor_speed;
// Positive means forwards
if (motor_speed >= 0) {
analogWrite(speed_pin, motor_speed*255.0);
digitalWrite(dir_pin, HIGH); // HIGH is forward
}
// Negative means backwards
else {
analogWrite(speed_pin, -motor_speed*255.0);
digitalWrite(dir_pin, LOW);
}
}
// Main motor speed function: input values are of range -1.0 to 1.0
// These are converted to output signals of range 0 to 255 plus direction.
void set_speeds(float speed_l, float speed_r) {
_motor_speed(SPEED_L, DIR_L, speed_l);
_motor_speed(SPEED_R, DIR_R, speed_r);
}
| [
"me@gary600.xyz"
] | me@gary600.xyz |
984ab815736eb4a0082dd42a9752f1b352956ce4 | 4212b420e0067e14c97d14a31b6444c28215903f | /Programs/Data_Structrures/RingBuffer/rg_iterator_Elegant.cpp | 0d2df9299328dd87d3f8a2ed4c23cd9acc13b4ba | [] | no_license | StavrosMar/CPP | 929f6dc4e642a32e8d0bd84994b94b90cd19f64e | 3512dc09bf6b2a93130898c16471768052ad5ca1 | refs/heads/master | 2021-09-23T18:16:55.619093 | 2021-09-13T17:41:05 | 2021-09-13T17:41:05 | 86,387,879 | 0 | 0 | null | 2018-08-06T15:41:03 | 2017-03-27T21:57:04 | C++ | UTF-8 | C++ | false | false | 2,880 | cpp | /*
*
* Topics covered:
* 1) Iterator for my ringBuffer
* 2) Consolidate Eliminate code for iterator and const iterator
* 3) TODO - complete operators
* 4) Equality / conversions between const iter and iter should work
*
*/
#include <iostream>
using namespace std;
template <typename T, bool Const = false> class rg_iterator { //by default non-const iterator
//Friend declaration necessary to make members visible to copy/conversion constructor.
friend class rg_iterator<T, true>;
typedef typename std::conditional<Const, const T, T>::type IterType;
using pointer = IterType*;
using reference = IterType&;
T* _ptr;
int _indx;
const size_t _size;
public:
//Constructors
rg_iterator(T* ptr_start,const int& index, const size_t& N) : _ptr{ptr_start}, _indx{index}, _size{N} {};
rg_iterator(const rg_iterator<T,false>& i) : _ptr{i._ptr}, _indx{i._indx}, _size{i._size} {}; //Very important to add template parameters - A temporary object is created before conversion below on ==
rg_iterator() = delete;
reference operator*() {
return *_ptr;
}
void operator++() {
int indx_after = (_indx+1)%_size;
int diff = indx_after - _indx;
_indx = indx_after;
_ptr = _ptr+diff;
}
//Here we are forcing a conversion - thus the copy constructor is called and needed.
friend bool operator==(const rg_iterator& x,
const rg_iterator& y) {
return (x._ptr == y._ptr && x._indx == y._indx && x._size == y._size) ;
}
};
int main()
{
//Test ++ and * operators
int a[2]={10,20};
rg_iterator<int> it{&a[0],0,2};
cout<<"===Increasing iterator using ++it==="<<endl;
cout<<"*it="<<*it<<endl;
++it;
cout<<"*it="<<*it<<endl;
++it;
cout<<"*it="<<*it<<endl;
cout<<"===Non const check - Altering contents test using *it==="<<endl;
*it = 39;
cout<<"a is now : "<<a[0]<<" "<<a[1]<<endl;
//Test const iterator
cout<<"\n=== Const Iterator - Testing ===\n"<<endl;
int b[2]={10,20};
rg_iterator<int,true> it2{&b[0],0,2};
cout<<"=== b: Increasing iterator using ++it==="<<endl;
cout<<"*it="<<*it2<<endl;
++it2;
cout<<"*it="<<*it2<<endl;
++it2;
cout<<"*it="<<*it2<<endl;
cout<<"===Const check - Altering contents test using *it==="<<endl;
//*it2 = 39; //Good - compile-time error
cout<<"b is now : "<<b[0]<<" "<<b[1]<<endl;
//Relationship between const and non-const
cout<<"\n=== Iterator - Const iterator relationship ==="<<endl;
rg_iterator<int,true> it3{&a[0],0,2};
cout<<"Equal iterators? : "<<(it==it3)<<endl; //Problem !! - Need to explicitly define operators for handling const and non-const iterators.
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
1e5587589896ba08d97a534dcf12c41b5adc2880 | c6e675ac42bf9dd7bd5967e73352427ba562530e | /src/StatTool.cpp | 12c7802cc3c2d60e2689154dca856ce35b8c447c | [] | no_license | adrien-zinger/async_stat_module | 2f8521e9e783914c03ecf8f22da87b2de1db3cbe | 787cc29b7bd6c2a9e68328e350ecad881f30cf76 | refs/heads/master | 2023-05-09T08:14:43.075145 | 2021-05-11T17:56:13 | 2021-05-11T17:56:13 | 366,470,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,652 | cpp | #include "StatTool.hpp"
#include <algorithm>
#include <math.h>
#include <iostream>
#define TRIM 5e6
StatTool::~StatTool() {
time_pos.val.clear();
time_pos.time_us.clear();
time_density.val.clear();
time_density.time_us.clear();
}
void StatTool::MesureDensityReady(int density, int time_us) {
std::lock_guard<std::mutex> lock(mtx_density);
impl.Push(TRIM, time_us, density, time_density);
}
void StatTool::MesurePositionReady(int position_mm, int time_us) {
std::lock_guard<std::mutex> lock(mtx_position);
impl.Push(TRIM, time_us, position_mm, time_pos);
}
void dumpError(std::string msg, int min_pos_mm, int max_pos_mm,
int min_time_val, int max_time_val) {
std::cerr << msg.c_str() << "\n";
std::cerr << " " << min_pos_mm << ", "
<< max_pos_mm << ", "
<< min_time_val << ", "
<< min_time_val << "\n";
}
void StatTool::Elaboration(int min_pos_mm, int max_pos_mm,
int *mean_density, int *min_density, int *median) {
std::unique_lock<std::mutex> pos_lock(mtx_position);
// Get time indexes from asked positions
int min_index = -1, max_index = -1;
bool success = impl.FindIndex(time_pos.val, min_pos_mm, false, min_index)
&& impl.FindIndex(time_pos.val, max_pos_mm, true, max_index);
if (!success)
return dumpError("Position loss",
min_pos_mm, max_pos_mm, min_index, max_index);
// I suppose that's included in the 5 previous seconds
const int time_min = time_pos.time_us[min_index];
const int time_max = time_pos.time_us[max_index];
pos_lock.unlock();
std::unique_lock<std::mutex> den_lock(mtx_density);
// Get densities index from time_min and time_max
success = impl.FindIndex(time_density.time_us, time_min, false, min_index)
&& impl.FindIndex(time_pos.time_us, time_max, true, max_index);
if (!success)
return dumpError("Density loss",
min_pos_mm, max_pos_mm, min_index, max_index);
// Get subvector
const auto begin = time_density.val.begin() + min_index;
const auto end = time_density.val.begin() + max_index;
const int size = max_index - min_index;
// Compute mean
*mean_density = impl.Sum(begin, end, size) / size;
// Compute min
*min_density = *std::min_element(begin, end);
// Compute median (Need a copy or we may loose information)
std::vector<int> sorted(begin, end);
std::sort(sorted.begin(), sorted.end());
*median = sorted.size() % 2 != 0 ?
std::floor(sorted[sorted.size() / 2])
: (sorted[(sorted.size() - 1) / 2] + sorted[sorted.size() / 2]) / 2;
den_lock.unlock();
}
| [
"azinger@eos-imaging.com"
] | azinger@eos-imaging.com |
c60c9bc0da4388376b64473c0013ae05a21ccdb7 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/LArCalorimeter/LArCalibTools/src/LArCaliWaves2Ntuple.cxx | 07eb40c490d2bf7a280aa5a2be480581599def42 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,735 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "LArCalibTools/LArCaliWaves2Ntuple.h"
#include "CaloIdentifier/CaloGain.h"
//#include "TGraph.h"
//#include "TF1.h"
LArCaliWaves2Ntuple::LArCaliWaves2Ntuple(const std::string& name, ISvcLocator* pSvcLocator): LArWaves2Ntuple(name, pSvcLocator)
{
m_keylist.clear() ;
declareProperty("KeyList", m_keylist);
declareProperty("DACSaturSkip", m_dacSaturSkip=false);
declareProperty("SaveJitter", m_saveJitter=false);
declareProperty("NtupleName", m_ntName="DELAYS");
declareProperty("NtupleFile", m_ntFile= "FILE1");
m_dacSaturLayer0.resize(0);
m_dacSaturLayer1.resize(0);
m_dacSaturLayer2.resize(0);
m_dacSaturLayer3.resize(0);
declareProperty("DACSaturPS", m_dacSaturLayer0);
declareProperty("DACSaturStrips",m_dacSaturLayer1);
declareProperty("DACSaturMiddle",m_dacSaturLayer2);
declareProperty("DACSaturBack", m_dacSaturLayer3);
declareProperty("AddCorrUndo", m_addCorrUndo=true);
declareProperty("ApplyCorrection",m_applyCorr=false);
}
StatusCode LArCaliWaves2Ntuple::initialize() {
m_ntTitle="Calibration Wave";
m_ntpath=std::string("/NTUPLES/")+m_ntFile+std::string("/")+m_ntName;
return LArWaves2Ntuple::initialize();
}
LArCaliWaves2Ntuple::~LArCaliWaves2Ntuple()
{}
StatusCode LArCaliWaves2Ntuple::stop()
{
// Check DACSatur jobOption consistency, in case setup default values
if ( m_dacSaturSkip && m_dacSaturLayer0.size()<3 ) {
ATH_MSG_WARNING( "DACSaturPS jobOption has wrong size. Will use default." ) ;
m_dacSaturLayer0.resize(3);
m_dacSaturLayer0[0] = 15000 ;
m_dacSaturLayer0[1] = 50000 ;
m_dacSaturLayer0[2] = 65000 ;
}
if ( m_dacSaturSkip && m_dacSaturLayer1.size()<3 ) {
ATH_MSG_WARNING( "DACSaturStrips jobOption has wrong size. Will use default." ) ;
m_dacSaturLayer1.resize(3);
m_dacSaturLayer1[0] = 800 ;
m_dacSaturLayer1[1] = 8000 ;
m_dacSaturLayer1[2] = 65000 ;
}
if ( m_dacSaturSkip && m_dacSaturLayer2.size()<3 ) {
ATH_MSG_WARNING( "DACSaturMiddle jobOption has wrong size. Will use default." ) ;
m_dacSaturLayer2.resize(3);
m_dacSaturLayer2[0] = 1000 ;
m_dacSaturLayer2[1] = 10000 ;
m_dacSaturLayer2[2] = 65000 ;
}
if ( m_dacSaturSkip && m_dacSaturLayer3.size()<3 ) {
ATH_MSG_WARNING( "DACSaturBack jobOption has wrong size. Will use default." ) ;
m_dacSaturLayer3.resize(3);
m_dacSaturLayer3[0] = 800 ;
m_dacSaturLayer3[1] = 8000 ;
m_dacSaturLayer3[2] = 65000 ;
}
StatusCode sc;
sc=m_nt->addItem("DAC",m_dac,0,64000);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'DAC' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("gain",m_gain,0,3);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'gain' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("nPulsedCalibLines",m_nPulsedCalibLines,0,4);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'nPulsedCalibLines' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("pulsedCalibLines",4,m_pulsedCalibLines);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'pulsedCalibLines' failed" );
return StatusCode::FAILURE;
}
if (m_saveJitter) {
sc=m_nt->addItem("Jitter",m_jitter,0.,1.);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'Jitter' failed" );
return StatusCode::FAILURE;
}
}
if (m_addCorrUndo) {
sc=m_nt->addItem("corrUndo",m_corrUndo,0,1);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'corrUndo' failed" );
return StatusCode::FAILURE;
}
}
for ( unsigned k=0 ; k<m_keylist.size() ; k++ ) {
const std::string& key = m_keylist[k] ;
ATH_MSG_INFO( "Processing WaveContainer from StoreGate! key=" << m_keylist[k] );
const LArCaliWaveContainer* caliWaveContainer;
StatusCode sc = m_detStore->retrieve(caliWaveContainer,key);
if (sc.isFailure()) {
ATH_MSG_ERROR( "Cannot read LArCaliWaveContainer from StoreGate! key=" << key );
return StatusCode::FAILURE;
} else
ATH_MSG_INFO( "Read LArCaliWaveContainer from StoreGate! key= " << key );
if (m_applyCorr) {
if (!caliWaveContainer->correctionsApplied()) {
LArCaliWaveContainer* caliWaveContainer_nc=const_cast<LArCaliWaveContainer*>(caliWaveContainer);
sc=caliWaveContainer_nc->applyCorrections();
if (sc.isFailure()) {
ATH_MSG_ERROR( "Failed to apply corrections to LArCaliWaveContainer!" );
}
else
ATH_MSG_INFO( "Applied corrections to LArCaliWaveContainer" );
}
else {
ATH_MSG_WARNING( "Corrections already applied. Can't apply twice!" );
}
}// end if applyCorr
for (unsigned igain=CaloGain::LARHIGHGAIN;igain<CaloGain::LARNGAIN ;++igain){
std::vector<HWIdentifier>::const_iterator itOnId = m_onlineId->channel_begin();
std::vector<HWIdentifier>::const_iterator itOnIdEnd = m_onlineId->channel_end();
for(; itOnId!=itOnIdEnd;++itOnId){
const HWIdentifier chid = *itOnId;
m_gain=(long)igain;
const LArCaliWaveVec& cwv = caliWaveContainer->get(chid,igain);
if (cwv.size()==0) continue;
LArCaliWaveVec::const_iterator cwv_it=cwv.begin();
LArCaliWaveVec::const_iterator cwv_it_e=cwv.end();
for (;cwv_it!=cwv_it_e;++cwv_it) {
const LArCaliWave& wave=*cwv_it;
if (wave.isEmpty()) continue;
if (m_addCorrUndo) m_corrUndo=0;
bool skip=writeEntry(chid,igain,wave);
if (skip) continue;
sc=ntupleSvc()->writeRecord(m_nt);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "writeRecord failed" );
return sc;
}
}//End loop over DAC
}//end loop over identifiers
}//end loop over gains
if (m_addCorrUndo) {
for (unsigned igain=CaloGain::LARHIGHGAIN;igain<CaloGain::LARNGAIN ;++igain) {
LArCaliWaveContainer::ConstCorrectionIt itUndo=caliWaveContainer->undoCorrBegin(igain);
LArCaliWaveContainer::ConstCorrectionIt itUndo_e=caliWaveContainer->undoCorrEnd(igain);
for(;itUndo!=itUndo_e;itUndo++) {
const HWIdentifier chid(itUndo->first);
const LArCaliWaveVec& cwv = itUndo->second;
m_gain = (long)igain;
m_corrUndo = 1;
LArCaliWaveVec::const_iterator cwv_it=cwv.begin();
LArCaliWaveVec::const_iterator cwv_it_e=cwv.end();
for (;cwv_it!=cwv_it_e;++cwv_it) {
const LArCaliWave& wave=*cwv_it;
bool skip=writeEntry(chid,igain,wave);
if (skip) continue;
sc=ntupleSvc()->writeRecord(m_nt);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "writeRecord failed" );
return sc;
}
}//end loop over DAC
}//end loop over corrections
}//end loop over gain
}//end if addUndoCorr
}//end loop over container keys
ATH_MSG_INFO( "LArWave2Ntuple has finished." );
return StatusCode::SUCCESS;
} // end finalize-method.
bool LArCaliWaves2Ntuple::writeEntry(const HWIdentifier chid, const unsigned gain, const LArCaliWave& wave) {
//call fill method of base-class
fillWave(chid,wave);
m_dac = wave.getDAC();
int DACSatur = 100000;
if (m_dacSaturSkip) {
switch (m_layer) {
case 0:
DACSatur = m_dacSaturLayer0[gain];
break;
case 1:
DACSatur = m_dacSaturLayer1[gain];
break;
case 2:
DACSatur = m_dacSaturLayer2[gain];
break;
case 3:
DACSatur = m_dacSaturLayer3[gain];
break;
}
if (m_dac > DACSatur ) return true;
}
/// HEC calibration lines
if ( !m_isSC ) {
const std::vector<HWIdentifier>& calibLineV = ((LArCablingService*)m_larCablingSvc)->calibSlotLine(chid);
if ( calibLineV.size()>0 ) {
ATH_MSG_DEBUG( "wave.getIsPulsedInt() " << wave.getIsPulsedInt()<<" : "<< calibLineV.size());
for(int i=0;i<4;i++)
m_pulsedCalibLines[i] = NOT_VALID;
std::vector<HWIdentifier>::const_iterator calibLineIt = calibLineV.begin();
unsigned iCalibLine=0;
m_nPulsedCalibLines=0;
for(calibLineIt = calibLineV.begin(); calibLineIt != calibLineV.end();++calibLineIt) {
if ( (wave.getIsPulsedInt()>>iCalibLine) & 1 ){
m_pulsedCalibLines[iCalibLine] = m_onlineId->channel(*calibLineIt);
if (m_pulsedCalibLines[iCalibLine]>=0) m_calibLine = m_onlineId->channel(*calibLineIt);
m_nPulsedCalibLines++;
}
iCalibLine++;
}
ATH_MSG_DEBUG( "m_pulsedCalibLines: "<<m_pulsedCalibLines[0]<<"/"<<m_pulsedCalibLines[1]<<"/"<<m_pulsedCalibLines[2]<<"/"<<m_pulsedCalibLines[3]);
}else {
m_nPulsedCalibLines = 0 ;
m_pulsedCalibLines[0] = NOT_VALID;
}
}else {
m_nPulsedCalibLines = 0 ;
m_pulsedCalibLines[0] = NOT_VALID;
}
// Jitter
if ( m_saveJitter ) {
m_jitter = m_waveHelper.getJitter(wave);
}
return false;
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
5118ebc311530637f0f90c39e9f07d7ed84e0bd7 | 9a33566bdd5fd8a1a7f40b27f69ad8d1118f8f18 | /epoch/lucca/include/lucca/painter/painter.hpp | a859f744e07c777b4701dd2de041a24eb4d07033 | [
"MIT"
] | permissive | nwalablessing/vize | d0968f6208d608d9b158f0b21b0d063a12a45c81 | 042c16f96d8790303563be6787200558e1ec00b2 | refs/heads/master | 2023-05-31T15:39:02.877681 | 2019-12-22T14:09:02 | 2019-12-22T14:09:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | hpp | #ifndef LUCCA_PAINTER_HPP
#define LUCCA_PAINTER_HPP
#include "lucca/config.hpp"
#include <boost/noncopyable.hpp>
namespace ayla {
class AxisAlignedBox;
}
namespace lucca {
class RenderTarget;
class Camera;
/**
* Knows how to draw something on a render target.
*
* @see lucca::RenderTarget
*
* @author O Programador
*/
class LUCCA_API Painter : boost::noncopyable {
public:
virtual ~Painter() = default;
/**
* Initialize this painter with some render target. Must be called before drawing.
*/
virtual void initialize(RenderTarget* target) = 0;
/**
* Release resources and undo the job made on "initialize" method.
*/
virtual void dispose() = 0;
/**
* Draw data from @param camera point of view.
*
* @param camera must be associated with the same
* render target that was used to initialize this painter.
*
* @return True on success. False to indicate that it needs repaint.
*/
virtual bool paint(const Camera& camera) = 0;
/**
* Tells this painter that the render target was resized.
*/
virtual void resize(SizeType width, SizeType height) = 0;
/**
* @return True if the render target used to initialize
* this painter is the same object of @param target.
*/
virtual bool compareRenderTarget(const RenderTarget* target) const = 0;
/**
* @return True if the render target of this painter has the current rendering context.
*/
virtual bool hasCurrentRenderingContext() const = 0;
/**
* @return A bounding box for the data rendered by this painter.
*/
virtual ayla::AxisAlignedBox getAABB() const = 0;
/**
* @return A copy of this painter.
*/
virtual std::unique_ptr<Painter> clone() const = 0;
/**
* @see lucca::PainterComposite
*/
virtual void addSubPainter(std::unique_ptr<Painter> subPainter) = 0;
};
}
#endif // LUCCA_PAINTER_HPP | [
"sms.cpp@gmail.com"
] | sms.cpp@gmail.com |
93444d12737811771cb4cc73ea8cfb3a257f5326 | 41c47786101f8bce66a39a99866d735230c41d19 | /CSC 461/PA6/Test/Performance_ColMajorCPP.cpp | a0b7723e1c98b24e51b122dc0e3593971d33b249 | [] | no_license | brianabauman/depaul | 2ef5913db9372dabf5522317ca5975f830212665 | c9162e17ad63228046ba4dc7017b8e00acf9fc31 | refs/heads/main | 2023-05-10T14:48:28.840279 | 2021-06-09T19:19:12 | 2021-06-09T19:19:12 | 375,392,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,970 | cpp | //----------------------------------------------------------------------------
// Copyright Ed Keenan 2019
//----------------------------------------------------------------------------
#include "Framework.h"
#include "PerformanceTest.h"
//-------------------------------------------
// ---> DO NOT MODIFY <---
//-------------------------------------------
extern PerformanceTimer tACol;
Vect4D colMajor_test()
{
Matrix Rx(Vect4D(1.000000f, 0.000000f, 0.000000f, 0.000000f),
Vect4D(0.000000f, -0.500000f, 0.866025f, 0.000000f),
Vect4D(0.000000f, -0.866025f, -0.500000f, 0.000000f),
Vect4D(0.000000f, 0.000000f, 0.000000f, 1.000000f));
Matrix Ry(Vect4D(0.707107f, 0.000000f, -0.707107f, 0.000000f),
Vect4D(0.000000f, 1.000000f, 0.000000f, 0.000000f),
Vect4D(0.707107f, 0.000000f, 0.707107f, 0.000000f),
Vect4D(0.000000f, 0.000000f, 0.000000f, 1.000000f));
Matrix Rz(Vect4D(0.500000f, -0.866025f, 0.000000f, 0.000000f),
Vect4D(0.866025f, 0.500000f, 0.000000f, 0.000000f),
Vect4D(0.000000f, 0.000000f, 1.000000f, 0.000000f),
Vect4D(0.000000f, 0.000000f, 0.000000f, 1.000000f));
Matrix T(Vect4D(1.000000f, 0.000000f, 0.000000f, 0.000000f),
Vect4D(0.000000f, 1.000000f, 0.000000f, 0.000000f),
Vect4D(0.000000f, 0.000000f, 1.000000f, 0.000000f),
Vect4D(4.000000f, 5.000000f, 6.000000f, 1.000000f));
Matrix S(Vect4D(1.000000f, 0.000000f, 0.000000f, 0.200000f),
Vect4D(0.000000f, 2.000000f, 0.000000f, 0.300000f),
Vect4D(0.000000f, 0.000000f, 0.500000f, 0.500000f),
Vect4D(0.000000f, 0.000000f, 0.000000f, 0.130000f));
Vect4D v(0.500000f, 0.600000f, 0.700000f, 0.900000f);
Vect4D vOut;
tACol.Tic();
for (int i = 0; i < COL_MAJOR_COUNT; i++)
{
vOut = S * Rx *Ry * Rz * T * v;
}
tACol.Toc();
return vOut;
}
// --- End of File ---------------
| [
"brianabauman@yahoo.com"
] | brianabauman@yahoo.com |
d28b1bbb2bfa237506e5cc9e79d604b0217d6a57 | bec4ce7862948e5057b9573dd82a4aa0733ff485 | /src/ch6/features/default2/fac.cc | ba372d3c94c74aecd8ff6b2f52f31cd8b25f648b | [
"MIT"
] | permissive | HerculesShek/cpp-practise | 27b850a9c446a6571a95629cb6045e18957e6071 | aa0cdc3101c831c1c677f0de46a2f85a4b407bc3 | refs/heads/master | 2016-09-06T13:05:04.184703 | 2014-09-23T01:41:38 | 2014-09-23T01:41:38 | 17,898,200 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cc | #include "fac.h"
#include <iostream>
using std::cout;
using std::endl;
int a = 44;
const double pi = 3.1415926;
void foo(int i, double d, int b)
{
cout << i << " " << d << " " << b << endl;
}
| [
"hercules.shek@gmail.com"
] | hercules.shek@gmail.com |
6cf99050ee3bca907d5b075e8448b175eece9e39 | 74627fe21cde81dcecaa7aa692347bb51e77f130 | /src/rostools/include/geometry_msgs/Point.h | bffbdef869ddceafb88367eb626796f280bcee9d | [] | no_license | AFEICHINA/EasyRosBag | b6b8b6b48444239c24954674bfdfc01f6bb09be7 | 04708f0c1d177c9fc6e71c273935877555331557 | refs/heads/main | 2023-07-30T09:20:45.935318 | 2021-10-08T11:10:14 | 2021-10-08T11:10:14 | 414,954,873 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,928 | h | // Generated by gencpp from file geometry_msgs/Point.msg
// DO NOT EDIT!
#ifndef GEOMETRY_MSGS_MESSAGE_POINT_H
#define GEOMETRY_MSGS_MESSAGE_POINT_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace geometry_msgs
{
template <class ContainerAllocator>
struct Point_
{
typedef Point_<ContainerAllocator> Type;
Point_()
: x(0.0)
, y(0.0)
, z(0.0) {
}
Point_(const ContainerAllocator& _alloc)
: x(0.0)
, y(0.0)
, z(0.0) {
(void)_alloc;
}
typedef double _x_type;
_x_type x;
typedef double _y_type;
_y_type y;
typedef double _z_type;
_z_type z;
typedef boost::shared_ptr< ::geometry_msgs::Point_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::geometry_msgs::Point_<ContainerAllocator> const> ConstPtr;
}; // struct Point_
typedef ::geometry_msgs::Point_<std::allocator<void> > Point;
typedef boost::shared_ptr< ::geometry_msgs::Point > PointPtr;
typedef boost::shared_ptr< ::geometry_msgs::Point const> PointConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::geometry_msgs::Point_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::geometry_msgs::Point_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::geometry_msgs::Point_<ContainerAllocator1> & lhs, const ::geometry_msgs::Point_<ContainerAllocator2> & rhs)
{
return lhs.x == rhs.x &&
lhs.y == rhs.y &&
lhs.z == rhs.z;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::geometry_msgs::Point_<ContainerAllocator1> & lhs, const ::geometry_msgs::Point_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace geometry_msgs
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsFixedSize< ::geometry_msgs::Point_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::geometry_msgs::Point_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::geometry_msgs::Point_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::geometry_msgs::Point_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::geometry_msgs::Point_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::geometry_msgs::Point_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::geometry_msgs::Point_<ContainerAllocator> >
{
static const char* value()
{
return "4a842b65f413084dc2b10fb484ea7f17";
}
static const char* value(const ::geometry_msgs::Point_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x4a842b65f413084dULL;
static const uint64_t static_value2 = 0xc2b10fb484ea7f17ULL;
};
template<class ContainerAllocator>
struct DataType< ::geometry_msgs::Point_<ContainerAllocator> >
{
static const char* value()
{
return "geometry_msgs/Point";
}
static const char* value(const ::geometry_msgs::Point_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::geometry_msgs::Point_<ContainerAllocator> >
{
static const char* value()
{
return "# This contains the position of a point in free space\n"
"float64 x\n"
"float64 y\n"
"float64 z\n"
;
}
static const char* value(const ::geometry_msgs::Point_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::geometry_msgs::Point_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.x);
stream.next(m.y);
stream.next(m.z);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Point_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::geometry_msgs::Point_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::geometry_msgs::Point_<ContainerAllocator>& v)
{
s << indent << "x: ";
Printer<double>::stream(s, indent + " ", v.x);
s << indent << "y: ";
Printer<double>::stream(s, indent + " ", v.y);
s << indent << "z: ";
Printer<double>::stream(s, indent + " ", v.z);
}
};
} // namespace message_operations
} // namespace ros
#endif // GEOMETRY_MSGS_MESSAGE_POINT_H
| [
"80672451@qq.com"
] | 80672451@qq.com |
ee6ad36479f9627bd3e7e911b1c9366e661b3a71 | 198f071c0f3db78fc2b2209a2ab7da65f8f3b66e | /BOJ Originals/[BOJ Steps] BOJ 단계별로 풀어보기/[36] 최소 신장 트리/09372 상근이의 여행.cpp | cd95e26de92734ae258e1d912e007202ef997e45 | [] | no_license | gratus907/Gratus_PS | a33924836f67c14c3b1f8d4eecdfea73cd5cb98f | 7efdc7f37f268dccd2f8a0ec562aa7a4a67adf15 | refs/heads/master | 2023-07-27T03:43:17.731930 | 2021-08-31T17:26:54 | 2021-08-31T17:26:54 | 235,131,504 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,659 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) ((x).begin()),((x).end())
#define usecppio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define V 1050
struct edge
{
int s, e, w;
};
struct Disjoint_Set_Union
{
int parent[V], size[V];
Disjoint_Set_Union(int N = V-1)
{
init(N);
}
void init(int N)
{
for(int i=1;i<=N;i++)
{
parent[i]=i;
size[i]=1;
}
}
int Find(int K)
{
while(K!=parent[K])
{
parent[K]=parent[parent[K]];
K=parent[K];
}
return K;
}
int getSize(int K)
{
return size[Find(K)];
}
void unite(int x, int y)
{
int u=Find(x), v=Find(y);
if(u==v)
return;
if(size[u]>size[v])
swap(u, v);
size[v]+=size[u];
size[u] = 0;
parent[u] = parent[v];
}
} dsu;
vector <edge> edgelist;
int Kruskal()
{
int mstlen = 0;
sort(edgelist.begin(),edgelist.end(),[](auto &a, auto &b){ return a.w < b.w; });
for (auto it:edgelist)
{
if (dsu.Find(it.s)==dsu.Find(it.e)) // Cycle Detection
continue;
else
{
dsu.unite(it.s,it.e);
mstlen += it.w;
}
}
return mstlen;
}
int32_t main()
{
int T; cin >> T;
while(T--)
{
dsu.init(1010);
edgelist.clear();
int n, m; cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b; cin >> a >> b;
edgelist.push_back({a, b, 1});
}
cout << Kruskal() << '\n';
}
} | [
"gratus907@naver.com"
] | gratus907@naver.com |
2b5fb1e60b0f14cb111c63219ae579acce30fe25 | 0990f8898c00077ff97b41a147a1cae8f32a380a | /src/masternode-helpers.h | e975ba43a363a0ec4361655c2e395f6268632b6a | [
"MIT"
] | permissive | TheUCoin/theucoin | 12ddf35d29cd89e1b34afa4ca974383d85334967 | 886ed0cff8758e6e625ade8d52597d4cb03ec73a | refs/heads/master | 2020-06-14T10:26:15.640967 | 2019-07-03T04:53:01 | 2019-07-03T04:53:01 | 194,981,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | h | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2019 The TheUCoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODEHELPERS_H
#define MASTERNODEHELPERS_H
#include "main.h"
#include "sync.h"
#include "base58.h"
/** Helper object for signing and checking signatures
*/
class CMasternodeSigner
{
public:
CScript collateralPubKey;
/// Is the inputs associated with this public key? (and there is TUC collateral - checking if valid masternode)
bool IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey);
/// Set the private/public key values, returns true if successful
bool GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet);
/// Set the private/public key values, returns true if successful
bool SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey);
/// Sign the message, returns true if successful
bool SignMessage(std::string strMessage, std::string& errorMessage, std::vector<unsigned char>& vchSig, CKey key);
/// Verify the message, returns true if succcessful
bool VerifyMessage(CPubKey pubkey, std::vector<unsigned char>& vchSig, std::string strMessage, std::string& errorMessage);
bool SetCollateralAddress(std::string strAddress);
void InitCollateralAddress()
{
SetCollateralAddress(Params().MasternodePoolDummyAddress());
}
};
void ThreadMasternodePool();
extern CMasternodeSigner masternodeSigner;
#endif
| [
"vric.team@gmail.com"
] | vric.team@gmail.com |
defa40e59e172834a73f74419ec7ff71e629d547 | 9824d607fab0a0a827abff255865f320e2a7a692 | /界面资源/[XTreme.Toolkit.9.6.MFC].Xtreme.Toolkit.Pro.v9.60/Samples/Common/TabbedView/ResourceTreeView.cpp | 5630f7f0a048beda0243a010024a3d65ea3d77ec | [] | no_license | tuian/pcshare | 013b24af954b671aaf98604d6ab330def675a561 | 5d6455226d9720d65cfce841f8d00ef9eb09a5b8 | refs/heads/master | 2021-01-23T19:16:44.227266 | 2014-09-18T02:31:05 | 2014-09-18T02:31:05 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,761 | cpp | // ResourceTreeView.cpp : implementation file
//
// This file is a part of the XTREME TOOLKIT PRO MFC class library.
// ©1998-2005 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "TabbedView.h"
#include "ResourceTreeView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CResourceTreeView
IMPLEMENT_DYNCREATE(CResourceTreeView, CTreeView)
CResourceTreeView::CResourceTreeView()
{
}
CResourceTreeView::~CResourceTreeView()
{
}
BEGIN_MESSAGE_MAP(CResourceTreeView, CTreeView)
//{{AFX_MSG_MAP(CResourceTreeView)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CResourceTreeView drawing
void CResourceTreeView::OnDraw(CDC*)
{
}
/////////////////////////////////////////////////////////////////////////////
// CResourceTreeView diagnostics
#ifdef _DEBUG
void CResourceTreeView::AssertValid() const
{
CTreeView::AssertValid();
}
void CResourceTreeView::Dump(CDumpContext& dc) const
{
CTreeView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CResourceTreeView message handlers
BOOL CResourceTreeView::PreCreateWindow(CREATESTRUCT& cs)
{
cs.style |= TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS;
return CTreeView::PreCreateWindow(cs);
}
int CResourceTreeView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CTreeView::OnCreate(lpCreateStruct) == -1)
return -1;
// load the tree images bitmap and add it to the image list.
if (!CreateImageList(m_ilResourceView, IDB_RESTREE))
return 0;
// Set the image list for the tree control.
GetTreeCtrl().SetImageList( &m_ilResourceView, TVSIL_NORMAL );
// add the parent item
HTREEITEM htItem = GetTreeCtrl().InsertItem(_T("XtremeDemo resources"), 0, 1);
GetTreeCtrl().SetItemState(htItem, TVIS_BOLD, TVIS_BOLD);
HTREEITEM hti = GetTreeCtrl().InsertItem(_T("Accelerator"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("IDR_MAINFRAME"), 2, 2, hti);
GetTreeCtrl().Expand(hti, TVE_EXPAND);
hti = GetTreeCtrl().InsertItem(_T("Dialog"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("IDD_ABOUTBOX"), 3, 3, hti);
GetTreeCtrl().Expand(hti, TVE_EXPAND);
hti = GetTreeCtrl().InsertItem(_T("Icon"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("IDR_MAINFRAME"), 4, 4, hti);
GetTreeCtrl().InsertItem(_T("IDR_XTREMETYPE"), 4, 4, hti);
GetTreeCtrl().Expand(hti, TVE_EXPAND);
hti = GetTreeCtrl().InsertItem(_T("Menu"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("IDR_MAINFRAME"), 5, 5, hti);
GetTreeCtrl().InsertItem(_T("IDR_XTREMETYPE"), 5, 5, hti);
hti = GetTreeCtrl().InsertItem(_T("String Table"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("String Table"), 6, 6, hti);
hti = GetTreeCtrl().InsertItem(_T("Toolbar"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("IDR_MAINFRAME"), 7, 7, hti);
hti = GetTreeCtrl().InsertItem(_T("Version"), 0, 1, htItem);
GetTreeCtrl().InsertItem(_T("VS_VERSION_INFO"), 8, 8, hti);
GetTreeCtrl().Expand (htItem, TVE_EXPAND);
return 0;
}
| [
"sincoder@vip.qq.com"
] | sincoder@vip.qq.com |
cd75ed2b8fb17b6a11974b67b3a90596b69ac8c6 | 339e62bdc9d6d85a74d0053a220faf16335a3682 | /Programarea3D/lab1bcb/HeartConeTexture1.h | 2718fa36a466524f14494a603aaefe50bb8ab42e | [] | no_license | armagedescu/MasteratTehnologiiInformationale | 6304546cfe2e958513766dddf9f4e0153219a730 | 08b54d855d91391eaa93b711dbced6cf3a4b512f | refs/heads/master | 2022-05-08T00:10:52.433602 | 2022-04-02T18:06:55 | 2022-04-02T18:06:55 | 68,286,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | h | #pragma once
#ifndef __HEART_CONE_TEXTURE_1_H___
#define __HEART_CONE_TEXTURE_1_H___
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "constante.h"
#include "MemoryHelpers.h"
class HeartConeTexture1
{
protected:
int nh;
int ns;
MultiArray<double, 3> points;
static const int mx = 1024;
static const int ny = 1024;
unsigned char p[mx][ny][3];
GLuint tex_phobos;
GLuint tex_generated;
void draw(GLuint texture);
//MultiArray<double, 2> norms;
public:
HeartConeTexture1(int, int);
void calculate();
void draw();
void drawInverse();
};
#endif | [
"armagedescu@gmail.com"
] | armagedescu@gmail.com |
0f6578d7c96cee9beb1c0983ade02f7ea4944f84 | 666e2ff7aa1a4bcf3592331062ce774373fe6fa6 | /crypto/tls_socket.cpp | 3a14b2770c707faecc9b7f319506f942f53d82de | [] | no_license | asyr625/mini_sip | aeffd6e5ea1dafafa817b1137859b41351fe9580 | 12ea4b9a03585b5c7e5b5faeeed0a5bc6a9c19cc | refs/heads/master | 2021-01-20T12:06:33.212419 | 2015-11-24T02:33:26 | 2015-11-24T02:33:26 | 46,761,914 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 54 | cpp | #include "tls_socket.h"
Tls_Socket::Tls_Socket()
{
}
| [
"619695356@qq.com"
] | 619695356@qq.com |
0c85f03093fbcbe06db375352a6a1ea3d766503b | 6e71fe93ba10f8c4a03912ec26383bc1dde93518 | /ex-4/ListaImplementacao.hpp | 1934345944edc20997ce6036060855b898bfb225 | [] | no_license | LucasEBSkora/exercicios-monitoria-tec-prog | 74540bf187a66c58b49ca336ff5c8ffdd21fe0d0 | 5c0c51dc5f52a6edf3095536b23452a0722802f5 | refs/heads/master | 2021-02-14T05:01:12.490995 | 2020-07-08T20:22:33 | 2020-07-08T20:22:33 | 244,771,753 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,299 | hpp | namespace exercicio {
template <typename TF>
template <typename TE>
Lista<TF>::ElementoLista<TE>::ElementoLista(TE Info, ElementoLista<TE>* Ant, ElementoLista<TE>* Prox) :
info{Info}, ant{Ant}, prox{Prox} {
}
template <typename TF>
template <typename TE>
Lista<TF>::ElementoLista<TE>::~ElementoLista() {
}
template <typename TF>
template <typename TE>
TE Lista<TF>::ElementoLista<TE>::getInfo() {
return info;
}
template <typename TF>
template <typename TE>
void Lista<TF>::ElementoLista<TE>::setInfo(TE Info) {
info = Info;
}
template <typename TF>
template <typename TE>
Lista<TF>::ElementoLista<TE>* Lista<TF>::ElementoLista<TE>::getAnt() {
return ant;
}
template <typename TF>
template <typename TE>
void Lista<TF>::ElementoLista<TE>::setAnt(ElementoLista<TE>* Ant) {
ant = Ant;
}
template <typename TF>
template <typename TE>
Lista<TF>::ElementoLista<TE>* Lista<TF>::ElementoLista<TE>::getProx() {
return prox;
}
template <typename TF>
template <typename TE>
void Lista<TF>::ElementoLista<TE>::setProx(ElementoLista<TE>* Prox) {
prox = Prox;
}
template <typename TF>
Lista<TF>::Lista() :
inicio{nullptr}, fim{nullptr}, atual{nullptr} {
}
template <typename TF>
Lista<TF>::~Lista() {
esvaziar();
}
template <typename TF>
void Lista<TF>::inserir(TF info) {
if (info) { //info == NULL == 0 == false
ElementoLista<TF>* novo = new ElementoLista<TF>(info);
if (!inicio) {
inicio = novo;
fim = novo;
} else {
fim->setProx(novo);
novo->setAnt(fim);
fim = novo;
}
}
}
template <typename TF>
void Lista<TF>::esvaziar() {
ElementoLista<TF>* paux = inicio;
atual = inicio;
while (atual != nullptr) {
paux = atual->getProx();
delete atual;
atual = paux;
}
inicio = nullptr;
fim = nullptr;
atual = nullptr;
}
template <typename TF>
TF Lista<TF>::voltarInicio() {
atual = inicio;
if (atual) return atual->getInfo();
else return nullptr;
}
template <typename TF>
TF Lista<TF>::irProximo() {
atual = atual->getProx();
return (atual) ? atual->getInfo() : nullptr;
}
} | [
"skora.lucas@gmail.com"
] | skora.lucas@gmail.com |
4589dcb6c1716cf94fe0eb1834465e5904e99358 | de9ccefbcf5e9010db4a5e1961a0e7b4419a7889 | /server/cmdProcess.h | d02366ca6851abda3c4c9a02a0306a486009f4a3 | [] | no_license | shengpub/MyCacheDb | b1d7e0a4ed13fae7806a949c1ad3edd4e70ee91d | d4f371510117b0ab9c4874696b9f4e52391ab41a | refs/heads/master | 2020-12-27T19:15:10.142892 | 2020-02-03T15:04:34 | 2020-02-03T15:04:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | h | #pragma once
#include <iostream>
#include <map>
#include <memory>
#include <vector>
#include <string>
#include "timeManagerFactory.h"
#include "timerHeap.h"
#include "aeEvent.h"
#include "buffer.h"
#include "backInfo.h"
#include "redisDb.h"
#include "cmdSet.h"
#include "serializeParse.h"
#include "readWrite.h"
#include "rpc.h"
#include "msg.pb.h"
#include "aofRecord.h"
#define SIZE 4096
using namespace Messages ;
using namespace std ;
class timeManagerFactory ;
class rpc ;
class cmdSet ;
class redisCommand ;
class cmdSet ;
class backInfo ;
class listWaitQueue ;
class aeEvent ;
class listWaitQueue ;
class TimerManager ;
class MyTimer ;
class aofRecord ;
//错误类型
enum {
NOT_FOUND = 1,
FOUND_ = 2,
KEY_INVALID = 3,
SUCESS_ = 4,
PROCESS_ERROR = -1
} ;
//处理消息请求的函数
class cmdProcess {
typedef function<void(shared_ptr<Response>res, int fd)> request ;
typedef function<void(void)> task ;
public :
//创建
//消息处理
cmdProcess() {
cmdSet_ = make_shared<cmdSet>() ;
//获取命令表
rc = make_shared<rpc>() ;
}
~cmdProcess() {}
public :
void initCmdCb() ;
//时间事件回调
void timeCb() ;
public :
int initRedis() ;
void setRpc(shared_ptr<rpc>rc) { this->rc = rc ; }
void setRpcMethod() ;
int processMsg(shared_ptr<aeEvent>&tmp) ;
int sendMsg(shared_ptr<aeEvent>tmp) ;
void getAfterKeyPart() ;
int findCmd(shared_ptr<::Command>tmp) ;
private :
//命令集
//键值以后的部分成员
shared_ptr<cmdSet> cmdSet_ ;
vector<string> lastKey ;
task timeCall ;
//rpc,主要进行序列化和反序列化
shared_ptr<rpc> rc ;
};
| [
"1433882609@qq.com"
] | 1433882609@qq.com |
789a6bd05cdc82d71d57400802398845ee81c7fc | 90047daeb462598a924d76ddf4288e832e86417c | /cc/layers/picture_layer_impl_perftest.cc | a434297fbc9d6fce7f705d5cda81e68df7fa3aaf | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 10,022 | cc | // 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 "cc/layers/picture_layer_impl.h"
#include "base/macros.h"
#include "base/threading/thread_task_runner_handle.h"
#include "cc/base/lap_timer.h"
#include "cc/test/fake_compositor_frame_sink.h"
#include "cc/test/fake_impl_task_runner_provider.h"
#include "cc/test/fake_layer_tree_host_impl.h"
#include "cc/test/fake_picture_layer_impl.h"
#include "cc/test/fake_raster_source.h"
#include "cc/test/test_task_graph_runner.h"
#include "cc/tiles/tiling_set_raster_queue_all.h"
#include "cc/trees/layer_tree_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_test.h"
namespace cc {
namespace {
static const int kTimeLimitMillis = 2000;
static const int kWarmupRuns = 5;
static const int kTimeCheckInterval = 10;
void AddTiling(float scale,
FakePictureLayerImpl* layer,
std::vector<Tile*>* all_tiles) {
PictureLayerTiling* tiling = layer->AddTiling(scale);
tiling->set_resolution(HIGH_RESOLUTION);
tiling->CreateAllTilesForTesting();
std::vector<Tile*> tiling_tiles = tiling->AllTilesForTesting();
std::copy(
tiling_tiles.begin(), tiling_tiles.end(), std::back_inserter(*all_tiles));
}
class PictureLayerImplPerfTest : public testing::Test {
public:
PictureLayerImplPerfTest()
: task_runner_provider_(base::ThreadTaskRunnerHandle::Get()),
compositor_frame_sink_(FakeCompositorFrameSink::Create3d()),
host_impl_(LayerTreeSettings(),
&task_runner_provider_,
&task_graph_runner_),
timer_(kWarmupRuns,
base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
kTimeCheckInterval) {}
void SetUp() override {
host_impl_.SetVisible(true);
host_impl_.InitializeRenderer(compositor_frame_sink_.get());
}
void SetupPendingTree(const gfx::Size& layer_bounds) {
scoped_refptr<FakeRasterSource> raster_source =
FakeRasterSource::CreateFilled(layer_bounds);
host_impl_.CreatePendingTree();
LayerTreeImpl* pending_tree = host_impl_.pending_tree();
pending_tree->DetachLayers();
std::unique_ptr<FakePictureLayerImpl> pending_layer =
FakePictureLayerImpl::CreateWithRasterSource(pending_tree, 7,
raster_source);
pending_layer->SetDrawsContent(true);
pending_layer->test_properties()->force_render_surface = true;
pending_tree->SetRootLayerForTesting(std::move(pending_layer));
pending_tree->BuildLayerListAndPropertyTreesForTesting();
pending_layer_ = static_cast<FakePictureLayerImpl*>(
host_impl_.pending_tree()->LayerById(7));
}
void RunRasterQueueConstructAndIterateTest(const std::string& test_name,
int num_tiles,
const gfx::Size& viewport_size) {
host_impl_.SetViewportSize(viewport_size);
bool update_lcd_text = false;
host_impl_.pending_tree()->UpdateDrawProperties(update_lcd_text);
timer_.Reset();
do {
int count = num_tiles;
std::unique_ptr<TilingSetRasterQueueAll> queue(
new TilingSetRasterQueueAll(
pending_layer_->picture_layer_tiling_set(), false));
while (count--) {
ASSERT_TRUE(!queue->IsEmpty()) << "count: " << count;
ASSERT_TRUE(queue->Top().tile()) << "count: " << count;
queue->Pop();
}
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
perf_test::PrintResult("tiling_set_raster_queue_construct_and_iterate", "",
test_name, timer_.LapsPerSecond(), "runs/s", true);
}
void RunRasterQueueConstructTest(const std::string& test_name,
const gfx::Rect& viewport) {
host_impl_.SetViewportSize(viewport.size());
host_impl_.pending_tree()
->property_trees()
->scroll_tree.UpdateScrollOffsetBaseForTesting(
pending_layer_->id(),
gfx::ScrollOffset(viewport.x(), viewport.y()));
bool update_lcd_text = false;
host_impl_.pending_tree()->UpdateDrawProperties(update_lcd_text);
timer_.Reset();
do {
std::unique_ptr<TilingSetRasterQueueAll> queue(
new TilingSetRasterQueueAll(
pending_layer_->picture_layer_tiling_set(), false));
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
perf_test::PrintResult("tiling_set_raster_queue_construct", "", test_name,
timer_.LapsPerSecond(), "runs/s", true);
}
void RunEvictionQueueConstructAndIterateTest(
const std::string& test_name,
int num_tiles,
const gfx::Size& viewport_size) {
host_impl_.SetViewportSize(viewport_size);
bool update_lcd_text = false;
host_impl_.pending_tree()->UpdateDrawProperties(update_lcd_text);
timer_.Reset();
do {
int count = num_tiles;
std::unique_ptr<TilingSetEvictionQueue> queue(new TilingSetEvictionQueue(
pending_layer_->picture_layer_tiling_set()));
while (count--) {
ASSERT_TRUE(!queue->IsEmpty()) << "count: " << count;
ASSERT_TRUE(queue->Top().tile()) << "count: " << count;
queue->Pop();
}
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
perf_test::PrintResult("tiling_set_eviction_queue_construct_and_iterate",
"", test_name, timer_.LapsPerSecond(), "runs/s",
true);
}
void RunEvictionQueueConstructTest(const std::string& test_name,
const gfx::Rect& viewport) {
host_impl_.SetViewportSize(viewport.size());
host_impl_.pending_tree()
->property_trees()
->scroll_tree.UpdateScrollOffsetBaseForTesting(
pending_layer_->id(),
gfx::ScrollOffset(viewport.x(), viewport.y()));
bool update_lcd_text = false;
host_impl_.pending_tree()->UpdateDrawProperties(update_lcd_text);
timer_.Reset();
do {
std::unique_ptr<TilingSetEvictionQueue> queue(new TilingSetEvictionQueue(
pending_layer_->picture_layer_tiling_set()));
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
perf_test::PrintResult("tiling_set_eviction_queue_construct", "", test_name,
timer_.LapsPerSecond(), "runs/s", true);
}
protected:
TestTaskGraphRunner task_graph_runner_;
FakeImplTaskRunnerProvider task_runner_provider_;
std::unique_ptr<CompositorFrameSink> compositor_frame_sink_;
FakeLayerTreeHostImpl host_impl_;
FakePictureLayerImpl* pending_layer_;
LapTimer timer_;
private:
DISALLOW_COPY_AND_ASSIGN(PictureLayerImplPerfTest);
};
TEST_F(PictureLayerImplPerfTest, TilingSetRasterQueueConstructAndIterate) {
SetupPendingTree(gfx::Size(10000, 10000));
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
pending_layer_->AddTiling(low_res_factor);
pending_layer_->AddTiling(0.3f);
pending_layer_->AddTiling(0.7f);
pending_layer_->AddTiling(1.0f);
pending_layer_->AddTiling(2.0f);
RunRasterQueueConstructAndIterateTest("32_100x100", 32, gfx::Size(100, 100));
RunRasterQueueConstructAndIterateTest("32_500x500", 32, gfx::Size(500, 500));
RunRasterQueueConstructAndIterateTest("64_100x100", 64, gfx::Size(100, 100));
RunRasterQueueConstructAndIterateTest("64_500x500", 64, gfx::Size(500, 500));
}
TEST_F(PictureLayerImplPerfTest, TilingSetRasterQueueConstruct) {
SetupPendingTree(gfx::Size(10000, 10000));
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
pending_layer_->AddTiling(low_res_factor);
pending_layer_->AddTiling(0.3f);
pending_layer_->AddTiling(0.7f);
pending_layer_->AddTiling(1.0f);
pending_layer_->AddTiling(2.0f);
RunRasterQueueConstructTest("0_0_100x100", gfx::Rect(0, 0, 100, 100));
RunRasterQueueConstructTest("5000_0_100x100", gfx::Rect(5000, 0, 100, 100));
RunRasterQueueConstructTest("9999_0_100x100", gfx::Rect(9999, 0, 100, 100));
}
TEST_F(PictureLayerImplPerfTest, TilingSetEvictionQueueConstructAndIterate) {
SetupPendingTree(gfx::Size(10000, 10000));
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
std::vector<Tile*> all_tiles;
AddTiling(low_res_factor, pending_layer_, &all_tiles);
AddTiling(0.3f, pending_layer_, &all_tiles);
AddTiling(0.7f, pending_layer_, &all_tiles);
AddTiling(1.0f, pending_layer_, &all_tiles);
AddTiling(2.0f, pending_layer_, &all_tiles);
ASSERT_TRUE(host_impl_.tile_manager() != nullptr);
host_impl_.tile_manager()->InitializeTilesWithResourcesForTesting(all_tiles);
RunEvictionQueueConstructAndIterateTest(
"32_100x100", 32, gfx::Size(100, 100));
RunEvictionQueueConstructAndIterateTest(
"32_500x500", 32, gfx::Size(500, 500));
RunEvictionQueueConstructAndIterateTest(
"64_100x100", 64, gfx::Size(100, 100));
RunEvictionQueueConstructAndIterateTest(
"64_500x500", 64, gfx::Size(500, 500));
}
TEST_F(PictureLayerImplPerfTest, TilingSetEvictionQueueConstruct) {
SetupPendingTree(gfx::Size(10000, 10000));
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
std::vector<Tile*> all_tiles;
AddTiling(low_res_factor, pending_layer_, &all_tiles);
AddTiling(0.3f, pending_layer_, &all_tiles);
AddTiling(0.7f, pending_layer_, &all_tiles);
AddTiling(1.0f, pending_layer_, &all_tiles);
AddTiling(2.0f, pending_layer_, &all_tiles);
ASSERT_TRUE(host_impl_.tile_manager() != nullptr);
host_impl_.tile_manager()->InitializeTilesWithResourcesForTesting(all_tiles);
RunEvictionQueueConstructTest("0_0_100x100", gfx::Rect(0, 0, 100, 100));
RunEvictionQueueConstructTest("5000_0_100x100", gfx::Rect(5000, 0, 100, 100));
RunEvictionQueueConstructTest("9999_0_100x100", gfx::Rect(9999, 0, 100, 100));
}
} // namespace
} // namespace cc
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
dd40f33f93e889996966e454706dfa96185d1822 | a28685167ce3f9ea86288891667a1afe824b3b8e | /Coronet/src/Metrics.cpp | 4bcf92d03ad0edcfdad3d08169beffbafccc7275 | [] | no_license | aoki-marika/coronet | 237acefea8a1727623a7c3f6ce4006df2baaa877 | 8173e79b2495e6aadae8b4e6b10a7e137138dd3e | refs/heads/master | 2020-03-13T03:53:21.562729 | 2018-05-06T01:20:20 | 2018-05-06T01:20:20 | 130,952,597 | 0 | 0 | null | 2018-05-06T01:00:37 | 2018-04-25T04:54:59 | C++ | UTF-8 | C++ | false | false | 810 | cpp | #include "Metrics.hpp"
namespace Coronet
{
Metrics::Metrics(int tileWidth, int tileHeight, int blockTilesHorizontal, int blockTilesVertical, int screenTilesHorizontal, int screenTilesVertical)
{
tileSize = { tileWidth, tileHeight };
tileCount = { screenTilesHorizontal, screenTilesVertical };
blockSize = { tileWidth * blockTilesHorizontal, tileHeight * blockTilesVertical };
screenSize = { tileWidth * screenTilesHorizontal, tileHeight * screenTilesVertical };
}
Vector2 Metrics::GetTileSize()
{
return tileSize;
}
Vector2 Metrics::GetTileCount()
{
return tileCount;
}
Vector2 Metrics::GetBlockSize()
{
return blockSize;
}
Vector2 Metrics::GetScreenSize()
{
return screenSize;
}
} | [
"marika@waifu.club"
] | marika@waifu.club |
623f27e0445cbc816a995c05eb142a1594a3dd43 | c03fd7482030098d4d4afdaef536b8bad4c1ad5f | /1074.元素和为目标值的子矩阵数量/solution.cpp | 793e72710e7a9a130cc42813de2c10c593d94810 | [] | no_license | Zhenghao-Liu/LeetCode_problem-and-solution | 79c88766c341c7789b5b01efd997fd6384edd8c3 | 09e9c9be2fc1d8f900e1e07fb5298c7c59596262 | refs/heads/master | 2022-11-02T00:15:21.089949 | 2022-10-07T12:06:41 | 2022-10-07T12:06:41 | 216,760,405 | 54 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | cpp | class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
int row=matrix.size(),col=matrix.at(0).size();
int ans=0;
vector<vector<int>> sum(row+1,vector<int>(col+1));
for (int i=0;i<row;i++) {
for (int j=0;j<col;j++) {
sum.at(i+1).at(j+1)=
sum.at(i).at(j+1)+
sum.at(i+1).at(j)-
sum.at(i).at(j)+
matrix.at(i).at(j);
}
}
unordered_map<int,int> ump;
for (int up=0;up<row;up++) {
for (int down=up;down<row;down++) {
ump.clear();
ump[0]++;
for (int j=0;j<col;j++) {
//[up][0],[down][j]
int cur=
sum.at(down+1).at(j+1)-
sum.at(down+1).at(0)-
sum.at(up).at(j+1)+
sum.at(up).at(0);
auto p=ump.find(cur-target);
if (p!=ump.end()) {
ans+=p->second;
}
ump[cur]++;
}
}
}
return ans;
}
}; | [
"750307817@qq.com"
] | 750307817@qq.com |
1d541a8d79b53ba40965c6480b5a8f05afc595cd | 9f5eb206f30b38f65feaefadb8a14e0238771b5c | /AK8963_as_slave/MPU9250.cpp | 7447367afef915a87f919cc40b35abdffb432b96 | [] | no_license | SrayZoe/MPU9250 | bde066229b4529c9826c5caa8ce3c2ace797356e | ce11f85de7ab233784c49baabe002521d9d8600c | refs/heads/master | 2020-04-05T03:04:39.826948 | 2018-11-04T18:43:34 | 2018-11-04T18:43:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,477 | cpp | /* 06/16/2017 Copyright Tlera Corporation
*
* Created by Kris Winer
*
Demonstrate basic MPU-9250 functionality including parameterizing the register addresses, initializing the sensor,
getting properly scaled accelerometer, gyroscope, and magnetometer data out.
Addition of 9 DoF sensor fusion using open source Madgwick and Mahony filter algorithms.
Sketch runs on the 3.3 V Dragonfly STM32L476 Breakout Board.
Library may be used freely and without limit with attribution.
*/
#include "MPU9250.h"
#include "Wire.h"
MPU9250::MPU9250(uint8_t intPin)
{
_intPin = intPin;
}
uint8_t MPU9250::getMPU9250ID()
{
uint8_t c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250); // Read WHO_AM_I register for MPU-9250
return c;
}
uint8_t MPU9250::getAK8963CID()
{
// uint8_t c = readByte(AK8963_ADDRESS, WHO_AM_I_AK8963); // Read WHO_AM_I register for MPU-9250
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x20); // Enable I2C Master mode
writeByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x0D); // I2C configuration multi-master I2C 400KHz
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS | 0x80); // Set the I2C slave address of AK8963 and set for read.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, WHO_AM_I_AK8963); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and transfer 1 byte
delay(10);
uint8_t c = readByte(MPU9250_ADDRESS, EXT_SENS_DATA_00); // Read the WHO_AM_I byte
return c;
}
float MPU9250::getMres(uint8_t Mscale) {
switch (Mscale)
{
// Possible magnetometer scales (and their register bit settings) are:
// 14 bit resolution (0) and 16 bit resolution (1)
case MFS_14BITS:
_mRes = 10.*4912./8190.; // Proper scale to return milliGauss
return _mRes;
break;
case MFS_16BITS:
_mRes = 10.*4912./32760.0; // Proper scale to return milliGauss
return _mRes;
break;
}
}
float MPU9250::getGres(uint8_t Gscale) {
switch (Gscale)
{
// Possible gyro scales (and their register bit settings) are:
// 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11).
case GFS_250DPS:
_gRes = 250.0/32768.0;
return _gRes;
break;
case GFS_500DPS:
_gRes = 500.0/32768.0;
return _gRes;
break;
case GFS_1000DPS:
_gRes = 1000.0/32768.0;
return _gRes;
break;
case GFS_2000DPS:
_gRes = 2000.0/32768.0;
return _gRes;
break;
}
}
float MPU9250::getAres(uint8_t Ascale) {
switch (Ascale)
{
// Possible accelerometer scales (and their register bit settings) are:
// 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case AFS_2G:
_aRes = 2.0f/32768.0f;
return _aRes;
break;
case AFS_4G:
_aRes = 4.0f/32768.0f;
return _aRes;
break;
case AFS_8G:
_aRes = 8.0f/32768.0f;
return _aRes;
break;
case AFS_16G:
_aRes = 16.0f/32768.0f;
return _aRes;
break;
}
}
void MPU9250::accelWakeOnMotion()
{
// Set accelerometer sample rate configuration
// It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for
// accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz
uint8_t c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2); // get current ACCEL_CONFIG2 register value
c = c & ~0x0F; // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])
c = c | 0x01; // Set accelerometer rate to 1 kHz and bandwidth to 184 Hz
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c); // Write new ACCEL_CONFIG2 register value
// Configure Interrupts and Bypass Enable
// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared,
// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips
// can join the I2C bus and all can be controlled by the Arduino as master
writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x12); // INT is 50 microsecond pulse and any read to clear
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x41); // Enable data ready (bit 0) and wake on motion (bit 6) interrupt
// enable wake on motion detection logic (bit 7) and compare current sample to previous sample (bit 6)
writeByte(MPU9250_ADDRESS, MOT_DETECT_CTRL, 0xC0);
// set accel threshold for wake up at mG per LSB, 1 - 255 LSBs == 0 - 1020 mg), pic 0x19 for 25 mg
writeByte(MPU9250_ADDRESS, WOM_THR, 0x19);
// set sample rate in low power mode
/* choices are 0 == 0.24 Hz, 1 == 0.49 Hz, 2 == 0.98 Hz, 3 == 1.958 Hz, 4 == 3.91 Hz, 5 == 7.81 Hz
* 6 == 15.63 Hz, 7 == 31.25 Hz, 8 == 62.50 Hz, 9 = 125 Hz, 10 == 250 Hz, and 11 == 500 Hz
*/
writeByte(MPU9250_ADDRESS, LP_ACCEL_ODR, 0x02);
c = readByte(MPU9250_ADDRESS, PWR_MGMT_1);
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, c | 0x20); // Write bit 5 to enable accel cycling
gyromagSleep();
delay(100); // Wait for all registers to reset
}
void MPU9250::gyromagSleep()
{
uint8_t temp = 0;
temp = readByte(AK8963_ADDRESS, AK8963_CNTL);
writeByte(AK8963_ADDRESS, AK8963_CNTL, temp & ~(0x0F) ); // Clear bits 0 - 3 to power down magnetometer
temp = readByte(MPU9250_ADDRESS, PWR_MGMT_1);
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, temp | 0x10); // Write bit 4 to enable gyro standby
delay(10); // Wait for all registers to reset
}
void MPU9250::gyromagWake(uint8_t Mmode)
{
uint8_t temp = 0;
temp = readByte(AK8963_ADDRESS, AK8963_CNTL);
writeByte(AK8963_ADDRESS, AK8963_CNTL, temp | Mmode ); // Reset normal mode for magnetometer
temp = readByte(MPU9250_ADDRESS, PWR_MGMT_1);
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); // return gyro and accel normal mode
delay(10); // Wait for all registers to reset
}
void MPU9250::resetMPU9250()
{
// reset device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Set bit 7 to reset MPU9250
delay(100); // Wait for all registers to reset
}
void MPU9250::readMPU9250Data(int16_t * destination)
{
uint8_t rawData[14]; // x/y/z accel register data stored here
readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 14, &rawData[0]); // Read the 14 raw data registers into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
destination[3] = ((int16_t)rawData[6] << 8) | rawData[7] ;
destination[4] = ((int16_t)rawData[8] << 8) | rawData[9] ;
destination[5] = ((int16_t)rawData[10] << 8) | rawData[11] ;
destination[6] = ((int16_t)rawData[12] << 8) | rawData[13] ;
}
void MPU9250::readAccelData(int16_t * destination)
{
uint8_t rawData[6]; // x/y/z accel register data stored here
readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
}
void MPU9250::readGyroData(int16_t * destination)
{
uint8_t rawData[6]; // x/y/z gyro register data stored here
readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array
destination[0] = ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[2] << 8) | rawData[3] ;
destination[2] = ((int16_t)rawData[4] << 8) | rawData[5] ;
}
bool MPU9250::checkNewMagData()
{
bool test;
// test = (readByte(AK8963_ADDRESS, AK8963_ST1) & 0x01);
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS | 0x80); // Set the I2C slave address of AK8963 and set for read.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_ST1); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and transfer 1 byte
delay(2);
test = (readByte(MPU9250_ADDRESS, EXT_SENS_DATA_00) & 0x01); // Check data ready status byte
return test;
}
bool MPU9250::checkNewAccelGyroData()
{
bool test;
test = (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01);
return test;
}
bool MPU9250::checkWakeOnMotion()
{
bool test;
test = (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x40);
return test;
}
void MPU9250::readMagData(int16_t * destination)
{
uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition
// readBytes(AK8963_ADDRESS, AK8963_XOUT_L, 7, &rawData[0]); // Read the six raw data and ST2 registers sequentially into data array
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS | 0x80); // Set the I2C slave address of AK8963 and set for read.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_XOUT_L); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x87); // Enable I2C and read 7 bytes
delay(2);
readBytes(MPU9250_ADDRESS, EXT_SENS_DATA_00, 7, &rawData[0]); // Read the x-, y-, and z-axis calibration values
uint8_t c = rawData[6]; // End data read by reading ST2 register
if(!(c & 0x08)) { // Check if magnetic sensor overflow set, if not then report data
destination[0] = ((int16_t)rawData[1] << 8) | rawData[0] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rawData[3] << 8) | rawData[2] ; // Data stored as little Endian
destination[2] = ((int16_t)rawData[5] << 8) | rawData[4] ;
}
}
int16_t MPU9250::readGyroTempData()
{
uint8_t rawData[2]; // x/y/z gyro register data stored here
readBytes(MPU9250_ADDRESS, TEMP_OUT_H, 2, &rawData[0]); // Read the two raw data registers sequentially into data array
return ((int16_t)rawData[0] << 8) | rawData[1] ; // Turn the MSB and LSB into a 16-bit value
}
void MPU9250::initAK8963(uint8_t Mscale, uint8_t Mmode, float * magCalibration)
{
// First extract the factory calibration for each magnetometer axis
uint8_t rawData[3]; // x/y/z gyro calibration data stored here
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
delay(10);
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode
delay(10);
readBytes(AK8963_ADDRESS, AK8963_ASAX, 3, &rawData[0]); // Read the x-, y-, and z-axis calibration values
magCalibration[0] = (float)(rawData[0] - 128)/256.0f + 1.0f; // Return x-axis sensitivity adjustment values, etc.
magCalibration[1] = (float)(rawData[1] - 128)/256.0f + 1.0f;
magCalibration[2] = (float)(rawData[2] - 128)/256.0f + 1.0f;
_magCalibration[0] = magCalibration[0];
_magCalibration[1] = magCalibration[1];
_magCalibration[2] = magCalibration[2];
_Mmode = Mmode;
writeByte(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
delay(10);
// Configure the magnetometer for continuous read and highest resolution
// set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register,
// and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates
writeByte(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode); // Set magnetometer data resolution and sample ODR
delay(10);
}
void MPU9250::initAK8963Slave(uint8_t Mscale, uint8_t Mmode, float * magCalibration)
{
// First extract the factory calibration for each magnetometer axis
uint8_t rawData[3]; // x/y/z gyro calibration data stored here
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS); // Set the I2C slave address of AK8963 and set for write.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_CNTL2); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_DO, 0x01); // Reset AK8963
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and write 1 byte
delay(50);
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS); // Set the I2C slave address of AK8963 and set for write.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_CNTL); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_DO, 0x00); // Power down magnetometer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and write 1 byte
delay(50);
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS); // Set the I2C slave address of AK8963 and set for write.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_CNTL); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_DO, 0x0F); // Enter fuze mode
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and write 1 byte
delay(50);
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS | 0x80); // Set the I2C slave address of AK8963 and set for read.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_ASAX); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x83); // Enable I2C and read 3 bytes
delay(50);
readBytes(MPU9250_ADDRESS, EXT_SENS_DATA_00, 3, &rawData[0]); // Read the x-, y-, and z-axis calibration values
magCalibration[0] = (float)(rawData[0] - 128)/256.0f + 1.0f; // Return x-axis sensitivity adjustment values, etc.
magCalibration[1] = (float)(rawData[1] - 128)/256.0f + 1.0f;
magCalibration[2] = (float)(rawData[2] - 128)/256.0f + 1.0f;
_magCalibration[0] = magCalibration[0];
_magCalibration[1] = magCalibration[1];
_magCalibration[2] = magCalibration[2];
_Mmode = Mmode;
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS); // Set the I2C slave address of AK8963 and set for write.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_CNTL); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_DO, 0x00); // Power down magnetometer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and transfer 1 byte
delay(50);
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS); // Set the I2C slave address of AK8963 and set for write.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_CNTL); // I2C slave 0 register address from where to begin data transfer
// Configure the magnetometer for continuous read and highest resolution
// set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register,
// and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates
writeByte(MPU9250_ADDRESS, I2C_SLV0_DO, Mscale << 4 | Mmode); // Set magnetometer data resolution and sample ODR
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and transfer 1 byte
delay(50);
writeByte(MPU9250_ADDRESS, I2C_SLV0_ADDR, AK8963_ADDRESS | 0x80); // Set the I2C slave address of AK8963 and set for read.
writeByte(MPU9250_ADDRESS, I2C_SLV0_REG, AK8963_CNTL); // I2C slave 0 register address from where to begin data transfer
writeByte(MPU9250_ADDRESS, I2C_SLV0_CTRL, 0x81); // Enable I2C and transfer 1 byte
delay(50);
}
void MPU9250::initMPU9250(uint8_t Ascale, uint8_t Gscale, uint8_t sampleRate)
{
// wake up device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6), enable all sensors
delay(100); // Wait for all registers to reset
// get stable time source
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01); // Auto select clock source to be PLL gyroscope reference if ready else
delay(200);
// Configure Gyro and Thermometer
// Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively;
// minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot
// be higher than 1 / 0.0059 = 170 Hz
// DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both
// With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz
writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
// Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, sampleRate); // Use a 200 Hz rate; a rate consistent with the filter update rate
// determined inset in CONFIG above
// Set gyroscope full scale range
// Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3
uint8_t c = readByte(MPU9250_ADDRESS, GYRO_CONFIG); // get current GYRO_CONFIG register value
// c = c & ~0xE0; // Clear self-test bits [7:5]
c = c & ~0x02; // Clear Fchoice bits [1:0]
c = c & ~0x18; // Clear AFS bits [4:3]
c = c | Gscale << 3; // Set full scale range for the gyro
// c =| 0x00; // Set Fchoice for the gyro to 11 by writing its inverse to bits 1:0 of GYRO_CONFIG
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, c ); // Write new GYRO_CONFIG value to register
// Set accelerometer full-scale range configuration
c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG); // get current ACCEL_CONFIG register value
// c = c & ~0xE0; // Clear self-test bits [7:5]
c = c & ~0x18; // Clear AFS bits [4:3]
c = c | Ascale << 3; // Set full scale range for the accelerometer
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, c); // Write new ACCEL_CONFIG register value
// Set accelerometer sample rate configuration
// It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for
// accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz
c = readByte(MPU9250_ADDRESS, ACCEL_CONFIG2); // get current ACCEL_CONFIG2 register value
c = c & ~0x0F; // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])
c = c | 0x03; // Set accelerometer rate to 1 kHz and bandwidth to 41 Hz
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, c); // Write new ACCEL_CONFIG2 register value
// The accelerometer, gyro, and thermometer are set to 1 kHz sample rates,
// but all these rates are further reduced by a factor of 5 to 200 Hz because of the SMPLRT_DIV setting
// Configure Interrupts and Bypass Enable
// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared,
// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips
// can join the I2C bus and all can be controlled by the Arduino as master
writeByte(MPU9250_ADDRESS, INT_PIN_CFG, 0x10); // INT is 50 microsecond pulse and any read to clear
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0) interrupt
delay(100);
}
void MPU9250::magcalMPU9250(float * dest1, float * dest2)
{
uint16_t ii = 0, sample_count = 0;
int32_t mag_bias[3] = {0, 0, 0}, mag_scale[3] = {0, 0, 0};
int16_t mag_max[3] = {-32767, -32767, -32767}, mag_min[3] = {32767, 32767, 32767}, mag_temp[3] = {0, 0, 0};
Serial.println("Mag Calibration: Wave device in a figure eight until done!");
delay(4000);
// shoot for ~fifteen seconds of mag data
if(_Mmode == 0x02) sample_count = 128; // at 8 Hz ODR, new mag data is available every 125 ms
if(_Mmode == 0x06) sample_count = 1500; // at 100 Hz ODR, new mag data is available every 10 ms
for(ii = 0; ii < sample_count; ii++) {
readMagData(mag_temp); // Read the mag data
for (int jj = 0; jj < 3; jj++) {
if(mag_temp[jj] > mag_max[jj]) mag_max[jj] = mag_temp[jj];
if(mag_temp[jj] < mag_min[jj]) mag_min[jj] = mag_temp[jj];
}
if(_Mmode == 0x02) delay(135); // at 8 Hz ODR, new mag data is available every 125 ms
if(_Mmode == 0x06) delay(12); // at 100 Hz ODR, new mag data is available every 10 ms
}
// Serial.println("mag x min/max:"); Serial.println(mag_max[0]); Serial.println(mag_min[0]);
// Serial.println("mag y min/max:"); Serial.println(mag_max[1]); Serial.println(mag_min[1]);
// Serial.println("mag z min/max:"); Serial.println(mag_max[2]); Serial.println(mag_min[2]);
// Get hard iron correction
mag_bias[0] = (mag_max[0] + mag_min[0])/2; // get average x mag bias in counts
mag_bias[1] = (mag_max[1] + mag_min[1])/2; // get average y mag bias in counts
mag_bias[2] = (mag_max[2] + mag_min[2])/2; // get average z mag bias in counts
dest1[0] = (float) mag_bias[0]*_mRes*_magCalibration[0]; // save mag biases in G for main program
dest1[1] = (float) mag_bias[1]*_mRes*_magCalibration[1];
dest1[2] = (float) mag_bias[2]*_mRes*_magCalibration[2];
// Get soft iron correction estimate
mag_scale[0] = (mag_max[0] - mag_min[0])/2; // get average x axis max chord length in counts
mag_scale[1] = (mag_max[1] - mag_min[1])/2; // get average y axis max chord length in counts
mag_scale[2] = (mag_max[2] - mag_min[2])/2; // get average z axis max chord length in counts
float avg_rad = mag_scale[0] + mag_scale[1] + mag_scale[2];
avg_rad /= 3.0;
dest2[0] = avg_rad/((float)mag_scale[0]);
dest2[1] = avg_rad/((float)mag_scale[1]);
dest2[2] = avg_rad/((float)mag_scale[2]);
Serial.println("Mag Calibration done!");
}
// Function which accumulates gyro and accelerometer data after device initialization. It calculates the average
// of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.
void MPU9250::calibrateMPU9250(float * dest1, float * dest2)
{
uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data
uint16_t ii, packet_count, fifo_count;
int32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0};
// reset device
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device
delay(100);
// get stable time source; Auto select clock source to be PLL gyroscope reference if ready
// else use the internal oscillator, bits 2:0 = 001
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
writeByte(MPU9250_ADDRESS, PWR_MGMT_2, 0x00);
delay(200);
// Configure device for bias calculation
writeByte(MPU9250_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable FIFO
writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock source
writeByte(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master modes
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP
delay(15);
// Configure MPU6050 gyro and accelerometer for bias calculation
writeByte(MPU9250_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250 degrees per second, maximum sensitivity
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity
uint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec
uint16_t accelsensitivity = 16384; // = 16384 LSB/g
// Configure FIFO to capture accelerometer and gyro data for bias calculation
writeByte(MPU9250_ADDRESS, USER_CTRL, 0x40); // Enable FIFO
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer sensors for FIFO (max size 512 bytes in MPU-9150)
delay(40); // accumulate 40 samples in 40 milliseconds = 480 bytes
// At end of sample accumulation, turn off FIFO sensor read
writeByte(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable gyro and accelerometer sensors for FIFO
readBytes(MPU9250_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample count
fifo_count = ((uint16_t)data[0] << 8) | data[1];
packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging
for (ii = 0; ii < packet_count; ii++) {
int16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0};
readBytes(MPU9250_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for averaging
accel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1] ) ; // Form signed 16-bit integer for each sample in FIFO
accel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3] ) ;
accel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5] ) ;
gyro_temp[0] = (int16_t) (((int16_t)data[6] << 8) | data[7] ) ;
gyro_temp[1] = (int16_t) (((int16_t)data[8] << 8) | data[9] ) ;
gyro_temp[2] = (int16_t) (((int16_t)data[10] << 8) | data[11]) ;
accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases
accel_bias[1] += (int32_t) accel_temp[1];
accel_bias[2] += (int32_t) accel_temp[2];
gyro_bias[0] += (int32_t) gyro_temp[0];
gyro_bias[1] += (int32_t) gyro_temp[1];
gyro_bias[2] += (int32_t) gyro_temp[2];
}
accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases
accel_bias[1] /= (int32_t) packet_count;
accel_bias[2] /= (int32_t) packet_count;
gyro_bias[0] /= (int32_t) packet_count;
gyro_bias[1] /= (int32_t) packet_count;
gyro_bias[2] /= (int32_t) packet_count;
if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;} // Remove gravity from the z-axis accelerometer bias calculation
else {accel_bias[2] += (int32_t) accelsensitivity;}
// Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup
data[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input format
data[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign on calculated average gyro biases
data[2] = (-gyro_bias[1]/4 >> 8) & 0xFF;
data[3] = (-gyro_bias[1]/4) & 0xFF;
data[4] = (-gyro_bias[2]/4 >> 8) & 0xFF;
data[5] = (-gyro_bias[2]/4) & 0xFF;
// Push gyro biases to hardware registers
writeByte(MPU9250_ADDRESS, XG_OFFSET_H, data[0]);
writeByte(MPU9250_ADDRESS, XG_OFFSET_L, data[1]);
writeByte(MPU9250_ADDRESS, YG_OFFSET_H, data[2]);
writeByte(MPU9250_ADDRESS, YG_OFFSET_L, data[3]);
writeByte(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]);
writeByte(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]);
// Output scaled gyro biases for display in the main program
dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity;
dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;
dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;
// Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain
// factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold
// non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature
// compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that
// the accelerometer biases calculated above must be divided by 8.
int32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory accelerometer trim biases
readBytes(MPU9250_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory accelerometer trim values
accel_bias_reg[0] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
readBytes(MPU9250_ADDRESS, YA_OFFSET_H, 2, &data[0]);
accel_bias_reg[1] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
readBytes(MPU9250_ADDRESS, ZA_OFFSET_H, 2, &data[0]);
accel_bias_reg[2] = (int32_t) (((int16_t)data[0] << 8) | data[1]);
uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers
uint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each accelerometer bias axis
for(ii = 0; ii < 3; ii++) {
if((accel_bias_reg[ii] & mask)) mask_bit[ii] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit
}
// Construct total accelerometer bias, including calculated average accelerometer bias from above
accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
accel_bias_reg[1] -= (accel_bias[1]/8);
accel_bias_reg[2] -= (accel_bias[2]/8);
data[0] = (accel_bias_reg[0] >> 8) & 0xFF;
data[1] = (accel_bias_reg[0]) & 0xFF;
data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[2] = (accel_bias_reg[1] >> 8) & 0xFF;
data[3] = (accel_bias_reg[1]) & 0xFF;
data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[4] = (accel_bias_reg[2] >> 8) & 0xFF;
data[5] = (accel_bias_reg[2]) & 0xFF;
data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers
// Apparently this is not working for the acceleration biases in the MPU-9250
// Are we handling the temperature correction bit properly?
// Push accelerometer biases to hardware registers
// writeByte(MPU9250_ADDRESS, XA_OFFSET_H, data[0]);
// writeByte(MPU9250_ADDRESS, XA_OFFSET_L, data[1]);
// writeByte(MPU9250_ADDRESS, YA_OFFSET_H, data[2]);
// writeByte(MPU9250_ADDRESS, YA_OFFSET_L, data[3]);
// writeByte(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]);
// writeByte(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]);
// Output scaled accelerometer biases for display in the main program
dest2[0] = (float)accel_bias[0]/(float)accelsensitivity;
dest2[1] = (float)accel_bias[1]/(float)accelsensitivity;
dest2[2] = (float)accel_bias[2]/(float)accelsensitivity;
}
// Accelerometer and gyroscope self test; check calibration wrt factory settings
void MPU9250::SelfTest(float * destination) // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass
{
uint8_t rawData[6] = {0, 0, 0, 0, 0, 0};
uint8_t selfTest[6];
int32_t gAvg[3] = {0}, aAvg[3] = {0}, aSTAvg[3] = {0}, gSTAvg[3] = {0};
float factoryTrim[6];
uint8_t FS = 0;
writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set gyro sample rate to 1 kHz
writeByte(MPU9250_ADDRESS, CONFIG, 0x02); // Set gyro sample rate to 1 kHz and DLPF to 92 Hz
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 1<<FS); // Set full scale range for the gyro to 250 dps
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate to 1 kHz and bandwidth to 92 Hz
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 1<<FS); // Set full scale range for the accelerometer to 2 g
for( int ii = 0; ii < 200; ii++) { // get average current values of gyro and acclerometer
readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
aAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array
gAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}
for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average current readings
aAvg[ii] /= 200;
gAvg[ii] /= 200;
}
// Configure the accelerometer for self-test
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all three axes and set accelerometer range to +/- 2 g
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s
delay(25); // Delay a while to let the device stabilize
for( int ii = 0; ii < 200; ii++) { // get average self-test values of gyro and acclerometer
readBytes(MPU9250_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
aSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
readBytes(MPU9250_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array
gSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}
for (int ii =0; ii < 3; ii++) { // Get average of 200 values and store as average self-test readings
aSTAvg[ii] /= 200;
gSTAvg[ii] /= 200;
}
// Configure the gyro and accelerometer for normal operation
writeByte(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00);
writeByte(MPU9250_ADDRESS, GYRO_CONFIG, 0x00);
delay(25); // Delay a while to let the device stabilize
// Retrieve accelerometer and gyro factory Self-Test Code from USR_Reg
selfTest[0] = readByte(MPU9250_ADDRESS, SELF_TEST_X_ACCEL); // X-axis accel self-test results
selfTest[1] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL); // Y-axis accel self-test results
selfTest[2] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL); // Z-axis accel self-test results
selfTest[3] = readByte(MPU9250_ADDRESS, SELF_TEST_X_GYRO); // X-axis gyro self-test results
selfTest[4] = readByte(MPU9250_ADDRESS, SELF_TEST_Y_GYRO); // Y-axis gyro self-test results
selfTest[5] = readByte(MPU9250_ADDRESS, SELF_TEST_Z_GYRO); // Z-axis gyro self-test results
// Retrieve factory self-test value from self-test code reads
factoryTrim[0] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[0] - 1.0) )); // FT[Xa] factory trim calculation
factoryTrim[1] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[1] - 1.0) )); // FT[Ya] factory trim calculation
factoryTrim[2] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[2] - 1.0) )); // FT[Za] factory trim calculation
factoryTrim[3] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[3] - 1.0) )); // FT[Xg] factory trim calculation
factoryTrim[4] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[4] - 1.0) )); // FT[Yg] factory trim calculation
factoryTrim[5] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[5] - 1.0) )); // FT[Zg] factory trim calculation
// Report results as a ratio of (STR - FT)/FT; the change from Factory Trim of the Self-Test Response
// To get percent, must multiply by 100
for (int i = 0; i < 3; i++) {
destination[i] = 100.0f*((float)(aSTAvg[i] - aAvg[i]))/factoryTrim[i] - 100.0f; // Report percent differences
destination[i+3] = 100.0f*((float)(gSTAvg[i] - gAvg[i]))/factoryTrim[i+3] - 100.0f; // Report percent differences
}
}
// simple function to scan for I2C devices on the bus
void MPU9250::I2Cscan()
{
// scan for i2c devices
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
}
// I2C read/write functions for the MPU9250 sensors
void MPU9250::writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
Wire.beginTransmission(address); // Initialize the Tx buffer
Wire.write(subAddress); // Put slave register address in Tx buffer
Wire.write(data); // Put data in Tx buffer
Wire.endTransmission(); // Send the Tx buffer
}
uint8_t MPU9250::readByte(uint8_t address, uint8_t subAddress)
{
uint8_t data = 0; // `data` will store the register data
Wire.beginTransmission(address); // Initialize the Tx buffer
Wire.write(subAddress); // Put slave register address in Tx buffer
Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
Wire.requestFrom(address, 1); // Read two bytes from slave register address on MPU9250
data = Wire.read(); // Fill Rx buffer with result
return data; // Return data read from slave register
}
void MPU9250::readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
{
Wire.beginTransmission(address); // Initialize the Tx buffer
Wire.write(subAddress); // Put slave register address in Tx buffer
Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
uint8_t i = 0;
Wire.requestFrom(address, count); // Read bytes from slave register address
while (Wire.available()) {
dest[i++] = Wire.read(); } // Put read results in the Rx buffer
}
| [
"noreply@github.com"
] | noreply@github.com |
ba70f038cb4e8695146746f720ab9ee4bfde34dd | d774554a5316b406efb95880b9546b9d292ed961 | /LadderProblem.cpp | 2ca53f23da1162f27d6cbb297429a47291c429c9 | [] | no_license | kartikeya72001/DyanamicProgrammingCpp | 6411dcec13dde0c2897198a18588e81fd9ba1739 | 00570be21cbcded0eccf88cd614862b1f5ef50e9 | refs/heads/master | 2022-11-12T01:27:23.670996 | 2020-06-29T08:11:07 | 2020-06-29T08:11:07 | 265,582,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | cpp | #include <iostream>
#include <ctime>
using namespace std;
int ladderTD(int n, int k, int dp[])
{
if(n==0)
return 1;
if(dp[n]!=0)
{
return dp[n];
}
int ways = 0;
for(int i=1;i<=k;i++)
{
if(n-i>=0)
{
ways+=ladderTD(n-i,k,dp);
}
}
return dp[n] = ways;
}
int ladderBU(int n, int k)
{
int dp[100] = {0};
dp[0] = 1;
for(int i=1;i<=n;i++)
{
dp[i] = 0;
for(int j = 1;j<=k;j++)
{
if(i-j>=0)
dp[i] += dp[i-j];
}
}
return dp[n];
}
int ladderBUOpt(int n, int k)
{
int dp[100] = {0};
dp[0] = dp[1] = 1;
for(int i=2;i<=n;i++)
{
if(i-k-1<0)
dp[i] = 2*dp[i-1];
else
dp[i] = 2*dp[i-1]-dp[i-k-1];
}
return dp[n];
}
int main(int argc, char const *argv[]) {
int n = 4,k = 3;
int dp[100] = {0};
//cin>>n>>k;
//cout<<ladderBU(n,k)<<endl;
cout<<ladderBUOpt(n,k)<<endl;
//cout<<ladderTD(n,k,dp)<<endl;
cout<<clock()<<"ms";
return 0;
}
| [
"kartikeya72001@gmail.com"
] | kartikeya72001@gmail.com |
6716a4d7c7019f37e161c7ac8544928a75637923 | 70d5e95037e674fe61e77601570fe01f81551720 | /lfr_length_53.cpp | 59a64c32da11cc50b7abbc8fdbb794256111a9b5 | [] | no_license | BGI-Qingdao/stLFRQC | 8fef7364d7beda3beadbeb5f9c47840f39b1c139 | e448c6d57979c95b012cc979ccf7f13d7c7d2d67 | refs/heads/master | 2022-11-09T21:29:47.428169 | 2020-06-22T06:33:16 | 2020-06-22T06:33:16 | 259,590,577 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,688 | cpp | #include <vector>
#include <iostream>
#include <map>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <getopt.h>
// lfr-length-distrubution , bined by 1000 bp
std::map<int , int > lfr_length_freq_1000;
// lfr-length-cache : for min ,max and median
std::vector<long long> length_cache;
void incr(int length) {
assert(length > 0 );
int b_index=length/1000;
if( lfr_length_freq_1000.find(b_index) == lfr_length_freq_1000.end() )
lfr_length_freq_1000[b_index]=1;
else
lfr_length_freq_1000[b_index]++;
length_cache.push_back(length);
}
void printUsage(){
std::cerr<<"Usage :\n";
std::cerr<<" lfr_length_53 [options] < long_fragment.details.txt\n\n";
std::cerr<<"Options :\n"
<<" -h/--help print this usage.\n"
<<" -l/--valid_lfr_readpair min valid lfr read pair threshold.\n"
<<" default 3.\n"
<<" -b/--valid_barcode_readpair min valid lfr read pair threshold.\n"
<<" default 5.\n";
}
int main(int argc , char ** argv)
{
static struct option long_options[] = {
{"valid_lfr_readpair", required_argument, NULL, 'l'},
{"valid_barcode_readpair", required_argument, NULL, 'b'},
{"help", no_argument, NULL, 'h'},
{0, 0, 0, 0}
};
static char optstring[] = "l:b:h";
int valid_lfr_readpair = 3;
int valid_barcode_readpair = 5 ;
while(1){
int c = getopt_long(argc, argv, optstring, long_options, NULL);
if (c<0) break;
switch (c){
case 'l':
valid_lfr_readpair = atoi(optarg);
break;
case 'b':
valid_barcode_readpair = atoi(optarg);
break;
case 'h':
printUsage();
return 0;
default:
printUsage();
return 1 ;
}
}
if( valid_barcode_readpair < 0 || valid_lfr_readpair < 0){
std::cerr<<"error : valid_barcode_readpair < 0 || valid_lfr_readpair < 0 . exit ..."<<std::endl;
return 1 ;
}
if( valid_barcode_readpair < valid_lfr_readpair ) {
std::cerr<<"error : valid_barcode_readpair < valid_lfr_readpair . exit ..."<<std::endl;
return 1 ;
}
// cache all lfr info
std::vector<std::vector<std::pair<int,int>> > cache ;
// 1. load long_fragment_detail.txt
int prev_barcode = -1 ;
std::string line ;
std::getline(std::cin,line); // remove header
while( ! std::cin.eof() ) {
int tmp , barcode , rp , length;
std::cin>>barcode>>tmp>>rp>>tmp>>length;
if(barcode != prev_barcode ) {
prev_barcode = barcode ;
cache.push_back(std::vector<std::pair<int,int>>());
}
assert(length>0);
cache[cache.size()-1].push_back(std::make_pair(rp,length));
}
// 2. filter valid lfr information
int min_brp = valid_barcode_readpair ; // min read-pair-number of valid barcode
int min_lrp = valid_lfr_readpair; // min read-pair-number of valid lfr
std::cerr<<"##############\t################"<<std::endl;
std::cerr<<"Barcode-filter\tread-pair<"<<min_brp<<std::endl;
std::cerr<<"LFR-filter\tread-pair<"<<min_lrp<<std::endl;
for(const auto & d : cache ) {
int br = 0 ; // read-pair in barcode
int v = 0 ; // valid barcode or not
if( d.size() == 1 ) {
v =1;
br=d.at(0).first;
}else {
for( const std::pair<int,int> & p : d ) {
br += p.first ;
if ( p.first >=min_lrp )
v=1;
}
}
if( v==1 && br >=min_brp ) {
if( d.size() == 1 )
incr(d.at(0).second);
else {
for( const std::pair<int,int> & p : d )
if ( p.first >=min_lrp )
incr(p.second);
}
}
}
std::sort(length_cache.begin(),length_cache.end());
long long sum = 0 ;
for( long x : length_cache) sum +=x ;
std::cerr<<"Average-lfr-length\t"<<sum/length_cache.size()<<std::endl;
std::cerr<<"Min-lfr-length\t"<<length_cache.at(0)<<std::endl;
std::cerr<<"Max-lfr-length\t"<<length_cache.at(length_cache.size()-1)<<std::endl;
std::cerr<<"Median-lfr-length\t"<<length_cache.at(length_cache.size()/2)<<std::endl;
std::cerr<<"LFR-length/1000\tcount\n";
for(const std::pair<long,long> & p : lfr_length_freq_1000 ){
std::cerr<<p.first<<"\t"<<p.second<<"\n";
}
}
| [
"guolidong@genomics.cn"
] | guolidong@genomics.cn |
a82172ecfe12a011666a992046b88024fd926413 | 497c6f4c3f5cdb0573a5d892b7a2e2464f5f5b8e | /Sorting/SelectionSort.cpp | 198a8d3cfc2f50d25e6ea61ac64bfb6abebb70b9 | [] | no_license | Sanyam96/Programming | cde481359f361d3c055285b5b772525a752be256 | 507cc12fc124612764764f888720643ff4d76a88 | refs/heads/master | 2020-12-02T16:38:22.499217 | 2017-10-26T18:04:24 | 2017-10-26T18:04:24 | 96,563,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,917 | cpp | // Selection Sort!
/*
The selection sort algorithm sorts an array by
repeatedly finding the minimum element (considering ascending order)
from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort,
the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.
arr[] = 64 25 12 22 11
// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64
// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64
// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64
// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64
*/
#include <bits/stdc++.h>
using namespace std;
/* Function for Swapping of 2 Elements*/
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
/* Function for Selection Sort */
void selectionSort(int arr[], int n) {
int min_idx;
for (int i = 0; i < n-1; ++i) {
for (int j = i + 1; j < n; ++j) {
if( arr[i] > arr[j] ) {
swap(&arr[i], &arr[j]);
}
}
}
}
/* Function to print an array */
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
/* Main Function */
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted Array : ";
printArray(arr, n);
return 0;
}
/*
Note:
Time Complexity: O(n^2) as there are two nested loops.
Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps
and can be useful when memory write is a costly operation.
*/ | [
"sanyam.bvcoe96@gmail.com"
] | sanyam.bvcoe96@gmail.com |
2a5a2592765446446450faff58b4703a93eedab1 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/renderer/bindings/modules/v8/v8_authenticator_response.cc | 6534b58e0daa26d3324b019a00850c675bebc8e7 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,830 | cc | // 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/modules/v8/v8_authenticator_response.h"
#include <algorithm>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_array_buffer.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/bindings/v8_private_property.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo v8_authenticator_response_wrapper_type_info = {
gin::kEmbedderBlink,
V8AuthenticatorResponse::DomTemplate,
V8AuthenticatorResponse::InstallConditionalFeatures,
"AuthenticatorResponse",
nullptr,
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in AuthenticatorResponse.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// platform/bindings/ScriptWrappable.h.
const WrapperTypeInfo& AuthenticatorResponse::wrapper_type_info_ = v8_authenticator_response_wrapper_type_info;
// not [ActiveScriptWrappable]
static_assert(
!std::is_base_of<ActiveScriptWrappableBase, AuthenticatorResponse>::value,
"AuthenticatorResponse inherits from ActiveScriptWrappable<>, but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
static_assert(
std::is_same<decltype(&AuthenticatorResponse::HasPendingActivity),
decltype(&ScriptWrappable::HasPendingActivity)>::value,
"AuthenticatorResponse is overriding hasPendingActivity(), but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
namespace authenticator_response_v8_internal {
static void ClientDataJSONAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
AuthenticatorResponse* impl = V8AuthenticatorResponse::ToImpl(holder);
DOMArrayBuffer* cpp_value(WTF::GetPtr(impl->clientDataJSON()));
// Keep the wrapper object for the return value alive as long as |this|
// object is alive in order to save creation time of the wrapper object.
if (cpp_value && DOMDataStore::SetReturnValue(info.GetReturnValue(), cpp_value))
return;
v8::Local<v8::Value> v8_value(ToV8(cpp_value, holder, info.GetIsolate()));
static const V8PrivateProperty::SymbolKey kKeepAliveKey;
V8PrivateProperty::GetSymbol(info.GetIsolate(), kKeepAliveKey)
.Set(holder, v8_value);
V8SetReturnValue(info, v8_value);
}
} // namespace authenticator_response_v8_internal
void V8AuthenticatorResponse::ClientDataJSONAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_AuthenticatorResponse_clientDataJSON_Getter");
authenticator_response_v8_internal::ClientDataJSONAttributeGetter(info);
}
static void InstallV8AuthenticatorResponseTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
// Initialize the interface object's template.
V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8AuthenticatorResponse::GetWrapperTypeInfo()->interface_name, v8::Local<v8::FunctionTemplate>(), V8AuthenticatorResponse::kInternalFieldCount);
if (!RuntimeEnabledFeatures::WebAuthEnabled()) {
return;
}
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
V8AuthenticatorResponse::InstallRuntimeEnabledFeaturesOnTemplate(
isolate, world, interface_template);
}
void V8AuthenticatorResponse::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
if (!RuntimeEnabledFeatures::WebAuthEnabled()) {
return;
}
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
}
v8::Local<v8::FunctionTemplate> V8AuthenticatorResponse::DomTemplate(
v8::Isolate* isolate, const DOMWrapperWorld& world) {
return V8DOMConfiguration::DomClassTemplate(
isolate, world, const_cast<WrapperTypeInfo*>(V8AuthenticatorResponse::GetWrapperTypeInfo()),
InstallV8AuthenticatorResponseTemplate);
}
bool V8AuthenticatorResponse::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->HasInstance(V8AuthenticatorResponse::GetWrapperTypeInfo(), v8_value);
}
v8::Local<v8::Object> V8AuthenticatorResponse::FindInstanceInPrototypeChain(
v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(
V8AuthenticatorResponse::GetWrapperTypeInfo(), v8_value);
}
AuthenticatorResponse* V8AuthenticatorResponse::ToImplWithTypeCheck(
v8::Isolate* isolate, v8::Local<v8::Value> value) {
return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
void V8AuthenticatorResponse::InstallConditionalFeatures(
v8::Local<v8::Context> context,
const DOMWrapperWorld& world,
v8::Local<v8::Object> instance_object,
v8::Local<v8::Object> prototype_object,
v8::Local<v8::Function> interface_object,
v8::Local<v8::FunctionTemplate> interface_template) {
CHECK(!interface_template.IsEmpty());
DCHECK((!prototype_object.IsEmpty() && !interface_object.IsEmpty()) ||
!instance_object.IsEmpty());
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ExecutionContext* execution_context = ToExecutionContext(context);
DCHECK(execution_context);
bool is_secure_context = (execution_context && execution_context->IsSecureContext());
if (!prototype_object.IsEmpty() || !interface_object.IsEmpty()) {
if (is_secure_context) {
static constexpr V8DOMConfiguration::AccessorConfiguration
kAccessorConfigurations[] = {
{ "clientDataJSON", V8AuthenticatorResponse::ClientDataJSONAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
};
V8DOMConfiguration::InstallAccessors(
isolate, world, instance_object, prototype_object, interface_object,
signature, kAccessorConfigurations,
base::size(kAccessorConfigurations));
}
}
}
} // namespace blink
| [
"xueqi@zjmedia.net"
] | xueqi@zjmedia.net |
d57c118b5acd488cfb4166c6bdc16ca48fa6af9e | dd76575c8e6db25fa7a8ca6fa7e0c63678fb7e38 | /code_notes/C.C++/designPattern/单例模式/Singleton.h | 7907ae3b86f4ab7c085fefaba39368c38ad26ffd | [] | no_license | jiemingliu/private_notes | d2124b88426ab7abbb458152482c6b88ff60b531 | 954c255960f66a16493f62f5513b17c72617af78 | refs/heads/master | 2023-05-06T00:27:05.338589 | 2021-05-31T10:59:16 | 2021-05-31T10:59:16 | 110,777,485 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 571 | h | #pragma once
#include <cassert>
using namespace std;
template <typename T>
class Singleton
{
private:
static T* & ms_Singleton()
{
static T* ms_Singleton_ = new T ;
return ms_Singleton_;
}
public:
Singleton()
{
assert( !ms_Singleton());
ms_Singleton() = static_cast< T* >( this );
}
~Singleton()
{
assert(ms_Singleton());
ms_Singleton() = 0;
}
static T& getSingleton()
{
assert( ms_Singleton());
return ( *ms_Singleton());
}
static T* getSingletonPtr()
{
return (ms_Singleton());
}
};
| [
"liumingjie.blog@gmail.com"
] | liumingjie.blog@gmail.com |
644bda911ff27d8520546b72307d04340c5a3fd5 | 59cc24555bc7d3a1ce39034755b35c4ac3867150 | /Assignment1/Assignment1/ExprTree.h | 36a6cb5c6050f9a702ee6caa173e029c04397b43 | [] | no_license | FarahWheelbarrah/ExpressionTree | 6e427d9070d9721e5d93a6330137977fb42209a4 | e46f4973ed5bc5cc3b7331645355a18f3e3a56ac | refs/heads/master | 2021-08-22T03:51:11.368510 | 2017-11-29T06:18:09 | 2017-11-29T06:18:09 | 112,435,093 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,808 | h | #ifndef EXPRTREE_H
#define EXPRTREE_H
/*
* std::queue and std::stack have been included for your
* convenience, you don't have to build your own or anything.
* With std::queue, the important methods are push(...), front(), pop() and empty().
* With std::stack, the important methods are push(...), top(), pop() and empty().
*/
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <cstdlib> //This is include for the atoi() function used in the to_number(string) helper function.
#include "TreeNode.h"
/*
* The four included data types have been imported into the
* local namespace so you don't have to write std:: all the time.
*/
using std::queue;
using std::stack;
using std::vector;
using std::string;
class ExprTree {
private:
TreeNode * root; //The root of the tree! What a surprise :0.
int _size; //The number of nodes in the tree. To keep things simple,
//it's just an int.
public:
/*
* See the .cpp file for what these methods do. Note that
* most are static, so you don't need to instantiate the class
* to use them (same as Java).
*/
ExprTree();
ExprTree(TreeNode *);
~ExprTree();
static vector<string> tokenise(string);
static ExprTree buildTree(vector<string>);
static int evaluate(TreeNode *);
int evaluateWholeTree();
/*
* The parameters of the next three methods have been made
* into const references. This is to stop the ExprTree parameter
* being deleted when they finish. This shouldn't make a difference
* from your perspective, you can just use the parameter as if it were
* the object itself (just like a Java object).
*/
static string prefixOrder(const ExprTree &);
static string infixOrder(const ExprTree &);
static string postfixOrder(const ExprTree &);
int size();
bool isEmpty();
TreeNode * getRoot();
};
#endif | [
"andrefarah5@gmail.com"
] | andrefarah5@gmail.com |
d1eeaf897c810e88d666d9633e2404ba682a8aab | 59c94d223c8e1eb1720d608b9fc040af22f09e3a | /peridot/tests/maxwell_integration/maxwell_service_provider_bridge.cc | f973261ac1f652fff9bab8bd205715bcbc8c378a | [
"BSD-3-Clause"
] | permissive | bootingman/fuchsia2 | 67f527712e505c4dca000a9d54d3be1a4def3afa | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | refs/heads/master | 2022-12-25T20:28:37.134803 | 2019-05-14T08:26:08 | 2019-05-14T08:26:08 | 186,606,695 | 1 | 1 | BSD-3-Clause | 2022-12-16T21:17:16 | 2019-05-14T11:17:16 | C++ | UTF-8 | C++ | false | false | 1,842 | cc | // Copyright 2016 The Fuchsia 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 "peridot/tests/maxwell_integration/maxwell_service_provider_bridge.h"
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async/default.h>
#include <lib/component/cpp/connect.h>
namespace maxwell {
namespace {
// TODO(abarth): Get this constant from a generated header once netstack uses
// FIDL.
constexpr char kNetstack[] = "net.Netstack";
} // namespace
MaxwellServiceProviderBridge::MaxwellServiceProviderBridge(
fuchsia::sys::Environment* parent_env)
: vfs_(async_get_default_dispatcher()),
services_dir_(fbl::AdoptRef(new fs::PseudoDir)) {
AddService<fuchsia::sys::Loader>(
[parent_env](fidl::InterfaceRequest<fuchsia::sys::Loader> request) {
fuchsia::sys::ServiceProviderPtr services;
parent_env->GetServices(services.NewRequest());
component::ConnectToService(services.get(), std::move(request));
});
AddServiceWithName(
kNetstack,
fbl::AdoptRef(new fs::Service([parent_env](zx::channel request) {
fuchsia::sys::ServiceProviderPtr services;
parent_env->GetServices(services.NewRequest());
services->ConnectToService(kNetstack, std::move(request));
return ZX_OK;
})));
}
void MaxwellServiceProviderBridge::AddServiceWithName(
const char* name, fbl::RefPtr<fs::Service> service) {
service_names_.push_back(name);
services_dir_->AddEntry(name, service);
}
zx::channel MaxwellServiceProviderBridge::OpenAsDirectory() {
zx::channel h1, h2;
if (zx::channel::create(0, &h1, &h2) != ZX_OK)
return zx::channel();
if (vfs_.ServeDirectory(services_dir_, std::move(h1)) != ZX_OK)
return zx::channel();
return h2;
}
} // namespace maxwell
| [
"thatguy@google.com"
] | thatguy@google.com |
31430157d5089b2c71ebfcfd548b65bacfec872a | fbb38b3cff258b5dcd161ea2046b7fca566def5c | /problem5-SmallestMultiple.cpp | 3ee0bc6539da55799143f4f2e3e0beb7c2d3435c | [] | no_license | rishav2416/ProjectEuler | 208633b5c7319864deae5984fab6b73184f2757f | 1713c5017f5b21850bc4bf974783332f28271d83 | refs/heads/master | 2021-06-18T21:18:52.478923 | 2017-05-27T11:04:11 | 2017-05-27T11:04:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | cpp | #include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int evenlyDivided(int n){
int factorList[n-1];
for (int k=2; k<=n; ++k) factorList[k-2]=k;
for (int m=0; m<n-2; ++m)
for (int u=m+1; u<n-1; ++u)
if (factorList[u] % factorList[m] == 0 ) factorList[u]= factorList[u]/factorList[m];
int output = 1;
for (int k=0; k<n-1; ++k) {
cout << factorList[k] << " ";
output *= factorList[k];
}
return output;
}
int main (int argc, char * const argv[]) {
cout << endl<< evenlyDivided(20)<< endl;
return 0;
} | [
"barmpoutis@gmail.com"
] | barmpoutis@gmail.com |
86523e0af43a412b8866f703ba25cfe1a64e3dca | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/wget/new_hunk_2374.cpp | 288eed91b00c2723e46e0047cfd4bf8b968c77da | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239,230 | cpp | % texinfo.tex -- TeX macros to handle Texinfo files.
%
% Load plain if necessary, i.e., if running under initex.
\expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi
%
\def\texinfoversion{2006-10-04.17}
%
% Copyright (C) 1985, 1986, 1988, 1990, 1991, 1992, 1993, 1994, 1995,
% 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free
% Software Foundation, Inc.
%
% This texinfo.tex file 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, or (at
% your option) any later version.
%
% This texinfo.tex file 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 texinfo.tex file; see the file COPYING. If not, write
% to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
% Boston, MA 02110-1301, USA.
%
% As a special exception, when this file is read by TeX when processing
% a Texinfo source document, you may use the result without
% restriction. (This has been our intent since Texinfo was invented.)
%
% Please try the latest version of texinfo.tex before submitting bug
% reports; you can get the latest version from:
% http://www.gnu.org/software/texinfo/ (the Texinfo home page), or
% ftp://tug.org/tex/texinfo.tex
% (and all CTAN mirrors, see http://www.ctan.org).
% The texinfo.tex in any given distribution could well be out
% of date, so if that's what you're using, please check.
%
% Send bug reports to bug-texinfo@gnu.org. Please include including a
% complete document in each bug report with which we can reproduce the
% problem. Patches are, of course, greatly appreciated.
%
% To process a Texinfo manual with TeX, it's most reliable to use the
% texi2dvi shell script that comes with the distribution. For a simple
% manual foo.texi, however, you can get away with this:
% tex foo.texi
% texindex foo.??
% tex foo.texi
% tex foo.texi
% dvips foo.dvi -o # or whatever; this makes foo.ps.
% The extra TeX runs get the cross-reference information correct.
% Sometimes one run after texindex suffices, and sometimes you need more
% than two; texi2dvi does it as many times as necessary.
%
% It is possible to adapt texinfo.tex for other languages, to some
% extent. You can get the existing language-specific files from the
% full Texinfo distribution.
%
% The GNU Texinfo home page is http://www.gnu.org/software/texinfo.
\message{Loading texinfo [version \texinfoversion]:}
% If in a .fmt file, print the version number
% and turn on active characters that we couldn't do earlier because
% they might have appeared in the input file name.
\everyjob{\message{[Texinfo version \texinfoversion]}%
\catcode`+=\active \catcode`\_=\active}
\message{Basics,}
\chardef\other=12
% We never want plain's \outer definition of \+ in Texinfo.
% For @tex, we can use \tabalign.
\let\+ = \relax
% Save some plain tex macros whose names we will redefine.
\let\ptexb=\b
\let\ptexbullet=\bullet
\let\ptexc=\c
\let\ptexcomma=\,
\let\ptexdot=\.
\let\ptexdots=\dots
\let\ptexend=\end
\let\ptexequiv=\equiv
\let\ptexexclam=\!
\let\ptexfootnote=\footnote
\let\ptexgtr=>
\let\ptexhat=^
\let\ptexi=\i
\let\ptexindent=\indent
\let\ptexinsert=\insert
\let\ptexlbrace=\{
\let\ptexless=<
\let\ptexnewwrite\newwrite
\let\ptexnoindent=\noindent
\let\ptexplus=+
\let\ptexrbrace=\}
\let\ptexslash=\/
\let\ptexstar=\*
\let\ptext=\t
% If this character appears in an error message or help string, it
% starts a new line in the output.
\newlinechar = `^^J
% Use TeX 3.0's \inputlineno to get the line number, for better error
% messages, but if we're using an old version of TeX, don't do anything.
%
\ifx\inputlineno\thisisundefined
\let\linenumber = \empty % Pre-3.0.
\else
\def\linenumber{l.\the\inputlineno:\space}
\fi
% Set up fixed words for English if not already set.
\ifx\putwordAppendix\undefined \gdef\putwordAppendix{Appendix}\fi
\ifx\putwordChapter\undefined \gdef\putwordChapter{Chapter}\fi
\ifx\putwordfile\undefined \gdef\putwordfile{file}\fi
\ifx\putwordin\undefined \gdef\putwordin{in}\fi
\ifx\putwordIndexIsEmpty\undefined \gdef\putwordIndexIsEmpty{(Index is empty)}\fi
\ifx\putwordIndexNonexistent\undefined \gdef\putwordIndexNonexistent{(Index is nonexistent)}\fi
\ifx\putwordInfo\undefined \gdef\putwordInfo{Info}\fi
\ifx\putwordInstanceVariableof\undefined \gdef\putwordInstanceVariableof{Instance Variable of}\fi
\ifx\putwordMethodon\undefined \gdef\putwordMethodon{Method on}\fi
\ifx\putwordNoTitle\undefined \gdef\putwordNoTitle{No Title}\fi
\ifx\putwordof\undefined \gdef\putwordof{of}\fi
\ifx\putwordon\undefined \gdef\putwordon{on}\fi
\ifx\putwordpage\undefined \gdef\putwordpage{page}\fi
\ifx\putwordsection\undefined \gdef\putwordsection{section}\fi
\ifx\putwordSection\undefined \gdef\putwordSection{Section}\fi
\ifx\putwordsee\undefined \gdef\putwordsee{see}\fi
\ifx\putwordSee\undefined \gdef\putwordSee{See}\fi
\ifx\putwordShortTOC\undefined \gdef\putwordShortTOC{Short Contents}\fi
\ifx\putwordTOC\undefined \gdef\putwordTOC{Table of Contents}\fi
%
\ifx\putwordMJan\undefined \gdef\putwordMJan{January}\fi
\ifx\putwordMFeb\undefined \gdef\putwordMFeb{February}\fi
\ifx\putwordMMar\undefined \gdef\putwordMMar{March}\fi
\ifx\putwordMApr\undefined \gdef\putwordMApr{April}\fi
\ifx\putwordMMay\undefined \gdef\putwordMMay{May}\fi
\ifx\putwordMJun\undefined \gdef\putwordMJun{June}\fi
\ifx\putwordMJul\undefined \gdef\putwordMJul{July}\fi
\ifx\putwordMAug\undefined \gdef\putwordMAug{August}\fi
\ifx\putwordMSep\undefined \gdef\putwordMSep{September}\fi
\ifx\putwordMOct\undefined \gdef\putwordMOct{October}\fi
\ifx\putwordMNov\undefined \gdef\putwordMNov{November}\fi
\ifx\putwordMDec\undefined \gdef\putwordMDec{December}\fi
%
\ifx\putwordDefmac\undefined \gdef\putwordDefmac{Macro}\fi
\ifx\putwordDefspec\undefined \gdef\putwordDefspec{Special Form}\fi
\ifx\putwordDefvar\undefined \gdef\putwordDefvar{Variable}\fi
\ifx\putwordDefopt\undefined \gdef\putwordDefopt{User Option}\fi
\ifx\putwordDeffunc\undefined \gdef\putwordDeffunc{Function}\fi
% Since the category of space is not known, we have to be careful.
\chardef\spacecat = 10
\def\spaceisspace{\catcode`\ =\spacecat}
% sometimes characters are active, so we need control sequences.
\chardef\colonChar = `\:
\chardef\commaChar = `\,
\chardef\dashChar = `\-
\chardef\dotChar = `\.
\chardef\exclamChar= `\!
\chardef\lquoteChar= `\`
\chardef\questChar = `\?
\chardef\rquoteChar= `\'
\chardef\semiChar = `\;
\chardef\underChar = `\_
% Ignore a token.
%
\def\gobble#1{}
% The following is used inside several \edef's.
\def\makecsname#1{\expandafter\noexpand\csname#1\endcsname}
% Hyphenation fixes.
\hyphenation{
Flor-i-da Ghost-script Ghost-view Mac-OS Post-Script
ap-pen-dix bit-map bit-maps
data-base data-bases eshell fall-ing half-way long-est man-u-script
man-u-scripts mini-buf-fer mini-buf-fers over-view par-a-digm
par-a-digms rath-er rec-tan-gu-lar ro-bot-ics se-vere-ly set-up spa-ces
spell-ing spell-ings
stand-alone strong-est time-stamp time-stamps which-ever white-space
wide-spread wrap-around
}
% Margin to add to right of even pages, to left of odd pages.
\newdimen\bindingoffset
\newdimen\normaloffset
\newdimen\pagewidth \newdimen\pageheight
% For a final copy, take out the rectangles
% that mark overfull boxes (in case you have decided
% that the text looks ok even though it passes the margin).
%
\def\finalout{\overfullrule=0pt}
% @| inserts a changebar to the left of the current line. It should
% surround any changed text. This approach does *not* work if the
% change spans more than two lines of output. To handle that, we would
% have adopt a much more difficult approach (putting marks into the main
% vertical list for the beginning and end of each change).
%
\def\|{%
% \vadjust can only be used in horizontal mode.
\leavevmode
%
% Append this vertical mode material after the current line in the output.
\vadjust{%
% We want to insert a rule with the height and depth of the current
% leading; that is exactly what \strutbox is supposed to record.
\vskip-\baselineskip
%
% \vadjust-items are inserted at the left edge of the type. So
% the \llap here moves out into the left-hand margin.
\llap{%
%
% For a thicker or thinner bar, change the `1pt'.
\vrule height\baselineskip width1pt
%
% This is the space between the bar and the text.
\hskip 12pt
}%
}%
}
% Sometimes it is convenient to have everything in the transcript file
% and nothing on the terminal. We don't just call \tracingall here,
% since that produces some useless output on the terminal. We also make
% some effort to order the tracing commands to reduce output in the log
% file; cf. trace.sty in LaTeX.
%
\def\gloggingall{\begingroup \globaldefs = 1 \loggingall \endgroup}%
\def\loggingall{%
\tracingstats2
\tracingpages1
\tracinglostchars2 % 2 gives us more in etex
\tracingparagraphs1
\tracingoutput1
\tracingmacros2
\tracingrestores1
\showboxbreadth\maxdimen \showboxdepth\maxdimen
\ifx\eTeXversion\undefined\else % etex gives us more logging
\tracingscantokens1
\tracingifs1
\tracinggroups1
\tracingnesting2
\tracingassigns1
\fi
\tracingcommands3 % 3 gives us more in etex
\errorcontextlines16
}%
% add check for \lastpenalty to plain's definitions. If the last thing
% we did was a \nobreak, we don't want to insert more space.
%
\def\smallbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\smallskipamount
\removelastskip\penalty-50\smallskip\fi\fi}
\def\medbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\medskipamount
\removelastskip\penalty-100\medskip\fi\fi}
\def\bigbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\bigskipamount
\removelastskip\penalty-200\bigskip\fi\fi}
% For @cropmarks command.
% Do @cropmarks to get crop marks.
%
\newif\ifcropmarks
\let\cropmarks = \cropmarkstrue
%
% Dimensions to add cropmarks at corners.
% Added by P. A. MacKay, 12 Nov. 1986
%
\newdimen\outerhsize \newdimen\outervsize % set by the paper size routines
\newdimen\cornerlong \cornerlong=1pc
\newdimen\cornerthick \cornerthick=.3pt
\newdimen\topandbottommargin \topandbottommargin=.75in
% Main output routine.
\chardef\PAGE = 255
\output = {\onepageout{\pagecontents\PAGE}}
\newbox\headlinebox
\newbox\footlinebox
% \onepageout takes a vbox as an argument. Note that \pagecontents
% does insertions, but you have to call it yourself.
\def\onepageout#1{%
\ifcropmarks \hoffset=0pt \else \hoffset=\normaloffset \fi
%
\ifodd\pageno \advance\hoffset by \bindingoffset
\else \advance\hoffset by -\bindingoffset\fi
%
% Do this outside of the \shipout so @code etc. will be expanded in
% the headline as they should be, not taken literally (outputting ''code).
\setbox\headlinebox = \vbox{\let\hsize=\pagewidth \makeheadline}%
\setbox\footlinebox = \vbox{\let\hsize=\pagewidth \makefootline}%
%
{%
% Have to do this stuff outside the \shipout because we want it to
% take effect in \write's, yet the group defined by the \vbox ends
% before the \shipout runs.
%
\indexdummies % don't expand commands in the output.
\normalturnoffactive % \ in index entries must not stay \, e.g., if
% the page break happens to be in the middle of an example.
% We don't want .vr (or whatever) entries like this:
% \entry{{\tt \indexbackslash }acronym}{32}{\code {\acronym}}
% "\acronym" won't work when it's read back in;
% it needs to be
% {\code {{\tt \backslashcurfont }acronym}
\shipout\vbox{%
% Do this early so pdf references go to the beginning of the page.
\ifpdfmakepagedest \pdfdest name{\the\pageno} xyz\fi
%
\ifcropmarks \vbox to \outervsize\bgroup
\hsize = \outerhsize
\vskip-\topandbottommargin
\vtop to0pt{%
\line{\ewtop\hfil\ewtop}%
\nointerlineskip
\line{%
\vbox{\moveleft\cornerthick\nstop}%
\hfill
\vbox{\moveright\cornerthick\nstop}%
}%
\vss}%
\vskip\topandbottommargin
\line\bgroup
\hfil % center the page within the outer (page) hsize.
\ifodd\pageno\hskip\bindingoffset\fi
\vbox\bgroup
\fi
%
\unvbox\headlinebox
\pagebody{#1}%
\ifdim\ht\footlinebox > 0pt
% Only leave this space if the footline is nonempty.
% (We lessened \vsize for it in \oddfootingyyy.)
% The \baselineskip=24pt in plain's \makefootline has no effect.
\vskip 24pt
\unvbox\footlinebox
\fi
%
\ifcropmarks
\egroup % end of \vbox\bgroup
\hfil\egroup % end of (centering) \line\bgroup
\vskip\topandbottommargin plus1fill minus1fill
\boxmaxdepth = \cornerthick
\vbox to0pt{\vss
\line{%
\vbox{\moveleft\cornerthick\nsbot}%
\hfill
\vbox{\moveright\cornerthick\nsbot}%
}%
\nointerlineskip
\line{\ewbot\hfil\ewbot}%
}%
\egroup % \vbox from first cropmarks clause
\fi
}% end of \shipout\vbox
}% end of group with \indexdummies
\advancepageno
\ifnum\outputpenalty>-20000 \else\dosupereject\fi
}
\newinsert\margin \dimen\margin=\maxdimen
\def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}}
{\catcode`\@ =11
\gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi
% marginal hacks, juha@viisa.uucp (Juha Takala)
\ifvoid\margin\else % marginal info is present
\rlap{\kern\hsize\vbox to\z@{\kern1pt\box\margin \vss}}\fi
\dimen@=\dp#1 \unvbox#1
\ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi
\ifr@ggedbottom \kern-\dimen@ \vfil \fi}
}
% Here are the rules for the cropmarks. Note that they are
% offset so that the space between them is truly \outerhsize or \outervsize
% (P. A. MacKay, 12 November, 1986)
%
\def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong}
\def\nstop{\vbox
{\hrule height\cornerthick depth\cornerlong width\cornerthick}}
\def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong}
\def\nsbot{\vbox
{\hrule height\cornerlong depth\cornerthick width\cornerthick}}
% Parse an argument, then pass it to #1. The argument is the rest of
% the input line (except we remove a trailing comment). #1 should be a
% macro which expects an ordinary undelimited TeX argument.
%
\def\parsearg{\parseargusing{}}
\def\parseargusing#1#2{%
\def\argtorun{#2}%
\begingroup
\obeylines
\spaceisspace
#1%
\parseargline\empty% Insert the \empty token, see \finishparsearg below.
}
{\obeylines %
\gdef\parseargline#1^^M{%
\endgroup % End of the group started in \parsearg.
\argremovecomment #1\comment\ArgTerm%
}%
}
% First remove any @comment, then any @c comment.
\def\argremovecomment#1\comment#2\ArgTerm{\argremovec #1\c\ArgTerm}
\def\argremovec#1\c#2\ArgTerm{\argcheckspaces#1\^^M\ArgTerm}
% Each occurence of `\^^M' or `<space>\^^M' is replaced by a single space.
%
% \argremovec might leave us with trailing space, e.g.,
% @end itemize @c foo
% This space token undergoes the same procedure and is eventually removed
% by \finishparsearg.
%
\def\argcheckspaces#1\^^M{\argcheckspacesX#1\^^M \^^M}
\def\argcheckspacesX#1 \^^M{\argcheckspacesY#1\^^M}
\def\argcheckspacesY#1\^^M#2\^^M#3\ArgTerm{%
\def\temp{#3}%
\ifx\temp\empty
% Do not use \next, perhaps the caller of \parsearg uses it; reuse \temp:
\let\temp\finishparsearg
\else
\let\temp\argcheckspaces
\fi
% Put the space token in:
\temp#1 #3\ArgTerm
}
% If a _delimited_ argument is enclosed in braces, they get stripped; so
% to get _exactly_ the rest of the line, we had to prevent such situation.
% We prepended an \empty token at the very beginning and we expand it now,
% just before passing the control to \argtorun.
% (Similarily, we have to think about #3 of \argcheckspacesY above: it is
% either the null string, or it ends with \^^M---thus there is no danger
% that a pair of braces would be stripped.
%
% But first, we have to remove the trailing space token.
%
\def\finishparsearg#1 \ArgTerm{\expandafter\argtorun\expandafter{#1}}
% \parseargdef\foo{...}
% is roughly equivalent to
% \def\foo{\parsearg\Xfoo}
% \def\Xfoo#1{...}
%
% Actually, I use \csname\string\foo\endcsname, ie. \\foo, as it is my
% favourite TeX trick. --kasal, 16nov03
\def\parseargdef#1{%
\expandafter \doparseargdef \csname\string#1\endcsname #1%
}
\def\doparseargdef#1#2{%
\def#2{\parsearg#1}%
\def#1##1%
}
% Several utility definitions with active space:
{
\obeyspaces
\gdef\obeyedspace{ }
% Make each space character in the input produce a normal interword
% space in the output. Don't allow a line break at this space, as this
% is used only in environments like @example, where each line of input
% should produce a line of output anyway.
%
\gdef\sepspaces{\obeyspaces\let =\tie}
% If an index command is used in an @example environment, any spaces
% therein should become regular spaces in the raw index file, not the
% expansion of \tie (\leavevmode \penalty \@M \ ).
\gdef\unsepspaces{\let =\space}
}
\def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next}
% Define the framework for environments in texinfo.tex. It's used like this:
%
% \envdef\foo{...}
% \def\Efoo{...}
%
% It's the responsibility of \envdef to insert \begingroup before the
% actual body; @end closes the group after calling \Efoo. \envdef also
% defines \thisenv, so the current environment is known; @end checks
% whether the environment name matches. The \checkenv macro can also be
% used to check whether the current environment is the one expected.
%
% Non-false conditionals (@iftex, @ifset) don't fit into this, so they
% are not treated as enviroments; they don't open a group. (The
% implementation of @end takes care not to call \endgroup in this
% special case.)
% At runtime, environments start with this:
\def\startenvironment#1{\begingroup\def\thisenv{#1}}
% initialize
\let\thisenv\empty
% ... but they get defined via ``\envdef\foo{...}'':
\long\def\envdef#1#2{\def#1{\startenvironment#1#2}}
\def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}}
% Check whether we're in the right environment:
\def\checkenv#1{%
\def\temp{#1}%
\ifx\thisenv\temp
\else
\badenverr
\fi
}
% Evironment mismatch, #1 expected:
\def\badenverr{%
\errhelp = \EMsimple
\errmessage{This command can appear only \inenvironment\temp,
not \inenvironment\thisenv}%
}
\def\inenvironment#1{%
\ifx#1\empty
out of any environment%
\else
in environment \expandafter\string#1%
\fi
}
% @end foo executes the definition of \Efoo.
% But first, it executes a specialized version of \checkenv
%
\parseargdef\end{%
\if 1\csname iscond.#1\endcsname
\else
% The general wording of \badenverr may not be ideal, but... --kasal, 06nov03
\expandafter\checkenv\csname#1\endcsname
\csname E#1\endcsname
\endgroup
\fi
}
\newhelp\EMsimple{Press RETURN to continue.}
%% Simple single-character @ commands
% @@ prints an @
% Kludge this until the fonts are right (grr).
\def\@{{\tt\char64}}
% This is turned off because it was never documented
% and you can use @w{...} around a quote to suppress ligatures.
%% Define @` and @' to be the same as ` and '
%% but suppressing ligatures.
%\def\`{{`}}
%\def\'{{'}}
% Used to generate quoted braces.
\def\mylbrace {{\tt\char123}}
\def\myrbrace {{\tt\char125}}
\let\{=\mylbrace
\let\}=\myrbrace
\begingroup
% Definitions to produce \{ and \} commands for indices,
% and @{ and @} for the aux/toc files.
\catcode`\{ = \other \catcode`\} = \other
\catcode`\[ = 1 \catcode`\] = 2
\catcode`\! = 0 \catcode`\\ = \other
!gdef!lbracecmd[\{]%
!gdef!rbracecmd[\}]%
!gdef!lbraceatcmd[@{]%
!gdef!rbraceatcmd[@}]%
!endgroup
% @comma{} to avoid , parsing problems.
\let\comma = ,
% Accents: @, @dotaccent @ringaccent @ubaraccent @udotaccent
% Others are defined by plain TeX: @` @' @" @^ @~ @= @u @v @H.
\let\, = \c
\let\dotaccent = \.
\def\ringaccent#1{{\accent23 #1}}
\let\tieaccent = \t
\let\ubaraccent = \b
\let\udotaccent = \d
% Other special characters: @questiondown @exclamdown @ordf @ordm
% Plain TeX defines: @AA @AE @O @OE @L (plus lowercase versions) @ss.
\def\questiondown{?`}
\def\exclamdown{!`}
\def\ordf{\leavevmode\raise1ex\hbox{\selectfonts\lllsize \underbar{a}}}
\def\ordm{\leavevmode\raise1ex\hbox{\selectfonts\lllsize \underbar{o}}}
% Dotless i and dotless j, used for accents.
\def\imacro{i}
\def\jmacro{j}
\def\dotless#1{%
\def\temp{#1}%
\ifx\temp\imacro \ptexi
\else\ifx\temp\jmacro \j
\else \errmessage{@dotless can be used only with i or j}%
\fi\fi
}
% The \TeX{} logo, as in plain, but resetting the spacing so that a
% period following counts as ending a sentence. (Idea found in latex.)
%
\edef\TeX{\TeX \spacefactor=1000 }
% @LaTeX{} logo. Not quite the same results as the definition in
% latex.ltx, since we use a different font for the raised A; it's most
% convenient for us to use an explicitly smaller font, rather than using
% the \scriptstyle font (since we don't reset \scriptstyle and
% \scriptscriptstyle).
%
\def\LaTeX{%
L\kern-.36em
{\setbox0=\hbox{T}%
\vbox to \ht0{\hbox{\selectfonts\lllsize A}\vss}}%
\kern-.15em
\TeX
}
% Be sure we're in horizontal mode when doing a tie, since we make space
% equivalent to this in @example-like environments. Otherwise, a space
% at the beginning of a line will start with \penalty -- and
% since \penalty is valid in vertical mode, we'd end up putting the
% penalty on the vertical list instead of in the new paragraph.
{\catcode`@ = 11
% Avoid using \@M directly, because that causes trouble
% if the definition is written into an index file.
\global\let\tiepenalty = \@M
\gdef\tie{\leavevmode\penalty\tiepenalty\ }
}
% @: forces normal size whitespace following.
\def\:{\spacefactor=1000 }
% @* forces a line break.
\def\*{\hfil\break\hbox{}\ignorespaces}
% @/ allows a line break.
\let\/=\allowbreak
% @. is an end-of-sentence period.
\def\.{.\spacefactor=\endofsentencespacefactor\space}
% @! is an end-of-sentence bang.
\def\!{!\spacefactor=\endofsentencespacefactor\space}
% @? is an end-of-sentence query.
\def\?{?\spacefactor=\endofsentencespacefactor\space}
% @frenchspacing on|off says whether to put extra space after punctuation.
%
\def\onword{on}
\def\offword{off}
%
\parseargdef\frenchspacing{%
\def\temp{#1}%
\ifx\temp\onword \plainfrenchspacing
\else\ifx\temp\offword \plainnonfrenchspacing
\else
\errhelp = \EMsimple
\errmessage{Unknown @frenchspacing option `\temp', must be on/off}%
\fi\fi
}
% @w prevents a word break. Without the \leavevmode, @w at the
% beginning of a paragraph, when TeX is still in vertical mode, would
% produce a whole line of output instead of starting the paragraph.
\def\w#1{\leavevmode\hbox{#1}}
% @group ... @end group forces ... to be all on one page, by enclosing
% it in a TeX vbox. We use \vtop instead of \vbox to construct the box
% to keep its height that of a normal line. According to the rules for
% \topskip (p.114 of the TeXbook), the glue inserted is
% max (\topskip - \ht (first item), 0). If that height is large,
% therefore, no glue is inserted, and the space between the headline and
% the text is small, which looks bad.
%
% Another complication is that the group might be very large. This can
% cause the glue on the previous page to be unduly stretched, because it
% does not have much material. In this case, it's better to add an
% explicit \vfill so that the extra space is at the bottom. The
% threshold for doing this is if the group is more than \vfilllimit
% percent of a page (\vfilllimit can be changed inside of @tex).
%
\newbox\groupbox
\def\vfilllimit{0.7}
%
\envdef\group{%
\ifnum\catcode`\^^M=\active \else
\errhelp = \groupinvalidhelp
\errmessage{@group invalid in context where filling is enabled}%
\fi
\startsavinginserts
%
\setbox\groupbox = \vtop\bgroup
% Do @comment since we are called inside an environment such as
% @example, where each end-of-line in the input causes an
% end-of-line in the output. We don't want the end-of-line after
% the `@group' to put extra space in the output. Since @group
% should appear on a line by itself (according to the Texinfo
% manual), we don't worry about eating any user text.
\comment
}
%
% The \vtop produces a box with normal height and large depth; thus, TeX puts
% \baselineskip glue before it, and (when the next line of text is done)
% \lineskip glue after it. Thus, space below is not quite equal to space
% above. But it's pretty close.
\def\Egroup{%
% To get correct interline space between the last line of the group
% and the first line afterwards, we have to propagate \prevdepth.
\endgraf % Not \par, as it may have been set to \lisppar.
\global\dimen1 = \prevdepth
\egroup % End the \vtop.
% \dimen0 is the vertical size of the group's box.
\dimen0 = \ht\groupbox \advance\dimen0 by \dp\groupbox
% \dimen2 is how much space is left on the page (more or less).
\dimen2 = \pageheight \advance\dimen2 by -\pagetotal
% if the group doesn't fit on the current page, and it's a big big
% group, force a page break.
\ifdim \dimen0 > \dimen2
\ifdim \pagetotal < \vfilllimit\pageheight
\page
\fi
\fi
\box\groupbox
\prevdepth = \dimen1
\checkinserts
}
%
% TeX puts in an \escapechar (i.e., `@') at the beginning of the help
% message, so this ends up printing `@group can only ...'.
%
\newhelp\groupinvalidhelp{%
group can only be used in environments such as @example,^^J%
where each line of input produces a line of output.}
% @need space-in-mils
% forces a page break if there is not space-in-mils remaining.
\newdimen\mil \mil=0.001in
% Old definition--didn't work.
%\parseargdef\need{\par %
%% This method tries to make TeX break the page naturally
%% if the depth of the box does not fit.
%{\baselineskip=0pt%
%\vtop to #1\mil{\vfil}\kern -#1\mil\nobreak
%\prevdepth=-1000pt
%}}
\parseargdef\need{%
% Ensure vertical mode, so we don't make a big box in the middle of a
% paragraph.
\par
%
% If the @need value is less than one line space, it's useless.
\dimen0 = #1\mil
\dimen2 = \ht\strutbox
\advance\dimen2 by \dp\strutbox
\ifdim\dimen0 > \dimen2
%
% Do a \strut just to make the height of this box be normal, so the
% normal leading is inserted relative to the preceding line.
% And a page break here is fine.
\vtop to #1\mil{\strut\vfil}%
%
% TeX does not even consider page breaks if a penalty added to the
% main vertical list is 10000 or more. But in order to see if the
% empty box we just added fits on the page, we must make it consider
% page breaks. On the other hand, we don't want to actually break the
% page after the empty box. So we use a penalty of 9999.
%
% There is an extremely small chance that TeX will actually break the
% page at this \penalty, if there are no other feasible breakpoints in
% sight. (If the user is using lots of big @group commands, which
% almost-but-not-quite fill up a page, TeX will have a hard time doing
% good page breaking, for example.) However, I could not construct an
% example where a page broke at this \penalty; if it happens in a real
% document, then we can reconsider our strategy.
\penalty9999
%
% Back up by the size of the box, whether we did a page break or not.
\kern -#1\mil
%
% Do not allow a page break right after this kern.
\nobreak
\fi
}
% @br forces paragraph break (and is undocumented).
\let\br = \par
% @page forces the start of a new page.
%
\def\page{\par\vfill\supereject}
% @exdent text....
% outputs text on separate line in roman font, starting at standard page margin
% This records the amount of indent in the innermost environment.
% That's how much \exdent should take out.
\newskip\exdentamount
% This defn is used inside fill environments such as @defun.
\parseargdef\exdent{\hfil\break\hbox{\kern -\exdentamount{\rm#1}}\hfil\break}
% This defn is used inside nofill environments such as @example.
\parseargdef\nofillexdent{{\advance \leftskip by -\exdentamount
\leftline{\hskip\leftskip{\rm#1}}}}
% @inmargin{WHICH}{TEXT} puts TEXT in the WHICH margin next to the current
% paragraph. For more general purposes, use the \margin insertion
% class. WHICH is `l' or `r'.
%
\newskip\inmarginspacing \inmarginspacing=1cm
\def\strutdepth{\dp\strutbox}
%
\def\doinmargin#1#2{\strut\vadjust{%
\nobreak
\kern-\strutdepth
\vtop to \strutdepth{%
\baselineskip=\strutdepth
\vss
% if you have multiple lines of stuff to put here, you'll need to
% make the vbox yourself of the appropriate size.
\ifx#1l%
\llap{\ignorespaces #2\hskip\inmarginspacing}%
\else
\rlap{\hskip\hsize \hskip\inmarginspacing \ignorespaces #2}%
\fi
\null
}%
}}
\def\inleftmargin{\doinmargin l}
\def\inrightmargin{\doinmargin r}
%
% @inmargin{TEXT [, RIGHT-TEXT]}
% (if RIGHT-TEXT is given, use TEXT for left page, RIGHT-TEXT for right;
% else use TEXT for both).
%
\def\inmargin#1{\parseinmargin #1,,\finish}
\def\parseinmargin#1,#2,#3\finish{% not perfect, but better than nothing.
\setbox0 = \hbox{\ignorespaces #2}%
\ifdim\wd0 > 0pt
\def\lefttext{#1}% have both texts
\def\righttext{#2}%
\else
\def\lefttext{#1}% have only one text
\def\righttext{#1}%
\fi
%
\ifodd\pageno
\def\temp{\inrightmargin\righttext}% odd page -> outside is right margin
\else
\def\temp{\inleftmargin\lefttext}%
\fi
\temp
}
% @include file insert text of that file as input.
%
\def\include{\parseargusing\filenamecatcodes\includezzz}
\def\includezzz#1{%
\pushthisfilestack
\def\thisfile{#1}%
{%
\makevalueexpandable
\def\temp{\input #1 }%
\expandafter
}\temp
\popthisfilestack
}
\def\filenamecatcodes{%
\catcode`\\=\other
\catcode`~=\other
\catcode`^=\other
\catcode`_=\other
\catcode`|=\other
\catcode`<=\other
\catcode`>=\other
\catcode`+=\other
\catcode`-=\other
}
\def\pushthisfilestack{%
\expandafter\pushthisfilestackX\popthisfilestack\StackTerm
}
\def\pushthisfilestackX{%
\expandafter\pushthisfilestackY\thisfile\StackTerm
}
\def\pushthisfilestackY #1\StackTerm #2\StackTerm {%
\gdef\popthisfilestack{\gdef\thisfile{#1}\gdef\popthisfilestack{#2}}%
}
\def\popthisfilestack{\errthisfilestackempty}
\def\errthisfilestackempty{\errmessage{Internal error:
the stack of filenames is empty.}}
\def\thisfile{}
% @center line
% outputs that line, centered.
%
\parseargdef\center{%
\ifhmode
\let\next\centerH
\else
\let\next\centerV
\fi
\next{\hfil \ignorespaces#1\unskip \hfil}%
}
\def\centerH#1{%
{%
\hfil\break
\advance\hsize by -\leftskip
\advance\hsize by -\rightskip
\line{#1}%
\break
}%
}
\def\centerV#1{\line{\kern\leftskip #1\kern\rightskip}}
% @sp n outputs n lines of vertical space
\parseargdef\sp{\vskip #1\baselineskip}
% @comment ...line which is ignored...
% @c is the same as @comment
% @ignore ... @end ignore is another way to write a comment
\def\comment{\begingroup \catcode`\^^M=\other%
\catcode`\@=\other \catcode`\{=\other \catcode`\}=\other%
\commentxxx}
{\catcode`\^^M=\other \gdef\commentxxx#1^^M{\endgroup}}
\let\c=\comment
% @paragraphindent NCHARS
% We'll use ems for NCHARS, close enough.
% NCHARS can also be the word `asis' or `none'.
% We cannot feasibly implement @paragraphindent asis, though.
%
\def\asisword{asis} % no translation, these are keywords
\def\noneword{none}
%
\parseargdef\paragraphindent{%
\def\temp{#1}%
\ifx\temp\asisword
\else
\ifx\temp\noneword
\defaultparindent = 0pt
\else
\defaultparindent = #1em
\fi
\fi
\parindent = \defaultparindent
}
% @exampleindent NCHARS
% We'll use ems for NCHARS like @paragraphindent.
% It seems @exampleindent asis isn't necessary, but
% I preserve it to make it similar to @paragraphindent.
\parseargdef\exampleindent{%
\def\temp{#1}%
\ifx\temp\asisword
\else
\ifx\temp\noneword
\lispnarrowing = 0pt
\else
\lispnarrowing = #1em
\fi
\fi
}
% @firstparagraphindent WORD
% If WORD is `none', then suppress indentation of the first paragraph
% after a section heading. If WORD is `insert', then do indent at such
% paragraphs.
%
% The paragraph indentation is suppressed or not by calling
% \suppressfirstparagraphindent, which the sectioning commands do.
% We switch the definition of this back and forth according to WORD.
% By default, we suppress indentation.
%
\def\suppressfirstparagraphindent{\dosuppressfirstparagraphindent}
\def\insertword{insert}
%
\parseargdef\firstparagraphindent{%
\def\temp{#1}%
\ifx\temp\noneword
\let\suppressfirstparagraphindent = \dosuppressfirstparagraphindent
\else\ifx\temp\insertword
\let\suppressfirstparagraphindent = \relax
\else
\errhelp = \EMsimple
\errmessage{Unknown @firstparagraphindent option `\temp'}%
\fi\fi
}
% Here is how we actually suppress indentation. Redefine \everypar to
% \kern backwards by \parindent, and then reset itself to empty.
%
% We also make \indent itself not actually do anything until the next
% paragraph.
%
\gdef\dosuppressfirstparagraphindent{%
\gdef\indent{%
\restorefirstparagraphindent
\indent
}%
\gdef\noindent{%
\restorefirstparagraphindent
\noindent
}%
\global\everypar = {%
\kern -\parindent
\restorefirstparagraphindent
}%
}
\gdef\restorefirstparagraphindent{%
\global \let \indent = \ptexindent
\global \let \noindent = \ptexnoindent
\global \everypar = {}%
}
% @asis just yields its argument. Used with @table, for example.
%
\def\asis#1{#1}
% @math outputs its argument in math mode.
%
% One complication: _ usually means subscripts, but it could also mean
% an actual _ character, as in @math{@var{some_variable} + 1}. So make
% _ active, and distinguish by seeing if the current family is \slfam,
% which is what @var uses.
{
\catcode`\_ = \active
\gdef\mathunderscore{%
\catcode`\_=\active
\def_{\ifnum\fam=\slfam \_\else\sb\fi}%
}
}
% Another complication: we want \\ (and @\) to output a \ character.
% FYI, plain.tex uses \\ as a temporary control sequence (why?), but
% this is not advertised and we don't care. Texinfo does not
% otherwise define @\.
%
% The \mathchar is class=0=ordinary, family=7=ttfam, position=5C=\.
\def\mathbackslash{\ifnum\fam=\ttfam \mathchar"075C \else\backslash \fi}
%
\def\math{%
\tex
\mathunderscore
\let\\ = \mathbackslash
\mathactive
$\finishmath
}
\def\finishmath#1{#1$\endgroup} % Close the group opened by \tex.
% Some active characters (such as <) are spaced differently in math.
% We have to reset their definitions in case the @math was an argument
% to a command which sets the catcodes (such as @item or @section).
%
{
\catcode`^ = \active
\catcode`< = \active
\catcode`> = \active
\catcode`+ = \active
\gdef\mathactive{%
\let^ = \ptexhat
\let< = \ptexless
\let> = \ptexgtr
\let+ = \ptexplus
}
}
% @bullet and @minus need the same treatment as @math, just above.
\def\bullet{$\ptexbullet$}
\def\minus{$-$}
% @dots{} outputs an ellipsis using the current font.
% We do .5em per period so that it has the same spacing in the cm
% typewriter fonts as three actual period characters; on the other hand,
% in other typewriter fonts three periods are wider than 1.5em. So do
% whichever is larger.
%
\def\dots{%
\leavevmode
\setbox0=\hbox{...}% get width of three periods
\ifdim\wd0 > 1.5em
\dimen0 = \wd0
\else
\dimen0 = 1.5em
\fi
\hbox to \dimen0{%
\hskip 0pt plus.25fil
.\hskip 0pt plus1fil
.\hskip 0pt plus1fil
.\hskip 0pt plus.5fil
}%
}
% @enddots{} is an end-of-sentence ellipsis.
%
\def\enddots{%
\dots
\spacefactor=\endofsentencespacefactor
}
% @comma{} is so commas can be inserted into text without messing up
% Texinfo's parsing.
%
\let\comma = ,
% @refill is a no-op.
\let\refill=\relax
% If working on a large document in chapters, it is convenient to
% be able to disable indexing, cross-referencing, and contents, for test runs.
% This is done with @novalidate (before @setfilename).
%
\newif\iflinks \linkstrue % by default we want the aux files.
\let\novalidate = \linksfalse
% @setfilename is done at the beginning of every texinfo file.
% So open here the files we need to have open while reading the input.
% This makes it possible to make a .fmt file for texinfo.
\def\setfilename{%
\fixbackslash % Turn off hack to swallow `\input texinfo'.
\iflinks
\tryauxfile
% Open the new aux file. TeX will close it automatically at exit.
\immediate\openout\auxfile=\jobname.aux
\fi % \openindices needs to do some work in any case.
\openindices
\let\setfilename=\comment % Ignore extra @setfilename cmds.
%
% If texinfo.cnf is present on the system, read it.
% Useful for site-wide @afourpaper, etc.
\openin 1 texinfo.cnf
\ifeof 1 \else \input texinfo.cnf \fi
\closein 1
%
\comment % Ignore the actual filename.
}
% Called from \setfilename.
%
\def\openindices{%
\newindex{cp}%
\newcodeindex{fn}%
\newcodeindex{vr}%
\newcodeindex{tp}%
\newcodeindex{ky}%
\newcodeindex{pg}%
}
% @bye.
\outer\def\bye{\pagealignmacro\tracingstats=1\ptexend}
\message{pdf,}
% adobe `portable' document format
\newcount\tempnum
\newcount\lnkcount
\newtoks\filename
\newcount\filenamelength
\newcount\pgn
\newtoks\toksA
\newtoks\toksB
\newtoks\toksC
\newtoks\toksD
\newbox\boxA
\newcount\countA
\newif\ifpdf
\newif\ifpdfmakepagedest
% when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1
% can be set). So we test for \relax and 0 as well as \undefined,
% borrowed from ifpdf.sty.
\ifx\pdfoutput\undefined
\else
\ifx\pdfoutput\relax
\else
\ifcase\pdfoutput
\else
\pdftrue
\fi
\fi
\fi
% PDF uses PostScript string constants for the names of xref targets,
% for display in the outlines, and in other places. Thus, we have to
% double any backslashes. Otherwise, a name like "\node" will be
% interpreted as a newline (\n), followed by o, d, e. Not good.
% http://www.ntg.nl/pipermail/ntg-pdftex/2004-July/000654.html
% (and related messages, the final outcome is that it is up to the TeX
% user to double the backslashes and otherwise make the string valid, so
% that's what we do).
% double active backslashes.
%
{\catcode`\@=0 \catcode`\\=\active
@gdef@activebackslashdouble{%
@catcode`@\=@active
@let\=@doublebackslash}
}
% To handle parens, we must adopt a different approach, since parens are
% not active characters. hyperref.dtx (which has the same problem as
% us) handles it with this amazing macro to replace tokens. I've
% tinkered with it a little for texinfo, but it's definitely from there.
%
% #1 is the tokens to replace.
% #2 is the replacement.
% #3 is the control sequence with the string.
%
\def\HyPsdSubst#1#2#3{%
\def\HyPsdReplace##1#1##2\END{%
##1%
\ifx\\##2\\%
\else
#2%
\HyReturnAfterFi{%
\HyPsdReplace##2\END
}%
\fi
}%
\xdef#3{\expandafter\HyPsdReplace#3#1\END}%
}
\long\def\HyReturnAfterFi#1\fi{\fi#1}
% #1 is a control sequence in which to do the replacements.
\def\backslashparens#1{%
\xdef#1{#1}% redefine it as its expansion; the definition is simply
% \lastnode when called from \setref -> \pdfmkdest.
\HyPsdSubst{(}{\realbackslash(}{#1}%
\HyPsdSubst{)}{\realbackslash)}{#1}%
}
\ifpdf
\input pdfcolor
\pdfcatalog{/PageMode /UseOutlines}%
% #1 is image name, #2 width (might be empty/whitespace), #3 height (ditto).
\def\dopdfimage#1#2#3{%
\def\imagewidth{#2}\setbox0 = \hbox{\ignorespaces #2}%
\def\imageheight{#3}\setbox2 = \hbox{\ignorespaces #3}%
% without \immediate, pdftex seg faults when the same image is
% included twice. (Version 3.14159-pre-1.0-unofficial-20010704.)
\ifnum\pdftexversion < 14
\immediate\pdfimage
\else
\immediate\pdfximage
\fi
\ifdim \wd0 >0pt width \imagewidth \fi
\ifdim \wd2 >0pt height \imageheight \fi
\ifnum\pdftexversion<13
#1.pdf%
\else
{#1.pdf}%
\fi
\ifnum\pdftexversion < 14 \else
\pdfrefximage \pdflastximage
\fi}
\def\pdfmkdest#1{{%
% We have to set dummies so commands such as @code, and characters
% such as \, aren't expanded when present in a section title.
\atdummies
\activebackslashdouble
\def\pdfdestname{#1}%
\backslashparens\pdfdestname
\pdfdest name{\pdfdestname} xyz%
}}%
%
% used to mark target names; must be expandable.
\def\pdfmkpgn#1{#1}%
%
\let\linkcolor = \Blue % was Cyan, but that seems light?
\def\endlink{\Black\pdfendlink}
% Adding outlines to PDF; macros for calculating structure of outlines
% come from Petr Olsak
\def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0%
\else \csname#1\endcsname \fi}
\def\advancenumber#1{\tempnum=\expnumber{#1}\relax
\advance\tempnum by 1
\expandafter\xdef\csname#1\endcsname{\the\tempnum}}
%
% #1 is the section text, which is what will be displayed in the
% outline by the pdf viewer. #2 is the pdf expression for the number
% of subentries (or empty, for subsubsections). #3 is the node text,
% which might be empty if this toc entry had no corresponding node.
% #4 is the page number
%
\def\dopdfoutline#1#2#3#4{%
% Generate a link to the node text if that exists; else, use the
% page number. We could generate a destination for the section
% text in the case where a section has no node, but it doesn't
% seem worth the trouble, since most documents are normally structured.
\def\pdfoutlinedest{#3}%
\ifx\pdfoutlinedest\empty
\def\pdfoutlinedest{#4}%
\else
% Doubled backslashes in the name.
{\activebackslashdouble \xdef\pdfoutlinedest{#3}%
\backslashparens\pdfoutlinedest}%
\fi
%
% Also double the backslashes in the display string.
{\activebackslashdouble \xdef\pdfoutlinetext{#1}%
\backslashparens\pdfoutlinetext}%
%
\pdfoutline goto name{\pdfmkpgn{\pdfoutlinedest}}#2{\pdfoutlinetext}%
}
%
\def\pdfmakeoutlines{%
\begingroup
% Thanh's hack / proper braces in bookmarks
\edef\mylbrace{\iftrue \string{\else}\fi}\let\{=\mylbrace
\edef\myrbrace{\iffalse{\else\string}\fi}\let\}=\myrbrace
%
% Read toc silently, to get counts of subentries for \pdfoutline.
\def\numchapentry##1##2##3##4{%
\def\thischapnum{##2}%
\def\thissecnum{0}%
\def\thissubsecnum{0}%
}%
\def\numsecentry##1##2##3##4{%
\advancenumber{chap\thischapnum}%
\def\thissecnum{##2}%
\def\thissubsecnum{0}%
}%
\def\numsubsecentry##1##2##3##4{%
\advancenumber{sec\thissecnum}%
\def\thissubsecnum{##2}%
}%
\def\numsubsubsecentry##1##2##3##4{%
\advancenumber{subsec\thissubsecnum}%
}%
\def\thischapnum{0}%
\def\thissecnum{0}%
\def\thissubsecnum{0}%
%
% use \def rather than \let here because we redefine \chapentry et
% al. a second time, below.
\def\appentry{\numchapentry}%
\def\appsecentry{\numsecentry}%
\def\appsubsecentry{\numsubsecentry}%
\def\appsubsubsecentry{\numsubsubsecentry}%
\def\unnchapentry{\numchapentry}%
\def\unnsecentry{\numsecentry}%
\def\unnsubsecentry{\numsubsecentry}%
\def\unnsubsubsecentry{\numsubsubsecentry}%
\readdatafile{toc}%
%
% Read toc second time, this time actually producing the outlines.
% The `-' means take the \expnumber as the absolute number of
% subentries, which we calculated on our first read of the .toc above.
%
% We use the node names as the destinations.
\def\numchapentry##1##2##3##4{%
\dopdfoutline{##1}{count-\expnumber{chap##2}}{##3}{##4}}%
\def\numsecentry##1##2##3##4{%
\dopdfoutline{##1}{count-\expnumber{sec##2}}{##3}{##4}}%
\def\numsubsecentry##1##2##3##4{%
\dopdfoutline{##1}{count-\expnumber{subsec##2}}{##3}{##4}}%
\def\numsubsubsecentry##1##2##3##4{% count is always zero
\dopdfoutline{##1}{}{##3}{##4}}%
%
% PDF outlines are displayed using system fonts, instead of
% document fonts. Therefore we cannot use special characters,
% since the encoding is unknown. For example, the eogonek from
% Latin 2 (0xea) gets translated to a | character. Info from
% Staszek Wawrykiewicz, 19 Jan 2004 04:09:24 +0100.
%
% xx to do this right, we have to translate 8-bit characters to
% their "best" equivalent, based on the @documentencoding. Right
% now, I guess we'll just let the pdf reader have its way.
\indexnofonts
\setupdatafile
\catcode`\\=\active \otherbackslash
\input \jobname.toc
\endgroup
}
%
\def\skipspaces#1{\def\PP{#1}\def\D{|}%
\ifx\PP\D\let\nextsp\relax
\else\let\nextsp\skipspaces
\ifx\p\space\else\addtokens{\filename}{\PP}%
\advance\filenamelength by 1
\fi
\fi
\nextsp}
\def\getfilename#1{\filenamelength=0\expandafter\skipspaces#1|\relax}
\ifnum\pdftexversion < 14
\let \startlink \pdfannotlink
\else
\let \startlink \pdfstartlink
\fi
% make a live url in pdf output.
\def\pdfurl#1{%
\begingroup
% it seems we really need yet another set of dummies; have not
% tried to figure out what each command should do in the context
% of @url. for now, just make @/ a no-op, that's the only one
% people have actually reported a problem with.
%
\normalturnoffactive
\def\@{@}%
\let\/=\empty
\makevalueexpandable
\leavevmode\Red
\startlink attr{/Border [0 0 0]}%
user{/Subtype /Link /A << /S /URI /URI (#1) >>}%
\endgroup}
\def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}}
\def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks}
\def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks}
\def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}}
\def\maketoks{%
\expandafter\poptoks\the\toksA|ENDTOKS|\relax
\ifx\first0\adn0
\else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3
\else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6
\else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9
\else
\ifnum0=\countA\else\makelink\fi
\ifx\first.\let\next=\done\else
\let\next=\maketoks
\addtokens{\toksB}{\the\toksD}
\ifx\first,\addtokens{\toksB}{\space}\fi
\fi
\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
\next}
\def\makelink{\addtokens{\toksB}%
{\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0}
\def\pdflink#1{%
\startlink attr{/Border [0 0 0]} goto name{\pdfmkpgn{#1}}
\linkcolor #1\endlink}
\def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st}
\else
\let\pdfmkdest = \gobble
\let\pdfurl = \gobble
\let\endlink = \relax
\let\linkcolor = \relax
\let\pdfmakeoutlines = \relax
\fi % \ifx\pdfoutput
\message{fonts,}
% Change the current font style to #1, remembering it in \curfontstyle.
% For now, we do not accumulate font styles: @b{@i{foo}} prints foo in
% italics, not bold italics.
%
\def\setfontstyle#1{%
\def\curfontstyle{#1}% not as a control sequence, because we are \edef'd.
\csname ten#1\endcsname % change the current font
}
% Select #1 fonts with the current style.
%
\def\selectfonts#1{\csname #1fonts\endcsname \csname\curfontstyle\endcsname}
\def\rm{\fam=0 \setfontstyle{rm}}
\def\it{\fam=\itfam \setfontstyle{it}}
\def\sl{\fam=\slfam \setfontstyle{sl}}
\def\bf{\fam=\bffam \setfontstyle{bf}}\def\bfstylename{bf}
\def\tt{\fam=\ttfam \setfontstyle{tt}}
% Texinfo sort of supports the sans serif font style, which plain TeX does not.
% So we set up a \sf.
\newfam\sffam
\def\sf{\fam=\sffam \setfontstyle{sf}}
\let\li = \sf % Sometimes we call it \li, not \sf.
% We don't need math for this font style.
\def\ttsl{\setfontstyle{ttsl}}
% Default leading.
\newdimen\textleading \textleading = 13.2pt
% Set the baselineskip to #1, and the lineskip and strut size
% correspondingly. There is no deep meaning behind these magic numbers
% used as factors; they just match (closely enough) what Knuth defined.
%
\def\lineskipfactor{.08333}
\def\strutheightpercent{.70833}
\def\strutdepthpercent {.29167}
%
\def\setleading#1{%
\normalbaselineskip = #1\relax
\normallineskip = \lineskipfactor\normalbaselineskip
\normalbaselines
\setbox\strutbox =\hbox{%
\vrule width0pt height\strutheightpercent\baselineskip
depth \strutdepthpercent \baselineskip
}%
}
% Set the font macro #1 to the font named #2, adding on the
% specified font prefix (normally `cm').
% #3 is the font's design size, #4 is a scale factor
\def\setfont#1#2#3#4{\font#1=\fontprefix#2#3 scaled #4}
% Use cm as the default font prefix.
% To specify the font prefix, you must define \fontprefix
% before you read in texinfo.tex.
\ifx\fontprefix\undefined
\def\fontprefix{cm}
\fi
% Support font families that don't use the same naming scheme as CM.
\def\rmshape{r}
\def\rmbshape{bx} %where the normal face is bold
\def\bfshape{b}
\def\bxshape{bx}
\def\ttshape{tt}
\def\ttbshape{tt}
\def\ttslshape{sltt}
\def\itshape{ti}
\def\itbshape{bxti}
\def\slshape{sl}
\def\slbshape{bxsl}
\def\sfshape{ss}
\def\sfbshape{ss}
\def\scshape{csc}
\def\scbshape{csc}
% Definitions for a main text size of 11pt. This is the default in
% Texinfo.
%
\def\definetextfontsizexi{
% Text fonts (11.2pt, magstep1).
\def\textnominalsize{11pt}
\edef\mainmagstep{\magstephalf}
\setfont\textrm\rmshape{10}{\mainmagstep}
\setfont\texttt\ttshape{10}{\mainmagstep}
\setfont\textbf\bfshape{10}{\mainmagstep}
\setfont\textit\itshape{10}{\mainmagstep}
\setfont\textsl\slshape{10}{\mainmagstep}
\setfont\textsf\sfshape{10}{\mainmagstep}
\setfont\textsc\scshape{10}{\mainmagstep}
\setfont\textttsl\ttslshape{10}{\mainmagstep}
\font\texti=cmmi10 scaled \mainmagstep
\font\textsy=cmsy10 scaled \mainmagstep
% A few fonts for @defun names and args.
\setfont\defbf\bfshape{10}{\magstep1}
\setfont\deftt\ttshape{10}{\magstep1}
\setfont\defttsl\ttslshape{10}{\magstep1}
\def\df{\let\tentt=\deftt \let\tenbf = \defbf \let\tenttsl=\defttsl \bf}
% Fonts for indices, footnotes, small examples (9pt).
\def\smallnominalsize{9pt}
\setfont\smallrm\rmshape{9}{1000}
\setfont\smalltt\ttshape{9}{1000}
\setfont\smallbf\bfshape{10}{900}
\setfont\smallit\itshape{9}{1000}
\setfont\smallsl\slshape{9}{1000}
\setfont\smallsf\sfshape{9}{1000}
\setfont\smallsc\scshape{10}{900}
\setfont\smallttsl\ttslshape{10}{900}
\font\smalli=cmmi9
\font\smallsy=cmsy9
% Fonts for small examples (8pt).
\def\smallernominalsize{8pt}
\setfont\smallerrm\rmshape{8}{1000}
\setfont\smallertt\ttshape{8}{1000}
\setfont\smallerbf\bfshape{10}{800}
\setfont\smallerit\itshape{8}{1000}
\setfont\smallersl\slshape{8}{1000}
\setfont\smallersf\sfshape{8}{1000}
\setfont\smallersc\scshape{10}{800}
\setfont\smallerttsl\ttslshape{10}{800}
\font\smalleri=cmmi8
\font\smallersy=cmsy8
% Fonts for title page (20.4pt):
\def\titlenominalsize{20pt}
\setfont\titlerm\rmbshape{12}{\magstep3}
\setfont\titleit\itbshape{10}{\magstep4}
\setfont\titlesl\slbshape{10}{\magstep4}
\setfont\titlett\ttbshape{12}{\magstep3}
\setfont\titlettsl\ttslshape{10}{\magstep4}
\setfont\titlesf\sfbshape{17}{\magstep1}
\let\titlebf=\titlerm
\setfont\titlesc\scbshape{10}{\magstep4}
\font\titlei=cmmi12 scaled \magstep3
\font\titlesy=cmsy10 scaled \magstep4
\def\authorrm{\secrm}
\def\authortt{\sectt}
% Chapter (and unnumbered) fonts (17.28pt).
\def\chapnominalsize{17pt}
\setfont\chaprm\rmbshape{12}{\magstep2}
\setfont\chapit\itbshape{10}{\magstep3}
\setfont\chapsl\slbshape{10}{\magstep3}
\setfont\chaptt\ttbshape{12}{\magstep2}
\setfont\chapttsl\ttslshape{10}{\magstep3}
\setfont\chapsf\sfbshape{17}{1000}
\let\chapbf=\chaprm
\setfont\chapsc\scbshape{10}{\magstep3}
\font\chapi=cmmi12 scaled \magstep2
\font\chapsy=cmsy10 scaled \magstep3
% Section fonts (14.4pt).
\def\secnominalsize{14pt}
\setfont\secrm\rmbshape{12}{\magstep1}
\setfont\secit\itbshape{10}{\magstep2}
\setfont\secsl\slbshape{10}{\magstep2}
\setfont\sectt\ttbshape{12}{\magstep1}
\setfont\secttsl\ttslshape{10}{\magstep2}
\setfont\secsf\sfbshape{12}{\magstep1}
\let\secbf\secrm
\setfont\secsc\scbshape{10}{\magstep2}
\font\seci=cmmi12 scaled \magstep1
\font\secsy=cmsy10 scaled \magstep2
% Subsection fonts (13.15pt).
\def\ssecnominalsize{13pt}
\setfont\ssecrm\rmbshape{12}{\magstephalf}
\setfont\ssecit\itbshape{10}{1315}
\setfont\ssecsl\slbshape{10}{1315}
\setfont\ssectt\ttbshape{12}{\magstephalf}
\setfont\ssecttsl\ttslshape{10}{1315}
\setfont\ssecsf\sfbshape{12}{\magstephalf}
\let\ssecbf\ssecrm
\setfont\ssecsc\scbshape{10}{1315}
\font\sseci=cmmi12 scaled \magstephalf
\font\ssecsy=cmsy10 scaled 1315
% Reduced fonts for @acro in text (10pt).
\def\reducednominalsize{10pt}
\setfont\reducedrm\rmshape{10}{1000}
\setfont\reducedtt\ttshape{10}{1000}
\setfont\reducedbf\bfshape{10}{1000}
\setfont\reducedit\itshape{10}{1000}
\setfont\reducedsl\slshape{10}{1000}
\setfont\reducedsf\sfshape{10}{1000}
\setfont\reducedsc\scshape{10}{1000}
\setfont\reducedttsl\ttslshape{10}{1000}
\font\reducedi=cmmi10
\font\reducedsy=cmsy10
% reset the current fonts
\textfonts
\rm
} % end of 11pt text font size definitions
% Definitions to make the main text be 10pt Computer Modern, with
% section, chapter, etc., sizes following suit. This is for the GNU
% Press printing of the Emacs 22 manual. Maybe other manuals in the
% future. Used with @smallbook, which sets the leading to 12pt.
%
\def\definetextfontsizex{%
% Text fonts (10pt).
\def\textnominalsize{10pt}
\edef\mainmagstep{1000}
\setfont\textrm\rmshape{10}{\mainmagstep}
\setfont\texttt\ttshape{10}{\mainmagstep}
\setfont\textbf\bfshape{10}{\mainmagstep}
\setfont\textit\itshape{10}{\mainmagstep}
\setfont\textsl\slshape{10}{\mainmagstep}
\setfont\textsf\sfshape{10}{\mainmagstep}
\setfont\textsc\scshape{10}{\mainmagstep}
\setfont\textttsl\ttslshape{10}{\mainmagstep}
\font\texti=cmmi10 scaled \mainmagstep
\font\textsy=cmsy10 scaled \mainmagstep
% A few fonts for @defun names and args.
\setfont\defbf\bfshape{10}{\magstephalf}
\setfont\deftt\ttshape{10}{\magstephalf}
\setfont\defttsl\ttslshape{10}{\magstephalf}
\def\df{\let\tentt=\deftt \let\tenbf = \defbf \let\tenttsl=\defttsl \bf}
% Fonts for indices, footnotes, small examples (9pt).
\def\smallnominalsize{9pt}
\setfont\smallrm\rmshape{9}{1000}
\setfont\smalltt\ttshape{9}{1000}
\setfont\smallbf\bfshape{10}{900}
\setfont\smallit\itshape{9}{1000}
\setfont\smallsl\slshape{9}{1000}
\setfont\smallsf\sfshape{9}{1000}
\setfont\smallsc\scshape{10}{900}
\setfont\smallttsl\ttslshape{10}{900}
\font\smalli=cmmi9
\font\smallsy=cmsy9
% Fonts for small examples (8pt).
\def\smallernominalsize{8pt}
\setfont\smallerrm\rmshape{8}{1000}
\setfont\smallertt\ttshape{8}{1000}
\setfont\smallerbf\bfshape{10}{800}
\setfont\smallerit\itshape{8}{1000}
\setfont\smallersl\slshape{8}{1000}
\setfont\smallersf\sfshape{8}{1000}
\setfont\smallersc\scshape{10}{800}
\setfont\smallerttsl\ttslshape{10}{800}
\font\smalleri=cmmi8
\font\smallersy=cmsy8
% Fonts for title page (20.4pt):
\def\titlenominalsize{20pt}
\setfont\titlerm\rmbshape{12}{\magstep3}
\setfont\titleit\itbshape{10}{\magstep4}
\setfont\titlesl\slbshape{10}{\magstep4}
\setfont\titlett\ttbshape{12}{\magstep3}
\setfont\titlettsl\ttslshape{10}{\magstep4}
\setfont\titlesf\sfbshape{17}{\magstep1}
\let\titlebf=\titlerm
\setfont\titlesc\scbshape{10}{\magstep4}
\font\titlei=cmmi12 scaled \magstep3
\font\titlesy=cmsy10 scaled \magstep4
\def\authorrm{\secrm}
\def\authortt{\sectt}
% Chapter fonts (14.4pt).
\def\chapnominalsize{14pt}
\setfont\chaprm\rmbshape{12}{\magstep1}
\setfont\chapit\itbshape{10}{\magstep2}
\setfont\chapsl\slbshape{10}{\magstep2}
\setfont\chaptt\ttbshape{12}{\magstep1}
\setfont\chapttsl\ttslshape{10}{\magstep2}
\setfont\chapsf\sfbshape{12}{\magstep1}
\let\chapbf\chaprm
\setfont\chapsc\scbshape{10}{\magstep2}
\font\chapi=cmmi12 scaled \magstep1
\font\chapsy=cmsy10 scaled \magstep2
% Section fonts (12pt).
\def\secnominalsize{12pt}
\setfont\secrm\rmbshape{12}{1000}
\setfont\secit\itbshape{10}{\magstep1}
\setfont\secsl\slbshape{10}{\magstep1}
\setfont\sectt\ttbshape{12}{1000}
\setfont\secttsl\ttslshape{10}{\magstep1}
\setfont\secsf\sfbshape{12}{1000}
\let\secbf\secrm
\setfont\secsc\scbshape{10}{\magstep1}
\font\seci=cmmi12
\font\secsy=cmsy10 scaled \magstep1
% Subsection fonts (10pt).
\def\ssecnominalsize{10pt}
\setfont\ssecrm\rmbshape{10}{1000}
\setfont\ssecit\itbshape{10}{1000}
\setfont\ssecsl\slbshape{10}{1000}
\setfont\ssectt\ttbshape{10}{1000}
\setfont\ssecttsl\ttslshape{10}{1000}
\setfont\ssecsf\sfbshape{10}{1000}
\let\ssecbf\ssecrm
\setfont\ssecsc\scbshape{10}{1000}
\font\sseci=cmmi10
\font\ssecsy=cmsy10
% Reduced fonts for @acro in text (9pt).
\def\reducednominalsize{9pt}
\setfont\reducedrm\rmshape{9}{1000}
\setfont\reducedtt\ttshape{9}{1000}
\setfont\reducedbf\bfshape{10}{900}
\setfont\reducedit\itshape{9}{1000}
\setfont\reducedsl\slshape{9}{1000}
\setfont\reducedsf\sfshape{9}{1000}
\setfont\reducedsc\scshape{10}{900}
\setfont\reducedttsl\ttslshape{10}{900}
\font\reducedi=cmmi9
\font\reducedsy=cmsy9
% reduce space between paragraphs
\divide\parskip by 2
% reset the current fonts
\textfonts
\rm
} % end of 10pt text font size definitions
% We provide the user-level command
% @fonttextsize 10
% (or 11) to redefine the text font size. pt is assumed.
%
\def\xword{10}
\def\xiword{11}
%
\parseargdef\fonttextsize{%
\def\textsizearg{#1}%
\wlog{doing @fonttextsize \textsizearg}%
%
% Set \globaldefs so that documents can use this inside @tex, since
% makeinfo 4.8 does not support it, but we need it nonetheless.
%
\begingroup \globaldefs=1
\ifx\textsizearg\xword \definetextfontsizex
\else \ifx\textsizearg\xiword \definetextfontsizexi
\else
\errhelp=\EMsimple
\errmessage{@fonttextsize only supports `10' or `11', not `\textsizearg'}
\fi\fi
\endgroup
}
% In order for the font changes to affect most math symbols and letters,
% we have to define the \textfont of the standard families. Since
% texinfo doesn't allow for producing subscripts and superscripts except
% in the main text, we don't bother to reset \scriptfont and
% \scriptscriptfont (which would also require loading a lot more fonts).
%
\def\resetmathfonts{%
\textfont0=\tenrm \textfont1=\teni \textfont2=\tensy
\textfont\itfam=\tenit \textfont\slfam=\tensl \textfont\bffam=\tenbf
\textfont\ttfam=\tentt \textfont\sffam=\tensf
}
% The font-changing commands redefine the meanings of \tenSTYLE, instead
% of just \STYLE. We do this because \STYLE needs to also set the
% current \fam for math mode. Our \STYLE (e.g., \rm) commands hardwire
% \tenSTYLE to set the current font.
%
% Each font-changing command also sets the names \lsize (one size lower)
% and \lllsize (three sizes lower). These relative commands are used in
% the LaTeX logo and acronyms.
%
% This all needs generalizing, badly.
%
\def\textfonts{%
\let\tenrm=\textrm \let\tenit=\textit \let\tensl=\textsl
\let\tenbf=\textbf \let\tentt=\texttt \let\smallcaps=\textsc
\let\tensf=\textsf \let\teni=\texti \let\tensy=\textsy
\let\tenttsl=\textttsl
\def\curfontsize{text}%
\def\lsize{reduced}\def\lllsize{smaller}%
\resetmathfonts \setleading{\textleading}}
\def\titlefonts{%
\let\tenrm=\titlerm \let\tenit=\titleit \let\tensl=\titlesl
\let\tenbf=\titlebf \let\tentt=\titlett \let\smallcaps=\titlesc
\let\tensf=\titlesf \let\teni=\titlei \let\tensy=\titlesy
\let\tenttsl=\titlettsl
\def\curfontsize{title}%
\def\lsize{chap}\def\lllsize{subsec}%
\resetmathfonts \setleading{25pt}}
\def\titlefont#1{{\titlefonts\rm #1}}
\def\chapfonts{%
\let\tenrm=\chaprm \let\tenit=\chapit \let\tensl=\chapsl
\let\tenbf=\chapbf \let\tentt=\chaptt \let\smallcaps=\chapsc
\let\tensf=\chapsf \let\teni=\chapi \let\tensy=\chapsy
\let\tenttsl=\chapttsl
\def\curfontsize{chap}%
\def\lsize{sec}\def\lllsize{text}%
\resetmathfonts \setleading{19pt}}
\def\secfonts{%
\let\tenrm=\secrm \let\tenit=\secit \let\tensl=\secsl
\let\tenbf=\secbf \let\tentt=\sectt \let\smallcaps=\secsc
\let\tensf=\secsf \let\teni=\seci \let\tensy=\secsy
\let\tenttsl=\secttsl
\def\curfontsize{sec}%
\def\lsize{subsec}\def\lllsize{reduced}%
\resetmathfonts \setleading{16pt}}
\def\subsecfonts{%
\let\tenrm=\ssecrm \let\tenit=\ssecit \let\tensl=\ssecsl
\let\tenbf=\ssecbf \let\tentt=\ssectt \let\smallcaps=\ssecsc
\let\tensf=\ssecsf \let\teni=\sseci \let\tensy=\ssecsy
\let\tenttsl=\ssecttsl
\def\curfontsize{ssec}%
\def\lsize{text}\def\lllsize{small}%
\resetmathfonts \setleading{15pt}}
\let\subsubsecfonts = \subsecfonts
\def\reducedfonts{%
\let\tenrm=\reducedrm \let\tenit=\reducedit \let\tensl=\reducedsl
\let\tenbf=\reducedbf \let\tentt=\reducedtt \let\reducedcaps=\reducedsc
\let\tensf=\reducedsf \let\teni=\reducedi \let\tensy=\reducedsy
\let\tenttsl=\reducedttsl
\def\curfontsize{reduced}%
\def\lsize{small}\def\lllsize{smaller}%
\resetmathfonts \setleading{10.5pt}}
\def\smallfonts{%
\let\tenrm=\smallrm \let\tenit=\smallit \let\tensl=\smallsl
\let\tenbf=\smallbf \let\tentt=\smalltt \let\smallcaps=\smallsc
\let\tensf=\smallsf \let\teni=\smalli \let\tensy=\smallsy
\let\tenttsl=\smallttsl
\def\curfontsize{small}%
\def\lsize{smaller}\def\lllsize{smaller}%
\resetmathfonts \setleading{10.5pt}}
\def\smallerfonts{%
\let\tenrm=\smallerrm \let\tenit=\smallerit \let\tensl=\smallersl
\let\tenbf=\smallerbf \let\tentt=\smallertt \let\smallcaps=\smallersc
\let\tensf=\smallersf \let\teni=\smalleri \let\tensy=\smallersy
\let\tenttsl=\smallerttsl
\def\curfontsize{smaller}%
\def\lsize{smaller}\def\lllsize{smaller}%
\resetmathfonts \setleading{9.5pt}}
% Set the fonts to use with the @small... environments.
\let\smallexamplefonts = \smallfonts
% About \smallexamplefonts. If we use \smallfonts (9pt), @smallexample
% can fit this many characters:
% 8.5x11=86 smallbook=72 a4=90 a5=69
% If we use \scriptfonts (8pt), then we can fit this many characters:
% 8.5x11=90+ smallbook=80 a4=90+ a5=77
% For me, subjectively, the few extra characters that fit aren't worth
% the additional smallness of 8pt. So I'm making the default 9pt.
%
% By the way, for comparison, here's what fits with @example (10pt):
% 8.5x11=71 smallbook=60 a4=75 a5=58
%
% I wish the USA used A4 paper.
% --karl, 24jan03.
% Set up the default fonts, so we can use them for creating boxes.
%
\definetextfontsizexi
% Define these so they can be easily changed for other fonts.
\def\angleleft{$\langle$}
\def\angleright{$\rangle$}
% Count depth in font-changes, for error checks
\newcount\fontdepth \fontdepth=0
% Fonts for short table of contents.
\setfont\shortcontrm\rmshape{12}{1000}
\setfont\shortcontbf\bfshape{10}{\magstep1} % no cmb12
\setfont\shortcontsl\slshape{12}{1000}
\setfont\shortconttt\ttshape{12}{1000}
%% Add scribe-like font environments, plus @l for inline lisp (usually sans
%% serif) and @ii for TeX italic
% \smartitalic{ARG} outputs arg in italics, followed by an italic correction
% unless the following character is such as not to need one.
\def\smartitalicx{\ifx\next,\else\ifx\next-\else\ifx\next.\else
\ptexslash\fi\fi\fi}
\def\smartslanted#1{{\ifusingtt\ttsl\sl #1}\futurelet\next\smartitalicx}
\def\smartitalic#1{{\ifusingtt\ttsl\it #1}\futurelet\next\smartitalicx}
% like \smartslanted except unconditionally uses \ttsl.
% @var is set to this for defun arguments.
\def\ttslanted#1{{\ttsl #1}\futurelet\next\smartitalicx}
% like \smartslanted except unconditionally use \sl. We never want
% ttsl for book titles, do we?
\def\cite#1{{\sl #1}\futurelet\next\smartitalicx}
\let\i=\smartitalic
\let\slanted=\smartslanted
\let\var=\smartslanted
\let\dfn=\smartslanted
\let\emph=\smartitalic
% @b, explicit bold.
\def\b#1{{\bf #1}}
\let\strong=\b
% @sansserif, explicit sans.
\def\sansserif#1{{\sf #1}}
% We can't just use \exhyphenpenalty, because that only has effect at
% the end of a paragraph. Restore normal hyphenation at the end of the
% group within which \nohyphenation is presumably called.
%
\def\nohyphenation{\hyphenchar\font = -1 \aftergroup\restorehyphenation}
\def\restorehyphenation{\hyphenchar\font = `- }
% Set sfcode to normal for the chars that usually have another value.
% Can't use plain's \frenchspacing because it uses the `\x notation, and
% sometimes \x has an active definition that messes things up.
%
\catcode`@=11
\def\plainfrenchspacing{%
\sfcode\dotChar =\@m \sfcode\questChar=\@m \sfcode\exclamChar=\@m
\sfcode\colonChar=\@m \sfcode\semiChar =\@m \sfcode\commaChar =\@m
\def\endofsentencespacefactor{1000}% for @. and friends
}
\def\plainnonfrenchspacing{%
\sfcode`\.3000\sfcode`\?3000\sfcode`\!3000
\sfcode`\:2000\sfcode`\;1500\sfcode`\,1250
\def\endofsentencespacefactor{3000}% for @. and friends
}
\catcode`@=\other
\def\endofsentencespacefactor{3000}% default
\def\t#1{%
{\tt \rawbackslash \plainfrenchspacing #1}%
\null
}
\def\samp#1{`\tclose{#1}'\null}
\setfont\keyrm\rmshape{8}{1000}
\font\keysy=cmsy9
\def\key#1{{\keyrm\textfont2=\keysy \leavevmode\hbox{%
\raise0.4pt\hbox{\angleleft}\kern-.08em\vtop{%
\vbox{\hrule\kern-0.4pt
\hbox{\raise0.4pt\hbox{\vphantom{\angleleft}}#1}}%
\kern-0.4pt\hrule}%
\kern-.06em\raise0.4pt\hbox{\angleright}}}}
% The old definition, with no lozenge:
%\def\key #1{{\ttsl \nohyphenation \uppercase{#1}}\null}
\def\ctrl #1{{\tt \rawbackslash \hat}#1}
% @file, @option are the same as @samp.
\let\file=\samp
\let\option=\samp
% @code is a modification of @t,
% which makes spaces the same size as normal in the surrounding text.
\def\tclose#1{%
{%
% Change normal interword space to be same as for the current font.
\spaceskip = \fontdimen2\font
%
% Switch to typewriter.
\tt
%
% But `\ ' produces the large typewriter interword space.
\def\ {{\spaceskip = 0pt{} }}%
%
% Turn off hyphenation.
\nohyphenation
%
\rawbackslash
\plainfrenchspacing
#1%
}%
\null
}
% We *must* turn on hyphenation at `-' and `_' in @code.
% Otherwise, it is too hard to avoid overfull hboxes
% in the Emacs manual, the Library manual, etc.
% Unfortunately, TeX uses one parameter (\hyphenchar) to control
% both hyphenation at - and hyphenation within words.
% We must therefore turn them both off (\tclose does that)
% and arrange explicitly to hyphenate at a dash.
% -- rms.
{
\catcode`\-=\active \catcode`\_=\active
\catcode`\'=\active \catcode`\`=\active
%
\global\def\code{\begingroup
\catcode\rquoteChar=\active \catcode\lquoteChar=\active
\let'\codequoteright \let`\codequoteleft
%
\catcode\dashChar=\active \catcode\underChar=\active
\ifallowcodebreaks
\let-\codedash
\let_\codeunder
\else
\let-\realdash
\let_\realunder
\fi
\codex
}
}
\def\realdash{-}
\def\codedash{-\discretionary{}{}{}}
\def\codeunder{%
% this is all so @math{@code{var_name}+1} can work. In math mode, _
% is "active" (mathcode"8000) and \normalunderscore (or \char95, etc.)
% will therefore expand the active definition of _, which is us
% (inside @code that is), therefore an endless loop.
\ifusingtt{\ifmmode
\mathchar"075F % class 0=ordinary, family 7=ttfam, pos 0x5F=_.
\else\normalunderscore \fi
\discretionary{}{}{}}%
{\_}%
}
\def\codex #1{\tclose{#1}\endgroup}
% An additional complication: the above will allow breaks after, e.g.,
% each of the four underscores in __typeof__. This is undesirable in
% some manuals, especially if they don't have long identifiers in
% general. @allowcodebreaks provides a way to control this.
%
\newif\ifallowcodebreaks \allowcodebreakstrue
\def\keywordtrue{true}
\def\keywordfalse{false}
\parseargdef\allowcodebreaks{%
\def\txiarg{#1}%
\ifx\txiarg\keywordtrue
\allowcodebreakstrue
\else\ifx\txiarg\keywordfalse
\allowcodebreaksfalse
\else
\errhelp = \EMsimple
\errmessage{Unknown @allowcodebreaks option `\txiarg'}%
\fi\fi
}
% @kbd is like @code, except that if the argument is just one @key command,
% then @kbd has no effect.
% @kbdinputstyle -- arg is `distinct' (@kbd uses slanted tty font always),
% `example' (@kbd uses ttsl only inside of @example and friends),
% or `code' (@kbd uses normal tty font always).
\parseargdef\kbdinputstyle{%
\def\txiarg{#1}%
\ifx\txiarg\worddistinct
\gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl}%
\else\ifx\txiarg\wordexample
\gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\tt}%
\else\ifx\txiarg\wordcode
\gdef\kbdexamplefont{\tt}\gdef\kbdfont{\tt}%
\else
\errhelp = \EMsimple
\errmessage{Unknown @kbdinputstyle option `\txiarg'}%
\fi\fi\fi
}
\def\worddistinct{distinct}
\def\wordexample{example}
\def\wordcode{code}
% Default is `distinct.'
\kbdinputstyle distinct
\def\xkey{\key}
\def\kbdfoo#1#2#3\par{\def\one{#1}\def\three{#3}\def\threex{??}%
\ifx\one\xkey\ifx\threex\three \key{#2}%
\else{\tclose{\kbdfont\look}}\fi
\else{\tclose{\kbdfont\look}}\fi}
% For @indicateurl, @env, @command quotes seem unnecessary, so use \code.
\let\indicateurl=\code
\let\env=\code
\let\command=\code
% @uref (abbreviation for `urlref') takes an optional (comma-separated)
% second argument specifying the text to display and an optional third
% arg as text to display instead of (rather than in addition to) the url
% itself. First (mandatory) arg is the url. Perhaps eventually put in
% a hypertex \special here.
%
\def\uref#1{\douref #1,,,\finish}
\def\douref#1,#2,#3,#4\finish{\begingroup
\unsepspaces
\pdfurl{#1}%
\setbox0 = \hbox{\ignorespaces #3}%
\ifdim\wd0 > 0pt
\unhbox0 % third arg given, show only that
\else
\setbox0 = \hbox{\ignorespaces #2}%
\ifdim\wd0 > 0pt
\ifpdf
\unhbox0 % PDF: 2nd arg given, show only it
\else
\unhbox0\ (\code{#1})% DVI: 2nd arg given, show both it and url
\fi
\else
\code{#1}% only url given, so show it
\fi
\fi
\endlink
\endgroup}
% @url synonym for @uref, since that's how everyone uses it.
%
\let\url=\uref
% rms does not like angle brackets --karl, 17may97.
% So now @email is just like @uref, unless we are pdf.
%
%\def\email#1{\angleleft{\tt #1}\angleright}
\ifpdf
\def\email#1{\doemail#1,,\finish}
\def\doemail#1,#2,#3\finish{\begingroup
\unsepspaces
\pdfurl{mailto:#1}%
\setbox0 = \hbox{\ignorespaces #2}%
\ifdim\wd0>0pt\unhbox0\else\code{#1}\fi
\endlink
\endgroup}
\else
\let\email=\uref
\fi
% Check if we are currently using a typewriter font. Since all the
% Computer Modern typewriter fonts have zero interword stretch (and
% shrink), and it is reasonable to expect all typewriter fonts to have
% this property, we can check that font parameter.
%
\def\ifmonospace{\ifdim\fontdimen3\font=0pt }
% Typeset a dimension, e.g., `in' or `pt'. The only reason for the
% argument is to make the input look right: @dmn{pt} instead of @dmn{}pt.
%
\def\dmn#1{\thinspace #1}
\def\kbd#1{\def\look{#1}\expandafter\kbdfoo\look??\par}
% @l was never documented to mean ``switch to the Lisp font'',
% and it is not used as such in any manual I can find. We need it for
% Polish suppressed-l. --karl, 22sep96.
%\def\l#1{{\li #1}\null}
% Explicit font changes: @r, @sc, undocumented @ii.
\def\r#1{{\rm #1}} % roman font
\def\sc#1{{\smallcaps#1}} % smallcaps font
\def\ii#1{{\it #1}} % italic font
% @acronym for "FBI", "NATO", and the like.
% We print this one point size smaller, since it's intended for
% all-uppercase.
%
\def\acronym#1{\doacronym #1,,\finish}
\def\doacronym#1,#2,#3\finish{%
{\selectfonts\lsize #1}%
\def\temp{#2}%
\ifx\temp\empty \else
\space ({\unsepspaces \ignorespaces \temp \unskip})%
\fi
}
% @abbr for "Comput. J." and the like.
% No font change, but don't do end-of-sentence spacing.
%
\def\abbr#1{\doabbr #1,,\finish}
\def\doabbr#1,#2,#3\finish{%
{\plainfrenchspacing #1}%
\def\temp{#2}%
\ifx\temp\empty \else
\space ({\unsepspaces \ignorespaces \temp \unskip})%
\fi
}
% @pounds{} is a sterling sign, which Knuth put in the CM italic font.
%
\def\pounds{{\it\$}}
% @euro{} comes from a separate font, depending on the current style.
% We use the free feym* fonts from the eurosym package by Henrik
% Theiling, which support regular, slanted, bold and bold slanted (and
% "outlined" (blackboard board, sort of) versions, which we don't need).
% It is available from http://www.ctan.org/tex-archive/fonts/eurosym.
%
% Although only regular is the truly official Euro symbol, we ignore
% that. The Euro is designed to be slightly taller than the regular
% font height.
%
% feymr - regular
% feymo - slanted
% feybr - bold
% feybo - bold slanted
%
% There is no good (free) typewriter version, to my knowledge.
% A feymr10 euro is ~7.3pt wide, while a normal cmtt10 char is ~5.25pt wide.
% Hmm.
%
% Also doesn't work in math. Do we need to do math with euro symbols?
% Hope not.
%
%
\def\euro{{\eurofont e}}
\def\eurofont{%
% We set the font at each command, rather than predefining it in
% \textfonts and the other font-switching commands, so that
% installations which never need the symbol don't have to have the
% font installed.
%
% There is only one designed size (nominal 10pt), so we always scale
% that to the current nominal size.
%
% By the way, simply using "at 1em" works for cmr10 and the like, but
% does not work for cmbx10 and other extended/shrunken fonts.
%
\def\eurosize{\csname\curfontsize nominalsize\endcsname}%
%
\ifx\curfontstyle\bfstylename
% bold:
\font\thiseurofont = \ifusingit{feybo10}{feybr10} at \eurosize
\else
% regular:
\font\thiseurofont = \ifusingit{feymo10}{feymr10} at \eurosize
\fi
\thiseurofont
}
% @registeredsymbol - R in a circle. The font for the R should really
% be smaller yet, but lllsize is the best we can do for now.
% Adapted from the plain.tex definition of \copyright.
%
\def\registeredsymbol{%
$^{{\ooalign{\hfil\raise.07ex\hbox{\selectfonts\lllsize R}%
\hfil\crcr\Orb}}%
}$%
}
% @textdegree - the normal degrees sign.
%
\def\textdegree{$^\circ$}
% Laurent Siebenmann reports \Orb undefined with:
% Textures 1.7.7 (preloaded format=plain 93.10.14) (68K) 16 APR 2004 02:38
% so we'll define it if necessary.
%
\ifx\Orb\undefined
\def\Orb{\mathhexbox20D}
\fi
\message{page headings,}
\newskip\titlepagetopglue \titlepagetopglue = 1.5in
\newskip\titlepagebottomglue \titlepagebottomglue = 2pc
% First the title page. Must do @settitle before @titlepage.
\newif\ifseenauthor
\newif\iffinishedtitlepage
% Do an implicit @contents or @shortcontents after @end titlepage if the
% user says @setcontentsaftertitlepage or @setshortcontentsaftertitlepage.
%
\newif\ifsetcontentsaftertitlepage
\let\setcontentsaftertitlepage = \setcontentsaftertitlepagetrue
\newif\ifsetshortcontentsaftertitlepage
\let\setshortcontentsaftertitlepage = \setshortcontentsaftertitlepagetrue
\parseargdef\shorttitlepage{\begingroup\hbox{}\vskip 1.5in \chaprm \centerline{#1}%
\endgroup\page\hbox{}\page}
\envdef\titlepage{%
% Open one extra group, as we want to close it in the middle of \Etitlepage.
\begingroup
\parindent=0pt \textfonts
% Leave some space at the very top of the page.
\vglue\titlepagetopglue
% No rule at page bottom unless we print one at the top with @title.
\finishedtitlepagetrue
%
% Most title ``pages'' are actually two pages long, with space
% at the top of the second. We don't want the ragged left on the second.
\let\oldpage = \page
\def\page{%
\iffinishedtitlepage\else
\finishtitlepage
\fi
\let\page = \oldpage
\page
\null
}%
}
\def\Etitlepage{%
\iffinishedtitlepage\else
\finishtitlepage
\fi
% It is important to do the page break before ending the group,
% because the headline and footline are only empty inside the group.
% If we use the new definition of \page, we always get a blank page
% after the title page, which we certainly don't want.
\oldpage
\endgroup
%
% Need this before the \...aftertitlepage checks so that if they are
% in effect the toc pages will come out with page numbers.
\HEADINGSon
%
% If they want short, they certainly want long too.
\ifsetshortcontentsaftertitlepage
\shortcontents
\contents
\global\let\shortcontents = \relax
\global\let\contents = \relax
\fi
%
\ifsetcontentsaftertitlepage
\contents
\global\let\contents = \relax
\global\let\shortcontents = \relax
\fi
}
\def\finishtitlepage{%
\vskip4pt \hrule height 2pt width \hsize
\vskip\titlepagebottomglue
\finishedtitlepagetrue
}
%%% Macros to be used within @titlepage:
\let\subtitlerm=\tenrm
\def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines}
\def\authorfont{\authorrm \normalbaselineskip = 16pt \normalbaselines
\let\tt=\authortt}
\parseargdef\title{%
\checkenv\titlepage
\leftline{\titlefonts\rm #1}
% print a rule at the page bottom also.
\finishedtitlepagefalse
\vskip4pt \hrule height 4pt width \hsize \vskip4pt
}
\parseargdef\subtitle{%
\checkenv\titlepage
{\subtitlefont \rightline{#1}}%
}
% @author should come last, but may come many times.
% It can also be used inside @quotation.
%
\parseargdef\author{%
\def\temp{\quotation}%
\ifx\thisenv\temp
\def\quotationauthor{#1}% printed in \Equotation.
\else
\checkenv\titlepage
\ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi
{\authorfont \leftline{#1}}%
\fi
}
%%% Set up page headings and footings.
\let\thispage=\folio
\newtoks\evenheadline % headline on even pages
\newtoks\oddheadline % headline on odd pages
\newtoks\evenfootline % footline on even pages
\newtoks\oddfootline % footline on odd pages
% Now make TeX use those variables
\headline={{\textfonts\rm \ifodd\pageno \the\oddheadline
\else \the\evenheadline \fi}}
\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline
\else \the\evenfootline \fi}\HEADINGShook}
\let\HEADINGShook=\relax
% Commands to set those variables.
% For example, this is what @headings on does
% @evenheading @thistitle|@thispage|@thischapter
% @oddheading @thischapter|@thispage|@thistitle
% @evenfooting @thisfile||
% @oddfooting ||@thisfile
\def\evenheading{\parsearg\evenheadingxxx}
\def\evenheadingxxx #1{\evenheadingyyy #1\|\|\|\|\finish}
\def\evenheadingyyy #1\|#2\|#3\|#4\finish{%
\global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
\def\oddheading{\parsearg\oddheadingxxx}
\def\oddheadingxxx #1{\oddheadingyyy #1\|\|\|\|\finish}
\def\oddheadingyyy #1\|#2\|#3\|#4\finish{%
\global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
\parseargdef\everyheading{\oddheadingxxx{#1}\evenheadingxxx{#1}}%
\def\evenfooting{\parsearg\evenfootingxxx}
\def\evenfootingxxx #1{\evenfootingyyy #1\|\|\|\|\finish}
\def\evenfootingyyy #1\|#2\|#3\|#4\finish{%
\global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
\def\oddfooting{\parsearg\oddfootingxxx}
\def\oddfootingxxx #1{\oddfootingyyy #1\|\|\|\|\finish}
\def\oddfootingyyy #1\|#2\|#3\|#4\finish{%
\global\oddfootline = {\rlap{\centerline{#2}}\line{#1\hfil#3}}%
%
% Leave some space for the footline. Hopefully ok to assume
% @evenfooting will not be used by itself.
\global\advance\pageheight by -12pt
\global\advance\vsize by -12pt
}
\parseargdef\everyfooting{\oddfootingxxx{#1}\evenfootingxxx{#1}}
% @headings double turns headings on for double-sided printing.
% @headings single turns headings on for single-sided printing.
% @headings off turns them off.
% @headings on same as @headings double, retained for compatibility.
% @headings after turns on double-sided headings after this page.
% @headings doubleafter turns on double-sided headings after this page.
% @headings singleafter turns on single-sided headings after this page.
% By default, they are off at the start of a document,
% and turned `on' after @end titlepage.
\def\headings #1 {\csname HEADINGS#1\endcsname}
\def\HEADINGSoff{%
\global\evenheadline={\hfil} \global\evenfootline={\hfil}
\global\oddheadline={\hfil} \global\oddfootline={\hfil}}
\HEADINGSoff
% When we turn headings on, set the page number to 1.
% For double-sided printing, put current file name in lower left corner,
% chapter name on inside top of right hand pages, document
% title on inside top of left hand pages, and page numbers on outside top
% edge of all pages.
\def\HEADINGSdouble{%
\global\pageno=1
\global\evenfootline={\hfil}
\global\oddfootline={\hfil}
\global\evenheadline={\line{\folio\hfil\thistitle}}
\global\oddheadline={\line{\thischapter\hfil\folio}}
\global\let\contentsalignmacro = \chapoddpage
}
\let\contentsalignmacro = \chappager
% For single-sided printing, chapter title goes across top left of page,
% page number on top right.
\def\HEADINGSsingle{%
\global\pageno=1
\global\evenfootline={\hfil}
\global\oddfootline={\hfil}
\global\evenheadline={\line{\thischapter\hfil\folio}}
\global\oddheadline={\line{\thischapter\hfil\folio}}
\global\let\contentsalignmacro = \chappager
}
\def\HEADINGSon{\HEADINGSdouble}
\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex}
\let\HEADINGSdoubleafter=\HEADINGSafter
\def\HEADINGSdoublex{%
\global\evenfootline={\hfil}
\global\oddfootline={\hfil}
\global\evenheadline={\line{\folio\hfil\thistitle}}
\global\oddheadline={\line{\thischapter\hfil\folio}}
\global\let\contentsalignmacro = \chapoddpage
}
\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex}
\def\HEADINGSsinglex{%
\global\evenfootline={\hfil}
\global\oddfootline={\hfil}
\global\evenheadline={\line{\thischapter\hfil\folio}}
\global\oddheadline={\line{\thischapter\hfil\folio}}
\global\let\contentsalignmacro = \chappager
}
% Subroutines used in generating headings
% This produces Day Month Year style of output.
% Only define if not already defined, in case a txi-??.tex file has set
% up a different format (e.g., txi-cs.tex does this).
\ifx\today\undefined
\def\today{%
\number\day\space
\ifcase\month
\or\putwordMJan\or\putwordMFeb\or\putwordMMar\or\putwordMApr
\or\putwordMMay\or\putwordMJun\or\putwordMJul\or\putwordMAug
\or\putwordMSep\or\putwordMOct\or\putwordMNov\or\putwordMDec
\fi
\space\number\year}
\fi
% @settitle line... specifies the title of the document, for headings.
% It generates no output of its own.
\def\thistitle{\putwordNoTitle}
\def\settitle{\parsearg{\gdef\thistitle}}
\message{tables,}
% Tables -- @table, @ftable, @vtable, @item(x).
% default indentation of table text
\newdimen\tableindent \tableindent=.8in
% default indentation of @itemize and @enumerate text
\newdimen\itemindent \itemindent=.3in
% margin between end of table item and start of table text.
\newdimen\itemmargin \itemmargin=.1in
% used internally for \itemindent minus \itemmargin
\newdimen\itemmax
% Note @table, @ftable, and @vtable define @item, @itemx, etc., with
% these defs.
% They also define \itemindex
% to index the item name in whatever manner is desired (perhaps none).
\newif\ifitemxneedsnegativevskip
\def\itemxpar{\par\ifitemxneedsnegativevskip\nobreak\vskip-\parskip\nobreak\fi}
\def\internalBitem{\smallbreak \parsearg\itemzzz}
\def\internalBitemx{\itemxpar \parsearg\itemzzz}
\def\itemzzz #1{\begingroup %
\advance\hsize by -\rightskip
\advance\hsize by -\tableindent
\setbox0=\hbox{\itemindicate{#1}}%
\itemindex{#1}%
\nobreak % This prevents a break before @itemx.
%
% If the item text does not fit in the space we have, put it on a line
% by itself, and do not allow a page break either before or after that
% line. We do not start a paragraph here because then if the next
% command is, e.g., @kindex, the whatsit would get put into the
% horizontal list on a line by itself, resulting in extra blank space.
\ifdim \wd0>\itemmax
%
% Make this a paragraph so we get the \parskip glue and wrapping,
% but leave it ragged-right.
\begingroup
\advance\leftskip by-\tableindent
\advance\hsize by\tableindent
\advance\rightskip by0pt plus1fil
\leavevmode\unhbox0\par
\endgroup
%
% We're going to be starting a paragraph, but we don't want the
% \parskip glue -- logically it's part of the @item we just started.
\nobreak \vskip-\parskip
%
% Stop a page break at the \parskip glue coming up. However, if
% what follows is an environment such as @example, there will be no
% \parskip glue; then the negative vskip we just inserted would
% cause the example and the item to crash together. So we use this
% bizarre value of 10001 as a signal to \aboveenvbreak to insert
% \parskip glue after all. Section titles are handled this way also.
%
\penalty 10001
\endgroup
\itemxneedsnegativevskipfalse
\else
% The item text fits into the space. Start a paragraph, so that the
% following text (if any) will end up on the same line.
\noindent
% Do this with kerns and \unhbox so that if there is a footnote in
% the item text, it can migrate to the main vertical list and
% eventually be printed.
\nobreak\kern-\tableindent
\dimen0 = \itemmax \advance\dimen0 by \itemmargin \advance\dimen0 by -\wd0
\unhbox0
\nobreak\kern\dimen0
\endgroup
\itemxneedsnegativevskiptrue
\fi
}
\def\item{\errmessage{@item while not in a list environment}}
\def\itemx{\errmessage{@itemx while not in a list environment}}
% @table, @ftable, @vtable.
\envdef\table{%
\let\itemindex\gobble
\tablecheck{table}%
}
\envdef\ftable{%
\def\itemindex ##1{\doind {fn}{\code{##1}}}%
\tablecheck{ftable}%
}
\envdef\vtable{%
\def\itemindex ##1{\doind {vr}{\code{##1}}}%
\tablecheck{vtable}%
}
\def\tablecheck#1{%
\ifnum \the\catcode`\^^M=\active
\endgroup
\errmessage{This command won't work in this context; perhaps the problem is
that we are \inenvironment\thisenv}%
\def\next{\doignore{#1}}%
\else
\let\next\tablex
\fi
\next
}
\def\tablex#1{%
\def\itemindicate{#1}%
\parsearg\tabley
}
\def\tabley#1{%
{%
\makevalueexpandable
\edef\temp{\noexpand\tablez #1\space\space\space}%
\expandafter
}\temp \endtablez
}
\def\tablez #1 #2 #3 #4\endtablez{%
\aboveenvbreak
\ifnum 0#1>0 \advance \leftskip by #1\mil \fi
\ifnum 0#2>0 \tableindent=#2\mil \fi
\ifnum 0#3>0 \advance \rightskip by #3\mil \fi
\itemmax=\tableindent
\advance \itemmax by -\itemmargin
\advance \leftskip by \tableindent
\exdentamount=\tableindent
\parindent = 0pt
\parskip = \smallskipamount
\ifdim \parskip=0pt \parskip=2pt \fi
\let\item = \internalBitem
\let\itemx = \internalBitemx
}
\def\Etable{\endgraf\afterenvbreak}
\let\Eftable\Etable
\let\Evtable\Etable
\let\Eitemize\Etable
\let\Eenumerate\Etable
% This is the counter used by @enumerate, which is really @itemize
\newcount \itemno
\envdef\itemize{\parsearg\doitemize}
\def\doitemize#1{%
\aboveenvbreak
\itemmax=\itemindent
\advance\itemmax by -\itemmargin
\advance\leftskip by \itemindent
\exdentamount=\itemindent
\parindent=0pt
\parskip=\smallskipamount
\ifdim\parskip=0pt \parskip=2pt \fi
\def\itemcontents{#1}%
% @itemize with no arg is equivalent to @itemize @bullet.
\ifx\itemcontents\empty\def\itemcontents{\bullet}\fi
\let\item=\itemizeitem
}
% Definition of @item while inside @itemize and @enumerate.
%
\def\itemizeitem{%
\advance\itemno by 1 % for enumerations
{\let\par=\endgraf \smallbreak}% reasonable place to break
{%
% If the document has an @itemize directly after a section title, a
% \nobreak will be last on the list, and \sectionheading will have
% done a \vskip-\parskip. In that case, we don't want to zero
% parskip, or the item text will crash with the heading. On the
% other hand, when there is normal text preceding the item (as there
% usually is), we do want to zero parskip, or there would be too much
% space. In that case, we won't have a \nobreak before. At least
% that's the theory.
\ifnum\lastpenalty<10000 \parskip=0in \fi
\noindent
\hbox to 0pt{\hss \itemcontents \kern\itemmargin}%
\vadjust{\penalty 1200}}% not good to break after first line of item.
\flushcr
}
% \splitoff TOKENS\endmark defines \first to be the first token in
% TOKENS, and \rest to be the remainder.
%
\def\splitoff#1#2\endmark{\def\first{#1}\def\rest{#2}}%
% Allow an optional argument of an uppercase letter, lowercase letter,
% or number, to specify the first label in the enumerated list. No
% argument is the same as `1'.
%
\envparseargdef\enumerate{\enumeratey #1 \endenumeratey}
\def\enumeratey #1 #2\endenumeratey{%
% If we were given no argument, pretend we were given `1'.
\def\thearg{#1}%
\ifx\thearg\empty \def\thearg{1}\fi
%
% Detect if the argument is a single token. If so, it might be a
% letter. Otherwise, the only valid thing it can be is a number.
% (We will always have one token, because of the test we just made.
% This is a good thing, since \splitoff doesn't work given nothing at
% all -- the first parameter is undelimited.)
\expandafter\splitoff\thearg\endmark
\ifx\rest\empty
% Only one token in the argument. It could still be anything.
% A ``lowercase letter'' is one whose \lccode is nonzero.
% An ``uppercase letter'' is one whose \lccode is both nonzero, and
% not equal to itself.
% Otherwise, we assume it's a number.
%
% We need the \relax at the end of the \ifnum lines to stop TeX from
% continuing to look for a <number>.
%
\ifnum\lccode\expandafter`\thearg=0\relax
\numericenumerate % a number (we hope)
\else
% It's a letter.
\ifnum\lccode\expandafter`\thearg=\expandafter`\thearg\relax
\lowercaseenumerate % lowercase letter
\else
\uppercaseenumerate % uppercase letter
\fi
\fi
\else
% Multiple tokens in the argument. We hope it's a number.
\numericenumerate
\fi
}
% An @enumerate whose labels are integers. The starting integer is
% given in \thearg.
%
\def\numericenumerate{%
\itemno = \thearg
\startenumeration{\the\itemno}%
}
% The starting (lowercase) letter is in \thearg.
\def\lowercaseenumerate{%
\itemno = \expandafter`\thearg
\startenumeration{%
% Be sure we're not beyond the end of the alphabet.
\ifnum\itemno=0
\errmessage{No more lowercase letters in @enumerate; get a bigger
alphabet}%
\fi
\char\lccode\itemno
}%
}
% The starting (uppercase) letter is in \thearg.
\def\uppercaseenumerate{%
\itemno = \expandafter`\thearg
\startenumeration{%
% Be sure we're not beyond the end of the alphabet.
\ifnum\itemno=0
\errmessage{No more uppercase letters in @enumerate; get a bigger
alphabet}
\fi
\char\uccode\itemno
}%
}
% Call \doitemize, adding a period to the first argument and supplying the
% common last two arguments. Also subtract one from the initial value in
% \itemno, since @item increments \itemno.
%
\def\startenumeration#1{%
\advance\itemno by -1
\doitemize{#1.}\flushcr
}
% @alphaenumerate and @capsenumerate are abbreviations for giving an arg
% to @enumerate.
%
\def\alphaenumerate{\enumerate{a}}
\def\capsenumerate{\enumerate{A}}
\def\Ealphaenumerate{\Eenumerate}
\def\Ecapsenumerate{\Eenumerate}
% @multitable macros
% Amy Hendrickson, 8/18/94, 3/6/96
%
% @multitable ... @end multitable will make as many columns as desired.
% Contents of each column will wrap at width given in preamble. Width
% can be specified either with sample text given in a template line,
% or in percent of \hsize, the current width of text on page.
% Table can continue over pages but will only break between lines.
% To make preamble:
%
% Either define widths of columns in terms of percent of \hsize:
% @multitable @columnfractions .25 .3 .45
% @item ...
%
% Numbers following @columnfractions are the percent of the total
% current hsize to be used for each column. You may use as many
% columns as desired.
% Or use a template:
% @multitable {Column 1 template} {Column 2 template} {Column 3 template}
% @item ...
% using the widest term desired in each column.
% Each new table line starts with @item, each subsequent new column
% starts with @tab. Empty columns may be produced by supplying @tab's
% with nothing between them for as many times as empty columns are needed,
% ie, @tab@tab@tab will produce two empty columns.
% @item, @tab do not need to be on their own lines, but it will not hurt
% if they are.
% Sample multitable:
% @multitable {Column 1 template} {Column 2 template} {Column 3 template}
% @item first col stuff @tab second col stuff @tab third col
% @item
% first col stuff
% @tab
% second col stuff
% @tab
% third col
% @item first col stuff @tab second col stuff
% @tab Many paragraphs of text may be used in any column.
%
% They will wrap at the width determined by the template.
% @item@tab@tab This will be in third column.
% @end multitable
% Default dimensions may be reset by user.
% @multitableparskip is vertical space between paragraphs in table.
% @multitableparindent is paragraph indent in table.
% @multitablecolmargin is horizontal space to be left between columns.
% @multitablelinespace is space to leave between table items, baseline
% to baseline.
% 0pt means it depends on current normal line spacing.
%
\newskip\multitableparskip
\newskip\multitableparindent
\newdimen\multitablecolspace
\newskip\multitablelinespace
\multitableparskip=0pt
\multitableparindent=6pt
\multitablecolspace=12pt
\multitablelinespace=0pt
% Macros used to set up halign preamble:
%
\let\endsetuptable\relax
\def\xendsetuptable{\endsetuptable}
\let\columnfractions\relax
\def\xcolumnfractions{\columnfractions}
\newif\ifsetpercent
% #1 is the @columnfraction, usually a decimal number like .5, but might
% be just 1. We just use it, whatever it is.
%
\def\pickupwholefraction#1 {%
\global\advance\colcount by 1
\expandafter\xdef\csname col\the\colcount\endcsname{#1\hsize}%
\setuptable
}
\newcount\colcount
\def\setuptable#1{%
\def\firstarg{#1}%
\ifx\firstarg\xendsetuptable
\let\go = \relax
\else
\ifx\firstarg\xcolumnfractions
\global\setpercenttrue
\else
\ifsetpercent
\let\go\pickupwholefraction
\else
\global\advance\colcount by 1
\setbox0=\hbox{#1\unskip\space}% Add a normal word space as a
% separator; typically that is always in the input, anyway.
\expandafter\xdef\csname col\the\colcount\endcsname{\the\wd0}%
\fi
\fi
\ifx\go\pickupwholefraction
% Put the argument back for the \pickupwholefraction call, so
% we'll always have a period there to be parsed.
\def\go{\pickupwholefraction#1}%
\else
\let\go = \setuptable
\fi%
\fi
\go
}
% multitable-only commands.
%
% @headitem starts a heading row, which we typeset in bold.
% Assignments have to be global since we are inside the implicit group
% of an alignment entry. Note that \everycr resets \everytab.
\def\headitem{\checkenv\multitable \crcr \global\everytab={\bf}\the\everytab}%
%
% A \tab used to include \hskip1sp. But then the space in a template
% line is not enough. That is bad. So let's go back to just `&' until
% we encounter the problem it was intended to solve again.
% --karl, nathan@acm.org, 20apr99.
\def\tab{\checkenv\multitable &\the\everytab}%
% @multitable ... @end multitable definitions:
%
\newtoks\everytab % insert after every tab.
%
\envdef\multitable{%
\vskip\parskip
\startsavinginserts
%
% @item within a multitable starts a normal row.
% We use \def instead of \let so that if one of the multitable entries
% contains an @itemize, we don't choke on the \item (seen as \crcr aka
% \endtemplate) expanding \doitemize.
\def\item{\crcr}%
%
\tolerance=9500
\hbadness=9500
\setmultitablespacing
\parskip=\multitableparskip
\parindent=\multitableparindent
\overfullrule=0pt
\global\colcount=0
%
\everycr = {%
\noalign{%
\global\everytab={}%
\global\colcount=0 % Reset the column counter.
% Check for saved footnotes, etc.
\checkinserts
% Keeps underfull box messages off when table breaks over pages.
%\filbreak
% Maybe so, but it also creates really weird page breaks when the
% table breaks over pages. Wouldn't \vfil be better? Wait until the
% problem manifests itself, so it can be fixed for real --karl.
}%
}%
%
\parsearg\domultitable
}
\def\domultitable#1{%
% To parse everything between @multitable and @item:
\setuptable#1 \endsetuptable
%
% This preamble sets up a generic column definition, which will
% be used as many times as user calls for columns.
% \vtop will set a single line and will also let text wrap and
% continue for many paragraphs if desired.
\halign\bgroup &%
\global\advance\colcount by 1
\multistrut
\vtop{%
% Use the current \colcount to find the correct column width:
\hsize=\expandafter\csname col\the\colcount\endcsname
%
% In order to keep entries from bumping into each other
% we will add a \leftskip of \multitablecolspace to all columns after
% the first one.
%
% If a template has been used, we will add \multitablecolspace
% to the width of each template entry.
%
% If the user has set preamble in terms of percent of \hsize we will
% use that dimension as the width of the column, and the \leftskip
% will keep entries from bumping into each other. Table will start at
% left margin and final column will justify at right margin.
%
% Make sure we don't inherit \rightskip from the outer environment.
\rightskip=0pt
\ifnum\colcount=1
% The first column will be indented with the surrounding text.
\advance\hsize by\leftskip
\else
\ifsetpercent \else
% If user has not set preamble in terms of percent of \hsize
% we will advance \hsize by \multitablecolspace.
\advance\hsize by \multitablecolspace
\fi
% In either case we will make \leftskip=\multitablecolspace:
\leftskip=\multitablecolspace
\fi
% Ignoring space at the beginning and end avoids an occasional spurious
% blank line, when TeX decides to break the line at the space before the
% box from the multistrut, so the strut ends up on a line by itself.
% For example:
% @multitable @columnfractions .11 .89
% @item @code{#}
% @tab Legal holiday which is valid in major parts of the whole country.
% Is automatically provided with highlighting sequences respectively
% marking characters.
\noindent\ignorespaces##\unskip\multistrut
}\cr
}
\def\Emultitable{%
\crcr
\egroup % end the \halign
\global\setpercentfalse
}
\def\setmultitablespacing{%
\def\multistrut{\strut}% just use the standard line spacing
%
% Compute \multitablelinespace (if not defined by user) for use in
% \multitableparskip calculation. We used define \multistrut based on
% this, but (ironically) that caused the spacing to be off.
% See bug-texinfo report from Werner Lemberg, 31 Oct 2004 12:52:20 +0100.
\ifdim\multitablelinespace=0pt
\setbox0=\vbox{X}\global\multitablelinespace=\the\baselineskip
\global\advance\multitablelinespace by-\ht0
\fi
%% Test to see if parskip is larger than space between lines of
%% table. If not, do nothing.
%% If so, set to same dimension as multitablelinespace.
\ifdim\multitableparskip>\multitablelinespace
\global\multitableparskip=\multitablelinespace
\global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller
%% than skip between lines in the table.
\fi%
\ifdim\multitableparskip=0pt
\global\multitableparskip=\multitablelinespace
\global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller
%% than skip between lines in the table.
\fi}
\message{conditionals,}
% @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotplaintext,
% @ifnotxml always succeed. They currently do nothing; we don't
% attempt to check whether the conditionals are properly nested. But we
% have to remember that they are conditionals, so that @end doesn't
% attempt to close an environment group.
%
\def\makecond#1{%
\expandafter\let\csname #1\endcsname = \relax
\expandafter\let\csname iscond.#1\endcsname = 1
}
\makecond{iftex}
\makecond{ifnotdocbook}
\makecond{ifnothtml}
\makecond{ifnotinfo}
\makecond{ifnotplaintext}
\makecond{ifnotxml}
% Ignore @ignore, @ifhtml, @ifinfo, and the like.
%
\def\direntry{\doignore{direntry}}
\def\documentdescription{\doignore{documentdescription}}
\def\docbook{\doignore{docbook}}
\def\html{\doignore{html}}
\def\ifdocbook{\doignore{ifdocbook}}
\def\ifhtml{\doignore{ifhtml}}
\def\ifinfo{\doignore{ifinfo}}
\def\ifnottex{\doignore{ifnottex}}
\def\ifplaintext{\doignore{ifplaintext}}
\def\ifxml{\doignore{ifxml}}
\def\ignore{\doignore{ignore}}
\def\menu{\doignore{menu}}
\def\xml{\doignore{xml}}
% Ignore text until a line `@end #1', keeping track of nested conditionals.
%
% A count to remember the depth of nesting.
\newcount\doignorecount
\def\doignore#1{\begingroup
% Scan in ``verbatim'' mode:
\obeylines
\catcode`\@ = \other
\catcode`\{ = \other
\catcode`\} = \other
%
% Make sure that spaces turn into tokens that match what \doignoretext wants.
\spaceisspace
%
% Count number of #1's that we've seen.
\doignorecount = 0
%
% Swallow text until we reach the matching `@end #1'.
\dodoignore{#1}%
}
{ \catcode`_=11 % We want to use \_STOP_ which cannot appear in texinfo source.
\obeylines %
%
\gdef\dodoignore#1{%
% #1 contains the command name as a string, e.g., `ifinfo'.
%
% Define a command to find the next `@end #1'.
\long\def\doignoretext##1^^M@end #1{%
\doignoretextyyy##1^^M@#1\_STOP_}%
%
% And this command to find another #1 command, at the beginning of a
% line. (Otherwise, we would consider a line `@c @ifset', for
% example, to count as an @ifset for nesting.)
\long\def\doignoretextyyy##1^^M@#1##2\_STOP_{\doignoreyyy{##2}\_STOP_}%
%
% And now expand that command.
\doignoretext ^^M%
}%
}
\def\doignoreyyy#1{%
\def\temp{#1}%
\ifx\temp\empty % Nothing found.
\let\next\doignoretextzzz
\else % Found a nested condition, ...
\advance\doignorecount by 1
\let\next\doignoretextyyy % ..., look for another.
% If we're here, #1 ends with ^^M\ifinfo (for example).
\fi
\next #1% the token \_STOP_ is present just after this macro.
}
% We have to swallow the remaining "\_STOP_".
%
\def\doignoretextzzz#1{%
\ifnum\doignorecount = 0 % We have just found the outermost @end.
\let\next\enddoignore
\else % Still inside a nested condition.
\advance\doignorecount by -1
\let\next\doignoretext % Look for the next @end.
\fi
\next
}
% Finish off ignored text.
{ \obeylines%
% Ignore anything after the last `@end #1'; this matters in verbatim
% environments, where otherwise the newline after an ignored conditional
% would result in a blank line in the output.
\gdef\enddoignore#1^^M{\endgroup\ignorespaces}%
}
% @set VAR sets the variable VAR to an empty value.
% @set VAR REST-OF-LINE sets VAR to the value REST-OF-LINE.
%
% Since we want to separate VAR from REST-OF-LINE (which might be
% empty), we can't just use \parsearg; we have to insert a space of our
% own to delimit the rest of the line, and then take it out again if we
% didn't need it.
% We rely on the fact that \parsearg sets \catcode`\ =10.
%
\parseargdef\set{\setyyy#1 \endsetyyy}
\def\setyyy#1 #2\endsetyyy{%
{%
\makevalueexpandable
\def\temp{#2}%
\edef\next{\gdef\makecsname{SET#1}}%
\ifx\temp\empty
\next{}%
\else
\setzzz#2\endsetzzz
\fi
}%
}
% Remove the trailing space \setxxx inserted.
\def\setzzz#1 \endsetzzz{\next{#1}}
% @clear VAR clears (i.e., unsets) the variable VAR.
%
\parseargdef\clear{%
{%
\makevalueexpandable
\global\expandafter\let\csname SET#1\endcsname=\relax
}%
}
% @value{foo} gets the text saved in variable foo.
\def\value{\begingroup\makevalueexpandable\valuexxx}
\def\valuexxx#1{\expandablevalue{#1}\endgroup}
{
\catcode`\- = \active \catcode`\_ = \active
%
\gdef\makevalueexpandable{%
\let\value = \expandablevalue
% We don't want these characters active, ...
\catcode`\-=\other \catcode`\_=\other
% ..., but we might end up with active ones in the argument if
% we're called from @code, as @code{@value{foo-bar_}}, though.
% So \let them to their normal equivalents.
\let-\realdash \let_\normalunderscore
}
}
% We have this subroutine so that we can handle at least some @value's
% properly in indexes (we call \makevalueexpandable in \indexdummies).
% The command has to be fully expandable (if the variable is set), since
% the result winds up in the index file. This means that if the
% variable's value contains other Texinfo commands, it's almost certain
% it will fail (although perhaps we could fix that with sufficient work
% to do a one-level expansion on the result, instead of complete).
%
\def\expandablevalue#1{%
\expandafter\ifx\csname SET#1\endcsname\relax
{[No value for ``#1'']}%
\message{Variable `#1', used in @value, is not set.}%
\else
\csname SET#1\endcsname
\fi
}
% @ifset VAR ... @end ifset reads the `...' iff VAR has been defined
% with @set.
%
% To get special treatment of `@end ifset,' call \makeond and the redefine.
%
\makecond{ifset}
\def\ifset{\parsearg{\doifset{\let\next=\ifsetfail}}}
\def\doifset#1#2{%
{%
\makevalueexpandable
\let\next=\empty
\expandafter\ifx\csname SET#2\endcsname\relax
#1% If not set, redefine \next.
\fi
\expandafter
}\next
}
\def\ifsetfail{\doignore{ifset}}
% @ifclear VAR ... @end ifclear reads the `...' iff VAR has never been
% defined with @set, or has been undefined with @clear.
%
% The `\else' inside the `\doifset' parameter is a trick to reuse the
% above code: if the variable is not set, do nothing, if it is set,
% then redefine \next to \ifclearfail.
%
\makecond{ifclear}
\def\ifclear{\parsearg{\doifset{\else \let\next=\ifclearfail}}}
\def\ifclearfail{\doignore{ifclear}}
% @dircategory CATEGORY -- specify a category of the dir file
% which this file should belong to. Ignore this in TeX.
\let\dircategory=\comment
% @defininfoenclose.
\let\definfoenclose=\comment
\message{indexing,}
% Index generation facilities
% Define \newwrite to be identical to plain tex's \newwrite
% except not \outer, so it can be used within macros and \if's.
\edef\newwrite{\makecsname{ptexnewwrite}}
% \newindex {foo} defines an index named foo.
% It automatically defines \fooindex such that
% \fooindex ...rest of line... puts an entry in the index foo.
% It also defines \fooindfile to be the number of the output channel for
% the file that accumulates this index. The file's extension is foo.
% The name of an index should be no more than 2 characters long
% for the sake of vms.
%
\def\newindex#1{%
\iflinks
\expandafter\newwrite \csname#1indfile\endcsname
\openout \csname#1indfile\endcsname \jobname.#1 % Open the file
\fi
\expandafter\xdef\csname#1index\endcsname{% % Define @#1index
\noexpand\doindex{#1}}
}
% @defindex foo == \newindex{foo}
%
\def\defindex{\parsearg\newindex}
% Define @defcodeindex, like @defindex except put all entries in @code.
%
\def\defcodeindex{\parsearg\newcodeindex}
%
\def\newcodeindex#1{%
\iflinks
\expandafter\newwrite \csname#1indfile\endcsname
\openout \csname#1indfile\endcsname \jobname.#1
\fi
\expandafter\xdef\csname#1index\endcsname{%
\noexpand\docodeindex{#1}}%
}
% @synindex foo bar makes index foo feed into index bar.
% Do this instead of @defindex foo if you don't want it as a separate index.
%
% @syncodeindex foo bar similar, but put all entries made for index foo
% inside @code.
%
\def\synindex#1 #2 {\dosynindex\doindex{#1}{#2}}
\def\syncodeindex#1 #2 {\dosynindex\docodeindex{#1}{#2}}
% #1 is \doindex or \docodeindex, #2 the index getting redefined (foo),
% #3 the target index (bar).
\def\dosynindex#1#2#3{%
% Only do \closeout if we haven't already done it, else we'll end up
% closing the target index.
\expandafter \ifx\csname donesynindex#2\endcsname \undefined
% The \closeout helps reduce unnecessary open files; the limit on the
% Acorn RISC OS is a mere 16 files.
\expandafter\closeout\csname#2indfile\endcsname
\expandafter\let\csname\donesynindex#2\endcsname = 1
\fi
% redefine \fooindfile:
\expandafter\let\expandafter\temp\expandafter=\csname#3indfile\endcsname
\expandafter\let\csname#2indfile\endcsname=\temp
% redefine \fooindex:
\expandafter\xdef\csname#2index\endcsname{\noexpand#1{#3}}%
}
% Define \doindex, the driver for all \fooindex macros.
% Argument #1 is generated by the calling \fooindex macro,
% and it is "foo", the name of the index.
% \doindex just uses \parsearg; it calls \doind for the actual work.
% This is because \doind is more useful to call from other macros.
% There is also \dosubind {index}{topic}{subtopic}
% which makes an entry in a two-level index such as the operation index.
\def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer}
\def\singleindexer #1{\doind{\indexname}{#1}}
% like the previous two, but they put @code around the argument.
\def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer}
\def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}}
% Take care of Texinfo commands that can appear in an index entry.
% Since there are some commands we want to expand, and others we don't,
% we have to laboriously prevent expansion for those that we don't.
%
\def\indexdummies{%
\escapechar = `\\ % use backslash in output files.
\def\@{@}% change to @@ when we switch to @ as escape char in index files.
\def\ {\realbackslash\space }%
%
% Need these in case \tex is in effect and \{ is a \delimiter again.
% But can't use \lbracecmd and \rbracecmd because texindex assumes
% braces and backslashes are used only as delimiters.
\let\{ = \mylbrace
\let\} = \myrbrace
%
% I don't entirely understand this, but when an index entry is
% generated from a macro call, the \endinput which \scanmacro inserts
% causes processing to be prematurely terminated. This is,
% apparently, because \indexsorttmp is fully expanded, and \endinput
% is an expandable command. The redefinition below makes \endinput
% disappear altogether for that purpose -- although logging shows that
% processing continues to some further point. On the other hand, it
% seems \endinput does not hurt in the printed index arg, since that
% is still getting written without apparent harm.
%
% Sample source (mac-idx3.tex, reported by Graham Percival to
% help-texinfo, 22may06):
% @macro funindex {WORD}
% @findex xyz
% @end macro
% ...
% @funindex commtest
%
% The above is not enough to reproduce the bug, but it gives the flavor.
%
% Sample whatsit resulting:
% .@write3{\entry{xyz}{@folio }{@code {xyz@endinput }}}
%
% So:
\let\endinput = \empty
%
% Do the redefinitions.
\commondummies
}
% For the aux and toc files, @ is the escape character. So we want to
% redefine everything using @ as the escape character (instead of
% \realbackslash, still used for index files). When everything uses @,
% this will be simpler.
%
\def\atdummies{%
\def\@{@@}%
\def\ {@ }%
\let\{ = \lbraceatcmd
\let\} = \rbraceatcmd
%
% Do the redefinitions.
\commondummies
\otherbackslash
}
% Called from \indexdummies and \atdummies.
%
\def\commondummies{%
%
% \definedummyword defines \#1 as \string\#1\space, thus effectively
% preventing its expansion. This is used only for control% words,
% not control letters, because the \space would be incorrect for
% control characters, but is needed to separate the control word
% from whatever follows.
%
% For control letters, we have \definedummyletter, which omits the
% space.
%
% These can be used both for control words that take an argument and
% those that do not. If it is followed by {arg} in the input, then
% that will dutifully get written to the index (or wherever).
%
\def\definedummyword ##1{\def##1{\string##1\space}}%
\def\definedummyletter##1{\def##1{\string##1}}%
\let\definedummyaccent\definedummyletter
%
\commondummiesnofonts
%
\definedummyletter\_%
%
% Non-English letters.
\definedummyword\AA
\definedummyword\AE
\definedummyword\L
\definedummyword\OE
\definedummyword\O
\definedummyword\aa
\definedummyword\ae
\definedummyword\l
\definedummyword\oe
\definedummyword\o
\definedummyword\ss
\definedummyword\exclamdown
\definedummyword\questiondown
\definedummyword\ordf
\definedummyword\ordm
%
% Although these internal commands shouldn't show up, sometimes they do.
\definedummyword\bf
\definedummyword\gtr
\definedummyword\hat
\definedummyword\less
\definedummyword\sf
\definedummyword\sl
\definedummyword\tclose
\definedummyword\tt
%
\definedummyword\LaTeX
\definedummyword\TeX
%
% Assorted special characters.
\definedummyword\bullet
\definedummyword\comma
\definedummyword\copyright
\definedummyword\registeredsymbol
\definedummyword\dots
\definedummyword\enddots
\definedummyword\equiv
\definedummyword\error
\definedummyword\euro
\definedummyword\expansion
\definedummyword\minus
\definedummyword\pounds
\definedummyword\point
\definedummyword\print
\definedummyword\result
\definedummyword\textdegree
%
% We want to disable all macros so that they are not expanded by \write.
\macrolist
%
\normalturnoffactive
%
% Handle some cases of @value -- where it does not contain any
% (non-fully-expandable) commands.
\makevalueexpandable
}
% \commondummiesnofonts: common to \commondummies and \indexnofonts.
%
\def\commondummiesnofonts{%
% Control letters and accents.
\definedummyletter\!%
\definedummyaccent\"%
\definedummyaccent\'%
\definedummyletter\*%
\definedummyaccent\,%
\definedummyletter\.%
\definedummyletter\/%
\definedummyletter\:%
\definedummyaccent\=%
\definedummyletter\?%
\definedummyaccent\^%
\definedummyaccent\`%
\definedummyaccent\~%
\definedummyword\u
\definedummyword\v
\definedummyword\H
\definedummyword\dotaccent
\definedummyword\ringaccent
\definedummyword\tieaccent
\definedummyword\ubaraccent
\definedummyword\udotaccent
\definedummyword\dotless
%
% Texinfo font commands.
\definedummyword\b
\definedummyword\i
\definedummyword\r
\definedummyword\sc
\definedummyword\t
%
% Commands that take arguments.
\definedummyword\acronym
\definedummyword\cite
\definedummyword\code
\definedummyword\command
\definedummyword\dfn
\definedummyword\emph
\definedummyword\env
\definedummyword\file
\definedummyword\kbd
\definedummyword\key
\definedummyword\math
\definedummyword\option
\definedummyword\pxref
\definedummyword\ref
\definedummyword\samp
\definedummyword\strong
\definedummyword\tie
\definedummyword\uref
\definedummyword\url
\definedummyword\var
\definedummyword\verb
\definedummyword\w
\definedummyword\xref
}
% \indexnofonts is used when outputting the strings to sort the index
% by, and when constructing control sequence names. It eliminates all
% control sequences and just writes whatever the best ASCII sort string
% would be for a given command (usually its argument).
%
\def\indexnofonts{%
% Accent commands should become @asis.
\def\definedummyaccent##1{\let##1\asis}%
% We can just ignore other control letters.
\def\definedummyletter##1{\let##1\empty}%
% Hopefully, all control words can become @asis.
\let\definedummyword\definedummyaccent
%
\commondummiesnofonts
%
% Don't no-op \tt, since it isn't a user-level command
% and is used in the definitions of the active chars like <, >, |, etc.
% Likewise with the other plain tex font commands.
%\let\tt=\asis
%
\def\ { }%
\def\@{@}%
% how to handle braces?
\def\_{\normalunderscore}%
%
% Non-English letters.
\def\AA{AA}%
\def\AE{AE}%
\def\L{L}%
\def\OE{OE}%
\def\O{O}%
\def\aa{aa}%
\def\ae{ae}%
\def\l{l}%
\def\oe{oe}%
\def\o{o}%
\def\ss{ss}%
\def\exclamdown{!}%
\def\questiondown{?}%
\def\ordf{a}%
\def\ordm{o}%
%
\def\LaTeX{LaTeX}%
\def\TeX{TeX}%
%
% Assorted special characters.
% (The following {} will end up in the sort string, but that's ok.)
\def\bullet{bullet}%
\def\comma{,}%
\def\copyright{copyright}%
\def\registeredsymbol{R}%
\def\dots{...}%
\def\enddots{...}%
\def\equiv{==}%
\def\error{error}%
\def\euro{euro}%
\def\expansion{==>}%
\def\minus{-}%
\def\pounds{pounds}%
\def\point{.}%
\def\print{-|}%
\def\result{=>}%
\def\textdegree{degrees}%
%
% We need to get rid of all macros, leaving only the arguments (if present).
% Of course this is not nearly correct, but it is the best we can do for now.
% makeinfo does not expand macros in the argument to @deffn, which ends up
% writing an index entry, and texindex isn't prepared for an index sort entry
% that starts with \.
%
% Since macro invocations are followed by braces, we can just redefine them
% to take a single TeX argument. The case of a macro invocation that
% goes to end-of-line is not handled.
%
\macrolist
}
\let\indexbackslash=0 %overridden during \printindex.
\let\SETmarginindex=\relax % put index entries in margin (undocumented)?
% Most index entries go through here, but \dosubind is the general case.
% #1 is the index name, #2 is the entry text.
\def\doind#1#2{\dosubind{#1}{#2}{}}
% Workhorse for all \fooindexes.
% #1 is name of index, #2 is stuff to put there, #3 is subentry --
% empty if called from \doind, as we usually are (the main exception
% is with most defuns, which call us directly).
%
\def\dosubind#1#2#3{%
\iflinks
{%
% Store the main index entry text (including the third arg).
\toks0 = {#2}%
% If third arg is present, precede it with a space.
\def\thirdarg{#3}%
\ifx\thirdarg\empty \else
\toks0 = \expandafter{\the\toks0 \space #3}%
\fi
%
\edef\writeto{\csname#1indfile\endcsname}%
%
\ifvmode
\dosubindsanitize
\else
\dosubindwrite
\fi
}%
\fi
}
% Write the entry in \toks0 to the index file:
%
\def\dosubindwrite{%
% Put the index entry in the margin if desired.
\ifx\SETmarginindex\relax\else
\insert\margin{\hbox{\vrule height8pt depth3pt width0pt \the\toks0}}%
\fi
%
% Remember, we are within a group.
\indexdummies % Must do this here, since \bf, etc expand at this stage
\def\backslashcurfont{\indexbackslash}% \indexbackslash isn't defined now
% so it will be output as is; and it will print as backslash.
%
% Process the index entry with all font commands turned off, to
% get the string to sort by.
{\indexnofonts
\edef\temp{\the\toks0}% need full expansion
\xdef\indexsorttmp{\temp}%
}%
%
% Set up the complete index entry, with both the sort key and
% the original text, including any font commands. We write
% three arguments to \entry to the .?? file (four in the
% subentry case), texindex reduces to two when writing the .??s
% sorted result.
\edef\temp{%
\write\writeto{%
\string\entry{\indexsorttmp}{\noexpand\folio}{\the\toks0}}%
}%
\temp
}
% Take care of unwanted page breaks:
%
% If a skip is the last thing on the list now, preserve it
% by backing up by \lastskip, doing the \write, then inserting
% the skip again. Otherwise, the whatsit generated by the
% \write will make \lastskip zero. The result is that sequences
% like this:
% @end defun
% @tindex whatever
% @defun ...
% will have extra space inserted, because the \medbreak in the
% start of the @defun won't see the skip inserted by the @end of
% the previous defun.
%
% But don't do any of this if we're not in vertical mode. We
% don't want to do a \vskip and prematurely end a paragraph.
%
% Avoid page breaks due to these extra skips, too.
%
% But wait, there is a catch there:
% We'll have to check whether \lastskip is zero skip. \ifdim is not
% sufficient for this purpose, as it ignores stretch and shrink parts
% of the skip. The only way seems to be to check the textual
% representation of the skip.
%
% The following is almost like \def\zeroskipmacro{0.0pt} except that
% the ``p'' and ``t'' characters have catcode \other, not 11 (letter).
%
\edef\zeroskipmacro{\expandafter\the\csname z@skip\endcsname}
%
% ..., ready, GO:
%
\def\dosubindsanitize{%
% \lastskip and \lastpenalty cannot both be nonzero simultaneously.
\skip0 = \lastskip
\edef\lastskipmacro{\the\lastskip}%
\count255 = \lastpenalty
%
% If \lastskip is nonzero, that means the last item was a
% skip. And since a skip is discardable, that means this
% -\skip0 glue we're inserting is preceded by a
% non-discardable item, therefore it is not a potential
% breakpoint, therefore no \nobreak needed.
\ifx\lastskipmacro\zeroskipmacro
\else
\vskip-\skip0
\fi
%
\dosubindwrite
%
\ifx\lastskipmacro\zeroskipmacro
% If \lastskip was zero, perhaps the last item was a penalty, and
% perhaps it was >=10000, e.g., a \nobreak. In that case, we want
% to re-insert the same penalty (values >10000 are used for various
% signals); since we just inserted a non-discardable item, any
% following glue (such as a \parskip) would be a breakpoint. For example:
%
% @deffn deffn-whatever
% @vindex index-whatever
% Description.
% would allow a break between the index-whatever whatsit
% and the "Description." paragraph.
\ifnum\count255>9999 \penalty\count255 \fi
\else
% On the other hand, if we had a nonzero \lastskip,
% this make-up glue would be preceded by a non-discardable item
% (the whatsit from the \write), so we must insert a \nobreak.
\nobreak\vskip\skip0
\fi
}
% The index entry written in the file actually looks like
% \entry {sortstring}{page}{topic}
% or
% \entry {sortstring}{page}{topic}{subtopic}
% The texindex program reads in these files and writes files
% containing these kinds of lines:
% \initial {c}
% before the first topic whose initial is c
% \entry {topic}{pagelist}
% for a topic that is used without subtopics
% \primary {topic}
% for the beginning of a topic that is used with subtopics
% \secondary {subtopic}{pagelist}
% for each subtopic.
% Define the user-accessible indexing commands
% @findex, @vindex, @kindex, @cindex.
\def\findex {\fnindex}
\def\kindex {\kyindex}
\def\cindex {\cpindex}
\def\vindex {\vrindex}
\def\tindex {\tpindex}
\def\pindex {\pgindex}
\def\cindexsub {\begingroup\obeylines\cindexsub}
{\obeylines %
\gdef\cindexsub "#1" #2^^M{\endgroup %
\dosubind{cp}{#2}{#1}}}
% Define the macros used in formatting output of the sorted index material.
% @printindex causes a particular index (the ??s file) to get printed.
% It does not print any chapter heading (usually an @unnumbered).
%
\parseargdef\printindex{\begingroup
\dobreak \chapheadingskip{10000}%
%
\smallfonts \rm
\tolerance = 9500
\everypar = {}% don't want the \kern\-parindent from indentation suppression.
%
% See if the index file exists and is nonempty.
% Change catcode of @ here so that if the index file contains
% \initial {@}
% as its first line, TeX doesn't complain about mismatched braces
% (because it thinks @} is a control sequence).
\catcode`\@ = 11
\openin 1 \jobname.#1s
\ifeof 1
% \enddoublecolumns gets confused if there is no text in the index,
% and it loses the chapter title and the aux file entries for the
% index. The easiest way to prevent this problem is to make sure
% there is some text.
\putwordIndexNonexistent
\else
%
% If the index file exists but is empty, then \openin leaves \ifeof
% false. We have to make TeX try to read something from the file, so
% it can discover if there is anything in it.
\read 1 to \temp
\ifeof 1
\putwordIndexIsEmpty
\else
% Index files are almost Texinfo source, but we use \ as the escape
% character. It would be better to use @, but that's too big a change
% to make right now.
\def\indexbackslash{\backslashcurfont}%
\catcode`\\ = 0
\escapechar = `\\
\begindoublecolumns
\input \jobname.#1s
\enddoublecolumns
\fi
\fi
\closein 1
\endgroup}
% These macros are used by the sorted index file itself.
% Change them to control the appearance of the index.
\def\initial#1{{%
% Some minor font changes for the special characters.
\let\tentt=\sectt \let\tt=\sectt \let\sf=\sectt
%
% Remove any glue we may have, we'll be inserting our own.
\removelastskip
%
% We like breaks before the index initials, so insert a bonus.
\nobreak
\vskip 0pt plus 3\baselineskip
\penalty 0
\vskip 0pt plus -3\baselineskip
%
% Typeset the initial. Making this add up to a whole number of
% baselineskips increases the chance of the dots lining up from column
% to column. It still won't often be perfect, because of the stretch
% we need before each entry, but it's better.
%
% No shrink because it confuses \balancecolumns.
\vskip 1.67\baselineskip plus .5\baselineskip
\leftline{\secbf #1}%
% Do our best not to break after the initial.
\nobreak
\vskip .33\baselineskip plus .1\baselineskip
}}
% \entry typesets a paragraph consisting of the text (#1), dot leaders, and
% then page number (#2) flushed to the right margin. It is used for index
% and table of contents entries. The paragraph is indented by \leftskip.
%
% A straightforward implementation would start like this:
% \def\entry#1#2{...
% But this frozes the catcodes in the argument, and can cause problems to
% @code, which sets - active. This problem was fixed by a kludge---
% ``-'' was active throughout whole index, but this isn't really right.
%
% The right solution is to prevent \entry from swallowing the whole text.
% --kasal, 21nov03
\def\entry{%
\begingroup
%
% Start a new paragraph if necessary, so our assignments below can't
% affect previous text.
\par
%
% Do not fill out the last line with white space.
\parfillskip = 0in
%
% No extra space above this paragraph.
\parskip = 0in
%
% Do not prefer a separate line ending with a hyphen to fewer lines.
\finalhyphendemerits = 0
%
% \hangindent is only relevant when the entry text and page number
% don't both fit on one line. In that case, bob suggests starting the
% dots pretty far over on the line. Unfortunately, a large
% indentation looks wrong when the entry text itself is broken across
% lines. So we use a small indentation and put up with long leaders.
%
% \hangafter is reset to 1 (which is the value we want) at the start
% of each paragraph, so we need not do anything with that.
\hangindent = 2em
%
% When the entry text needs to be broken, just fill out the first line
% with blank space.
\rightskip = 0pt plus1fil
%
% A bit of stretch before each entry for the benefit of balancing
% columns.
\vskip 0pt plus1pt
%
% Swallow the left brace of the text (first parameter):
\afterassignment\doentry
\let\temp =
}
\def\doentry{%
\bgroup % Instead of the swallowed brace.
\noindent
\aftergroup\finishentry
% And now comes the text of the entry.
}
\def\finishentry#1{%
% #1 is the page number.
%
% The following is kludged to not output a line of dots in the index if
% there are no page numbers. The next person who breaks this will be
% cursed by a Unix daemon.
\def\tempa{{\rm }}%
\def\tempb{#1}%
\edef\tempc{\tempa}%
\edef\tempd{\tempb}%
\ifx\tempc\tempd
\ %
\else
%
% If we must, put the page number on a line of its own, and fill out
% this line with blank space. (The \hfil is overwhelmed with the
% fill leaders glue in \indexdotfill if the page number does fit.)
\hfil\penalty50
\null\nobreak\indexdotfill % Have leaders before the page number.
%
% The `\ ' here is removed by the implicit \unskip that TeX does as
% part of (the primitive) \par. Without it, a spurious underfull
% \hbox ensues.
\ifpdf
\pdfgettoks#1.%
\ \the\toksA
\else
\ #1%
\fi
\fi
\par
\endgroup
}
% Like plain.tex's \dotfill, except uses up at least 1 em.
\def\indexdotfill{\cleaders
\hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 1em plus 1fill}
\def\primary #1{\line{#1\hfil}}
\newskip\secondaryindent \secondaryindent=0.5cm
\def\secondary#1#2{{%
\parfillskip=0in
\parskip=0in
\hangindent=1in
\hangafter=1
\noindent\hskip\secondaryindent\hbox{#1}\indexdotfill
\ifpdf
\pdfgettoks#2.\ \the\toksA % The page number ends the paragraph.
\else
#2
\fi
\par
}}
% Define two-column mode, which we use to typeset indexes.
% Adapted from the TeXbook, page 416, which is to say,
% the manmac.tex format used to print the TeXbook itself.
\catcode`\@=11
\newbox\partialpage
\newdimen\doublecolumnhsize
\def\begindoublecolumns{\begingroup % ended by \enddoublecolumns
% Grab any single-column material above us.
\output = {%
%
% Here is a possibility not foreseen in manmac: if we accumulate a
% whole lot of material, we might end up calling this \output
% routine twice in a row (see the doublecol-lose test, which is
% essentially a couple of indexes with @setchapternewpage off). In
% that case we just ship out what is in \partialpage with the normal
% output routine. Generally, \partialpage will be empty when this
% runs and this will be a no-op. See the indexspread.tex test case.
\ifvoid\partialpage \else
\onepageout{\pagecontents\partialpage}%
\fi
%
\global\setbox\partialpage = \vbox{%
% Unvbox the main output page.
\unvbox\PAGE
\kern-\topskip \kern\baselineskip
}%
}%
\eject % run that output routine to set \partialpage
%
% Use the double-column output routine for subsequent pages.
\output = {\doublecolumnout}%
%
% Change the page size parameters. We could do this once outside this
% routine, in each of @smallbook, @afourpaper, and the default 8.5x11
% format, but then we repeat the same computation. Repeating a couple
% of assignments once per index is clearly meaningless for the
% execution time, so we may as well do it in one place.
%
% First we halve the line length, less a little for the gutter between
% the columns. We compute the gutter based on the line length, so it
% changes automatically with the paper format. The magic constant
% below is chosen so that the gutter has the same value (well, +-<1pt)
% as it did when we hard-coded it.
%
% We put the result in a separate register, \doublecolumhsize, so we
% can restore it in \pagesofar, after \hsize itself has (potentially)
% been clobbered.
%
\doublecolumnhsize = \hsize
\advance\doublecolumnhsize by -.04154\hsize
\divide\doublecolumnhsize by 2
\hsize = \doublecolumnhsize
%
% Double the \vsize as well. (We don't need a separate register here,
% since nobody clobbers \vsize.)
\vsize = 2\vsize
}
% The double-column output routine for all double-column pages except
% the last.
%
\def\doublecolumnout{%
\splittopskip=\topskip \splitmaxdepth=\maxdepth
% Get the available space for the double columns -- the normal
% (undoubled) page height minus any material left over from the
% previous page.
\dimen@ = \vsize
\divide\dimen@ by 2
\advance\dimen@ by -\ht\partialpage
%
% box0 will be the left-hand column, box2 the right.
\setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@
\onepageout\pagesofar
\unvbox255
\penalty\outputpenalty
}
%
% Re-output the contents of the output page -- any previous material,
% followed by the two boxes we just split, in box0 and box2.
\def\pagesofar{%
\unvbox\partialpage
%
\hsize = \doublecolumnhsize
\wd0=\hsize \wd2=\hsize
\hbox to\pagewidth{\box0\hfil\box2}%
}
%
% All done with double columns.
\def\enddoublecolumns{%
\output = {%
% Split the last of the double-column material. Leave it on the
% current page, no automatic page break.
\balancecolumns
%
% If we end up splitting too much material for the current page,
% though, there will be another page break right after this \output
% invocation ends. Having called \balancecolumns once, we do not
% want to call it again. Therefore, reset \output to its normal
% definition right away. (We hope \balancecolumns will never be
% called on to balance too much material, but if it is, this makes
% the output somewhat more palatable.)
\global\output = {\onepageout{\pagecontents\PAGE}}%
}%
\eject
\endgroup % started in \begindoublecolumns
%
% \pagegoal was set to the doubled \vsize above, since we restarted
% the current page. We're now back to normal single-column
% typesetting, so reset \pagegoal to the normal \vsize (after the
% \endgroup where \vsize got restored).
\pagegoal = \vsize
}
%
% Called at the end of the double column material.
\def\balancecolumns{%
\setbox0 = \vbox{\unvbox255}% like \box255 but more efficient, see p.120.
\dimen@ = \ht0
\advance\dimen@ by \topskip
\advance\dimen@ by-\baselineskip
\divide\dimen@ by 2 % target to split to
%debug\message{final 2-column material height=\the\ht0, target=\the\dimen@.}%
\splittopskip = \topskip
% Loop until we get a decent breakpoint.
{%
\vbadness = 10000
\loop
\global\setbox3 = \copy0
\global\setbox1 = \vsplit3 to \dimen@
\ifdim\ht3>\dimen@
\global\advance\dimen@ by 1pt
\repeat
}%
%debug\message{split to \the\dimen@, column heights: \the\ht1, \the\ht3.}%
\setbox0=\vbox to\dimen@{\unvbox1}%
\setbox2=\vbox to\dimen@{\unvbox3}%
%
\pagesofar
}
\catcode`\@ = \other
\message{sectioning,}
% Chapters, sections, etc.
% \unnumberedno is an oxymoron, of course. But we count the unnumbered
% sections so that we can refer to them unambiguously in the pdf
% outlines by their "section number". We avoid collisions with chapter
% numbers by starting them at 10000. (If a document ever has 10000
% chapters, we're in trouble anyway, I'm sure.)
\newcount\unnumberedno \unnumberedno = 10000
\newcount\chapno
\newcount\secno \secno=0
\newcount\subsecno \subsecno=0
\newcount\subsubsecno \subsubsecno=0
% This counter is funny since it counts through charcodes of letters A, B, ...
\newcount\appendixno \appendixno = `\@
%
% \def\appendixletter{\char\the\appendixno}
% We do the following ugly conditional instead of the above simple
% construct for the sake of pdftex, which needs the actual
% letter in the expansion, not just typeset.
%
\def\appendixletter{%
\ifnum\appendixno=`A A%
\else\ifnum\appendixno=`B B%
\else\ifnum\appendixno=`C C%
\else\ifnum\appendixno=`D D%
\else\ifnum\appendixno=`E E%
\else\ifnum\appendixno=`F F%
\else\ifnum\appendixno=`G G%
\else\ifnum\appendixno=`H H%
\else\ifnum\appendixno=`I I%
\else\ifnum\appendixno=`J J%
\else\ifnum\appendixno=`K K%
\else\ifnum\appendixno=`L L%
\else\ifnum\appendixno=`M M%
\else\ifnum\appendixno=`N N%
\else\ifnum\appendixno=`O O%
\else\ifnum\appendixno=`P P%
\else\ifnum\appendixno=`Q Q%
\else\ifnum\appendixno=`R R%
\else\ifnum\appendixno=`S S%
\else\ifnum\appendixno=`T T%
\else\ifnum\appendixno=`U U%
\else\ifnum\appendixno=`V V%
\else\ifnum\appendixno=`W W%
\else\ifnum\appendixno=`X X%
\else\ifnum\appendixno=`Y Y%
\else\ifnum\appendixno=`Z Z%
% The \the is necessary, despite appearances, because \appendixletter is
% expanded while writing the .toc file. \char\appendixno is not
% expandable, thus it is written literally, thus all appendixes come out
% with the same letter (or @) in the toc without it.
\else\char\the\appendixno
\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi}
% Each @chapter defines this as the name of the chapter.
% page headings and footings can use it. @section does likewise.
% However, they are not reliable, because we don't use marks.
\def\thischapter{}
\def\thissection{}
\newcount\absseclevel % used to calculate proper heading level
\newcount\secbase\secbase=0 % @raisesections/@lowersections modify this count
% @raisesections: treat @section as chapter, @subsection as section, etc.
\def\raisesections{\global\advance\secbase by -1}
\let\up=\raisesections % original BFox name
% @lowersections: treat @chapter as section, @section as subsection, etc.
\def\lowersections{\global\advance\secbase by 1}
\let\down=\lowersections % original BFox name
% we only have subsub.
\chardef\maxseclevel = 3
%
% A numbered section within an unnumbered changes to unnumbered too.
% To achive this, remember the "biggest" unnum. sec. we are currently in:
\chardef\unmlevel = \maxseclevel
%
% Trace whether the current chapter is an appendix or not:
% \chapheadtype is "N" or "A", unnumbered chapters are ignored.
\def\chapheadtype{N}
% Choose a heading macro
% #1 is heading type
% #2 is heading level
% #3 is text for heading
\def\genhead#1#2#3{%
% Compute the abs. sec. level:
\absseclevel=#2
\advance\absseclevel by \secbase
% Make sure \absseclevel doesn't fall outside the range:
\ifnum \absseclevel < 0
\absseclevel = 0
\else
\ifnum \absseclevel > 3
\absseclevel = 3
\fi
\fi
% The heading type:
\def\headtype{#1}%
\if \headtype U%
\ifnum \absseclevel < \unmlevel
\chardef\unmlevel = \absseclevel
\fi
\else
% Check for appendix sections:
\ifnum \absseclevel = 0
\edef\chapheadtype{\headtype}%
\else
\if \headtype A\if \chapheadtype N%
\errmessage{@appendix... within a non-appendix chapter}%
\fi\fi
\fi
% Check for numbered within unnumbered:
\ifnum \absseclevel > \unmlevel
\def\headtype{U}%
\else
\chardef\unmlevel = 3
\fi
\fi
% Now print the heading:
\if \headtype U%
\ifcase\absseclevel
\unnumberedzzz{#3}%
\or \unnumberedseczzz{#3}%
\or \unnumberedsubseczzz{#3}%
\or \unnumberedsubsubseczzz{#3}%
\fi
\else
\if \headtype A%
\ifcase\absseclevel
\appendixzzz{#3}%
\or \appendixsectionzzz{#3}%
\or \appendixsubseczzz{#3}%
\or \appendixsubsubseczzz{#3}%
\fi
\else
\ifcase\absseclevel
\chapterzzz{#3}%
\or \seczzz{#3}%
\or \numberedsubseczzz{#3}%
\or \numberedsubsubseczzz{#3}%
\fi
\fi
\fi
\suppressfirstparagraphindent
}
% an interface:
\def\numhead{\genhead N}
\def\apphead{\genhead A}
\def\unnmhead{\genhead U}
% @chapter, @appendix, @unnumbered. Increment top-level counter, reset
% all lower-level sectioning counters to zero.
%
% Also set \chaplevelprefix, which we prepend to @float sequence numbers
% (e.g., figures), q.v. By default (before any chapter), that is empty.
\let\chaplevelprefix = \empty
%
\outer\parseargdef\chapter{\numhead0{#1}} % normally numhead0 calls chapterzzz
\def\chapterzzz#1{%
% section resetting is \global in case the chapter is in a group, such
% as an @include file.
\global\secno=0 \global\subsecno=0 \global\subsubsecno=0
\global\advance\chapno by 1
%
% Used for \float.
\gdef\chaplevelprefix{\the\chapno.}%
\resetallfloatnos
%
\message{\putwordChapter\space \the\chapno}%
%
% Write the actual heading.
\chapmacro{#1}{Ynumbered}{\the\chapno}%
%
% So @section and the like are numbered underneath this chapter.
\global\let\section = \numberedsec
\global\let\subsection = \numberedsubsec
\global\let\subsubsection = \numberedsubsubsec
}
\outer\parseargdef\appendix{\apphead0{#1}} % normally apphead0 calls appendixzzz
\def\appendixzzz#1{%
\global\secno=0 \global\subsecno=0 \global\subsubsecno=0
\global\advance\appendixno by 1
\gdef\chaplevelprefix{\appendixletter.}%
\resetallfloatnos
%
\def\appendixnum{\putwordAppendix\space \appendixletter}%
\message{\appendixnum}%
%
\chapmacro{#1}{Yappendix}{\appendixletter}%
%
\global\let\section = \appendixsec
\global\let\subsection = \appendixsubsec
\global\let\subsubsection = \appendixsubsubsec
}
\outer\parseargdef\unnumbered{\unnmhead0{#1}} % normally unnmhead0 calls unnumberedzzz
\def\unnumberedzzz#1{%
\global\secno=0 \global\subsecno=0 \global\subsubsecno=0
\global\advance\unnumberedno by 1
%
% Since an unnumbered has no number, no prefix for figures.
\global\let\chaplevelprefix = \empty
\resetallfloatnos
%
% This used to be simply \message{#1}, but TeX fully expands the
% argument to \message. Therefore, if #1 contained @-commands, TeX
% expanded them. For example, in `@unnumbered The @cite{Book}', TeX
% expanded @cite (which turns out to cause errors because \cite is meant
% to be executed, not expanded).
%
% Anyway, we don't want the fully-expanded definition of @cite to appear
% as a result of the \message, we just want `@cite' itself. We use
% \the<toks register> to achieve this: TeX expands \the<toks> only once,
% simply yielding the contents of <toks register>. (We also do this for
% the toc entries.)
\toks0 = {#1}%
\message{(\the\toks0)}%
%
\chapmacro{#1}{Ynothing}{\the\unnumberedno}%
%
\global\let\section = \unnumberedsec
\global\let\subsection = \unnumberedsubsec
\global\let\subsubsection = \unnumberedsubsubsec
}
% @centerchap is like @unnumbered, but the heading is centered.
\outer\parseargdef\centerchap{%
% Well, we could do the following in a group, but that would break
% an assumption that \chapmacro is called at the outermost level.
% Thus we are safer this way: --kasal, 24feb04
\let\centerparametersmaybe = \centerparameters
\unnmhead0{#1}%
\let\centerparametersmaybe = \relax
}
% @top is like @unnumbered.
\let\top\unnumbered
% Sections.
\outer\parseargdef\numberedsec{\numhead1{#1}} % normally calls seczzz
\def\seczzz#1{%
\global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1
\sectionheading{#1}{sec}{Ynumbered}{\the\chapno.\the\secno}%
}
\outer\parseargdef\appendixsection{\apphead1{#1}} % normally calls appendixsectionzzz
\def\appendixsectionzzz#1{%
\global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1
\sectionheading{#1}{sec}{Yappendix}{\appendixletter.\the\secno}%
}
\let\appendixsec\appendixsection
\outer\parseargdef\unnumberedsec{\unnmhead1{#1}} % normally calls unnumberedseczzz
\def\unnumberedseczzz#1{%
\global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1
\sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno.\the\secno}%
}
% Subsections.
\outer\parseargdef\numberedsubsec{\numhead2{#1}} % normally calls numberedsubseczzz
\def\numberedsubseczzz#1{%
\global\subsubsecno=0 \global\advance\subsecno by 1
\sectionheading{#1}{subsec}{Ynumbered}{\the\chapno.\the\secno.\the\subsecno}%
}
\outer\parseargdef\appendixsubsec{\apphead2{#1}} % normally calls appendixsubseczzz
\def\appendixsubseczzz#1{%
\global\subsubsecno=0 \global\advance\subsecno by 1
\sectionheading{#1}{subsec}{Yappendix}%
{\appendixletter.\the\secno.\the\subsecno}%
}
\outer\parseargdef\unnumberedsubsec{\unnmhead2{#1}} %normally calls unnumberedsubseczzz
\def\unnumberedsubseczzz#1{%
\global\subsubsecno=0 \global\advance\subsecno by 1
\sectionheading{#1}{subsec}{Ynothing}%
{\the\unnumberedno.\the\secno.\the\subsecno}%
}
% Subsubsections.
\outer\parseargdef\numberedsubsubsec{\numhead3{#1}} % normally numberedsubsubseczzz
\def\numberedsubsubseczzz#1{%
\global\advance\subsubsecno by 1
\sectionheading{#1}{subsubsec}{Ynumbered}%
{\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno}%
}
\outer\parseargdef\appendixsubsubsec{\apphead3{#1}} % normally appendixsubsubseczzz
\def\appendixsubsubseczzz#1{%
\global\advance\subsubsecno by 1
\sectionheading{#1}{subsubsec}{Yappendix}%
{\appendixletter.\the\secno.\the\subsecno.\the\subsubsecno}%
}
\outer\parseargdef\unnumberedsubsubsec{\unnmhead3{#1}} %normally unnumberedsubsubseczzz
\def\unnumberedsubsubseczzz#1{%
\global\advance\subsubsecno by 1
\sectionheading{#1}{subsubsec}{Ynothing}%
{\the\unnumberedno.\the\secno.\the\subsecno.\the\subsubsecno}%
}
% These macros control what the section commands do, according
% to what kind of chapter we are in (ordinary, appendix, or unnumbered).
% Define them by default for a numbered chapter.
\let\section = \numberedsec
\let\subsection = \numberedsubsec
\let\subsubsection = \numberedsubsubsec
% Define @majorheading, @heading and @subheading
% NOTE on use of \vbox for chapter headings, section headings, and such:
% 1) We use \vbox rather than the earlier \line to permit
% overlong headings to fold.
% 2) \hyphenpenalty is set to 10000 because hyphenation in a
% heading is obnoxious; this forbids it.
% 3) Likewise, headings look best if no \parindent is used, and
% if justification is not attempted. Hence \raggedright.
\def\majorheading{%
{\advance\chapheadingskip by 10pt \chapbreak }%
\parsearg\chapheadingzzz
}
\def\chapheading{\chapbreak \parsearg\chapheadingzzz}
\def\chapheadingzzz#1{%
{\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
\parindent=0pt\raggedright
\rm #1\hfill}}%
\bigskip \par\penalty 200\relax
\suppressfirstparagraphindent
}
% @heading, @subheading, @subsubheading.
\parseargdef\heading{\sectionheading{#1}{sec}{Yomitfromtoc}{}
\suppressfirstparagraphindent}
\parseargdef\subheading{\sectionheading{#1}{subsec}{Yomitfromtoc}{}
\suppressfirstparagraphindent}
\parseargdef\subsubheading{\sectionheading{#1}{subsubsec}{Yomitfromtoc}{}
\suppressfirstparagraphindent}
% These macros generate a chapter, section, etc. heading only
% (including whitespace, linebreaking, etc. around it),
% given all the information in convenient, parsed form.
%%% Args are the skip and penalty (usually negative)
\def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi}
%%% Define plain chapter starts, and page on/off switching for it
% Parameter controlling skip before chapter headings (if needed)
\newskip\chapheadingskip
\def\chapbreak{\dobreak \chapheadingskip {-4000}}
\def\chappager{\par\vfill\supereject}
\def\chapoddpage{\chappager \ifodd\pageno \else \hbox to 0pt{} \chappager\fi}
\def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname}
\def\CHAPPAGoff{%
\global\let\contentsalignmacro = \chappager
\global\let\pchapsepmacro=\chapbreak
\global\let\pagealignmacro=\chappager}
\def\CHAPPAGon{%
\global\let\contentsalignmacro = \chappager
\global\let\pchapsepmacro=\chappager
\global\let\pagealignmacro=\chappager
\global\def\HEADINGSon{\HEADINGSsingle}}
\def\CHAPPAGodd{%
\global\let\contentsalignmacro = \chapoddpage
\global\let\pchapsepmacro=\chapoddpage
\global\let\pagealignmacro=\chapoddpage
\global\def\HEADINGSon{\HEADINGSdouble}}
\CHAPPAGon
% Chapter opening.
%
% #1 is the text, #2 is the section type (Ynumbered, Ynothing,
% Yappendix, Yomitfromtoc), #3 the chapter number.
%
% To test against our argument.
\def\Ynothingkeyword{Ynothing}
\def\Yomitfromtockeyword{Yomitfromtoc}
\def\Yappendixkeyword{Yappendix}
%
\def\chapmacro#1#2#3{%
\pchapsepmacro
{%
\chapfonts \rm
%
% Have to define \thissection before calling \donoderef, because the
% xref code eventually uses it. On the other hand, it has to be called
% after \pchapsepmacro, or the headline will change too soon.
\gdef\thissection{#1}%
\gdef\thischaptername{#1}%
%
% Only insert the separating space if we have a chapter/appendix
% number, and don't print the unnumbered ``number''.
\def\temptype{#2}%
\ifx\temptype\Ynothingkeyword
\setbox0 = \hbox{}%
\def\toctype{unnchap}%
\gdef\thischapternum{}%
\gdef\thischapter{#1}%
\else\ifx\temptype\Yomitfromtockeyword
\setbox0 = \hbox{}% contents like unnumbered, but no toc entry
\def\toctype{omit}%
\gdef\thischapternum{}%
\gdef\thischapter{}%
\else\ifx\temptype\Yappendixkeyword
\setbox0 = \hbox{\putwordAppendix{} #3\enspace}%
\def\toctype{app}%
\xdef\thischapternum{\appendixletter}%
% We don't substitute the actual chapter name into \thischapter
% because we don't want its macros evaluated now. And we don't
% use \thissection because that changes with each section.
%
\xdef\thischapter{\putwordAppendix{} \appendixletter:
\noexpand\thischaptername}%
\else
\setbox0 = \hbox{#3\enspace}%
\def\toctype{numchap}%
\xdef\thischapternum{\the\chapno}%
\xdef\thischapter{\putwordChapter{} \the\chapno:
\noexpand\thischaptername}%
\fi\fi\fi
%
% Write the toc entry for this chapter. Must come before the
% \donoderef, because we include the current node name in the toc
% entry, and \donoderef resets it to empty.
\writetocentry{\toctype}{#1}{#3}%
%
% For pdftex, we have to write out the node definition (aka, make
% the pdfdest) after any page break, but before the actual text has
% been typeset. If the destination for the pdf outline is after the
% text, then jumping from the outline may wind up with the text not
% being visible, for instance under high magnification.
\donoderef{#2}%
%
% Typeset the actual heading.
\vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright
\hangindent=\wd0 \centerparametersmaybe
\unhbox0 #1\par}%
}%
\nobreak\bigskip % no page break after a chapter title
\nobreak
}
% @centerchap -- centered and unnumbered.
\let\centerparametersmaybe = \relax
\def\centerparameters{%
\advance\rightskip by 3\rightskip
\leftskip = \rightskip
\parfillskip = 0pt
}
% I don't think this chapter style is supported any more, so I'm not
% updating it with the new noderef stuff. We'll see. --karl, 11aug03.
%
\def\setchapterstyle #1 {\csname CHAPF#1\endcsname}
%
\def\unnchfopen #1{%
\chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
\parindent=0pt\raggedright
\rm #1\hfill}}\bigskip \par\nobreak
}
\def\chfopen #1#2{\chapoddpage {\chapfonts
\vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}%
\par\penalty 5000 %
}
\def\centerchfopen #1{%
\chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
\parindent=0pt
\hfill {\rm #1}\hfill}}\bigskip \par\nobreak
}
\def\CHAPFopen{%
\global\let\chapmacro=\chfopen
\global\let\centerchapmacro=\centerchfopen}
% Section titles. These macros combine the section number parts and
% call the generic \sectionheading to do the printing.
%
\newskip\secheadingskip
\def\secheadingbreak{\dobreak \secheadingskip{-1000}}
% Subsection titles.
\newskip\subsecheadingskip
\def\subsecheadingbreak{\dobreak \subsecheadingskip{-500}}
% Subsubsection titles.
\def\subsubsecheadingskip{\subsecheadingskip}
\def\subsubsecheadingbreak{\subsecheadingbreak}
% Print any size, any type, section title.
%
% #1 is the text, #2 is the section level (sec/subsec/subsubsec), #3 is
% the section type for xrefs (Ynumbered, Ynothing, Yappendix), #4 is the
% section number.
%
\def\sectionheading#1#2#3#4{%
{%
% Switch to the right set of fonts.
\csname #2fonts\endcsname \rm
%
% Insert space above the heading.
\csname #2headingbreak\endcsname
%
% Only insert the space after the number if we have a section number.
\def\sectionlevel{#2}%
\def\temptype{#3}%
%
\ifx\temptype\Ynothingkeyword
\setbox0 = \hbox{}%
\def\toctype{unn}%
\gdef\thissection{#1}%
\else\ifx\temptype\Yomitfromtockeyword
% for @headings -- no section number, don't include in toc,
% and don't redefine \thissection.
\setbox0 = \hbox{}%
\def\toctype{omit}%
\let\sectionlevel=\empty
\else\ifx\temptype\Yappendixkeyword
\setbox0 = \hbox{#4\enspace}%
\def\toctype{app}%
\gdef\thissection{#1}%
\else
\setbox0 = \hbox{#4\enspace}%
\def\toctype{num}%
\gdef\thissection{#1}%
\fi\fi\fi
%
% Write the toc entry (before \donoderef). See comments in \chapmacro.
\writetocentry{\toctype\sectionlevel}{#1}{#4}%
%
% Write the node reference (= pdf destination for pdftex).
% Again, see comments in \chapmacro.
\donoderef{#3}%
%
% Interline glue will be inserted when the vbox is completed.
% That glue will be a valid breakpoint for the page, since it'll be
% preceded by a whatsit (usually from the \donoderef, or from the
% \writetocentry if there was no node). We don't want to allow that
% break, since then the whatsits could end up on page n while the
% section is on page n+1, thus toc/etc. are wrong. Debian bug 276000.
\nobreak
%
% Output the actual section heading.
\vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright
\hangindent=\wd0 % zero if no section number
\unhbox0 #1}%
}%
% Add extra space after the heading -- half of whatever came above it.
% Don't allow stretch, though.
\kern .5 \csname #2headingskip\endcsname
%
% Do not let the kern be a potential breakpoint, as it would be if it
% was followed by glue.
\nobreak
%
% We'll almost certainly start a paragraph next, so don't let that
% glue accumulate. (Not a breakpoint because it's preceded by a
% discardable item.)
\vskip-\parskip
%
% This is purely so the last item on the list is a known \penalty >
% 10000. This is so \startdefun can avoid allowing breakpoints after
% section headings. Otherwise, it would insert a valid breakpoint between:
%
% @section sec-whatever
% @deffn def-whatever
\penalty 10001
}
\message{toc,}
% Table of contents.
\newwrite\tocfile
% Write an entry to the toc file, opening it if necessary.
% Called from @chapter, etc.
%
% Example usage: \writetocentry{sec}{Section Name}{\the\chapno.\the\secno}
% We append the current node name (if any) and page number as additional
% arguments for the \{chap,sec,...}entry macros which will eventually
% read this. The node name is used in the pdf outlines as the
% destination to jump to.
%
% We open the .toc file for writing here instead of at @setfilename (or
% any other fixed time) so that @contents can be anywhere in the document.
% But if #1 is `omit', then we don't do anything. This is used for the
% table of contents chapter openings themselves.
%
\newif\iftocfileopened
\def\omitkeyword{omit}%
%
\def\writetocentry#1#2#3{%
\edef\writetoctype{#1}%
\ifx\writetoctype\omitkeyword \else
\iftocfileopened\else
\immediate\openout\tocfile = \jobname.toc
\global\tocfileopenedtrue
\fi
%
\iflinks
{\atdummies
\edef\temp{%
\write\tocfile{@#1entry{#2}{#3}{\lastnode}{\noexpand\folio}}}%
\temp
}%
\fi
\fi
%
% Tell \shipout to create a pdf destination on each page, if we're
% writing pdf. These are used in the table of contents. We can't
% just write one on every page because the title pages are numbered
% 1 and 2 (the page numbers aren't printed), and so are the first
% two pages of the document. Thus, we'd have two destinations named
% `1', and two named `2'.
\ifpdf \global\pdfmakepagedesttrue \fi
}
% These characters do not print properly in the Computer Modern roman
% fonts, so we must take special care. This is more or less redundant
% with the Texinfo input format setup at the end of this file.
%
\def\activecatcodes{%
\catcode`\"=\active
\catcode`\$=\active
\catcode`\<=\active
\catcode`\>=\active
\catcode`\\=\active
\catcode`\^=\active
\catcode`\_=\active
\catcode`\|=\active
\catcode`\~=\active
}
% Read the toc file, which is essentially Texinfo input.
\def\readtocfile{%
\setupdatafile
\activecatcodes
\input \jobname.toc
}
\newskip\contentsrightmargin \contentsrightmargin=1in
\newcount\savepageno
\newcount\lastnegativepageno \lastnegativepageno = -1
% Prepare to read what we've written to \tocfile.
%
\def\startcontents#1{%
% If @setchapternewpage on, and @headings double, the contents should
% start on an odd page, unlike chapters. Thus, we maintain
% \contentsalignmacro in parallel with \pagealignmacro.
% From: Torbjorn Granlund <tege@matematik.su.se>
\contentsalignmacro
\immediate\closeout\tocfile
%
% Don't need to put `Contents' or `Short Contents' in the headline.
% It is abundantly clear what they are.
\def\thischapter{}%
\chapmacro{#1}{Yomitfromtoc}{}%
%
\savepageno = \pageno
\begingroup % Set up to handle contents files properly.
\raggedbottom % Worry more about breakpoints than the bottom.
\advance\hsize by -\contentsrightmargin % Don't use the full line length.
%
% Roman numerals for page numbers.
\ifnum \pageno>0 \global\pageno = \lastnegativepageno \fi
}
% Normal (long) toc.
\def\contents{%
\startcontents{\putwordTOC}%
\openin 1 \jobname.toc
\ifeof 1 \else
\readtocfile
\fi
\vfill \eject
\contentsalignmacro % in case @setchapternewpage odd is in effect
\ifeof 1 \else
\pdfmakeoutlines
\fi
\closein 1
\endgroup
\lastnegativepageno = \pageno
\global\pageno = \savepageno
}
% And just the chapters.
\def\summarycontents{%
\startcontents{\putwordShortTOC}%
%
\let\numchapentry = \shortchapentry
\let\appentry = \shortchapentry
\let\unnchapentry = \shortunnchapentry
% We want a true roman here for the page numbers.
\secfonts
\let\rm=\shortcontrm \let\bf=\shortcontbf
\let\sl=\shortcontsl \let\tt=\shortconttt
\rm
\hyphenpenalty = 10000
\advance\baselineskip by 1pt % Open it up a little.
\def\numsecentry##1##2##3##4{}
\let\appsecentry = \numsecentry
\let\unnsecentry = \numsecentry
\let\numsubsecentry = \numsecentry
\let\appsubsecentry = \numsecentry
\let\unnsubsecentry = \numsecentry
\let\numsubsubsecentry = \numsecentry
\let\appsubsubsecentry = \numsecentry
\let\unnsubsubsecentry = \numsecentry
\openin 1 \jobname.toc
\ifeof 1 \else
\readtocfile
\fi
\closein 1
\vfill \eject
\contentsalignmacro % in case @setchapternewpage odd is in effect
\endgroup
\lastnegativepageno = \pageno
\global\pageno = \savepageno
}
\let\shortcontents = \summarycontents
% Typeset the label for a chapter or appendix for the short contents.
% The arg is, e.g., `A' for an appendix, or `3' for a chapter.
%
\def\shortchaplabel#1{%
% This space should be enough, since a single number is .5em, and the
% widest letter (M) is 1em, at least in the Computer Modern fonts.
% But use \hss just in case.
% (This space doesn't include the extra space that gets added after
% the label; that gets put in by \shortchapentry above.)
%
% We'd like to right-justify chapter numbers, but that looks strange
% with appendix letters. And right-justifying numbers and
% left-justifying letters looks strange when there is less than 10
% chapters. Have to read the whole toc once to know how many chapters
% there are before deciding ...
\hbox to 1em{#1\hss}%
}
% These macros generate individual entries in the table of contents.
% The first argument is the chapter or section name.
% The last argument is the page number.
% The arguments in between are the chapter number, section number, ...
% Chapters, in the main contents.
\def\numchapentry#1#2#3#4{\dochapentry{#2\labelspace#1}{#4}}
%
% Chapters, in the short toc.
% See comments in \dochapentry re vbox and related settings.
\def\shortchapentry#1#2#3#4{%
\tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#4\egroup}%
}
% Appendices, in the main contents.
% Need the word Appendix, and a fixed-size box.
%
\def\appendixbox#1{%
% We use M since it's probably the widest letter.
\setbox0 = \hbox{\putwordAppendix{} M}%
\hbox to \wd0{\putwordAppendix{} #1\hss}}
%
\def\appentry#1#2#3#4{\dochapentry{\appendixbox{#2}\labelspace#1}{#4}}
% Unnumbered chapters.
\def\unnchapentry#1#2#3#4{\dochapentry{#1}{#4}}
\def\shortunnchapentry#1#2#3#4{\tocentry{#1}{\doshortpageno\bgroup#4\egroup}}
% Sections.
\def\numsecentry#1#2#3#4{\dosecentry{#2\labelspace#1}{#4}}
\let\appsecentry=\numsecentry
\def\unnsecentry#1#2#3#4{\dosecentry{#1}{#4}}
% Subsections.
\def\numsubsecentry#1#2#3#4{\dosubsecentry{#2\labelspace#1}{#4}}
\let\appsubsecentry=\numsubsecentry
\def\unnsubsecentry#1#2#3#4{\dosubsecentry{#1}{#4}}
% And subsubsections.
\def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#2\labelspace#1}{#4}}
\let\appsubsubsecentry=\numsubsubsecentry
\def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#4}}
% This parameter controls the indentation of the various levels.
% Same as \defaultparindent.
\newdimen\tocindent \tocindent = 15pt
% Now for the actual typesetting. In all these, #1 is the text and #2 is the
% page number.
%
% If the toc has to be broken over pages, we want it to be at chapters
% if at all possible; hence the \penalty.
\def\dochapentry#1#2{%
\penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip
\begingroup
\chapentryfonts
\tocentry{#1}{\dopageno\bgroup#2\egroup}%
\endgroup
\nobreak\vskip .25\baselineskip plus.1\baselineskip
}
\def\dosecentry#1#2{\begingroup
\secentryfonts \leftskip=\tocindent
\tocentry{#1}{\dopageno\bgroup#2\egroup}%
\endgroup}
\def\dosubsecentry#1#2{\begingroup
\subsecentryfonts \leftskip=2\tocindent
\tocentry{#1}{\dopageno\bgroup#2\egroup}%
\endgroup}
\def\dosubsubsecentry#1#2{\begingroup
\subsubsecentryfonts \leftskip=3\tocindent
\tocentry{#1}{\dopageno\bgroup#2\egroup}%
\endgroup}
% We use the same \entry macro as for the index entries.
\let\tocentry = \entry
% Space between chapter (or whatever) number and the title.
\def\labelspace{\hskip1em \relax}
\def\dopageno#1{{\rm #1}}
\def\doshortpageno#1{{\rm #1}}
\def\chapentryfonts{\secfonts \rm}
\def\secentryfonts{\textfonts}
\def\subsecentryfonts{\textfonts}
\def\subsubsecentryfonts{\textfonts}
\message{environments,}
% @foo ... @end foo.
% @point{}, @result{}, @expansion{}, @print{}, @equiv{}.
%
% Since these characters are used in examples, it should be an even number of
% \tt widths. Each \tt character is 1en, so two makes it 1em.
%
\def\point{$\star$}
\def\result{\leavevmode\raise.15ex\hbox to 1em{\hfil$\Rightarrow$\hfil}}
\def\expansion{\leavevmode\raise.1ex\hbox to 1em{\hfil$\mapsto$\hfil}}
\def\print{\leavevmode\lower.1ex\hbox to 1em{\hfil$\dashv$\hfil}}
\def\equiv{\leavevmode\lower.1ex\hbox to 1em{\hfil$\ptexequiv$\hfil}}
% The @error{} command.
% Adapted from the TeXbook's \boxit.
%
\newbox\errorbox
%
{\tentt \global\dimen0 = 3em}% Width of the box.
\dimen2 = .55pt % Thickness of rules
% The text. (`r' is open on the right, `e' somewhat less so on the left.)
\setbox0 = \hbox{\kern-.75pt \reducedsf error\kern-1.5pt}
%
\setbox\errorbox=\hbox to \dimen0{\hfil
\hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right.
\advance\hsize by -2\dimen2 % Rules.
\vbox{%
\hrule height\dimen2
\hbox{\vrule width\dimen2 \kern3pt % Space to left of text.
\vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below.
\kern3pt\vrule width\dimen2}% Space to right.
\hrule height\dimen2}
\hfil}
%
\def\error{\leavevmode\lower.7ex\copy\errorbox}
% @tex ... @end tex escapes into raw Tex temporarily.
% One exception: @ is still an escape character, so that @end tex works.
% But \@ or @@ will get a plain tex @ character.
\envdef\tex{%
\catcode `\\=0 \catcode `\{=1 \catcode `\}=2
\catcode `\$=3 \catcode `\&=4 \catcode `\#=6
\catcode `\^=7 \catcode `\_=8 \catcode `\~=\active \let~=\tie
\catcode `\%=14
\catcode `\+=\other
\catcode `\"=\other
\catcode `\|=\other
\catcode `\<=\other
\catcode `\>=\other
\escapechar=`\\
%
\let\b=\ptexb
\let\bullet=\ptexbullet
\let\c=\ptexc
\let\,=\ptexcomma
\let\.=\ptexdot
\let\dots=\ptexdots
\let\equiv=\ptexequiv
\let\!=\ptexexclam
\let\i=\ptexi
\let\indent=\ptexindent
\let\noindent=\ptexnoindent
\let\{=\ptexlbrace
\let\+=\tabalign
\let\}=\ptexrbrace
\let\/=\ptexslash
\let\*=\ptexstar
\let\t=\ptext
\let\frenchspacing=\plainfrenchspacing
%
\def\endldots{\mathinner{\ldots\ldots\ldots\ldots}}%
\def\enddots{\relax\ifmmode\endldots\else$\mathsurround=0pt \endldots\,$\fi}%
\def\@{@}%
}
% There is no need to define \Etex.
% Define @lisp ... @end lisp.
% @lisp environment forms a group so it can rebind things,
% including the definition of @end lisp (which normally is erroneous).
% Amount to narrow the margins by for @lisp.
\newskip\lispnarrowing \lispnarrowing=0.4in
% This is the definition that ^^M gets inside @lisp, @example, and other
% such environments. \null is better than a space, since it doesn't
% have any width.
\def\lisppar{\null\endgraf}
% This space is always present above and below environments.
\newskip\envskipamount \envskipamount = 0pt
% Make spacing and below environment symmetrical. We use \parskip here
% to help in doing that, since in @example-like environments \parskip
% is reset to zero; thus the \afterenvbreak inserts no space -- but the
% start of the next paragraph will insert \parskip.
%
\def\aboveenvbreak{{%
% =10000 instead of <10000 because of a special case in \itemzzz and
% \sectionheading, q.v.
\ifnum \lastpenalty=10000 \else
\advance\envskipamount by \parskip
\endgraf
\ifdim\lastskip<\envskipamount
\removelastskip
% it's not a good place to break if the last penalty was \nobreak
% or better ...
\ifnum\lastpenalty<10000 \penalty-50 \fi
\vskip\envskipamount
\fi
\fi
}}
\let\afterenvbreak = \aboveenvbreak
% \nonarrowing is a flag. If "set", @lisp etc don't narrow margins; it will
% also clear it, so that its embedded environments do the narrowing again.
\let\nonarrowing=\relax
% @cartouche ... @end cartouche: draw rectangle w/rounded corners around
% environment contents.
\font\circle=lcircle10
\newdimen\circthick
\newdimen\cartouter\newdimen\cartinner
\newskip\normbskip\newskip\normpskip\newskip\normlskip
\circthick=\fontdimen8\circle
%
\def\ctl{{\circle\char'013\hskip -6pt}}% 6pt from pl file: 1/2charwidth
\def\ctr{{\hskip 6pt\circle\char'010}}
\def\cbl{{\circle\char'012\hskip -6pt}}
\def\cbr{{\hskip 6pt\circle\char'011}}
\def\carttop{\hbox to \cartouter{\hskip\lskip
\ctl\leaders\hrule height\circthick\hfil\ctr
\hskip\rskip}}
\def\cartbot{\hbox to \cartouter{\hskip\lskip
\cbl\leaders\hrule height\circthick\hfil\cbr
\hskip\rskip}}
%
\newskip\lskip\newskip\rskip
\envdef\cartouche{%
\ifhmode\par\fi % can't be in the midst of a paragraph.
\startsavinginserts
\lskip=\leftskip \rskip=\rightskip
\leftskip=0pt\rightskip=0pt % we want these *outside*.
\cartinner=\hsize \advance\cartinner by-\lskip
\advance\cartinner by-\rskip
\cartouter=\hsize
\advance\cartouter by 18.4pt % allow for 3pt kerns on either
% side, and for 6pt waste from
% each corner char, and rule thickness
\normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip
% Flag to tell @lisp, etc., not to narrow margin.
\let\nonarrowing = t%
\vbox\bgroup
\baselineskip=0pt\parskip=0pt\lineskip=0pt
\carttop
\hbox\bgroup
\hskip\lskip
\vrule\kern3pt
\vbox\bgroup
\kern3pt
\hsize=\cartinner
\baselineskip=\normbskip
\lineskip=\normlskip
\parskip=\normpskip
\vskip -\parskip
\comment % For explanation, see the end of \def\group.
}
\def\Ecartouche{%
\ifhmode\par\fi
\kern3pt
\egroup
\kern3pt\vrule
\hskip\rskip
\egroup
\cartbot
\egroup
\checkinserts
}
% This macro is called at the beginning of all the @example variants,
% inside a group.
\def\nonfillstart{%
\aboveenvbreak
\hfuzz = 12pt % Don't be fussy
\sepspaces % Make spaces be word-separators rather than space tokens.
\let\par = \lisppar % don't ignore blank lines
\obeylines % each line of input is a line of output
\parskip = 0pt
\parindent = 0pt
\emergencystretch = 0pt % don't try to avoid overfull boxes
\ifx\nonarrowing\relax
\advance \leftskip by \lispnarrowing
\exdentamount=\lispnarrowing
\else
\let\nonarrowing = \relax
\fi
\let\exdent=\nofillexdent
}
% If you want all examples etc. small: @set dispenvsize small.
% If you want even small examples the full size: @set dispenvsize nosmall.
% This affects the following displayed environments:
% @example, @display, @format, @lisp
%
\def\smallword{small}
\def\nosmallword{nosmall}
\let\SETdispenvsize\relax
\def\setnormaldispenv{%
\ifx\SETdispenvsize\smallword
\smallexamplefonts \rm
\fi
}
\def\setsmalldispenv{%
\ifx\SETdispenvsize\nosmallword
\else
\smallexamplefonts \rm
\fi
}
% We often define two environments, @foo and @smallfoo.
% Let's do it by one command:
\def\makedispenv #1#2{
\expandafter\envdef\csname#1\endcsname {\setnormaldispenv #2}
\expandafter\envdef\csname small#1\endcsname {\setsmalldispenv #2}
\expandafter\let\csname E#1\endcsname \afterenvbreak
\expandafter\let\csname Esmall#1\endcsname \afterenvbreak
}
% Define two synonyms:
\def\maketwodispenvs #1#2#3{
\makedispenv{#1}{#3}
\makedispenv{#2}{#3}
}
% @lisp: indented, narrowed, typewriter font; @example: same as @lisp.
%
% @smallexample and @smalllisp: use smaller fonts.
% Originally contributed by Pavel@xerox.
%
\maketwodispenvs {lisp}{example}{%
\nonfillstart
\tt\quoteexpand
\let\kbdfont = \kbdexamplefont % Allow @kbd to do something special.
\gobble % eat return
}
% @display/@smalldisplay: same as @lisp except keep current font.
%
\makedispenv {display}{%
\nonfillstart
\gobble
}
% @format/@smallformat: same as @display except don't narrow margins.
%
\makedispenv{format}{%
\let\nonarrowing = t%
\nonfillstart
\gobble
}
% @flushleft: same as @format, but doesn't obey \SETdispenvsize.
\envdef\flushleft{%
\let\nonarrowing = t%
\nonfillstart
\gobble
}
\let\Eflushleft = \afterenvbreak
% @flushright.
%
\envdef\flushright{%
\let\nonarrowing = t%
\nonfillstart
\advance\leftskip by 0pt plus 1fill
\gobble
}
\let\Eflushright = \afterenvbreak
% @quotation does normal linebreaking (hence we can't use \nonfillstart)
% and narrows the margins. We keep \parskip nonzero in general, since
% we're doing normal filling. So, when using \aboveenvbreak and
% \afterenvbreak, temporarily make \parskip 0.
%
\envdef\quotation{%
{\parskip=0pt \aboveenvbreak}% because \aboveenvbreak inserts \parskip
\parindent=0pt
%
% @cartouche defines \nonarrowing to inhibit narrowing at next level down.
\ifx\nonarrowing\relax
\advance\leftskip by \lispnarrowing
\advance\rightskip by \lispnarrowing
\exdentamount = \lispnarrowing
\else
\let\nonarrowing = \relax
\fi
\parsearg\quotationlabel
}
% We have retained a nonzero parskip for the environment, since we're
% doing normal filling.
%
\def\Equotation{%
\par
\ifx\quotationauthor\undefined\else
% indent a bit.
\leftline{\kern 2\leftskip \sl ---\quotationauthor}%
\fi
{\parskip=0pt \afterenvbreak}%
}
% If we're given an argument, typeset it in bold with a colon after.
\def\quotationlabel#1{%
\def\temp{#1}%
\ifx\temp\empty \else
{\bf #1: }%
\fi
}
% LaTeX-like @verbatim...@end verbatim and @verb{<char>...<char>}
% If we want to allow any <char> as delimiter,
% we need the curly braces so that makeinfo sees the @verb command, eg:
% `@verbx...x' would look like the '@verbx' command. --janneke@gnu.org
%
% [Knuth]: Donald Ervin Knuth, 1996. The TeXbook.
%
% [Knuth] p.344; only we need to do the other characters Texinfo sets
% active too. Otherwise, they get lost as the first character on a
% verbatim line.
\def\dospecials{%
\do\ \do\\\do\{\do\}\do\$\do\&%
\do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~%
\do\<\do\>\do\|\do\@\do+\do\"%
}
%
% [Knuth] p. 380
\def\uncatcodespecials{%
\def\do##1{\catcode`##1=\other}\dospecials}
%
% [Knuth] pp. 380,381,391
% Disable Spanish ligatures ?` and !` of \tt font
\begingroup
\catcode`\`=\active\gdef`{\relax\lq}
\endgroup
%
% Setup for the @verb command.
%
% Eight spaces for a tab
\begingroup
\catcode`\^^I=\active
\gdef\tabeightspaces{\catcode`\^^I=\active\def^^I{\ \ \ \ \ \ \ \ }}
\endgroup
%
\def\setupverb{%
\tt % easiest (and conventionally used) font for verbatim
\def\par{\leavevmode\endgraf}%
\catcode`\`=\active
\tabeightspaces
% Respect line breaks,
% print special symbols as themselves, and
% make each space count
% must do in this order:
\obeylines \uncatcodespecials \sepspaces
}
% Setup for the @verbatim environment
%
% Real tab expansion
\newdimen\tabw \setbox0=\hbox{\tt\space} \tabw=8\wd0 % tab amount
%
\def\starttabbox{\setbox0=\hbox\bgroup}
% Allow an option to not replace quotes with a regular directed right
% quote/apostrophe (char 0x27), but instead use the undirected quote
% from cmtt (char 0x0d). The undirected quote is ugly, so don't make it
% the default, but it works for pasting with more pdf viewers (at least
% evince), the lilypond developers report. xpdf does work with the
% regular 0x27.
%
\def\codequoteright{%
\expandafter\ifx\csname SETcodequoteundirected\endcsname\relax
'%
\else
\char'15
\fi
}
%
% and a similar option for the left quote char vs. a grave accent.
% Modern fonts display ASCII 0x60 as a grave accent, so some people like
% the code environments to do likewise.
%
\def\codequoteleft{%
\expandafter\ifx\csname SETcodequotebacktick\endcsname\relax
`%
\else
\char'22
\fi
}
%
\begingroup
\catcode`\^^I=\active
\gdef\tabexpand{%
\catcode`\^^I=\active
\def^^I{\leavevmode\egroup
\dimen0=\wd0 % the width so far, or since the previous tab
\divide\dimen0 by\tabw
\multiply\dimen0 by\tabw % compute previous multiple of \tabw
\advance\dimen0 by\tabw % advance to next multiple of \tabw
\wd0=\dimen0 \box0 \starttabbox
}%
}
\catcode`\'=\active
\gdef\rquoteexpand{\catcode\rquoteChar=\active \def'{\codequoteright}}%
%
\catcode`\`=\active
\gdef\lquoteexpand{\catcode\lquoteChar=\active \def`{\codequoteleft}}%
%
\gdef\quoteexpand{\rquoteexpand \lquoteexpand}%
\endgroup
% start the verbatim environment.
\def\setupverbatim{%
\let\nonarrowing = t%
\nonfillstart
% Easiest (and conventionally used) font for verbatim
\tt
\def\par{\leavevmode\egroup\box0\endgraf}%
\catcode`\`=\active
\tabexpand
\quoteexpand
% Respect line breaks,
% print special symbols as themselves, and
% make each space count
% must do in this order:
\obeylines \uncatcodespecials \sepspaces
\everypar{\starttabbox}%
}
% Do the @verb magic: verbatim text is quoted by unique
% delimiter characters. Before first delimiter expect a
% right brace, after last delimiter expect closing brace:
%
% \def\doverb'{'<char>#1<char>'}'{#1}
%
% [Knuth] p. 382; only eat outer {}
\begingroup
\catcode`[=1\catcode`]=2\catcode`\{=\other\catcode`\}=\other
\gdef\doverb{#1[\def\next##1#1}[##1\endgroup]\next]
\endgroup
%
\def\verb{\begingroup\setupverb\doverb}
%
%
% Do the @verbatim magic: define the macro \doverbatim so that
% the (first) argument ends when '@end verbatim' is reached, ie:
%
% \def\doverbatim#1@end verbatim{#1}
%
% For Texinfo it's a lot easier than for LaTeX,
% because texinfo's \verbatim doesn't stop at '\end{verbatim}':
% we need not redefine '\', '{' and '}'.
%
% Inspired by LaTeX's verbatim command set [latex.ltx]
%
\begingroup
\catcode`\ =\active
\obeylines %
% ignore everything up to the first ^^M, that's the newline at the end
% of the @verbatim input line itself. Otherwise we get an extra blank
% line in the output.
\xdef\doverbatim#1^^M#2@end verbatim{#2\noexpand\end\gobble verbatim}%
% We really want {...\end verbatim} in the body of the macro, but
% without the active space; thus we have to use \xdef and \gobble.
\endgroup
%
\envdef\verbatim{%
\setupverbatim\doverbatim
}
\let\Everbatim = \afterenvbreak
% @verbatiminclude FILE - insert text of file in verbatim environment.
%
\def\verbatiminclude{\parseargusing\filenamecatcodes\doverbatiminclude}
%
\def\doverbatiminclude#1{%
{%
\makevalueexpandable
\setupverbatim
\input #1
\afterenvbreak
}%
}
% @copying ... @end copying.
% Save the text away for @insertcopying later.
%
% We save the uninterpreted tokens, rather than creating a box.
% Saving the text in a box would be much easier, but then all the
% typesetting commands (@smallbook, font changes, etc.) have to be done
% beforehand -- and a) we want @copying to be done first in the source
% file; b) letting users define the frontmatter in as flexible order as
% possible is very desirable.
%
\def\copying{\checkenv{}\begingroup\scanargctxt\docopying}
\def\docopying#1@end copying{\endgroup\def\copyingtext{#1}}
%
\def\insertcopying{%
\begingroup
\parindent = 0pt % paragraph indentation looks wrong on title page
\scanexp\copyingtext
\endgroup
}
\message{defuns,}
% @defun etc.
\newskip\defbodyindent \defbodyindent=.4in
\newskip\defargsindent \defargsindent=50pt
\newskip\deflastargmargin \deflastargmargin=18pt
% Start the processing of @deffn:
\def\startdefun{%
\ifnum\lastpenalty<10000
\medbreak
\else
% If there are two @def commands in a row, we'll have a \nobreak,
% which is there to keep the function description together with its
% header. But if there's nothing but headers, we need to allow a
% break somewhere. Check specifically for penalty 10002, inserted
% by \defargscommonending, instead of 10000, since the sectioning
% commands also insert a nobreak penalty, and we don't want to allow
% a break between a section heading and a defun.
%
\ifnum\lastpenalty=10002 \penalty2000 \fi
%
% Similarly, after a section heading, do not allow a break.
% But do insert the glue.
\medskip % preceded by discardable penalty, so not a breakpoint
\fi
%
\parindent=0in
\advance\leftskip by \defbodyindent
\exdentamount=\defbodyindent
}
\def\dodefunx#1{%
% First, check whether we are in the right environment:
\checkenv#1%
%
% As above, allow line break if we have multiple x headers in a row.
% It's not a great place, though.
\ifnum\lastpenalty=10002 \penalty3000 \fi
%
% And now, it's time to reuse the body of the original defun:
\expandafter\gobbledefun#1%
}
\def\gobbledefun#1\startdefun{}
% \printdefunline \deffnheader{text}
%
\def\printdefunline#1#2{%
\begingroup
% call \deffnheader:
#1#2 \endheader
% common ending:
\interlinepenalty = 10000
\advance\rightskip by 0pt plus 1fil
\endgraf
\nobreak\vskip -\parskip
\penalty 10002 % signal to \startdefun and \dodefunx
% Some of the @defun-type tags do not enable magic parentheses,
% rendering the following check redundant. But we don't optimize.
\checkparencounts
\endgroup
}
\def\Edefun{\endgraf\medbreak}
% \makedefun{deffn} creates \deffn, \deffnx and \Edeffn;
% the only thing remainnig is to define \deffnheader.
%
\def\makedefun#1{%
\expandafter\let\csname E#1\endcsname = \Edefun
\edef\temp{\noexpand\domakedefun
\makecsname{#1}\makecsname{#1x}\makecsname{#1header}}%
\temp
}
% \domakedefun \deffn \deffnx \deffnheader
%
% Define \deffn and \deffnx, without parameters.
% \deffnheader has to be defined explicitly.
%
\def\domakedefun#1#2#3{%
\envdef#1{%
\startdefun
\parseargusing\activeparens{\printdefunline#3}%
}%
\def#2{\dodefunx#1}%
\def#3%
}
%%% Untyped functions:
% @deffn category name args
\makedefun{deffn}{\deffngeneral{}}
% @deffn category class name args
\makedefun{defop}#1 {\defopon{#1\ \putwordon}}
% \defopon {category on}class name args
\def\defopon#1#2 {\deffngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} }
% \deffngeneral {subind}category name args
%
\def\deffngeneral#1#2 #3 #4\endheader{%
% Remember that \dosubind{fn}{foo}{} is equivalent to \doind{fn}{foo}.
\dosubind{fn}{\code{#3}}{#1}%
\defname{#2}{}{#3}\magicamp\defunargs{#4\unskip}%
}
%%% Typed functions:
% @deftypefn category type name args
\makedefun{deftypefn}{\deftypefngeneral{}}
% @deftypeop category class type name args
\makedefun{deftypeop}#1 {\deftypeopon{#1\ \putwordon}}
% \deftypeopon {category on}class type name args
\def\deftypeopon#1#2 {\deftypefngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} }
% \deftypefngeneral {subind}category type name args
%
\def\deftypefngeneral#1#2 #3 #4 #5\endheader{%
\dosubind{fn}{\code{#4}}{#1}%
\defname{#2}{#3}{#4}\defunargs{#5\unskip}%
}
%%% Typed variables:
% @deftypevr category type var args
\makedefun{deftypevr}{\deftypecvgeneral{}}
% @deftypecv category class type var args
\makedefun{deftypecv}#1 {\deftypecvof{#1\ \putwordof}}
% \deftypecvof {category of}class type var args
\def\deftypecvof#1#2 {\deftypecvgeneral{\putwordof\ \code{#2}}{#1\ \code{#2}} }
% \deftypecvgeneral {subind}category type var args
%
\def\deftypecvgeneral#1#2 #3 #4 #5\endheader{%
\dosubind{vr}{\code{#4}}{#1}%
\defname{#2}{#3}{#4}\defunargs{#5\unskip}%
}
%%% Untyped variables:
% @defvr category var args
\makedefun{defvr}#1 {\deftypevrheader{#1} {} }
% @defcv category class var args
\makedefun{defcv}#1 {\defcvof{#1\ \putwordof}}
% \defcvof {category of}class var args
\def\defcvof#1#2 {\deftypecvof{#1}#2 {} }
%%% Type:
% @deftp category name args
\makedefun{deftp}#1 #2 #3\endheader{%
\doind{tp}{\code{#2}}%
\defname{#1}{}{#2}\defunargs{#3\unskip}%
}
% Remaining @defun-like shortcuts:
\makedefun{defun}{\deffnheader{\putwordDeffunc} }
\makedefun{defmac}{\deffnheader{\putwordDefmac} }
\makedefun{defspec}{\deffnheader{\putwordDefspec} }
\makedefun{deftypefun}{\deftypefnheader{\putwordDeffunc} }
\makedefun{defvar}{\defvrheader{\putwordDefvar} }
\makedefun{defopt}{\defvrheader{\putwordDefopt} }
\makedefun{deftypevar}{\deftypevrheader{\putwordDefvar} }
\makedefun{defmethod}{\defopon\putwordMethodon}
\makedefun{deftypemethod}{\deftypeopon\putwordMethodon}
\makedefun{defivar}{\defcvof\putwordInstanceVariableof}
\makedefun{deftypeivar}{\deftypecvof\putwordInstanceVariableof}
% \defname, which formats the name of the @def (not the args).
% #1 is the category, such as "Function".
% #2 is the return type, if any.
% #3 is the function name.
%
% We are followed by (but not passed) the arguments, if any.
%
\def\defname#1#2#3{%
% Get the values of \leftskip and \rightskip as they were outside the @def...
\advance\leftskip by -\defbodyindent
%
% How we'll format the type name. Putting it in brackets helps
% distinguish it from the body text that may end up on the next line
% just below it.
\def\temp{#1}%
\setbox0=\hbox{\kern\deflastargmargin \ifx\temp\empty\else [\rm\temp]\fi}
%
% Figure out line sizes for the paragraph shape.
% The first line needs space for \box0; but if \rightskip is nonzero,
% we need only space for the part of \box0 which exceeds it:
\dimen0=\hsize \advance\dimen0 by -\wd0 \advance\dimen0 by \rightskip
% The continuations:
\dimen2=\hsize \advance\dimen2 by -\defargsindent
% (plain.tex says that \dimen1 should be used only as global.)
\parshape 2 0in \dimen0 \defargsindent \dimen2
%
% Put the type name to the right margin.
\noindent
\hbox to 0pt{%
\hfil\box0 \kern-\hsize
% \hsize has to be shortened this way:
\kern\leftskip
% Intentionally do not respect \rightskip, since we need the space.
}%
%
% Allow all lines to be underfull without complaint:
\tolerance=10000 \hbadness=10000
\exdentamount=\defbodyindent
{%
% defun fonts. We use typewriter by default (used to be bold) because:
% . we're printing identifiers, they should be in tt in principle.
% . in languages with many accents, such as Czech or French, it's
% common to leave accents off identifiers. The result looks ok in
% tt, but exceedingly strange in rm.
% . we don't want -- and --- to be treated as ligatures.
% . this still does not fix the ?` and !` ligatures, but so far no
% one has made identifiers using them :).
\df \tt
\def\temp{#2}% return value type
\ifx\temp\empty\else \tclose{\temp} \fi
#3% output function name
}%
{\rm\enskip}% hskip 0.5 em of \tenrm
%
\boldbrax
% arguments will be output next, if any.
}
% Print arguments in slanted roman (not ttsl), inconsistently with using
% tt for the name. This is because literal text is sometimes needed in
% the argument list (groff manual), and ttsl and tt are not very
% distinguishable. Prevent hyphenation at `-' chars.
%
\def\defunargs#1{%
% use sl by default (not ttsl),
% tt for the names.
\df \sl \hyphenchar\font=0
%
% On the other hand, if an argument has two dashes (for instance), we
% want a way to get ttsl. Let's try @var for that.
\let\var=\ttslanted
#1%
\sl\hyphenchar\font=45
}
% We want ()&[] to print specially on the defun line.
%
\def\activeparens{%
\catcode`\(=\active \catcode`\)=\active
\catcode`\[=\active \catcode`\]=\active
\catcode`\&=\active
}
% Make control sequences which act like normal parenthesis chars.
\let\lparen = ( \let\rparen = )
% Be sure that we always have a definition for `(', etc. For example,
% if the fn name has parens in it, \boldbrax will not be in effect yet,
% so TeX would otherwise complain about undefined control sequence.
{
\activeparens
\global\let(=\lparen \global\let)=\rparen
\global\let[=\lbrack \global\let]=\rbrack
\global\let& = \&
\gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb}
\gdef\magicamp{\let&=\amprm}
}
\newcount\parencount
% If we encounter &foo, then turn on ()-hacking afterwards
\newif\ifampseen
\def\amprm#1 {\ampseentrue{\bf\ }}
\def\parenfont{%
\ifampseen
% At the first level, print parens in roman,
% otherwise use the default font.
\ifnum \parencount=1 \rm \fi
\else
% The \sf parens (in \boldbrax) actually are a little bolder than
% the contained text. This is especially needed for [ and ] .
\sf
\fi
}
\def\infirstlevel#1{%
\ifampseen
\ifnum\parencount=1
#1%
\fi
\fi
}
\def\bfafterword#1 {#1 \bf}
\def\opnr{%
\global\advance\parencount by 1
{\parenfont(}%
\infirstlevel \bfafterword
}
\def\clnr{%
{\parenfont)}%
\infirstlevel \sl
\global\advance\parencount by -1
}
\newcount\brackcount
\def\lbrb{%
\global\advance\brackcount by 1
{\bf[}%
}
\def\rbrb{%
{\bf]}%
\global\advance\brackcount by -1
}
\def\checkparencounts{%
\ifnum\parencount=0 \else \badparencount \fi
\ifnum\brackcount=0 \else \badbrackcount \fi
}
\def\badparencount{%
\errmessage{Unbalanced parentheses in @def}%
\global\parencount=0
}
\def\badbrackcount{%
\errmessage{Unbalanced square braces in @def}%
\global\brackcount=0
}
\message{macros,}
% @macro.
% To do this right we need a feature of e-TeX, \scantokens,
% which we arrange to emulate with a temporary file in ordinary TeX.
\ifx\eTeXversion\undefined
\newwrite\macscribble
\def\scantokens#1{%
\toks0={#1}%
\immediate\openout\macscribble=\jobname.tmp
\immediate\write\macscribble{\the\toks0}%
\immediate\closeout\macscribble
\input \jobname.tmp
}
\fi
\def\scanmacro#1{%
\begingroup
\newlinechar`\^^M
\let\xeatspaces\eatspaces
% Undo catcode changes of \startcontents and \doprintindex
% When called from @insertcopying or (short)caption, we need active
% backslash to get it printed correctly. Previously, we had
% \catcode`\\=\other instead. We'll see whether a problem appears
% with macro expansion. --kasal, 19aug04
\catcode`\@=0 \catcode`\\=\active \escapechar=`\@
% ... and \example
\spaceisspace
%
% Append \endinput to make sure that TeX does not see the ending newline.
% I've verified that it is necessary both for e-TeX and for ordinary TeX
% --kasal, 29nov03
\scantokens{#1\endinput}%
\endgroup
}
\def\scanexp#1{%
\edef\temp{\noexpand\scanmacro{#1}}%
\temp
}
\newcount\paramno % Count of parameters
\newtoks\macname % Macro name
\newif\ifrecursive % Is it recursive?
% List of all defined macros in the form
% \definedummyword\macro1\definedummyword\macro2...
% Currently is also contains all @aliases; the list can be split
% if there is a need.
\def\macrolist{}
% Add the macro to \macrolist
\def\addtomacrolist#1{\expandafter \addtomacrolistxxx \csname#1\endcsname}
\def\addtomacrolistxxx#1{%
\toks0 = \expandafter{\macrolist\definedummyword#1}%
\xdef\macrolist{\the\toks0}%
}
% Utility routines.
% This does \let #1 = #2, with \csnames; that is,
% \let \csname#1\endcsname = \csname#2\endcsname
% (except of course we have to play expansion games).
%
\def\cslet#1#2{%
\expandafter\let
\csname#1\expandafter\endcsname
\csname#2\endcsname
}
% Trim leading and trailing spaces off a string.
% Concepts from aro-bend problem 15 (see CTAN).
{\catcode`\@=11
\gdef\eatspaces #1{\expandafter\trim@\expandafter{#1 }}
\gdef\trim@ #1{\trim@@ @#1 @ #1 @ @@}
\gdef\trim@@ #1@ #2@ #3@@{\trim@@@\empty #2 @}
\def\unbrace#1{#1}
\unbrace{\gdef\trim@@@ #1 } #2@{#1}
}
% Trim a single trailing ^^M off a string.
{\catcode`\^^M=\other \catcode`\Q=3%
\gdef\eatcr #1{\eatcra #1Q^^MQ}%
\gdef\eatcra#1^^MQ{\eatcrb#1Q}%
\gdef\eatcrb#1Q#2Q{#1}%
}
% Macro bodies are absorbed as an argument in a context where
% all characters are catcode 10, 11 or 12, except \ which is active
% (as in normal texinfo). It is necessary to change the definition of \.
% It's necessary to have hard CRs when the macro is executed. This is
% done by making ^^M (\endlinechar) catcode 12 when reading the macro
% body, and then making it the \newlinechar in \scanmacro.
\def\scanctxt{%
\catcode`\"=\other
\catcode`\+=\other
\catcode`\<=\other
\catcode`\>=\other
\catcode`\@=\other
\catcode`\^=\other
\catcode`\_=\other
\catcode`\|=\other
\catcode`\~=\other
}
\def\scanargctxt{%
\scanctxt
\catcode`\\=\other
\catcode`\^^M=\other
}
\def\macrobodyctxt{%
\scanctxt
\catcode`\{=\other
\catcode`\}=\other
\catcode`\^^M=\other
\usembodybackslash
}
\def\macroargctxt{%
\scanctxt
\catcode`\\=\other
}
% \mbodybackslash is the definition of \ in @macro bodies.
% It maps \foo\ => \csname macarg.foo\endcsname => #N
% where N is the macro parameter number.
% We define \csname macarg.\endcsname to be \realbackslash, so
% \\ in macro replacement text gets you a backslash.
{\catcode`@=0 @catcode`@\=@active
@gdef@usembodybackslash{@let\=@mbodybackslash}
@gdef@mbodybackslash#1\{@csname macarg.#1@endcsname}
}
\expandafter\def\csname macarg.\endcsname{\realbackslash}
\def\macro{\recursivefalse\parsearg\macroxxx}
\def\rmacro{\recursivetrue\parsearg\macroxxx}
\def\macroxxx#1{%
\getargs{#1}% now \macname is the macname and \argl the arglist
\ifx\argl\empty % no arguments
\paramno=0%
\else
\expandafter\parsemargdef \argl;%
\fi
\if1\csname ismacro.\the\macname\endcsname
\message{Warning: redefining \the\macname}%
\else
\expandafter\ifx\csname \the\macname\endcsname \relax
\else \errmessage{Macro name \the\macname\space already defined}\fi
\global\cslet{macsave.\the\macname}{\the\macname}%
\global\expandafter\let\csname ismacro.\the\macname\endcsname=1%
\addtomacrolist{\the\macname}%
\fi
\begingroup \macrobodyctxt
\ifrecursive \expandafter\parsermacbody
\else \expandafter\parsemacbody
\fi}
\parseargdef\unmacro{%
\if1\csname ismacro.#1\endcsname
\global\cslet{#1}{macsave.#1}%
\global\expandafter\let \csname ismacro.#1\endcsname=0%
% Remove the macro name from \macrolist:
\begingroup
\expandafter\let\csname#1\endcsname \relax
\let\definedummyword\unmacrodo
\xdef\macrolist{\macrolist}%
\endgroup
\else
\errmessage{Macro #1 not defined}%
\fi
}
% Called by \do from \dounmacro on each macro. The idea is to omit any
% macro definitions that have been changed to \relax.
%
\def\unmacrodo#1{%
\ifx #1\relax
% remove this
\else
\noexpand\definedummyword \noexpand#1%
\fi
}
% This makes use of the obscure feature that if the last token of a
% <parameter list> is #, then the preceding argument is delimited by
% an opening brace, and that opening brace is not consumed.
\def\getargs#1{\getargsxxx#1{}}
\def\getargsxxx#1#{\getmacname #1 \relax\getmacargs}
\def\getmacname #1 #2\relax{\macname={#1}}
\def\getmacargs#1{\def\argl{#1}}
% Parse the optional {params} list. Set up \paramno and \paramlist
% so \defmacro knows what to do. Define \macarg.blah for each blah
% in the params list, to be ##N where N is the position in that list.
% That gets used by \mbodybackslash (above).
% We need to get `macro parameter char #' into several definitions.
% The technique used is stolen from LaTeX: let \hash be something
% unexpandable, insert that wherever you need a #, and then redefine
% it to # just before using the token list produced.
%
% The same technique is used to protect \eatspaces till just before
% the macro is used.
\def\parsemargdef#1;{\paramno=0\def\paramlist{}%
\let\hash\relax\let\xeatspaces\relax\parsemargdefxxx#1,;,}
\def\parsemargdefxxx#1,{%
\if#1;\let\next=\relax
\else \let\next=\parsemargdefxxx
\advance\paramno by 1%
\expandafter\edef\csname macarg.\eatspaces{#1}\endcsname
{\xeatspaces{\hash\the\paramno}}%
\edef\paramlist{\paramlist\hash\the\paramno,}%
\fi\next}
% These two commands read recursive and nonrecursive macro bodies.
% (They're different since rec and nonrec macros end differently.)
\long\def\parsemacbody#1@end macro%
{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}%
\long\def\parsermacbody#1@end rmacro%
{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}%
% This defines the macro itself. There are six cases: recursive and
% nonrecursive macros of zero, one, and many arguments.
% Much magic with \expandafter here.
% \xdef is used so that macro definitions will survive the file
% they're defined in; @include reads the file inside a group.
\def\defmacro{%
\let\hash=##% convert placeholders to macro parameter chars
\ifrecursive
\ifcase\paramno
% 0
\expandafter\xdef\csname\the\macname\endcsname{%
\noexpand\scanmacro{\temp}}%
\or % 1
\expandafter\xdef\csname\the\macname\endcsname{%
\bgroup\noexpand\macroargctxt
\noexpand\braceorline
\expandafter\noexpand\csname\the\macname xxx\endcsname}%
\expandafter\xdef\csname\the\macname xxx\endcsname##1{%
\egroup\noexpand\scanmacro{\temp}}%
\else % many
\expandafter\xdef\csname\the\macname\endcsname{%
\bgroup\noexpand\macroargctxt
\noexpand\csname\the\macname xx\endcsname}%
\expandafter\xdef\csname\the\macname xx\endcsname##1{%
\expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}%
\expandafter\expandafter
\expandafter\xdef
\expandafter\expandafter
\csname\the\macname xxx\endcsname
\paramlist{\egroup\noexpand\scanmacro{\temp}}%
\fi
\else
\ifcase\paramno
% 0
\expandafter\xdef\csname\the\macname\endcsname{%
\noexpand\norecurse{\the\macname}%
\noexpand\scanmacro{\temp}\egroup}%
\or % 1
\expandafter\xdef\csname\the\macname\endcsname{%
\bgroup\noexpand\macroargctxt
\noexpand\braceorline
\expandafter\noexpand\csname\the\macname xxx\endcsname}%
\expandafter\xdef\csname\the\macname xxx\endcsname##1{%
\egroup
\noexpand\norecurse{\the\macname}%
\noexpand\scanmacro{\temp}\egroup}%
\else % many
\expandafter\xdef\csname\the\macname\endcsname{%
\bgroup\noexpand\macroargctxt
\expandafter\noexpand\csname\the\macname xx\endcsname}%
\expandafter\xdef\csname\the\macname xx\endcsname##1{%
\expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}%
\expandafter\expandafter
\expandafter\xdef
\expandafter\expandafter
\csname\the\macname xxx\endcsname
\paramlist{%
\egroup
\noexpand\norecurse{\the\macname}%
\noexpand\scanmacro{\temp}\egroup}%
\fi
\fi}
\def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}}
% \braceorline decides whether the next nonwhitespace character is a
% {. If so it reads up to the closing }, if not, it reads the whole
% line. Whatever was read is then fed to the next control sequence
% as an argument (by \parsebrace or \parsearg)
\def\braceorline#1{\let\macnamexxx=#1\futurelet\nchar\braceorlinexxx}
\def\braceorlinexxx{%
\ifx\nchar\bgroup\else
\expandafter\parsearg
\fi \macnamexxx}
% @alias.
% We need some trickery to remove the optional spaces around the equal
% sign. Just make them active and then expand them all to nothing.
\def\alias{\parseargusing\obeyspaces\aliasxxx}
\def\aliasxxx #1{\aliasyyy#1\relax}
\def\aliasyyy #1=#2\relax{%
{%
\expandafter\let\obeyedspace=\empty
\addtomacrolist{#1}%
\xdef\next{\global\let\makecsname{#1}=\makecsname{#2}}%
}%
\next
}
\message{cross references,}
\newwrite\auxfile
\newif\ifhavexrefs % True if xref values are known.
\newif\ifwarnedxrefs % True if we warned once that they aren't known.
% @inforef is relatively simple.
\def\inforef #1{\inforefzzz #1,,,,**}
\def\inforefzzz #1,#2,#3,#4**{\putwordSee{} \putwordInfo{} \putwordfile{} \file{\ignorespaces #3{}},
node \samp{\ignorespaces#1{}}}
% @node's only job in TeX is to define \lastnode, which is used in
% cross-references. The @node line might or might not have commas, and
% might or might not have spaces before the first comma, like:
% @node foo , bar , ...
% We don't want such trailing spaces in the node name.
%
\parseargdef\node{\checkenv{}\donode #1 ,\finishnodeparse}
%
% also remove a trailing comma, in case of something like this:
% @node Help-Cross, , , Cross-refs
\def\donode#1 ,#2\finishnodeparse{\dodonode #1,\finishnodeparse}
\def\dodonode#1,#2\finishnodeparse{\gdef\lastnode{#1}}
\let\nwnode=\node
\let\lastnode=\empty
% Write a cross-reference definition for the current node. #1 is the
% type (Ynumbered, Yappendix, Ynothing).
%
\def\donoderef#1{%
\ifx\lastnode\empty\else
\setref{\lastnode}{#1}%
\global\let\lastnode=\empty
\fi
}
% @anchor{NAME} -- define xref target at arbitrary point.
%
\newcount\savesfregister
%
\def\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi}
\def\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi}
\def\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces}
% \setref{NAME}{SNT} defines a cross-reference point NAME (a node or an
% anchor), which consists of three parts:
% 1) NAME-title - the current sectioning name taken from \thissection,
% or the anchor name.
% 2) NAME-snt - section number and type, passed as the SNT arg, or
% empty for anchors.
% 3) NAME-pg - the page number.
%
% This is called from \donoderef, \anchor, and \dofloat. In the case of
% floats, there is an additional part, which is not written here:
% 4) NAME-lof - the text as it should appear in a @listoffloats.
%
\def\setref#1#2{%
\pdfmkdest{#1}%
\iflinks
{%
\atdummies % preserve commands, but don't expand them
\edef\writexrdef##1##2{%
\write\auxfile{@xrdef{#1-% #1 of \setref, expanded by the \edef
##1}{##2}}% these are parameters of \writexrdef
}%
\toks0 = \expandafter{\thissection}%
\immediate \writexrdef{title}{\the\toks0 }%
\immediate \writexrdef{snt}{\csname #2\endcsname}% \Ynumbered etc.
\writexrdef{pg}{\folio}% will be written later, during \shipout
}%
\fi
}
% @xref, @pxref, and @ref generate cross-references. For \xrefX, #1 is
% the node name, #2 the name of the Info cross-reference, #3 the printed
% node name, #4 the name of the Info file, #5 the name of the printed
% manual. All but the node name can be omitted.
%
\def\pxref#1{\putwordsee{} \xrefX[#1,,,,,,,]}
\def\xref#1{\putwordSee{} \xrefX[#1,,,,,,,]}
\def\ref#1{\xrefX[#1,,,,,,,]}
\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
\unsepspaces
\def\printedmanual{\ignorespaces #5}%
\def\printedrefname{\ignorespaces #3}%
\setbox1=\hbox{\printedmanual\unskip}%
\setbox0=\hbox{\printedrefname\unskip}%
\ifdim \wd0 = 0pt
% No printed node name was explicitly given.
\expandafter\ifx\csname SETxref-automatic-section-title\endcsname\relax
% Use the node name inside the square brackets.
\def\printedrefname{\ignorespaces #1}%
\else
% Use the actual chapter/section title appear inside
% the square brackets. Use the real section title if we have it.
\ifdim \wd1 > 0pt
% It is in another manual, so we don't have it.
\def\printedrefname{\ignorespaces #1}%
\else
\ifhavexrefs
% We know the real title if we have the xref values.
\def\printedrefname{\refx{#1-title}{}}%
\else
% Otherwise just copy the Info node name.
\def\printedrefname{\ignorespaces #1}%
\fi%
\fi
\fi
\fi
%
% Make link in pdf output.
\ifpdf
\leavevmode
\getfilename{#4}%
{\turnoffactive
% See comments at \activebackslashdouble.
{\activebackslashdouble \xdef\pdfxrefdest{#1}%
\backslashparens\pdfxrefdest}%
%
\ifnum\filenamelength>0
\startlink attr{/Border [0 0 0]}%
goto file{\the\filename.pdf} name{\pdfxrefdest}%
\else
\startlink attr{/Border [0 0 0]}%
goto name{\pdfmkpgn{\pdfxrefdest}}%
\fi
}%
\linkcolor
\fi
%
% Float references are printed completely differently: "Figure 1.2"
% instead of "[somenode], p.3". We distinguish them by the
% LABEL-title being set to a magic string.
{%
% Have to otherify everything special to allow the \csname to
% include an _ in the xref name, etc.
\indexnofonts
\turnoffactive
\expandafter\global\expandafter\let\expandafter\Xthisreftitle
\csname XR#1-title\endcsname
}%
\iffloat\Xthisreftitle
% If the user specified the print name (third arg) to the ref,
% print it instead of our usual "Figure 1.2".
\ifdim\wd0 = 0pt
\refx{#1-snt}{}%
\else
\printedrefname
\fi
%
% if the user also gave the printed manual name (fifth arg), append
% "in MANUALNAME".
\ifdim \wd1 > 0pt
\space \putwordin{} \cite{\printedmanual}%
\fi
\else
% node/anchor (non-float) references.
%
% If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
% insert empty discretionaries after hyphens, which means that it will
% not find a line break at a hyphen in a node names. Since some manuals
% are best written with fairly long node names, containing hyphens, this
% is a loss. Therefore, we give the text of the node name again, so it
% is as if TeX is seeing it for the first time.
\ifdim \wd1 > 0pt
\putwordsection{} ``\printedrefname'' \putwordin{} \cite{\printedmanual}%
\else
% _ (for example) has to be the character _ for the purposes of the
% control sequence corresponding to the node, but it has to expand
% into the usual \leavevmode...\vrule stuff for purposes of
% printing. So we \turnoffactive for the \refx-snt, back on for the
% printing, back off for the \refx-pg.
{\turnoffactive
% Only output a following space if the -snt ref is nonempty; for
% @unnumbered and @anchor, it won't be.
\setbox2 = \hbox{\ignorespaces \refx{#1-snt}{}}%
\ifdim \wd2 > 0pt \refx{#1-snt}\space\fi
}%
% output the `[mynode]' via a macro so it can be overridden.
\xrefprintnodename\printedrefname
%
% But we always want a comma and a space:
,\space
%
% output the `page 3'.
\turnoffactive \putwordpage\tie\refx{#1-pg}{}%
\fi
\fi
\endlink
\endgroup}
% This macro is called from \xrefX for the `[nodename]' part of xref
% output. It's a separate macro only so it can be changed more easily,
% since square brackets don't work well in some documents. Particularly
% one that Bob is working on :).
%
\def\xrefprintnodename#1{[#1]}
% Things referred to by \setref.
%
\def\Ynothing{}
\def\Yomitfromtoc{}
\def\Ynumbered{%
\ifnum\secno=0
\putwordChapter@tie \the\chapno
\else \ifnum\subsecno=0
\putwordSection@tie \the\chapno.\the\secno
\else \ifnum\subsubsecno=0
\putwordSection@tie \the\chapno.\the\secno.\the\subsecno
\else
\putwordSection@tie \the\chapno.\the\secno.\the\subsecno.\the\subsubsecno
\fi\fi\fi
}
\def\Yappendix{%
\ifnum\secno=0
\putwordAppendix@tie @char\the\appendixno{}%
\else \ifnum\subsecno=0
\putwordSection@tie @char\the\appendixno.\the\secno
\else \ifnum\subsubsecno=0
\putwordSection@tie @char\the\appendixno.\the\secno.\the\subsecno
\else
\putwordSection@tie
@char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno
\fi\fi\fi
}
% Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME.
% If its value is nonempty, SUFFIX is output afterward.
%
\def\refx#1#2{%
{%
\indexnofonts
\otherbackslash
\expandafter\global\expandafter\let\expandafter\thisrefX
\csname XR#1\endcsname
}%
\ifx\thisrefX\relax
% If not defined, say something at least.
\angleleft un\-de\-fined\angleright
\iflinks
\ifhavexrefs
\message{\linenumber Undefined cross reference `#1'.}%
\else
\ifwarnedxrefs\else
\global\warnedxrefstrue
\message{Cross reference values unknown; you must run TeX again.}%
\fi
\fi
\fi
\else
% It's defined, so just use it.
\thisrefX
\fi
#2% Output the suffix in any case.
}
% This is the macro invoked by entries in the aux file. Usually it's
% just a \def (we prepend XR to the control sequence name to avoid
% collisions). But if this is a float type, we have more work to do.
%
\def\xrdef#1#2{%
\expandafter\gdef\csname XR#1\endcsname{#2}% remember this xref value.
%
% Was that xref control sequence that we just defined for a float?
\expandafter\iffloat\csname XR#1\endcsname
% it was a float, and we have the (safe) float type in \iffloattype.
\expandafter\let\expandafter\floatlist
\csname floatlist\iffloattype\endcsname
%
% Is this the first time we've seen this float type?
\expandafter\ifx\floatlist\relax
\toks0 = {\do}% yes, so just \do
\else
% had it before, so preserve previous elements in list.
\toks0 = \expandafter{\floatlist\do}%
\fi
%
% Remember this xref in the control sequence \floatlistFLOATTYPE,
% for later use in \listoffloats.
\expandafter\xdef\csname floatlist\iffloattype\endcsname{\the\toks0{#1}}%
\fi
}
% Read the last existing aux file, if any. No error if none exists.
%
\def\tryauxfile{%
\openin 1 \jobname.aux
\ifeof 1 \else
\readdatafile{aux}%
\global\havexrefstrue
\fi
\closein 1
}
\def\setupdatafile{%
\catcode`\^^@=\other
\catcode`\^^A=\other
\catcode`\^^B=\other
\catcode`\^^C=\other
\catcode`\^^D=\other
\catcode`\^^E=\other
\catcode`\^^F=\other
\catcode`\^^G=\other
\catcode`\^^H=\other
\catcode`\^^K=\other
\catcode`\^^L=\other
\catcode`\^^N=\other
\catcode`\^^P=\other
\catcode`\^^Q=\other
\catcode`\^^R=\other
\catcode`\^^S=\other
\catcode`\^^T=\other
\catcode`\^^U=\other
\catcode`\^^V=\other
\catcode`\^^W=\other
\catcode`\^^X=\other
\catcode`\^^Z=\other
\catcode`\^^[=\other
\catcode`\^^\=\other
\catcode`\^^]=\other
\catcode`\^^^=\other
\catcode`\^^_=\other
% It was suggested to set the catcode of ^ to 7, which would allow ^^e4 etc.
% in xref tags, i.e., node names. But since ^^e4 notation isn't
% supported in the main text, it doesn't seem desirable. Furthermore,
% that is not enough: for node names that actually contain a ^
% character, we would end up writing a line like this: 'xrdef {'hat
% b-title}{'hat b} and \xrdef does a \csname...\endcsname on the first
% argument, and \hat is not an expandable control sequence. It could
% all be worked out, but why? Either we support ^^ or we don't.
%
% The other change necessary for this was to define \auxhat:
% \def\auxhat{\def^{'hat }}% extra space so ok if followed by letter
% and then to call \auxhat in \setq.
%
\catcode`\^=\other
%
% Special characters. Should be turned off anyway, but...
\catcode`\~=\other
\catcode`\[=\other
\catcode`\]=\other
\catcode`\"=\other
\catcode`\_=\other
\catcode`\|=\other
\catcode`\<=\other
\catcode`\>=\other
\catcode`\$=\other
\catcode`\#=\other
\catcode`\&=\other
\catcode`\%=\other
\catcode`+=\other % avoid \+ for paranoia even though we've turned it off
%
% This is to support \ in node names and titles, since the \
% characters end up in a \csname. It's easier than
% leaving it active and making its active definition an actual \
% character. What I don't understand is why it works in the *value*
% of the xrdef. Seems like it should be a catcode12 \, and that
% should not typeset properly. But it works, so I'm moving on for
% now. --karl, 15jan04.
\catcode`\\=\other
%
% Make the characters 128-255 be printing characters.
{%
\count1=128
\def\loop{%
\catcode\count1=\other
\advance\count1 by 1
\ifnum \count1<256 \loop \fi
}%
}%
%
% @ is our escape character in .aux files, and we need braces.
\catcode`\{=1
\catcode`\}=2
\catcode`\@=0
}
\def\readdatafile#1{%
\begingroup
\setupdatafile
\input\jobname.#1
\endgroup}
\message{insertions,}
% including footnotes.
\newcount \footnoteno
% The trailing space in the following definition for supereject is
% vital for proper filling; pages come out unaligned when you do a
% pagealignmacro call if that space before the closing brace is
% removed. (Generally, numeric constants should always be followed by a
% space to prevent strange expansion errors.)
\def\supereject{\par\penalty -20000\footnoteno =0 }
% @footnotestyle is meaningful for info output only.
\let\footnotestyle=\comment
{\catcode `\@=11
%
% Auto-number footnotes. Otherwise like plain.
\gdef\footnote{%
\let\indent=\ptexindent
\let\noindent=\ptexnoindent
\global\advance\footnoteno by \@ne
\edef\thisfootno{$^{\the\footnoteno}$}%
%
% In case the footnote comes at the end of a sentence, preserve the
% extra spacing after we do the footnote number.
\let\@sf\empty
\ifhmode\edef\@sf{\spacefactor\the\spacefactor}\ptexslash\fi
%
% Remove inadvertent blank space before typesetting the footnote number.
\unskip
\thisfootno\@sf
\dofootnote
}%
% Don't bother with the trickery in plain.tex to not require the
% footnote text as a parameter. Our footnotes don't need to be so general.
%
% Oh yes, they do; otherwise, @ifset (and anything else that uses
% \parseargline) fails inside footnotes because the tokens are fixed when
% the footnote is read. --karl, 16nov96.
%
\gdef\dofootnote{%
\insert\footins\bgroup
% We want to typeset this text as a normal paragraph, even if the
% footnote reference occurs in (for example) a display environment.
% So reset some parameters.
\hsize=\pagewidth
\interlinepenalty\interfootnotelinepenalty
\splittopskip\ht\strutbox % top baseline for broken footnotes
\splitmaxdepth\dp\strutbox
\floatingpenalty\@MM
\leftskip\z@skip
\rightskip\z@skip
\spaceskip\z@skip
\xspaceskip\z@skip
\parindent\defaultparindent
%
\smallfonts \rm
%
% Because we use hanging indentation in footnotes, a @noindent appears
% to exdent this text, so make it be a no-op. makeinfo does not use
% hanging indentation so @noindent can still be needed within footnote
% text after an @example or the like (not that this is good style).
\let\noindent = \relax
%
% Hang the footnote text off the number. Use \everypar in case the
% footnote extends for more than one paragraph.
\everypar = {\hang}%
\textindent{\thisfootno}%
%
% Don't crash into the line above the footnote text. Since this
% expands into a box, it must come within the paragraph, lest it
% provide a place where TeX can split the footnote.
\footstrut
\futurelet\next\fo@t
}
}%end \catcode `\@=11
% In case a @footnote appears in a vbox, save the footnote text and create
% the real \insert just after the vbox finished. Otherwise, the insertion
% would be lost.
% Similarily, if a @footnote appears inside an alignment, save the footnote
% text to a box and make the \insert when a row of the table is finished.
% And the same can be done for other insert classes. --kasal, 16nov03.
% Replace the \insert primitive by a cheating macro.
% Deeper inside, just make sure that the saved insertions are not spilled
% out prematurely.
%
\def\startsavinginserts{%
\ifx \insert\ptexinsert
\let\insert\saveinsert
\else
\let\checkinserts\relax
\fi
}
% This \insert replacement works for both \insert\footins{foo} and
% \insert\footins\bgroup foo\egroup, but it doesn't work for \insert27{foo}.
%
\def\saveinsert#1{%
\edef\next{\noexpand\savetobox \makeSAVEname#1}%
\afterassignment\next
% swallow the left brace
\let\temp =
}
\def\makeSAVEname#1{\makecsname{SAVE\expandafter\gobble\string#1}}
\def\savetobox#1{\global\setbox#1 = \vbox\bgroup \unvbox#1}
\def\checksaveins#1{\ifvoid#1\else \placesaveins#1\fi}
\def\placesaveins#1{%
\ptexinsert \csname\expandafter\gobblesave\string#1\endcsname
{\box#1}%
}
% eat @SAVE -- beware, all of them have catcode \other:
{
\def\dospecials{\do S\do A\do V\do E} \uncatcodespecials % ;-)
\gdef\gobblesave @SAVE{}
}
% initialization:
\def\newsaveins #1{%
\edef\next{\noexpand\newsaveinsX \makeSAVEname#1}%
\next
}
\def\newsaveinsX #1{%
\csname newbox\endcsname #1%
\expandafter\def\expandafter\checkinserts\expandafter{\checkinserts
\checksaveins #1}%
}
% initialize:
\let\checkinserts\empty
\newsaveins\footins
\newsaveins\margin
% @image. We use the macros from epsf.tex to support this.
% If epsf.tex is not installed and @image is used, we complain.
%
% Check for and read epsf.tex up front. If we read it only at @image
% time, we might be inside a group, and then its definitions would get
% undone and the next image would fail.
\openin 1 = epsf.tex
\ifeof 1 \else
% Do not bother showing banner with epsf.tex v2.7k (available in
% doc/epsf.tex and on ctan).
\def\epsfannounce{\toks0 = }%
\input epsf.tex
\fi
\closein 1
%
% We will only complain once about lack of epsf.tex.
\newif\ifwarnednoepsf
\newhelp\noepsfhelp{epsf.tex must be installed for images to
work. It is also included in the Texinfo distribution, or you can get
it from ftp://tug.org/tex/epsf.tex.}
%
\def\image#1{%
\ifx\epsfbox\undefined
\ifwarnednoepsf \else
\errhelp = \noepsfhelp
\errmessage{epsf.tex not found, images will be ignored}%
\global\warnednoepsftrue
\fi
\else
\imagexxx #1,,,,,\finish
\fi
}
%
% Arguments to @image:
% #1 is (mandatory) image filename; we tack on .eps extension.
% #2 is (optional) width, #3 is (optional) height.
% #4 is (ignored optional) html alt text.
% #5 is (ignored optional) extension.
% #6 is just the usual extra ignored arg for parsing this stuff.
\newif\ifimagevmode
\def\imagexxx#1,#2,#3,#4,#5,#6\finish{\begingroup
\catcode`\^^M = 5 % in case we're inside an example
\normalturnoffactive % allow _ et al. in names
% If the image is by itself, center it.
\ifvmode
\imagevmodetrue
\nobreak\bigskip
% Usually we'll have text after the image which will insert
% \parskip glue, so insert it here too to equalize the space
% above and below.
\nobreak\vskip\parskip
\nobreak
\line\bgroup
\fi
%
% Output the image.
\ifpdf
\dopdfimage{#1}{#2}{#3}%
\else
% \epsfbox itself resets \epsf?size at each figure.
\setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \epsfxsize=#2\relax \fi
\setbox0 = \hbox{\ignorespaces #3}\ifdim\wd0 > 0pt \epsfysize=#3\relax \fi
\epsfbox{#1.eps}%
\fi
%
\ifimagevmode \egroup \bigbreak \fi % space after the image
\endgroup}
% @float FLOATTYPE,LABEL,LOC ... @end float for displayed figures, tables,
% etc. We don't actually implement floating yet, we always include the
% float "here". But it seemed the best name for the future.
%
\envparseargdef\float{\eatcommaspace\eatcommaspace\dofloat#1, , ,\finish}
% There may be a space before second and/or third parameter; delete it.
\def\eatcommaspace#1, {#1,}
% #1 is the optional FLOATTYPE, the text label for this float, typically
% "Figure", "Table", "Example", etc. Can't contain commas. If omitted,
% this float will not be numbered and cannot be referred to.
%
% #2 is the optional xref label. Also must be present for the float to
% be referable.
%
% #3 is the optional positioning argument; for now, it is ignored. It
% will somehow specify the positions allowed to float to (here, top, bottom).
%
% We keep a separate counter for each FLOATTYPE, which we reset at each
% chapter-level command.
\let\resetallfloatnos=\empty
%
\def\dofloat#1,#2,#3,#4\finish{%
\let\thiscaption=\empty
\let\thisshortcaption=\empty
%
% don't lose footnotes inside @float.
%
% BEWARE: when the floats start float, we have to issue warning whenever an
% insert appears inside a float which could possibly float. --kasal, 26may04
%
\startsavinginserts
%
% We can't be used inside a paragraph.
\par
%
\vtop\bgroup
\def\floattype{#1}%
\def\floatlabel{#2}%
\def\floatloc{#3}% we do nothing with this yet.
%
\ifx\floattype\empty
\let\safefloattype=\empty
\else
{%
% the floattype might have accents or other special characters,
% but we need to use it in a control sequence name.
\indexnofonts
\turnoffactive
\xdef\safefloattype{\floattype}%
}%
\fi
%
% If label is given but no type, we handle that as the empty type.
\ifx\floatlabel\empty \else
% We want each FLOATTYPE to be numbered separately (Figure 1,
% Table 1, Figure 2, ...). (And if no label, no number.)
%
\expandafter\getfloatno\csname\safefloattype floatno\endcsname
\global\advance\floatno by 1
%
{%
% This magic value for \thissection is output by \setref as the
% XREFLABEL-title value. \xrefX uses it to distinguish float
% labels (which have a completely different output format) from
% node and anchor labels. And \xrdef uses it to construct the
% lists of floats.
%
\edef\thissection{\floatmagic=\safefloattype}%
\setref{\floatlabel}{Yfloat}%
}%
\fi
%
% start with \parskip glue, I guess.
\vskip\parskip
%
% Don't suppress indentation if a float happens to start a section.
\restorefirstparagraphindent
}
% we have these possibilities:
% @float Foo,lbl & @caption{Cap}: Foo 1.1: Cap
% @float Foo,lbl & no caption: Foo 1.1
% @float Foo & @caption{Cap}: Foo: Cap
% @float Foo & no caption: Foo
% @float ,lbl & Caption{Cap}: 1.1: Cap
% @float ,lbl & no caption: 1.1
% @float & @caption{Cap}: Cap
% @float & no caption:
%
\def\Efloat{%
\let\floatident = \empty
%
% In all cases, if we have a float type, it comes first.
\ifx\floattype\empty \else \def\floatident{\floattype}\fi
%
% If we have an xref label, the number comes next.
\ifx\floatlabel\empty \else
\ifx\floattype\empty \else % if also had float type, need tie first.
\appendtomacro\floatident{\tie}%
\fi
% the number.
\appendtomacro\floatident{\chaplevelprefix\the\floatno}%
\fi
%
% Start the printed caption with what we've constructed in
% \floatident, but keep it separate; we need \floatident again.
\let\captionline = \floatident
%
\ifx\thiscaption\empty \else
\ifx\floatident\empty \else
\appendtomacro\captionline{: }% had ident, so need a colon between
\fi
%
% caption text.
\appendtomacro\captionline{\scanexp\thiscaption}%
\fi
%
% If we have anything to print, print it, with space before.
% Eventually this needs to become an \insert.
\ifx\captionline\empty \else
\vskip.5\parskip
\captionline
%
% Space below caption.
\vskip\parskip
\fi
%
% If have an xref label, write the list of floats info. Do this
% after the caption, to avoid chance of it being a breakpoint.
\ifx\floatlabel\empty \else
% Write the text that goes in the lof to the aux file as
% \floatlabel-lof. Besides \floatident, we include the short
% caption if specified, else the full caption if specified, else nothing.
{%
\atdummies
%
% since we read the caption text in the macro world, where ^^M
% is turned into a normal character, we have to scan it back, so
% we don't write the literal three characters "^^M" into the aux file.
\scanexp{%
\xdef\noexpand\gtemp{%
\ifx\thisshortcaption\empty
\thiscaption
\else
\thisshortcaption
\fi
}%
}%
\immediate\write\auxfile{@xrdef{\floatlabel-lof}{\floatident
\ifx\gtemp\empty \else : \gtemp \fi}}%
}%
\fi
\egroup % end of \vtop
%
% place the captured inserts
%
% BEWARE: when the floats start floating, we have to issue warning
% whenever an insert appears inside a float which could possibly
% float. --kasal, 26may04
%
\checkinserts
}
% Append the tokens #2 to the definition of macro #1, not expanding either.
%
\def\appendtomacro#1#2{%
\expandafter\def\expandafter#1\expandafter{#1#2}%
}
% @caption, @shortcaption
%
\def\caption{\docaption\thiscaption}
\def\shortcaption{\docaption\thisshortcaption}
\def\docaption{\checkenv\float \bgroup\scanargctxt\defcaption}
\def\defcaption#1#2{\egroup \def#1{#2}}
% The parameter is the control sequence identifying the counter we are
% going to use. Create it if it doesn't exist and assign it to \floatno.
\def\getfloatno#1{%
\ifx#1\relax
% Haven't seen this figure type before.
\csname newcount\endcsname #1%
%
% Remember to reset this floatno at the next chap.
\expandafter\gdef\expandafter\resetallfloatnos
\expandafter{\resetallfloatnos #1=0 }%
\fi
\let\floatno#1%
}
% \setref calls this to get the XREFLABEL-snt value. We want an @xref
% to the FLOATLABEL to expand to "Figure 3.1". We call \setref when we
% first read the @float command.
%
\def\Yfloat{\floattype@tie \chaplevelprefix\the\floatno}%
% Magic string used for the XREFLABEL-title value, so \xrefX can
% distinguish floats from other xref types.
\def\floatmagic{!!float!!}
% #1 is the control sequence we are passed; we expand into a conditional
% which is true if #1 represents a float ref. That is, the magic
% \thissection value which we \setref above.
%
\def\iffloat#1{\expandafter\doiffloat#1==\finish}
%
% #1 is (maybe) the \floatmagic string. If so, #2 will be the
% (safe) float type for this float. We set \iffloattype to #2.
%
\def\doiffloat#1=#2=#3\finish{%
\def\temp{#1}%
\def\iffloattype{#2}%
\ifx\temp\floatmagic
}
% @listoffloats FLOATTYPE - print a list of floats like a table of contents.
%
\parseargdef\listoffloats{%
\def\floattype{#1}% floattype
{%
% the floattype might have accents or other special characters,
% but we need to use it in a control sequence name.
\indexnofonts
\turnoffactive
\xdef\safefloattype{\floattype}%
}%
%
% \xrdef saves the floats as a \do-list in \floatlistSAFEFLOATTYPE.
\expandafter\ifx\csname floatlist\safefloattype\endcsname \relax
\ifhavexrefs
% if the user said @listoffloats foo but never @float foo.
\message{\linenumber No `\safefloattype' floats to list.}%
\fi
\else
\begingroup
\leftskip=\tocindent % indent these entries like a toc
\let\do=\listoffloatsdo
\csname floatlist\safefloattype\endcsname
\endgroup
\fi
}
% This is called on each entry in a list of floats. We're passed the
% xref label, in the form LABEL-title, which is how we save it in the
% aux file. We strip off the -title and look up \XRLABEL-lof, which
% has the text we're supposed to typeset here.
%
% Figures without xref labels will not be included in the list (since
% they won't appear in the aux file).
%
\def\listoffloatsdo#1{\listoffloatsdoentry#1\finish}
\def\listoffloatsdoentry#1-title\finish{{%
% Can't fully expand XR#1-lof because it can contain anything. Just
% pass the control sequence. On the other hand, XR#1-pg is just the
% page number, and we want to fully expand that so we can get a link
% in pdf output.
\toksA = \expandafter{\csname XR#1-lof\endcsname}%
%
% use the same \entry macro we use to generate the TOC and index.
\edef\writeentry{\noexpand\entry{\the\toksA}{\csname XR#1-pg\endcsname}}%
\writeentry
}}
\message{localization,}
% and i18n.
% @documentlanguage is usually given very early, just after
% @setfilename. If done too late, it may not override everything
% properly. Single argument is the language abbreviation.
% It would be nice if we could set up a hyphenation file here.
%
\parseargdef\documentlanguage{%
\tex % read txi-??.tex file in plain TeX.
% Read the file if it exists.
\openin 1 txi-#1.tex
\ifeof 1
\errhelp = \nolanghelp
\errmessage{Cannot read language file txi-#1.tex}%
\else
\input txi-#1.tex
\fi
\closein 1
\endgroup
}
\newhelp\nolanghelp{The given language definition file cannot be found or
is empty. Maybe you need to install it? In the current directory
should work if nowhere else does.}
% @documentencoding should change something in TeX eventually, most
% likely, but for now just recognize it.
\let\documentencoding = \comment
% Page size parameters.
%
\newdimen\defaultparindent \defaultparindent = 15pt
\chapheadingskip = 15pt plus 4pt minus 2pt
\secheadingskip = 12pt plus 3pt minus 2pt
\subsecheadingskip = 9pt plus 2pt minus 2pt
% Prevent underfull vbox error messages.
\vbadness = 10000
% Don't be so finicky about underfull hboxes, either.
\hbadness = 2000
% Following George Bush, just get rid of widows and orphans.
\widowpenalty=10000
\clubpenalty=10000
% Use TeX 3.0's \emergencystretch to help line breaking, but if we're
% using an old version of TeX, don't do anything. We want the amount of
% stretch added to depend on the line length, hence the dependence on
% \hsize. We call this whenever the paper size is set.
%
\def\setemergencystretch{%
\ifx\emergencystretch\thisisundefined
% Allow us to assign to \emergencystretch anyway.
\def\emergencystretch{\dimen0}%
\else
\emergencystretch = .15\hsize
\fi
}
% Parameters in order: 1) textheight; 2) textwidth;
% 3) voffset; 4) hoffset; 5) binding offset; 6) topskip;
% 7) physical page height; 8) physical page width.
%
% We also call \setleading{\textleading}, so the caller should define
% \textleading. The caller should also set \parskip.
%
\def\internalpagesizes#1#2#3#4#5#6#7#8{%
\voffset = #3\relax
\topskip = #6\relax
\splittopskip = \topskip
%
\vsize = #1\relax
\advance\vsize by \topskip
\outervsize = \vsize
\advance\outervsize by 2\topandbottommargin
\pageheight = \vsize
%
\hsize = #2\relax
\outerhsize = \hsize
\advance\outerhsize by 0.5in
\pagewidth = \hsize
%
\normaloffset = #4\relax
\bindingoffset = #5\relax
%
\ifpdf
\pdfpageheight #7\relax
\pdfpagewidth #8\relax
\fi
%
\setleading{\textleading}
%
\parindent = \defaultparindent
\setemergencystretch
}
% @letterpaper (the default).
\def\letterpaper{{\globaldefs = 1
\parskip = 3pt plus 2pt minus 1pt
\textleading = 13.2pt
%
% If page is nothing but text, make it come out even.
\internalpagesizes{46\baselineskip}{6in}%
{\voffset}{.25in}%
{\bindingoffset}{36pt}%
{11in}{8.5in}%
}}
% Use @smallbook to reset parameters for 7x9.25 trim size.
\def\smallbook{{\globaldefs = 1
\parskip = 2pt plus 1pt
\textleading = 12pt
%
\internalpagesizes{7.5in}{5in}%
{\voffset}{.25in}%
{\bindingoffset}{16pt}%
{9.25in}{7in}%
%
\lispnarrowing = 0.3in
\tolerance = 700
\hfuzz = 1pt
\contentsrightmargin = 0pt
\defbodyindent = .5cm
}}
% Use @smallerbook to reset parameters for 6x9 trim size.
% (Just testing, parameters still in flux.)
\def\smallerbook{{\globaldefs = 1
\parskip = 1.5pt plus 1pt
\textleading = 12pt
%
\internalpagesizes{7.4in}{4.8in}%
{-.2in}{-.4in}%
{0pt}{14pt}%
{9in}{6in}%
%
\lispnarrowing = 0.25in
\tolerance = 700
\hfuzz = 1pt
\contentsrightmargin = 0pt
\defbodyindent = .4cm
}}
% Use @afourpaper to print on European A4 paper.
\def\afourpaper{{\globaldefs = 1
\parskip = 3pt plus 2pt minus 1pt
\textleading = 13.2pt
%
% Double-side printing via postscript on Laserjet 4050
% prints double-sided nicely when \bindingoffset=10mm and \hoffset=-6mm.
% To change the settings for a different printer or situation, adjust
% \normaloffset until the front-side and back-side texts align. Then
% do the same for \bindingoffset. You can set these for testing in
% your texinfo source file like this:
% @tex
% \global\normaloffset = -6mm
% \global\bindingoffset = 10mm
% @end tex
\internalpagesizes{51\baselineskip}{160mm}
{\voffset}{\hoffset}%
{\bindingoffset}{44pt}%
{297mm}{210mm}%
%
\tolerance = 700
\hfuzz = 1pt
\contentsrightmargin = 0pt
\defbodyindent = 5mm
}}
% Use @afivepaper to print on European A5 paper.
% From romildo@urano.iceb.ufop.br, 2 July 2000.
% He also recommends making @example and @lisp be small.
\def\afivepaper{{\globaldefs = 1
\parskip = 2pt plus 1pt minus 0.1pt
\textleading = 12.5pt
%
\internalpagesizes{160mm}{120mm}%
{\voffset}{\hoffset}%
{\bindingoffset}{8pt}%
{210mm}{148mm}%
%
\lispnarrowing = 0.2in
\tolerance = 800
\hfuzz = 1.2pt
\contentsrightmargin = 0pt
\defbodyindent = 2mm
\tableindent = 12mm
}}
% A specific text layout, 24x15cm overall, intended for A4 paper.
\def\afourlatex{{\globaldefs = 1
\afourpaper
\internalpagesizes{237mm}{150mm}%
{\voffset}{4.6mm}%
{\bindingoffset}{7mm}%
{297mm}{210mm}%
%
% Must explicitly reset to 0 because we call \afourpaper.
\globaldefs = 0
}}
% Use @afourwide to print on A4 paper in landscape format.
\def\afourwide{{\globaldefs = 1
\afourpaper
\internalpagesizes{241mm}{165mm}%
{\voffset}{-2.95mm}%
{\bindingoffset}{7mm}%
{297mm}{210mm}%
\globaldefs = 0
}}
% @pagesizes TEXTHEIGHT[,TEXTWIDTH]
% Perhaps we should allow setting the margins, \topskip, \parskip,
% and/or leading, also. Or perhaps we should compute them somehow.
%
\parseargdef\pagesizes{\pagesizesyyy #1,,\finish}
\def\pagesizesyyy#1,#2,#3\finish{{%
\setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \hsize=#2\relax \fi
\globaldefs = 1
%
\parskip = 3pt plus 2pt minus 1pt
\setleading{\textleading}%
%
\dimen0 = #1
\advance\dimen0 by \voffset
%
\dimen2 = \hsize
\advance\dimen2 by \normaloffset
%
\internalpagesizes{#1}{\hsize}%
{\voffset}{\normaloffset}%
{\bindingoffset}{44pt}%
{\dimen0}{\dimen2}%
}}
% Set default to letter.
%
\letterpaper
\message{and turning on texinfo input format.}
% Define macros to output various characters with catcode for normal text.
\catcode`\"=\other
\catcode`\~=\other
\catcode`\^=\other
\catcode`\_=\other
\catcode`\|=\other
\catcode`\<=\other
\catcode`\>=\other
\catcode`\+=\other
\catcode`\$=\other
\def\normaldoublequote{"}
\def\normaltilde{~}
\def\normalcaret{^}
\def\normalunderscore{_}
\def\normalverticalbar{|}
\def\normalless{<}
\def\normalgreater{>}
\def\normalplus{+}
\def\normaldollar{$}%$ font-lock fix
% This macro is used to make a character print one way in \tt
% (where it can probably be output as-is), and another way in other fonts,
% where something hairier probably needs to be done.
%
% #1 is what to print if we are indeed using \tt; #2 is what to print
% otherwise. Since all the Computer Modern typewriter fonts have zero
% interword stretch (and shrink), and it is reasonable to expect all
% typewriter fonts to have this, we can check that font parameter.
%
\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi}
% Same as above, but check for italic font. Actually this also catches
% non-italic slanted fonts since it is impossible to distinguish them from
% italic fonts. But since this is only used by $ and it uses \sl anyway
% this is not a problem.
\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi}
% Turn off all special characters except @
% (and those which the user can use as if they were ordinary).
% Most of these we simply print from the \tt font, but for some, we can
% use math or other variants that look better in normal text.
\catcode`\"=\active
\def\activedoublequote{{\tt\char34}}
\let"=\activedoublequote
\catcode`\~=\active
\def~{{\tt\char126}}
\chardef\hat=`\^
\catcode`\^=\active
\def^{{\tt \hat}}
\catcode`\_=\active
\def_{\ifusingtt\normalunderscore\_}
\let\realunder=_
% Subroutine for the previous macro.
\def\_{\leavevmode \kern.07em \vbox{\hrule width.3em height.1ex}\kern .07em }
\catcode`\|=\active
\def|{{\tt\char124}}
\chardef \less=`\<
\catcode`\<=\active
\def<{{\tt \less}}
\chardef \gtr=`\>
\catcode`\>=\active
\def>{{\tt \gtr}}
\catcode`\+=\active
\def+{{\tt \char 43}}
\catcode`\$=\active
\def${\ifusingit{{\sl\$}}\normaldollar}%$ font-lock fix
% If a .fmt file is being used, characters that might appear in a file
% name cannot be active until we have parsed the command line.
% So turn them off again, and have \everyjob (or @setfilename) turn them on.
% \otherifyactive is called near the end of this file.
\def\otherifyactive{\catcode`+=\other \catcode`\_=\other}
% Used sometimes to turn off (effectively) the active characters even after
% parsing them.
\def\turnoffactive{%
\normalturnoffactive
\otherbackslash
}
\catcode`\@=0
% \backslashcurfont outputs one backslash character in current font,
% as in \char`\\.
\global\chardef\backslashcurfont=`\\
\global\let\rawbackslashxx=\backslashcurfont % let existing .??s files work
% \realbackslash is an actual character `\' with catcode other, and
% \doublebackslash is two of them (for the pdf outlines).
{\catcode`\\=\other @gdef@realbackslash{\} @gdef@doublebackslash{\\}}
% In texinfo, backslash is an active character; it prints the backslash
% in fixed width font.
\catcode`\\=\active
@def@normalbackslash{{@tt@backslashcurfont}}
% On startup, @fixbackslash assigns:
% @let \ = @normalbackslash
% \rawbackslash defines an active \ to do \backslashcurfont.
% \otherbackslash defines an active \ to be a literal `\' character with
% catcode other.
@gdef@rawbackslash{@let\=@backslashcurfont}
@gdef@otherbackslash{@let\=@realbackslash}
% Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of
% the literal character `\'.
%
@def@normalturnoffactive{%
@let\=@normalbackslash
@let"=@normaldoublequote
@let~=@normaltilde
@let^=@normalcaret
@let_=@normalunderscore
@let|=@normalverticalbar
@let<=@normalless
@let>=@normalgreater
@let+=@normalplus
@let$=@normaldollar %$ font-lock fix
@unsepspaces
}
% Make _ and + \other characters, temporarily.
% This is canceled by @fixbackslash.
@otherifyactive
% If a .fmt file is being used, we don't want the `\input texinfo' to show up.
% That is what \eatinput is for; after that, the `\' should revert to printing
% a backslash.
%
@gdef@eatinput input texinfo{@fixbackslash}
@global@let\ = @eatinput
% On the other hand, perhaps the file did not have a `\input texinfo'. Then
% the first `\' in the file would cause an error. This macro tries to fix
% that, assuming it is called before the first `\' could plausibly occur.
% Also turn back on active characters that might appear in the input
% file name, in case not using a pre-dumped format.
%
@gdef@fixbackslash{%
@ifx\@eatinput @let\ = @normalbackslash @fi
@catcode`+=@active
@catcode`@_=@active
}
% Say @foo, not \foo, in error messages.
@escapechar = `@@
% These look ok in all fonts, so just make them not special.
@catcode`@& = @other
@catcode`@# = @other
@catcode`@% = @other
@c Local variables:
@c eval: (add-hook 'write-file-hooks 'time-stamp)
@c page-delimiter: "^\\\\message"
@c time-stamp-start: "def\\\\texinfoversion{"
@c time-stamp-format: "%:y-%02m-%02d.%02H"
@c time-stamp-end: "}"
@c End:
@c vim:sw=2:
@ignore
arch-tag: e1b36e32-c96e-4135-a41a-0b2efa2ea115
@end ignore
.hgignore | 2 ++
1 file changed, 2 insertions(+)
| [
"993273596@qq.com"
] | 993273596@qq.com |
982a52322552cab9a7b28f8734c783ebdd02160b | 30e454af4970ecb2798ec45e48f2462ae25b8d56 | /21e/arbol.h | 92b3317601000fdaa6b61b4d8c511bdc5888b961 | [] | no_license | espilya/ed | b23794cfbc52460706a6d833896e9cd37b27a189 | 576eeada29d1f9bd4eef4d7f730ca55612c442f6 | refs/heads/master | 2022-11-12T01:26:09.642430 | 2020-07-03T21:43:30 | 2020-07-03T21:43:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | h | #ifndef tree_h
#define tree_h
#include "bintree_eda.h"
#include <algorithm>
#include <math.h>
#include <iostream>
#include <stack>
#include <vector>
template <class T>
class tree : public bintree<T> {
using Link = typename bintree<T>::Link;
using TreeNode = typename bintree<T>::TreeNode;
public:
tree() : bintree<T>() {}
tree(tree<T> const& r) : bintree<T>(r) {}
tree(tree<T> const& l, T const& e, tree<T> const& r) :
bintree<T>(l, e, r) {}
};
template <typename T>
inline tree<T> leerTree(T vacio) {
T raiz;
std::cin >> raiz;
if (raiz == vacio) { // es un árbol vacío
return {};
}
else { // leer recursivamente los hijos
auto iz = leerTree(vacio);
auto dr = leerTree(vacio);
return { iz, raiz, dr };
}
}
#endif // !tree_h | [
"espilya@gmail.com"
] | espilya@gmail.com |
2b85c91c2ad099687084d8bf52a3d89c46be707d | b71b8bd385c207dffda39d96c7bee5f2ccce946c | /testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_ifstream_17.cpp | 743b807f98898a1850e3f4c407ffd307da72565b | [] | no_license | Sporknugget/Juliet_prep | e9bda84a30bdc7938bafe338b4ab2e361449eda5 | 97d8922244d3d79b62496ede4636199837e8b971 | refs/heads/master | 2023-05-05T14:41:30.243718 | 2021-05-25T16:18:13 | 2021-05-25T16:18:13 | 369,334,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,384 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_ifstream_17.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-17.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sink: ifstream
* BadSink : Open the file named in data using ifstream::open()
* Flow Variant: 17 Control flow: for loops
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#include <fstream>
using namespace std;
namespace CWE36_Absolute_Path_Traversal__char_file_ifstream_17
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
{
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
}
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource in the for statement */
static void goodG2B()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
{
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
}
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__char_file_ifstream_17; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"jaredzap@rams.colostate.edu"
] | jaredzap@rams.colostate.edu |
ad5ba3ef6f4867d9f6197112b9d5d2a43b289081 | 27a7efe40e868fccd34e00b6af3669f5ed36ed0a | /experimental/jni/genzMain.cc | 4441eeb386353b206c885e18e70cfdb78d1ecaf4 | [
"BSD-3-Clause"
] | permissive | thanhen/onwards | cb360b4d1384916d4c31464f0adfb605f4a7ca48 | d01d7729f4c90c363531717a44bcc700fbf2c34a | refs/heads/master | 2022-12-05T17:30:31.833065 | 2020-08-29T04:46:21 | 2020-08-29T04:46:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cc | #include<cmw/BufferImpl.hh>
#include"genz.mdl.hh"
#include<stdio.h>
#include<stdlib.h>//exit
#include"jniGenz.h"
template<class...T>void leave (char const* fmt,T...t)noexcept{
::fprintf(stderr,fmt,t...);
::exit(EXIT_FAILURE);
}
int genzMain (int ac,char** av)try{
using namespace ::cmw;
if(ac<3||ac>5)
leave("Usage: genz account-num mdl-file-path [node] [port]\n");
winStart();
GetaddrinfoWrapper res(ac<4?"127.0.0.1":av[3],ac<5?"55555":av[4],SOCK_DGRAM);
BufferStack<SameFormat> buf(res.getSock());
::middle::marshal(buf,MarshallingInt(av[1]),av[2]);
for(int tm=8;tm<13;tm+=4){
buf.send(res()->ai_addr,res()->ai_addrlen);
setRcvTimeout(buf.sock_,tm);
if(buf.getPacket()){
if(giveBool(buf))::exit(EXIT_SUCCESS);
leave("cmwA:%s\n",buf.giveStringView().data());
}
}
leave("No reply received. Is the cmwA running?\n");
}catch(::std::exception& e){leave("%s\n",e.what());}
JNIEXPORT void JNICALL Java_jniGenz_wrap (JNIEnv *env,jobject obj,jobjectArray args){
auto argc=env->GetArrayLength(args);
auto argv=(char**)malloc(sizeof(char*)*(argc+1));// +1 for program name at index 0
argv[0]="jniGenz";
for(int i=0;i<argc;++i){
auto string=(jstring)env->GetObjectArrayElement(args,i);
argv[i+1]=(char*)env->GetStringUTFChars(string,0);
}
genzMain(argc+1,argv);
}
| [
"woodbrian77@gmail.com"
] | woodbrian77@gmail.com |
443df0f2a3cba6c62ef266a2650cb1e18a1d3128 | 6eab6c380fcbd6a695612113fcfe2681c2b27826 | /PyFlex/bindings/scenes/sdfcollision.h | 54facace328509dcf6328d3bab1ce2944097f4c2 | [
"Zlib",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | leledeyuan00/flingbot | 19a5bf48f5c3323794addb5c8c2b8a32b71dd3d9 | c5f35c785c6bc5d49282fb10117aa66ca04bf144 | refs/heads/master | 2023-08-12T00:41:36.669477 | 2021-10-13T00:04:33 | 2021-10-13T13:25:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,502 | h |
class SDFCollision : public Scene
{
public:
SDFCollision(const char *name) : Scene(name)
{
}
virtual void Initialize()
{
const int dim = 128;
NvFlexDistanceFieldId sdf = CreateSDF(GetFilePathByPlatform("../../data/bunny.ply").c_str(), dim);
AddSDF(sdf, Vec3(-1.f, 0.0f, 0.0f), QuatFromAxisAngle(Vec3(0.0f, 1.0f, 0.0f), DegToRad(-45.0f)), 0.5f);
AddSDF(sdf, Vec3(0.0f, 0.0f, 0.0f), QuatFromAxisAngle(Vec3(0.0f, 1.0f, 0.0f), DegToRad(0.0f)), 1.0f);
AddSDF(sdf, Vec3(1.0f, 0.0f, 0.0f), QuatFromAxisAngle(Vec3(0.0f, 1.0f, 0.0f), DegToRad(45.0f)), 2.0f);
float stretchStiffness = 1.0f;
float bendStiffness = 0.8f;
float shearStiffness = 0.5f;
int dimx = 64;
int dimz = 64;
float radius = 0.05f;
int phase = NvFlexMakePhase(0, eNvFlexPhaseSelfCollide | eNvFlexPhaseSelfCollideFilter);
CreateSpringGrid(Vec3(-0.6f, 2.9f, -0.6f), dimx, dimz, 1, radius * 0.75f, phase, stretchStiffness, bendStiffness, shearStiffness, 0.0f, 1.0f);
Vec3 lower, upper;
GetParticleBounds(lower, upper);
g_params.radius = radius * 1.0f;
g_params.dynamicFriction = 0.4f;
g_params.staticFriction = 0.4f;
g_params.particleFriction = 0.25f;
g_params.dissipation = 0.0f;
g_params.numIterations = 8;
g_params.viscosity = 0.0f;
g_params.drag = 0.02f;
g_params.lift = 0.1f;
g_params.collisionDistance = radius * 0.5f;
g_params.relaxationFactor = 1.3f;
g_numSubsteps = 3;
g_windStrength = 0.0f;
// draw options
g_drawPoints = false;
g_drawSprings = false;
}
};
| [
"hqh2101@columbia.edu"
] | hqh2101@columbia.edu |
402033446bf742f8725adca7392a69efcdec9ac3 | e07363e2f80131039afdccd9216a6385b527e631 | /thrift/compiler/test/fixtures/frozen-service/gen-cpp2/ServiceAAsyncClient.h | 3a6046f61d04aa3998e55d45e9b2602c785a0c87 | [
"Apache-2.0"
] | permissive | hvlong/fbthrift | 8f5fd0f80056363915de22dafc428d48c7d52319 | bc0b834940168bd95c3035bbab4668dfb7753609 | refs/heads/master | 2021-07-10T04:06:24.515212 | 2017-10-09T02:02:40 | 2017-10-09T02:08:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,877 | h | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#pragma once
#include <folly/futures/Future.h>
#include <thrift/lib/cpp/TApplicationException.h>
#include <thrift/lib/cpp2/ServiceIncludes.h>
#include <thrift/lib/cpp2/async/FutureRequest.h>
#include <thrift/lib/cpp2/async/HeaderChannel.h>
#include "src/gen-cpp2/module_types.h"
#include "src/gen-cpp2/module_layouts.h"
namespace folly {
class IOBuf;
class IOBufQueue;
}
namespace apache { namespace thrift {
class Cpp2RequestContext;
class BinaryProtocolReader;
class CompactProtocolReader;
class Frozen2ProtocolReader;
namespace transport { class THeader; }
}}
namespace some { namespace ns {
class ServiceAAsyncClient : public apache::thrift::TClientBase {
public:
virtual const char* getServiceName();
typedef std::unique_ptr<apache::thrift::RequestChannel, folly::DelayedDestruction::Destructor> channel_ptr;
virtual ~ServiceAAsyncClient() {}
ServiceAAsyncClient(std::shared_ptr<apache::thrift::RequestChannel> channel) :
channel_(channel) {
connectionContext_.reset(new apache::thrift::Cpp2ConnContext);
}
apache::thrift::RequestChannel* getChannel() {
return this->channel_.get();
}
apache::thrift::HeaderChannel* getHeaderChannel() {
return dynamic_cast<apache::thrift::HeaderChannel*>(this->channel_.get());
}
virtual void moduleAMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
virtual void moduleAMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
private:
virtual void moduleAMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
public:
virtual void sync_moduleAMethod(const ::some::ns::ModuleA& modArg);
virtual void sync_moduleAMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleA& modArg);
virtual folly::Future<folly::Unit> future_moduleAMethod(const ::some::ns::ModuleA& modArg);
virtual folly::Future<folly::Unit> future_moduleAMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleA& modArg);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_moduleAMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleA& modArg);
virtual void moduleAMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::some::ns::ModuleA& modArg);
static folly::exception_wrapper recv_wrapped_moduleAMethod(::apache::thrift::ClientReceiveState& state);
static void recv_moduleAMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_moduleAMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_moduleAMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void moduleAMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_moduleAMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_moduleAMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void moduleBMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleB& modArg);
virtual void moduleBMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleB& modArg);
private:
virtual void moduleBMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleB& modArg);
public:
virtual void sync_moduleBMethod(const ::some::ns::ModuleB& modArg);
virtual void sync_moduleBMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleB& modArg);
virtual folly::Future<folly::Unit> future_moduleBMethod(const ::some::ns::ModuleB& modArg);
virtual folly::Future<folly::Unit> future_moduleBMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleB& modArg);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_moduleBMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleB& modArg);
virtual void moduleBMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::some::ns::ModuleB& modArg);
static folly::exception_wrapper recv_wrapped_moduleBMethod(::apache::thrift::ClientReceiveState& state);
static void recv_moduleBMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_moduleBMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_moduleBMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void moduleBMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleB& modArg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_moduleBMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_moduleBMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void i32StrDoubleMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual void i32StrDoubleMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
private:
virtual void i32StrDoubleMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
public:
virtual void sync_i32StrDoubleMethod(int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual void sync_i32StrDoubleMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual folly::Future<folly::Unit> future_i32StrDoubleMethod(int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual folly::Future<folly::Unit> future_i32StrDoubleMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_i32StrDoubleMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual void i32StrDoubleMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
static folly::exception_wrapper recv_wrapped_i32StrDoubleMethod(::apache::thrift::ClientReceiveState& state);
static void recv_i32StrDoubleMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_i32StrDoubleMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_i32StrDoubleMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void i32StrDoubleMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_i32StrDoubleMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_i32StrDoubleMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void versioningMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual void versioningMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
private:
virtual void versioningMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
public:
virtual void sync_versioningMethod(int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual void sync_versioningMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual folly::Future<folly::Unit> future_versioningMethod(int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual folly::Future<folly::Unit> future_versioningMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_versioningMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg, const std::string& strArg, double doubleArg);
virtual void versioningMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
static folly::exception_wrapper recv_wrapped_versioningMethod(::apache::thrift::ClientReceiveState& state);
static void recv_versioningMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_versioningMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_versioningMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void versioningMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg, const std::string& strArg, double doubleArg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_versioningMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_versioningMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void retI32Method(std::unique_ptr<apache::thrift::RequestCallback> callback);
virtual void retI32Method(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
private:
virtual void retI32MethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
public:
virtual int32_t sync_retI32Method();
virtual int32_t sync_retI32Method(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<int32_t> future_retI32Method();
virtual folly::Future<int32_t> future_retI32Method(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<std::pair<int32_t, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_retI32Method(apache::thrift::RpcOptions& rpcOptions);
virtual void retI32Method(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback);
static folly::exception_wrapper recv_wrapped_retI32Method(int32_t& _return, ::apache::thrift::ClientReceiveState& state);
static int32_t recv_retI32Method(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual int32_t recv_instance_retI32Method(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_retI32Method(int32_t& _return, ::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void retI32MethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_retI32MethodT(Protocol_* prot, int32_t& _return, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static int32_t recv_retI32MethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void retModAMethod(std::unique_ptr<apache::thrift::RequestCallback> callback);
virtual void retModAMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
private:
virtual void retModAMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
public:
virtual void sync_retModAMethod( ::some::ns::ModuleA& _return);
virtual void sync_retModAMethod(apache::thrift::RpcOptions& rpcOptions, ::some::ns::ModuleA& _return);
virtual folly::Future< ::some::ns::ModuleA> future_retModAMethod();
virtual folly::Future< ::some::ns::ModuleA> future_retModAMethod(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<std::pair< ::some::ns::ModuleA, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_retModAMethod(apache::thrift::RpcOptions& rpcOptions);
virtual void retModAMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback);
static folly::exception_wrapper recv_wrapped_retModAMethod( ::some::ns::ModuleA& _return, ::apache::thrift::ClientReceiveState& state);
static void recv_retModAMethod( ::some::ns::ModuleA& _return, ::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_retModAMethod( ::some::ns::ModuleA& _return, ::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_retModAMethod( ::some::ns::ModuleA& _return, ::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void retModAMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_retModAMethodT(Protocol_* prot, ::some::ns::ModuleA& _return, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_retModAMethodT(Protocol_* prot, ::some::ns::ModuleA& _return, ::apache::thrift::ClientReceiveState& state);
public:
virtual void throwMethod(std::unique_ptr<apache::thrift::RequestCallback> callback);
virtual void throwMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
private:
virtual void throwMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
public:
virtual void sync_throwMethod();
virtual void sync_throwMethod(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<folly::Unit> future_throwMethod();
virtual folly::Future<folly::Unit> future_throwMethod(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_throwMethod(apache::thrift::RpcOptions& rpcOptions);
virtual void throwMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback);
static folly::exception_wrapper recv_wrapped_throwMethod(::apache::thrift::ClientReceiveState& state);
static void recv_throwMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_throwMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_throwMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void throwMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_throwMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_throwMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void multiThrowMethod(std::unique_ptr<apache::thrift::RequestCallback> callback);
virtual void multiThrowMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
private:
virtual void multiThrowMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
public:
virtual void sync_multiThrowMethod();
virtual void sync_multiThrowMethod(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<folly::Unit> future_multiThrowMethod();
virtual folly::Future<folly::Unit> future_multiThrowMethod(apache::thrift::RpcOptions& rpcOptions);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_multiThrowMethod(apache::thrift::RpcOptions& rpcOptions);
virtual void multiThrowMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback);
static folly::exception_wrapper recv_wrapped_multiThrowMethod(::apache::thrift::ClientReceiveState& state);
static void recv_multiThrowMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_multiThrowMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_multiThrowMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void multiThrowMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_multiThrowMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_multiThrowMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void i32ThrowMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg);
virtual void i32ThrowMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg);
private:
virtual void i32ThrowMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg);
public:
virtual void sync_i32ThrowMethod(int32_t i32Arg);
virtual void sync_i32ThrowMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg);
virtual folly::Future<folly::Unit> future_i32ThrowMethod(int32_t i32Arg);
virtual folly::Future<folly::Unit> future_i32ThrowMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_i32ThrowMethod(apache::thrift::RpcOptions& rpcOptions, int32_t i32Arg);
virtual void i32ThrowMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, int32_t i32Arg);
static folly::exception_wrapper recv_wrapped_i32ThrowMethod(::apache::thrift::ClientReceiveState& state);
static void recv_i32ThrowMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_i32ThrowMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_i32ThrowMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void i32ThrowMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, int32_t i32Arg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_i32ThrowMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_i32ThrowMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void moduleAThrowMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
virtual void moduleAThrowMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
private:
virtual void moduleAThrowMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
public:
virtual void sync_moduleAThrowMethod(const ::some::ns::ModuleA& modArg);
virtual void sync_moduleAThrowMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleA& modArg);
virtual folly::Future<folly::Unit> future_moduleAThrowMethod(const ::some::ns::ModuleA& modArg);
virtual folly::Future<folly::Unit> future_moduleAThrowMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleA& modArg);
virtual folly::Future<std::pair<folly::Unit, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_moduleAThrowMethod(apache::thrift::RpcOptions& rpcOptions, const ::some::ns::ModuleA& modArg);
virtual void moduleAThrowMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const ::some::ns::ModuleA& modArg);
static folly::exception_wrapper recv_wrapped_moduleAThrowMethod(::apache::thrift::ClientReceiveState& state);
static void recv_moduleAThrowMethod(::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_moduleAThrowMethod(::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_moduleAThrowMethod(::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void moduleAThrowMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const ::some::ns::ModuleA& modArg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_moduleAThrowMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_moduleAThrowMethodT(Protocol_* prot, ::apache::thrift::ClientReceiveState& state);
public:
virtual void mixedMethod(std::unique_ptr<apache::thrift::RequestCallback> callback, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
virtual void mixedMethod(apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
private:
virtual void mixedMethodImpl(bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
public:
virtual void sync_mixedMethod(std::string& _return, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
virtual void sync_mixedMethod(apache::thrift::RpcOptions& rpcOptions, std::string& _return, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
virtual folly::Future<std::string> future_mixedMethod(const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
virtual folly::Future<std::string> future_mixedMethod(apache::thrift::RpcOptions& rpcOptions, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
virtual folly::Future<std::pair<std::string, std::unique_ptr<apache::thrift::transport::THeader>>> header_future_mixedMethod(apache::thrift::RpcOptions& rpcOptions, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
virtual void mixedMethod(folly::Function<void (::apache::thrift::ClientReceiveState&&)> callback, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
static folly::exception_wrapper recv_wrapped_mixedMethod(std::string& _return, ::apache::thrift::ClientReceiveState& state);
static void recv_mixedMethod(std::string& _return, ::apache::thrift::ClientReceiveState& state);
// Mock friendly virtual instance method
virtual void recv_instance_mixedMethod(std::string& _return, ::apache::thrift::ClientReceiveState& state);
virtual folly::exception_wrapper recv_instance_wrapped_mixedMethod(std::string& _return, ::apache::thrift::ClientReceiveState& state);
private:
template <typename Protocol_>
void mixedMethodT(Protocol_* prot, bool useSync, apache::thrift::RpcOptions& rpcOptions, std::unique_ptr<apache::thrift::RequestCallback> callback, const std::string& strArg, int32_t i32Arg, const ::some::ns::ModuleB& modArg);
template <typename Protocol_>
static folly::exception_wrapper recv_wrapped_mixedMethodT(Protocol_* prot, std::string& _return, ::apache::thrift::ClientReceiveState& state);
template <typename Protocol_>
static void recv_mixedMethodT(Protocol_* prot, std::string& _return, ::apache::thrift::ClientReceiveState& state);
public:
protected:
std::unique_ptr<apache::thrift::Cpp2ConnContext> connectionContext_;
std::shared_ptr<apache::thrift::RequestChannel> channel_;
};
}} // some::ns
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
50160520bf989eeaeee3076346abca22851fd016 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/hunk_6583.cpp | 235b583cc93568afdd13592a3d7b659c71bcee70 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | die(msg, path, "");
}
+ /*
+ * Do not unlink a file in the work tree if we are not
+ * tracking it.
+ */
+ if (would_lose_untracked(path))
+ return error("refusing to lose untracked file at '%s'",
+ path);
+
/* Successful unlink is good.. */
if (!unlink(path))
return 0;
| [
"993273596@qq.com"
] | 993273596@qq.com |
3e9ca7aa11a1ee6fa1509b209b2ea37cc0561e13 | 0cd8d318705006305f8d527ae189d5f14a2d5af5 | /Ch4/10505 - Montesco vs Capuleto.cpp | 41ddf8c3bd5a279307faf41f21b089f987c322f7 | [] | no_license | johnsourour/UVA-Solutions | 3f4d115ecdd12d236e14f66fd2cbd9e6fda8edcd | 7ad116cea01bc0ada8c23729c8eedb60ad4b9346 | refs/heads/master | 2020-04-05T08:29:37.443746 | 2018-10-15T21:35:34 | 2018-10-15T21:35:34 | 81,753,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,559 | cpp | #include<bits/stdc++.h>
using namespace std;
#define MAX 205
#define INF 1e9
vector<vector<int> >adjList;
vector<int> seen;
int V[MAX];
void dfs(int s)
{
seen[s]=true;
for(int x:adjList[s])
{
if(!seen[x])dfs(x);
}
}
int cur;
int dfs2(int s)
{
int ans=V[s];
cur++;
seen[s]=true;
for(int x:adjList[s])
{
if(!seen[x])ans+=dfs2(x);
}
return ans;
}
void remove(int s)
{
V[s]=2;
seen[s]=true;
for(int x:adjList[s])
{
if(!seen[x])remove(x);
}
}
int main()
{
int m,n,t,k;
cin>>m;
while(m--)
{
cin>>n;
adjList.clear();
adjList.resize(n);
seen.clear();
seen.resize(n);
int f=-1;
for(int i=0;i<n;i++)
{
V[i]=INF;
int k;
cin>>k;
while(k--){
cin>>t;
if(t>n)continue;
t--;
adjList[i].push_back(t);
adjList[t].push_back(i);
}
}
vector<int> comp;
for(int i=0;i<n;i++)
{
if(!seen[i])
{
comp.push_back(i);
dfs(i);
}
}
bool isBipartite=true;
queue<int> q;
for(int v:comp)
{
V[v]=0;
q.push(v);
}
vector<int> mark;
while(!q.empty())
{
int v=q.front();q.pop();
for(int x:adjList[v])
{
if(V[x]==INF)
{
V[x]=1-V[v];
q.push(x);
}
else if(V[x]==V[v]){
mark.push_back(x);
break;
}
}
}
seen.clear();
seen.resize(n);
int tot=0;
for(int v:mark)remove(v);
seen.clear();
seen.resize(n);
for(int v:comp)
{
if(V[v]==2)continue;
if(!seen[v])
{
cur=0;
int cnt = dfs2(v);
tot+=max(cur-cnt,cnt);
}
}
if(!isBipartite)tot=0;
cout<<tot<<endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7f8efbdc048da77c5a341cc4e08c9bdf735fa124 | ed9f9b26e49dd8eb7027eb98680571164c90dbb2 | /mainwindow.h | 0af84560a37c001b8b1f8d2c1b5d527fb4e0f1a1 | [] | no_license | Doniasarsar/Projet_CPP | b606009e1e712584232c78503f8df8734971d63d | ef58198f17c4a4dfe1afcf24b0cfbf89188fdd0b | refs/heads/master | 2023-03-15T04:09:36.776752 | 2021-03-16T01:28:39 | 2021-03-16T01:28:39 | 346,869,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pb_ajouter_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"wael.ksila@esprit.tn"
] | wael.ksila@esprit.tn |
542cca2865c3b6eeb51484fd5e6c73351d59f8cf | f7df6576f641633ffa1290969e7b6da48ee3c26d | /src/OrbitVulkanLayer/QueueManager.cpp | c16902a7f15e48ba2c58e604703fba75f777c8c5 | [
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | beckerhe/orbitprofiler | 96fa8466dac647618e42ff45319d70aceb4505cc | 56541e1e53726f9f824e8216fdcbd4e7b1178965 | refs/heads/main | 2023-06-06T01:08:10.490090 | 2021-12-10T13:31:51 | 2021-12-10T13:31:51 | 235,291,165 | 2 | 0 | BSD-2-Clause | 2021-12-10T13:31:51 | 2020-01-21T08:32:27 | C++ | UTF-8 | C++ | false | false | 704 | cpp | // Copyright (c) 2020 The Orbit 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 "QueueManager.h"
#include "OrbitBase/Logging.h"
namespace orbit_vulkan_layer {
void QueueManager::TrackQueue(VkQueue queue, VkDevice device) {
absl::WriterMutexLock lock(&mutex_);
CHECK(!queue_to_device_.contains(queue) || queue_to_device_.at(queue) == device);
queue_to_device_.emplace(queue, device);
}
VkDevice QueueManager::GetDeviceOfQueue(VkQueue queue) {
absl::ReaderMutexLock lock(&mutex_);
CHECK(queue_to_device_.contains(queue));
return queue_to_device_.at(queue);
}
} // namespace orbit_vulkan_layer
| [
"noreply@github.com"
] | noreply@github.com |
2dedd24bb19afc68f463766fda470e3b9bcd7eb9 | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/Developer/Windows/WindowsClientTargetPlatform/Private/WindowsClientTargetPlatformModule.cpp | 79299ae03b10f27fedbda6c6f3fc474d8b2f2c05 | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 701 | cpp | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "WindowsClientTargetPlatformPrivatePCH.h"
/** Holds the target platform singleton. */
static ITargetPlatform* Singleton = nullptr;
/**
* Module for the Windows target platform as a server.
*/
class FWindowsClientTargetPlatformModule
: public ITargetPlatformModule
{
public:
virtual ~FWindowsClientTargetPlatformModule( )
{
Singleton = nullptr;
}
virtual ITargetPlatform* GetTargetPlatform( )
{
if (Singleton == nullptr)
{
Singleton = new TGenericWindowsTargetPlatform<false, false, true>();
}
return Singleton;
}
};
IMPLEMENT_MODULE(FWindowsClientTargetPlatformModule, WindowsClientTargetPlatform);
| [
"dkroell@acm.org"
] | dkroell@acm.org |
d78181b11153f3874146c0ab74274048f568a7cb | 13739586a566a82b47b88f06a9ba7da61d9f167e | /GeeksforGeeks/Remove duplicates from an unsorted linked list.cpp | 004c9caa8ec0f86799576025dd20e2ea080a08a8 | [] | no_license | sajalagrawal/BugFreeCodes | d712e5a46fa62319b66b00977a157e4c1758273f | c1930a68bdc50619daefea7f7088b506dd921e4c | refs/heads/master | 2023-01-20T19:13:08.736719 | 2023-01-15T14:38:27 | 2023-01-15T14:38:27 | 56,171,988 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 673 | cpp | //http://www.practice.geeksforgeeks.org/problem-page.php?pid=700125
//Author- Sajal Agrawal
//@sajal.agrawal1997@gmail.com
/*
The structure of linked list is the following
struct Node
{
int data;
Node* next;
};
*/
Node *removeDuplicates(Node *root)
{
Node *ptr1=root;
Node *ptr2,*temp;
while(ptr1!=NULL && ptr1->next!=NULL){
ptr2=ptr1;
while(ptr2->next!=NULL){
if(ptr1->data==ptr2->next->data){
temp=ptr2->next;
ptr2->next=ptr2->next->next;
free(temp);
}else{
ptr2=ptr2->next;
}
}
ptr1=ptr1->next;
}
return root;
}
| [
"noreply@github.com"
] | noreply@github.com |
3cb80ca9d262e8880d903c1ad044803696f93803 | 1fc4f5203d231f0abe1d1168298dd41e0ad2dc2e | /Bcode_WintgTerm_V2.6.6_Build_20180929(界面统一版本)/GpcTerms/WintgTerm/DlgTrainList.h | be314717873cf78e634f634a509eae3004e4a0d2 | [] | no_license | Huixaing/Project | 79d5ceb89620c0de6278cb211ef837c728f1af71 | fc3ab640265eaaed0c0a2c217370196525e1efc3 | refs/heads/master | 2020-03-30T00:44:07.773723 | 2018-10-08T05:44:22 | 2018-10-08T05:44:22 | 150,541,134 | 1 | 5 | null | null | null | null | GB18030 | C++ | false | false | 3,313 | h | #pragma once
#include "traingrid.h"
#include "markgrid.h"
#include "tg_schedule_base.h"
#include "tg_basicpara.h"
#include "td/td_data_def.h"
// CDlgTrainList 对话框
class CWorkScheduleHolder;
//class CTG_TrainScheduleBase;
class CTgDocument;
class CWintgViewMMI;
class CDlgTrainList : public CDialog
{
DECLARE_DYNAMIC(CDlgTrainList)
public:
BOOL m_bDirectlyRequestMode; // 直接申请模式,不是按照计划通知
private:
CTrainGridView m_grid;
CXMLDataGrid m_grid_plan;
CMarkGridView m_markgrid;
CWorkScheduleHolder *m_pHolder;
CTG_TrainScheduleBase *m_pSourceData;
CTG_TrainScheduleBase *m_pData;
CTG_ScheduleInfo m_schd_info;
CWnd *m_pWaitWnd;
CTgDocument *m_pDoc;
CWintgViewMMI *m_pTgMMI;
int m_nCurrentSel;
int m_nCurrentSelPlan;
CString m_szCaption;
int m_nGridType; // 0: train 1: mark
CTD_PlanInform m_plan_inform; // from opms
bool m_bSelAll;
// 新类型列车分割使用
int m_nSplitNum;
int m_cSplitStationList[NEW_SPLIT_ST_NUM];
int m_cSplitEntryList[NEW_SPLIT_ST_NUM];
public:
int m_nScheduleType;
BOOL m_bLoadFromSchedule;
int m_nDataChanged;
public:
void SetTgMMI(CWintgViewMMI *pmmi) {m_pTgMMI=pmmi;}
BOOL SetPlanInformXML(const char *token,const char *xml);
CDlgTrainList(const char *caption,CTgDocument *pdoc,int sche_type,int type,CWnd* pParent = NULL); // 标准构造函数
virtual ~CDlgTrainList();
void AddRequestTrainGUID(DWORD tid,const char *tno,BOOL local_add);
// 对话框数据
enum { IDD = IDD_DLG_TRAIN_LIST };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual BOOL OnInitDialog();
void OnOK();
void OnGridSelectChange(NMHDR* pNMHDR, LRESULT* pResult);
void OnMarkGridSelectChange(NMHDR* pNMHDR, LRESULT* pResult);
void OnPlanGridSelectChange(NMHDR* pNMHDR, LRESULT* pResult);
void OnBnClickedReq();
LRESULT OnCommMsg(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
void ShowTrainInfo();
void ShowMarkInfo();
BOOL ProcessTrainMsgFromOPMS(const char *token,const char *content);
BOOL ProcessReplyMsgFromOPMS(const char *token,const char *content);
BOOL ProcessShiftInfoMsgFromOPMS(const char *token,const char *content);
void RequestNewYLFromOPMS();
void RefreshTrainList();
void RequestShiftInfoFromOPMS(DWORD gtid);
void RefreshPlanList();
void RequestPlanDetail();
void OnTimer(UINT_PTR IDEvent);
void GetRecvCountRate(int &recved,int &tatol);
void OnDestroy();
void RefreshTrainList_Orig();
private:
CStringArray tdms_ctc_alarm;
struct SetInfo
{
int entry;
int exit;
int arrive; //由于货物列车分割后,不能保证首站有时间,该时间由前一段列车推出
bool bFirst;//是否首段列车
};
int SetNewTrainByOldTrain(int nSection, const SetInfo& info, CTD_Train& xmltrain, CTG_SingleTrain& newtrain, CTG_SingleTrain *ptrain);
BOOL SplitTDTrainx(CTD_Train &tdtrain, std::vector<CTD_Train>& train_list,const CTG_ScheduleInfo &schd,int entry_list[16], BOOL newflag) const;
void SplitTDTrain(CTD_Train& train, CTD_Train& other_train,int rec_index) const;
BOOL ProcessTrainMsgFromOPMS_NEW(const char *token,const char *content);
void CheckAndSetTipToDdyFlag(CTG_SingleTrain& train);
public:
afx_msg void OnBnClickedButton1();
};
| [
"32888508+Huixaing@users.noreply.github.com"
] | 32888508+Huixaing@users.noreply.github.com |
6e613efed1f45fd723ac42438a037051777cb152 | 91cdb0a2a9c9f1528337cdeb51345a16769d101b | /OpenGLAnimationTest/GameObject.h | 794bbe1157b74eba3298005e11b8ad66a2c26d7a | [] | no_license | sjadamem/MyGameEngine | d35300a65bc3def0e9798aab9c385d71520c26cc | f673a4d8f83658b914c2870c23be536b0eaabe1c | refs/heads/master | 2023-04-27T02:05:25.569181 | 2021-05-18T07:41:58 | 2021-05-18T07:41:58 | 364,518,755 | 0 | 0 | null | 2021-05-18T07:41:59 | 2021-05-05T09:04:35 | C | UTF-8 | C++ | false | false | 2,351 | h | #ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <glm/vec3.hpp>
#include <glm/mat4x4.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <string>
#include <vector>
#include <map>
#include "Shader.h"
#include "Model.h"
#include "Animator.h"
//#include "Transform.h"
using namespace std;
class Skeleton;
class GameObject
{
public:
// Transform mTransform;
Skeleton mSkeleton;
// string mName;
GameObject() {}
GameObject(const std::string& modelPath,
glm::vec3 pos = glm::vec3(0.0f),
glm::vec3 rot = glm::vec3(0.0f),
glm::vec3 scale = glm::vec3(1.0f));
void AddAnimation(const std::string& animName, const std::string& animFilePath, bool loop = false);
void SetCurrentAnimation(const std::string& animName);
void CreateCollision();
inline glm::vec3 getRotation() { return mTransform.mEulerAngles; }
inline void StartAnimator() { mAnimator->StartAnimator(); }
inline void StopAnimator() { mAnimator->StopAnimator(); }
void Move(glm::vec3 translate) { mTransform.Translate(translate); }
void Rotate(glm::vec3 rotate) { mTransform.Rotate(rotate); }
void Scale(glm::vec3 scale) { mTransform.Scale(scale); }
void Update(float deltaTime);
void Render(Shader* shader);
private:
// Is there any reason to separate these from the Model object?
vector<Mesh*> mMeshes;
Animator* mAnimator;
// Collision mCollision;
string mDirectory;
/* Like Unity, we can potentially contain all these 3D vectors into a single class 'Transform'.
This way I can simply point to this Transform object from other class objects to either move
this GameObject or have access to the relevant vectors instead of referencing each vector
separately.
Should I make this Transform object PUBLIC or PRIVATE? */
glm::vec3 mPosition;
// Consider using a quaternion instead of a vector.
// You will have to research the math behind quaternions (euler angles) before using it.
glm::quat mRotationQ;
glm::vec3 mRotation;
glm::vec3 mScale;
Transform mTransform;
// Is there any reason to have a model matrix property for a GameObject? It would probably be
// better to create a function to make and return the matrix in the Transform class and only call
// it when we need to send it to the GameObject's shader.
glm::mat4 mModelMatrix;
void UpdateModelMatrix();
};
#endif | [
"sjadamem@gmail.com"
] | sjadamem@gmail.com |
04a4c9482d8161b882c4f0fd81a211d8a056dc3d | 26a23a87317b942e0f8ce75591394d35f3d4d353 | /playerDead.cpp | bf1597607fe57518159841f09ac8f559bb72fcbc | [] | no_license | kodending/stoneAge | 34f183e29ce9a58a179f60a1732b17163b1e00e7 | 357949d414fd493b0bfcbeb8ea19849cd3da1b59 | refs/heads/master | 2023-08-03T09:56:07.624103 | 2021-09-10T04:12:26 | 2021-09-10T04:12:26 | 404,947,562 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,915 | cpp | #include "stdafx.h"
#include "player.h"
#include "playerStand.h"
#include "playerRun.h"
#include "playerSeat.h"
#include "playerDead.h"
#include "playerHurt.h"
#include "playerHello.h"
#include "playerAngry.h"
#include "playerDefense.h"
#include "playerAttack.h"
#include "playerCry.h"
#include "playerHappy.h"
playerState * playerDead::inputHandle(player * player)
{
if (player->getIsPlayerMove() == true)
{
player->setPlayerState(STATE_RUN);
return new playerRun();
}
//Y값이 바뀌면 다시 enter해라
if (_preCurrentFrameY != player->getPlayerCurrentFrameY())
{
return new playerDead();
}
if (player->getPlayerState() == STATE_STAND) return new playerStand();
if (player->getPlayerState() == STATE_RUN) return new playerRun();
if (player->getPlayerState() == STATE_SEAT) return new playerSeat();
if (player->getPlayerState() == STATE_HURT) return new playerHurt();
if (player->getPlayerState() == STATE_HELLO) return new playerHello();
if (player->getPlayerState() == STATE_ANGRY) return new playerAngry();
if (player->getPlayerState() == STATE_DEFENSE) return new playerDefense();
if (player->getPlayerState() == STATE_ATTACK) return new playerAttack();
if (player->getPlayerState() == STATE_CRY) return new playerCry();
if (player->getPlayerState() == STATE_HAPPY) return new playerHappy();
return nullptr;
}
void playerDead::update(player * player)
{
//플레이어 frame에 맞춘 방향 설정
player->setPlayerCurrentFrameY((int)(player->_player.direction));
}
void playerDead::enter(player * player)
{
SOUNDMANAGER->play("dead");
if (player->_player.playerCharacter == BLUE)
{
player->_player.img = IMAGEMANAGER->findImage("blue_dead_basic");
player->_playerImageName = "blue_dead_basic";
player->setPlayerCurrentFrameX(0);
player->setPlayerCurrentFrameY((int)(player->_player.direction));
if (player->getPlayerCurrentFrameY() == (int)DIR_SIX)
{
player->setPlayerImageMoveY(-10);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_SEVEN)
{
player->setPlayerImageMoveY(-15.5f);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_NINE)
{
player->setPlayerImageMoveY(-20.5f);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_ELEVEN)
{
player->setPlayerImageMoveY(-23.5f);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_TWELVE)
{
player->setPlayerImageMoveY(-23.5f);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_ONE)
{
player->setPlayerImageMoveY(-21.5f);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_THREE)
{
player->setPlayerImageMoveY(-20.5f);
player->setPlayerImageMoveX(0);
}
if (player->getPlayerCurrentFrameY() == (int)DIR_FIVE)
{
player->setPlayerImageMoveY(-19.5f);
player->setPlayerImageMoveX(0);
}
}
if (player->_player.playerCharacter == RED)
{
player->_player.img = IMAGEMANAGER->findImage("red_dead_basic");
player->_playerImageName = "red_dead_basic";
player->setPlayerImageMoveX(0);
player->setPlayerImageMoveY(-23.5f);
player->setPlayerCurrentFrameX(0);
player->setPlayerCurrentFrameY((int)(player->_player.direction));
}
player->setPlayerFrameAdjustTime(0.15f);
_preCurrentFrameY = player->getPlayerCurrentFrameY();
player->setPlayerRect(RectMakeCenter(player->getPlayerCenterX() + player->getPlayerImageMoveX(),
player->getPlayerCenterX() + player->getPlayerImageMoveY(),
player->getPlayerImage()->getFrameWidth(), player->getPlayerImage()->getFrameHeight()));
player->setPlayerImageCenterX(player->getPlayerCenterX() + player->getPlayerImageMoveX());
player->setPlayerImageCenterY(player->getPlayerCenterY() + player->getPlayerImageMoveY());
}
void playerDead::exit(player * player)
{
}
| [
"codending@gmail.com"
] | codending@gmail.com |
82e6d828cf32d7d9909b4f19f71c0513107bcf1f | 31c31345946b3526ffe3f1eafbc9dd7cdb48e03a | /Contests/Seletiva UPF 2018/A - Trilhos.cpp | 9c6a8154734023e45ef26cf151525549ce6cb3a1 | [] | no_license | felipefoschiera/Competitive-Programming | 84967cb7c6b82df5990cccea5d5b6862b9e63f65 | fe664046d0161fd6a15d4b8d8f983e77c6dc3dcb | refs/heads/master | 2022-02-23T16:07:04.326089 | 2019-10-04T19:22:22 | 2019-10-04T19:22:22 | 198,893,046 | 0 | 0 | null | 2019-07-25T19:53:36 | 2019-07-25T19:53:36 | null | UTF-8 | C++ | false | false | 954 | cpp | #include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
/**
* Para saber se podemos retirar os vagões como desejado, vamos empilhando os vagões
* na ordem de chegada, a partir de 1, e quando o vagão que chegou é o próximo a sair
* segundo a ordem da entrada, retiramos ele e avançamos para o próximo que se deseja retirar,
* retirando-o enquanto ele for o do topo da pilha.
*/
int main(){
int N;
while(scanf("%d", &N), N){
bool end = false;
while(1){
int v[N];
int x;
for(int i = 0; i < N; i++){
scanf("%d", &x);
if(x == 0) { end = true; break; }
v[i] = x;
}
if(end) break;
stack<int> pilha;
int ind = 0;
for(int i = 1; i <= N; i++){
pilha.push(i);
if(v[ind] == pilha.top()){
while(!pilha.empty() && pilha.top() == v[ind]){
pilha.pop();
ind++;
}
}
}
printf("%s\n", pilha.empty() ? "Yes" : "No");
}
printf("\n");
}
return 0;
} | [
"felipefoschiera@googlemail.com"
] | felipefoschiera@googlemail.com |
6577661da6867656f7ba514756db75d76152d71d | e278e572a5e826a5eea2936875ea0d41743ea96b | /tools/compilers/dmap/optimize.cpp | c0747f5de77f3c327aed4fdf5b146e16d6ee5e9c | [] | no_license | anastasiak2512/neo | 371258fd2475efb94248da809fa7c55169b8d90a | e3595d81366b232259dfaba3c7368c91d3fcef3f | refs/heads/master | 2020-05-18T16:33:33.583778 | 2015-02-10T13:44:34 | 2015-02-10T13:44:34 | 30,592,614 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 45,403 | cpp | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code 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 3 of the License, or
(at your option) any later version.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "sys/platform.h"
//#pragma optimize( "", off )
#ifdef WIN32
#include <windows.h>
#include <GL/gl.h>
#endif
#include "tools/compilers/dmap/dmap.h"
/*
New vertexes will be created where edges cross.
optimization requires an accurate t junction fixer.
*/
idBounds optBounds;
#define MAX_OPT_VERTEXES 0x10000
int numOptVerts;
optVertex_t optVerts[MAX_OPT_VERTEXES];
#define MAX_OPT_EDGES 0x40000
static int numOptEdges;
static optEdge_t optEdges[MAX_OPT_EDGES];
static bool IsTriangleValid( const optVertex_t *v1, const optVertex_t *v2, const optVertex_t *v3 );
static bool IsTriangleDegenerate( const optVertex_t *v1, const optVertex_t *v2, const optVertex_t *v3 );
static idRandom orandom;
/*
==============
ValidateEdgeCounts
==============
*/
static void ValidateEdgeCounts( optIsland_t *island ) {
optVertex_t *vert;
optEdge_t *e;
int c;
for ( vert = island->verts ; vert ; vert = vert->islandLink ) {
c = 0;
for ( e = vert->edges ; e ; ) {
c++;
if ( e->v1 == vert ) {
e = e->v1link;
} else if ( e->v2 == vert ) {
e = e->v2link;
} else {
common->Error( "ValidateEdgeCounts: mislinked" );
}
}
if ( c != 2 && c != 0 ) {
// this can still happen at diamond intersections
// common->Printf( "ValidateEdgeCounts: %i edges\n", c );
}
}
}
/*
====================
AllocEdge
====================
*/
static optEdge_t *AllocEdge( void ) {
optEdge_t *e;
if ( numOptEdges == MAX_OPT_EDGES ) {
common->Error( "MAX_OPT_EDGES" );
}
e = &optEdges[ numOptEdges ];
numOptEdges++;
memset( e, 0, sizeof( *e ) );
return e;
}
/*
====================
RemoveEdgeFromVert
====================
*/
static void RemoveEdgeFromVert( optEdge_t *e1, optVertex_t *vert ) {
optEdge_t **prev;
optEdge_t *e;
if ( !vert ) {
return;
}
prev = &vert->edges;
while ( *prev ) {
e = *prev;
if ( e == e1 ) {
if ( e1->v1 == vert ) {
*prev = e1->v1link;
} else if ( e1->v2 == vert ) {
*prev = e1->v2link;
} else {
common->Error( "RemoveEdgeFromVert: vert not found" );
}
return;
}
if ( e->v1 == vert ) {
prev = &e->v1link;
} else if ( e->v2 == vert ) {
prev = &e->v2link;
} else {
common->Error( "RemoveEdgeFromVert: vert not found" );
}
}
}
/*
====================
UnlinkEdge
====================
*/
static void UnlinkEdge( optEdge_t *e, optIsland_t *island ) {
optEdge_t **prev;
RemoveEdgeFromVert( e, e->v1 );
RemoveEdgeFromVert( e, e->v2 );
for ( prev = &island->edges ; *prev ; prev = &(*prev)->islandLink ) {
if ( *prev == e ) {
*prev = e->islandLink;
return;
}
}
common->Error( "RemoveEdgeFromIsland: couldn't free edge" );
}
/*
====================
LinkEdge
====================
*/
static void LinkEdge( optEdge_t *e ) {
e->v1link = e->v1->edges;
e->v1->edges = e;
e->v2link = e->v2->edges;
e->v2->edges = e;
}
/*
================
FindOptVertex
================
*/
static optVertex_t *FindOptVertex( idDrawVert *v, optimizeGroup_t *opt ) {
int i;
float x, y;
optVertex_t *vert;
// deal with everything strictly as 2D
x = v->xyz * opt->axis[0];
y = v->xyz * opt->axis[1];
// should we match based on the t-junction fixing hash verts?
for ( i = 0 ; i < numOptVerts ; i++ ) {
if ( optVerts[i].pv[0] == x && optVerts[i].pv[1] == y ) {
return &optVerts[i];
}
}
if ( numOptVerts >= MAX_OPT_VERTEXES ) {
common->Error( "MAX_OPT_VERTEXES" );
return NULL;
}
numOptVerts++;
vert = &optVerts[i];
memset( vert, 0, sizeof( *vert ) );
vert->v = *v;
vert->pv[0] = x;
vert->pv[1] = y;
vert->pv[2] = 0;
optBounds.AddPoint( vert->pv );
return vert;
}
/*
================
DrawAllEdges
================
*/
static void DrawAllEdges( void ) {
int i;
if ( !dmapGlobals.drawflag ) {
return;
}
Draw_ClearWindow();
qglBegin( GL_LINES );
for ( i = 0 ; i < numOptEdges ; i++ ) {
if ( optEdges[i].v1 == NULL ) {
continue;
}
qglColor3f( 1, 0, 0 );
qglVertex3fv( optEdges[i].v1->pv.ToFloatPtr() );
qglColor3f( 0, 0, 0 );
qglVertex3fv( optEdges[i].v2->pv.ToFloatPtr() );
}
qglEnd();
qglFlush();
// GLimp_SwapBuffers();
}
/*
================
DrawVerts
================
*/
static void DrawVerts( optIsland_t *island ) {
optVertex_t *vert;
if ( !dmapGlobals.drawflag ) {
return;
}
qglEnable( GL_BLEND );
qglBlendFunc( GL_ONE, GL_ONE );
qglColor3f( 0.3f, 0.3f, 0.3f );
qglPointSize( 3 );
qglBegin( GL_POINTS );
for ( vert = island->verts ; vert ; vert = vert->islandLink ) {
qglVertex3fv( vert->pv.ToFloatPtr() );
}
qglEnd();
qglDisable( GL_BLEND );
qglFlush();
}
/*
================
DrawEdges
================
*/
static void DrawEdges( optIsland_t *island ) {
optEdge_t *edge;
if ( !dmapGlobals.drawflag ) {
return;
}
Draw_ClearWindow();
qglBegin( GL_LINES );
for ( edge = island->edges ; edge ; edge = edge->islandLink ) {
if ( edge->v1 == NULL ) {
continue;
}
qglColor3f( 1, 0, 0 );
qglVertex3fv( edge->v1->pv.ToFloatPtr() );
qglColor3f( 0, 0, 0 );
qglVertex3fv( edge->v2->pv.ToFloatPtr() );
}
qglEnd();
qglFlush();
// GLimp_SwapBuffers();
}
//=================================================================
/*
=================
VertexBetween
=================
*/
static bool VertexBetween( const optVertex_t *p1, const optVertex_t *v1, const optVertex_t *v2 ) {
idVec3 d1, d2;
float d;
d1 = p1->pv - v1->pv;
d2 = p1->pv - v2->pv;
d = d1 * d2;
if ( d < 0 ) {
return true;
}
return false;
}
/*
====================
EdgeIntersection
Creates a new optVertex_t where the line segments cross.
This should only be called if PointsStraddleLine returned true
Will return NULL if the lines are colinear
====================
*/
static optVertex_t *EdgeIntersection( const optVertex_t *p1, const optVertex_t *p2,
const optVertex_t *l1, const optVertex_t *l2, optimizeGroup_t *opt ) {
float f;
idDrawVert *v;
idVec3 dir1, dir2, cross1, cross2;
dir1 = p1->pv - l1->pv;
dir2 = p1->pv - l2->pv;
cross1 = dir1.Cross( dir2 );
dir1 = p2->pv - l1->pv;
dir2 = p2->pv - l2->pv;
cross2 = dir1.Cross( dir2 );
if ( cross1[2] - cross2[2] == 0 ) {
return NULL;
}
f = cross1[2] / ( cross1[2] - cross2[2] );
// FIXME: how are we freeing this, since it doesn't belong to a tri?
v = (idDrawVert *)Mem_Alloc( sizeof( *v ) );
memset( v, 0, sizeof( *v ) );
v->xyz = p1->v.xyz * ( 1.0 - f ) + p2->v.xyz * f;
v->normal = p1->v.normal * ( 1.0 - f ) + p2->v.normal * f;
v->normal.Normalize();
v->st[0] = p1->v.st[0] * ( 1.0 - f ) + p2->v.st[0] * f;
v->st[1] = p1->v.st[1] * ( 1.0 - f ) + p2->v.st[1] * f;
return FindOptVertex( v, opt );
}
/*
====================
PointsStraddleLine
Colinear is considdered crossing.
====================
*/
static bool PointsStraddleLine( optVertex_t *p1, optVertex_t *p2, optVertex_t *l1, optVertex_t *l2 ) {
bool t1, t2;
t1 = IsTriangleDegenerate( l1, l2, p1 );
t2 = IsTriangleDegenerate( l1, l2, p2 );
if ( t1 && t2 ) {
// colinear case
float s1, s2, s3, s4;
bool positive, negative;
s1 = ( p1->pv - l1->pv ) * ( l2->pv - l1->pv );
s2 = ( p2->pv - l1->pv ) * ( l2->pv - l1->pv );
s3 = ( p1->pv - l2->pv ) * ( l2->pv - l1->pv );
s4 = ( p2->pv - l2->pv ) * ( l2->pv - l1->pv );
if ( s1 > 0 || s2 > 0 || s3 > 0 || s4 > 0 ) {
positive = true;
} else {
positive = false;
}
if ( s1 < 0 || s2 < 0 || s3 < 0 || s4 < 0 ) {
negative = true;
} else {
negative = false;
}
if ( positive && negative ) {
return true;
}
return false;
} else if ( p1 != l1 && p1 != l2 && p2 != l1 && p2 != l2 ) {
// no shared verts
t1 = IsTriangleValid( l1, l2, p1 );
t2 = IsTriangleValid( l1, l2, p2 );
if ( t1 && t2 ) {
return false;
}
t1 = IsTriangleValid( l1, p1, l2 );
t2 = IsTriangleValid( l1, p2, l2 );
if ( t1 && t2 ) {
return false;
}
return true;
} else {
// a shared vert, not colinear, so not crossing
return false;
}
}
/*
====================
EdgesCross
====================
*/
static bool EdgesCross( optVertex_t *a1, optVertex_t *a2, optVertex_t *b1, optVertex_t *b2 ) {
// if both verts match, consider it to be crossed
if ( a1 == b1 && a2 == b2 ) {
return true;
}
if ( a1 == b2 && a2 == b1 ) {
return true;
}
// if only one vert matches, it might still be colinear, which
// would be considered crossing
// if both lines' verts are on opposite sides of the other
// line, it is crossed
if ( !PointsStraddleLine( a1, a2, b1, b2 ) ) {
return false;
}
if ( !PointsStraddleLine( b1, b2, a1, a2 ) ) {
return false;
}
return true;
}
/*
====================
TryAddNewEdge
====================
*/
static bool TryAddNewEdge( optVertex_t *v1, optVertex_t *v2, optIsland_t *island ) {
optEdge_t *e;
// if the new edge crosses any other edges, don't add it
for ( e = island->edges ; e ; e = e->islandLink ) {
if ( EdgesCross( e->v1, e->v2, v1, v2 ) ) {
return false;
}
}
if ( dmapGlobals.drawflag ) {
qglBegin( GL_LINES );
qglColor3f( 0, ( 128 + orandom.RandomInt( 127 ) )/ 255.0, 0 );
qglVertex3fv( v1->pv.ToFloatPtr() );
qglVertex3fv( v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
}
// add it
e = AllocEdge();
e->islandLink = island->edges;
island->edges = e;
e->v1 = v1;
e->v2 = v2;
e->created = true;
// link the edge to its verts
LinkEdge( e );
return true;
}
typedef struct {
optVertex_t *v1, *v2;
float length;
} edgeLength_t;
static int LengthSort( const void *a, const void *b ) {
const edgeLength_t *ea, *eb;
ea = (const edgeLength_t *)a;
eb = (const edgeLength_t *)b;
if ( ea->length < eb->length ) {
return -1;
}
if ( ea->length > eb->length ) {
return 1;
}
return 0;
}
/*
==================
AddInteriorEdges
Add all possible edges between the verts
==================
*/
static void AddInteriorEdges( optIsland_t *island ) {
int c_addedEdges;
optVertex_t *vert, *vert2;
int c_verts;
edgeLength_t *lengths;
int numLengths;
int i;
DrawVerts( island );
// count the verts
c_verts = 0;
for ( vert = island->verts ; vert ; vert = vert->islandLink ) {
if ( !vert->edges ) {
continue;
}
c_verts++;
}
// allocate space for all the lengths
lengths = (edgeLength_t *)Mem_Alloc( sizeof( *lengths ) * c_verts * c_verts / 2 );
numLengths = 0;
for ( vert = island->verts ; vert ; vert = vert->islandLink ) {
if ( !vert->edges ) {
continue;
}
for ( vert2 = vert->islandLink ; vert2 ; vert2 = vert2->islandLink ) {
idVec3 dir;
if ( !vert2->edges ) {
continue;
}
lengths[numLengths].v1 = vert;
lengths[numLengths].v2 = vert2;
dir = ( vert->pv - vert2->pv ) ;
lengths[numLengths].length = dir.Length();
numLengths++;
}
}
// sort by length, shortest first
qsort( lengths, numLengths, sizeof( lengths[0] ), LengthSort );
// try to create them in that order
c_addedEdges = 0;
for ( i = 0 ; i < numLengths ; i++ ) {
if ( TryAddNewEdge( lengths[i].v1, lengths[i].v2, island ) ) {
c_addedEdges++;
}
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i tested segments\n", numLengths );
common->Printf( "%6i added interior edges\n", c_addedEdges );
}
Mem_Free( lengths );
}
//==================================================================
/*
====================
RemoveIfColinear
====================
*/
#define COLINEAR_EPSILON 0.1
static void RemoveIfColinear( optVertex_t *ov, optIsland_t *island ) {
optEdge_t *e, *e1, *e2;
optVertex_t *v1, *v2, *v3;
idVec3 dir1, dir2;
float dist;
idVec3 point;
idVec3 offset;
float off;
v2 = ov;
// we must find exactly two edges before testing for colinear
e1 = NULL;
e2 = NULL;
for ( e = ov->edges ; e ; ) {
if ( !e1 ) {
e1 = e;
} else if ( !e2 ) {
e2 = e;
} else {
return; // can't remove a vertex with three edges
}
if ( e->v1 == v2 ) {
e = e->v1link;
} else if ( e->v2 == v2 ) {
e = e->v2link;
} else {
common->Error( "RemoveIfColinear: mislinked edge" );
return;
}
}
// can't remove if no edges
if ( !e1 ) {
return;
}
if ( !e2 ) {
// this may still happen legally when a tiny triangle is
// the only thing in a group
common->Printf( "WARNING: vertex with only one edge\n" );
return;
}
if ( e1->v1 == v2 ) {
v1 = e1->v2;
} else if ( e1->v2 == v2 ) {
v1 = e1->v1;
} else {
common->Error( "RemoveIfColinear: mislinked edge" );
return;
}
if ( e2->v1 == v2 ) {
v3 = e2->v2;
} else if ( e2->v2 == v2 ) {
v3 = e2->v1;
} else {
common->Error( "RemoveIfColinear: mislinked edge" );
return;
}
if ( v1 == v3 ) {
common->Error( "RemoveIfColinear: mislinked edge" );
return;
}
// they must point in opposite directions
dist = ( v3->pv - v2->pv ) * ( v1->pv - v2->pv );
if ( dist >= 0 ) {
return;
}
// see if they are colinear
VectorSubtract( v3->v.xyz, v1->v.xyz, dir1 );
dir1.Normalize();
VectorSubtract( v2->v.xyz, v1->v.xyz, dir2 );
dist = DotProduct( dir2, dir1 );
VectorMA( v1->v.xyz, dist, dir1, point );
VectorSubtract( point, v2->v.xyz, offset );
off = offset.Length();
if ( off > COLINEAR_EPSILON ) {
return;
}
if ( dmapGlobals.drawflag ) {
qglBegin( GL_LINES );
qglColor3f( 1, 1, 0 );
qglVertex3fv( v1->pv.ToFloatPtr() );
qglVertex3fv( v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
qglBegin( GL_LINES );
qglColor3f( 0, 1, 1 );
qglVertex3fv( v2->pv.ToFloatPtr() );
qglVertex3fv( v3->pv.ToFloatPtr() );
qglEnd();
qglFlush();
}
// replace the two edges with a single edge
UnlinkEdge( e1, island );
UnlinkEdge( e2, island );
// v2 should have no edges now
if ( v2->edges ) {
common->Error( "RemoveIfColinear: didn't remove properly" );
return;
}
// if there is an existing edge that already
// has these exact verts, we have just collapsed a
// sliver triangle out of existance, and all the edges
// can be removed
for ( e = island->edges ; e ; e = e->islandLink ) {
if ( ( e->v1 == v1 && e->v2 == v3 )
|| ( e->v1 == v3 && e->v2 == v1 ) ) {
UnlinkEdge( e, island );
RemoveIfColinear( v1, island );
RemoveIfColinear( v3, island );
return;
}
}
// if we can't add the combined edge, link
// the originals back in
if ( !TryAddNewEdge( v1, v3, island ) ) {
e1->islandLink = island->edges;
island->edges = e1;
LinkEdge( e1 );
e2->islandLink = island->edges;
island->edges = e2;
LinkEdge( e2 );
return;
}
// recursively try to combine both verts now,
// because things may have changed since the last combine test
RemoveIfColinear( v1, island );
RemoveIfColinear( v3, island );
}
/*
====================
CombineColinearEdges
====================
*/
static void CombineColinearEdges( optIsland_t *island ) {
int c_edges;
optVertex_t *ov;
optEdge_t *e;
c_edges = 0;
for ( e = island->edges ; e ; e = e->islandLink ) {
c_edges++;
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i original exterior edges\n", c_edges );
}
for ( ov = island->verts ; ov ; ov = ov->islandLink ) {
RemoveIfColinear( ov, island );
}
c_edges = 0;
for ( e = island->edges ; e ; e = e->islandLink ) {
c_edges++;
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i optimized exterior edges\n", c_edges );
}
}
//==================================================================
/*
===================
FreeOptTriangles
===================
*/
static void FreeOptTriangles( optIsland_t *island ) {
optTri_t *opt, *next;
for ( opt = island->tris ; opt ; opt = next ) {
next = opt->next;
Mem_Free( opt );
}
island->tris = NULL;
}
/*
=================
IsTriangleValid
empty area will be considered invalid.
Due to some truly aweful epsilon issues, a triangle can switch between
valid and invalid depending on which order you look at the verts, so
consider it invalid if any one of the possibilities is invalid.
=================
*/
static bool IsTriangleValid( const optVertex_t *v1, const optVertex_t *v2, const optVertex_t *v3 ) {
idVec3 d1, d2, normal;
d1 = v2->pv - v1->pv;
d2 = v3->pv - v1->pv;
normal = d1.Cross( d2 );
if ( normal[2] <= 0 ) {
return false;
}
d1 = v3->pv - v2->pv;
d2 = v1->pv - v2->pv;
normal = d1.Cross( d2 );
if ( normal[2] <= 0 ) {
return false;
}
d1 = v1->pv - v3->pv;
d2 = v2->pv - v3->pv;
normal = d1.Cross( d2 );
if ( normal[2] <= 0 ) {
return false;
}
return true;
}
/*
=================
IsTriangleDegenerate
Returns false if it is either front or back facing
=================
*/
static bool IsTriangleDegenerate( const optVertex_t *v1, const optVertex_t *v2, const optVertex_t *v3 ) {
#if 1
idVec3 d1, d2, normal;
d1 = v2->pv - v1->pv;
d2 = v3->pv - v1->pv;
normal = d1.Cross( d2 );
if ( normal[2] == 0 ) {
return true;
}
return false;
#else
return (bool)!IsTriangleValid( v1, v2, v3 );
#endif
}
/*
==================
PointInTri
Tests if a 2D point is inside an original triangle
==================
*/
static bool PointInTri( const idVec3 &p, const mapTri_t *tri, optIsland_t *island ) {
idVec3 d1, d2, normal;
// the normal[2] == 0 case is not uncommon when a square is triangulated in
// the opposite manner to the original
d1 = tri->optVert[0]->pv - p;
d2 = tri->optVert[1]->pv - p;
normal = d1.Cross( d2 );
if ( normal[2] < 0 ) {
return false;
}
d1 = tri->optVert[1]->pv - p;
d2 = tri->optVert[2]->pv - p;
normal = d1.Cross( d2 );
if ( normal[2] < 0 ) {
return false;
}
d1 = tri->optVert[2]->pv - p;
d2 = tri->optVert[0]->pv - p;
normal = d1.Cross( d2 );
if ( normal[2] < 0 ) {
return false;
}
return true;
}
/*
====================
LinkTriToEdge
====================
*/
static void LinkTriToEdge( optTri_t *optTri, optEdge_t *edge ) {
if ( ( edge->v1 == optTri->v[0] && edge->v2 == optTri->v[1] )
|| ( edge->v1 == optTri->v[1] && edge->v2 == optTri->v[2] )
|| ( edge->v1 == optTri->v[2] && edge->v2 == optTri->v[0] ) ) {
if ( edge->backTri ) {
common->Printf( "Warning: LinkTriToEdge: already in use\n" );
return;
}
edge->backTri = optTri;
return;
}
if ( ( edge->v1 == optTri->v[1] && edge->v2 == optTri->v[0] )
|| ( edge->v1 == optTri->v[2] && edge->v2 == optTri->v[1] )
|| ( edge->v1 == optTri->v[0] && edge->v2 == optTri->v[2] ) ) {
if ( edge->frontTri ) {
common->Printf( "Warning: LinkTriToEdge: already in use\n" );
return;
}
edge->frontTri = optTri;
return;
}
common->Error( "LinkTriToEdge: edge not found on tri" );
}
/*
===============
CreateOptTri
===============
*/
static void CreateOptTri( optVertex_t *first, optEdge_t *e1, optEdge_t *e2, optIsland_t *island ) {
optEdge_t *opposite;
optVertex_t *second, *third;
optTri_t *optTri;
mapTri_t *tri;
if ( e1->v1 == first ) {
second = e1->v2;
} else if ( e1->v2 == first ) {
second = e1->v1;
} else {
common->Error( "CreateOptTri: mislinked edge" );
return;
}
if ( e2->v1 == first ) {
third = e2->v2;
} else if ( e2->v2 == first ) {
third = e2->v1;
} else {
common->Error( "CreateOptTri: mislinked edge" );
return;
}
if ( !IsTriangleValid( first, second, third ) ) {
common->Error( "CreateOptTri: invalid" );
return;
}
//DrawEdges( island );
// identify the third edge
if ( dmapGlobals.drawflag ) {
qglColor3f(1,1,0);
qglBegin( GL_LINES );
qglVertex3fv( e1->v1->pv.ToFloatPtr() );
qglVertex3fv( e1->v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
qglColor3f(0,1,1);
qglBegin( GL_LINES );
qglVertex3fv( e2->v1->pv.ToFloatPtr() );
qglVertex3fv( e2->v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
}
for ( opposite = second->edges ; opposite ; ) {
if ( opposite != e1 && ( opposite->v1 == third || opposite->v2 == third ) ) {
break;
}
if ( opposite->v1 == second ) {
opposite = opposite->v1link;
} else if ( opposite->v2 == second ) {
opposite = opposite->v2link;
} else {
common->Error( "BuildOptTriangles: mislinked edge" );
return;
}
}
if ( !opposite ) {
common->Printf( "Warning: BuildOptTriangles: couldn't locate opposite\n" );
return;
}
if ( dmapGlobals.drawflag ) {
qglColor3f(1,0,1);
qglBegin( GL_LINES );
qglVertex3fv( opposite->v1->pv.ToFloatPtr() );
qglVertex3fv( opposite->v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
}
// create new triangle
optTri = (optTri_t *)Mem_Alloc( sizeof( *optTri ) );
optTri->v[0] = first;
optTri->v[1] = second;
optTri->v[2] = third;
optTri->midpoint = ( optTri->v[0]->pv + optTri->v[1]->pv + optTri->v[2]->pv ) * ( 1.0f / 3.0f );
optTri->next = island->tris;
island->tris = optTri;
if ( dmapGlobals.drawflag ) {
qglColor3f( 1, 1, 1 );
qglPointSize( 4 );
qglBegin( GL_POINTS );
qglVertex3fv( optTri->midpoint.ToFloatPtr() );
qglEnd();
qglFlush();
}
// find the midpoint, and scan through all the original triangles to
// see if it is inside any of them
for ( tri = island->group->triList ; tri ; tri = tri->next ) {
if ( PointInTri( optTri->midpoint, tri, island ) ) {
break;
}
}
if ( tri ) {
optTri->filled = true;
} else {
optTri->filled = false;
}
if ( dmapGlobals.drawflag ) {
if ( optTri->filled ) {
qglColor3f( ( 128 + orandom.RandomInt( 127 ) )/ 255.0, 0, 0 );
} else {
qglColor3f( 0, ( 128 + orandom.RandomInt( 127 ) ) / 255.0, 0 );
}
qglBegin( GL_TRIANGLES );
qglVertex3fv( optTri->v[0]->pv.ToFloatPtr() );
qglVertex3fv( optTri->v[1]->pv.ToFloatPtr() );
qglVertex3fv( optTri->v[2]->pv.ToFloatPtr() );
qglEnd();
qglColor3f( 1, 1, 1 );
qglBegin( GL_LINE_LOOP );
qglVertex3fv( optTri->v[0]->pv.ToFloatPtr() );
qglVertex3fv( optTri->v[1]->pv.ToFloatPtr() );
qglVertex3fv( optTri->v[2]->pv.ToFloatPtr() );
qglEnd();
qglFlush();
}
// link the triangle to it's edges
LinkTriToEdge( optTri, e1 );
LinkTriToEdge( optTri, e2 );
LinkTriToEdge( optTri, opposite );
}
// debugging tool
#if 0
static void ReportNearbyVertexes( const optVertex_t *v, const optIsland_t *island ) {
const optVertex_t *ov;
float d;
idVec3 vec;
common->Printf( "verts near 0x%p (%f, %f)\n", v, v->pv[0], v->pv[1] );
for ( ov = island->verts ; ov ; ov = ov->islandLink ) {
if ( ov == v ) {
continue;
}
vec = ov->pv - v->pv;
d = vec.Length();
if ( d < 1 ) {
common->Printf( "0x%p = (%f, %f)\n", ov, ov->pv[0], ov->pv[1] );
}
}
}
#endif
/*
====================
BuildOptTriangles
Generate a new list of triangles from the optEdeges
====================
*/
static void BuildOptTriangles( optIsland_t *island ) {
optVertex_t *ov, *second = NULL, *third = NULL, *middle = NULL;
optEdge_t *e1, *e1Next = NULL, *e2, *e2Next = NULL, *check, *checkNext = NULL;
// free them
FreeOptTriangles( island );
// clear the vertex emitted flags
for ( ov = island->verts ; ov ; ov = ov->islandLink ) {
ov->emited = false;
}
// clear the edge triangle links
for ( check = island->edges ; check ; check = check->islandLink ) {
check->frontTri = check->backTri = NULL;
}
// check all possible triangle made up out of the
// edges coming off the vertex
for ( ov = island->verts ; ov ; ov = ov->islandLink ) {
if ( !ov->edges ) {
continue;
}
#if 0
if ( dmapGlobals.drawflag && ov == (optVertex_t *)0x1845a60 ) {
for ( e1 = ov->edges ; e1 ; e1 = e1Next ) {
qglBegin( GL_LINES );
qglColor3f( 0,1,0 );
qglVertex3fv( e1->v1->pv.ToFloatPtr() );
qglVertex3fv( e1->v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
if ( e1->v1 == ov ) {
e1Next = e1->v1link;
} else if ( e1->v2 == ov ) {
e1Next = e1->v2link;
}
}
}
#endif
for ( e1 = ov->edges ; e1 ; e1 = e1Next ) {
if ( e1->v1 == ov ) {
second = e1->v2;
e1Next = e1->v1link;
} else if ( e1->v2 == ov ) {
second = e1->v1;
e1Next = e1->v2link;
} else {
common->Error( "BuildOptTriangles: mislinked edge" );
}
// if the vertex has already been used, it can't be used again
if ( second->emited ) {
continue;
}
for ( e2 = ov->edges ; e2 ; e2 = e2Next ) {
if ( e2->v1 == ov ) {
third = e2->v2;
e2Next = e2->v1link;
} else if ( e2->v2 == ov ) {
third = e2->v1;
e2Next = e2->v2link;
} else {
common->Error( "BuildOptTriangles: mislinked edge" );
}
if ( e2 == e1 ) {
continue;
}
// if the vertex has already been used, it can't be used again
if ( third->emited ) {
continue;
}
// if the triangle is backwards or degenerate, don't use it
if ( !IsTriangleValid( ov, second, third ) ) {
continue;
}
// see if any other edge bisects these two, which means
// this triangle shouldn't be used
for ( check = ov->edges ; check ; check = checkNext ) {
if ( check->v1 == ov ) {
middle = check->v2;
checkNext = check->v1link;
} else if ( check->v2 == ov ) {
middle = check->v1;
checkNext = check->v2link;
} else {
common->Error( "BuildOptTriangles: mislinked edge" );
}
if ( check == e1 || check == e2 ) {
continue;
}
if ( IsTriangleValid( ov, second, middle )
&& IsTriangleValid( ov, middle, third ) ) {
break; // should use the subdivided ones
}
}
if ( check ) {
continue; // don't use it
}
// the triangle is valid
CreateOptTri( ov, e1, e2, island );
}
}
// later vertexes will not emit triangles that use an
// edge that this vert has already used
ov->emited = true;
}
}
/*
====================
RegenerateTriangles
Add new triangles to the group's regeneratedTris
====================
*/
static void RegenerateTriangles( optIsland_t *island ) {
optTri_t *optTri;
mapTri_t *tri;
int c_out;
c_out = 0;
for ( optTri = island->tris ; optTri ; optTri = optTri->next ) {
if ( !optTri->filled ) {
continue;
}
// create a new mapTri_t
tri = AllocTri();
tri->material = island->group->material;
tri->mergeGroup = island->group->mergeGroup;
tri->v[0] = optTri->v[0]->v;
tri->v[1] = optTri->v[1]->v;
tri->v[2] = optTri->v[2]->v;
idPlane plane;
PlaneForTri( tri, plane );
if ( plane.Normal() * dmapGlobals.mapPlanes[ island->group->planeNum ].Normal() <= 0 ) {
// this can happen reasonably when a triangle is nearly degenerate in
// optimization planar space, and winds up being degenerate in 3D space
common->Printf( "WARNING: backwards triangle generated!\n" );
// discard it
FreeTri( tri );
continue;
}
c_out++;
tri->next = island->group->regeneratedTris;
island->group->regeneratedTris = tri;
}
FreeOptTriangles( island );
if ( dmapGlobals.verbose ) {
common->Printf( "%6i tris out\n", c_out );
}
}
//===========================================================================
/*
====================
RemoveInteriorEdges
Edges that have triangles of the same type (filled / empty)
on both sides will be removed
====================
*/
static void RemoveInteriorEdges( optIsland_t *island ) {
int c_interiorEdges;
int c_exteriorEdges;
optEdge_t *e, *next;
bool front, back;
c_exteriorEdges = 0;
c_interiorEdges = 0;
for ( e = island->edges ; e ; e = next ) {
// we might remove the edge, so get the next link now
next = e->islandLink;
if ( !e->frontTri ) {
front = false;
} else {
front = e->frontTri->filled;
}
if ( !e->backTri ) {
back = false;
} else {
back = e->backTri->filled;
}
if ( front == back ) {
// free the edge
UnlinkEdge( e, island );
c_interiorEdges++;
continue;
}
c_exteriorEdges++;
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i original interior edges\n", c_interiorEdges );
common->Printf( "%6i original exterior edges\n", c_exteriorEdges );
}
}
//==================================================================================
typedef struct {
optVertex_t *v1, *v2;
} originalEdges_t;
/*
=================
AddEdgeIfNotAlready
=================
*/
void AddEdgeIfNotAlready( optVertex_t *v1, optVertex_t *v2 ) {
optEdge_t *e;
// make sure that there isn't an identical edge already added
for ( e = v1->edges ; e ; ) {
if ( ( e->v1 == v1 && e->v2 == v2 ) || ( e->v1 == v2 && e->v2 == v1 ) ) {
return; // already added
}
if ( e->v1 == v1 ) {
e = e->v1link;
} else if ( e->v2 == v1 ) {
e = e->v2link;
} else {
common->Error( "SplitEdgeByList: bad edge link" );
}
}
// this edge is a keeper
e = AllocEdge();
e->v1 = v1;
e->v2 = v2;
e->islandLink = NULL;
// link the edge to its verts
LinkEdge( e );
}
/*
=================
DrawOriginalEdges
=================
*/
static void DrawOriginalEdges( int numOriginalEdges, originalEdges_t *originalEdges ) {
int i;
if ( !dmapGlobals.drawflag ) {
return;
}
Draw_ClearWindow();
qglBegin( GL_LINES );
for ( i = 0 ; i < numOriginalEdges ; i++ ) {
qglColor3f( 1, 0, 0 );
qglVertex3fv( originalEdges[i].v1->pv.ToFloatPtr() );
qglColor3f( 0, 0, 0 );
qglVertex3fv( originalEdges[i].v2->pv.ToFloatPtr() );
}
qglEnd();
qglFlush();
}
typedef struct edgeCrossing_s {
struct edgeCrossing_s *next;
optVertex_t *ov;
} edgeCrossing_t;
static originalEdges_t *originalEdges;
static int numOriginalEdges;
/*
=================
AddOriginalTriangle
=================
*/
static void AddOriginalTriangle( optVertex_t *v[3] ) {
optVertex_t *v1, *v2;
// if this triangle is backwards (possible with epsilon issues)
// ignore it completely
if ( !IsTriangleValid( v[0], v[1], v[2] ) ) {
common->Printf( "WARNING: backwards triangle in input!\n" );
return;
}
for ( int i = 0 ; i < 3 ; i++ ) {
v1 = v[i];
v2 = v[(i+1)%3];
if ( v1 == v2 ) {
// this probably shouldn't happen, because the
// tri would be degenerate
continue;
}
int j;
// see if there is an existing one
for ( j = 0 ; j < numOriginalEdges ; j++ ) {
if ( originalEdges[j].v1 == v1 && originalEdges[j].v2 == v2 ) {
break;
}
if ( originalEdges[j].v2 == v1 && originalEdges[j].v1 == v2 ) {
break;
}
}
if ( j == numOriginalEdges ) {
// add it
originalEdges[j].v1 = v1;
originalEdges[j].v2 = v2;
numOriginalEdges++;
}
}
}
/*
=================
AddOriginalEdges
=================
*/
static void AddOriginalEdges( optimizeGroup_t *opt ) {
mapTri_t *tri;
optVertex_t *v[3];
int numTris;
if ( dmapGlobals.verbose ) {
common->Printf( "----\n" );
common->Printf( "%6i original tris\n", CountTriList( opt->triList ) );
}
optBounds.Clear();
// allocate space for max possible edges
numTris = CountTriList( opt->triList );
originalEdges = (originalEdges_t *)Mem_Alloc( numTris * 3 * sizeof( *originalEdges ) );
numOriginalEdges = 0;
// add all unique triangle edges
numOptVerts = 0;
numOptEdges = 0;
for ( tri = opt->triList ; tri ; tri = tri->next ) {
v[0] = tri->optVert[0] = FindOptVertex( &tri->v[0], opt );
v[1] = tri->optVert[1] = FindOptVertex( &tri->v[1], opt );
v[2] = tri->optVert[2] = FindOptVertex( &tri->v[2], opt );
AddOriginalTriangle( v );
}
}
/*
=====================
SplitOriginalEdgesAtCrossings
=====================
*/
void SplitOriginalEdgesAtCrossings( optimizeGroup_t *opt ) {
int i, j, k, l;
int numOriginalVerts;
edgeCrossing_t **crossings;
numOriginalVerts = numOptVerts;
// now split any crossing edges and create optEdges
// linked to the vertexes
// debug drawing bounds
dmapGlobals.drawBounds = optBounds;
dmapGlobals.drawBounds[0][0] -= 2;
dmapGlobals.drawBounds[0][1] -= 2;
dmapGlobals.drawBounds[1][0] += 2;
dmapGlobals.drawBounds[1][1] += 2;
// generate crossing points between all the original edges
crossings = (edgeCrossing_t **)Mem_ClearedAlloc( numOriginalEdges * sizeof( *crossings ) );
for ( i = 0 ; i < numOriginalEdges ; i++ ) {
if ( dmapGlobals.drawflag ) {
DrawOriginalEdges( numOriginalEdges, originalEdges );
qglBegin( GL_LINES );
qglColor3f( 0, 1, 0 );
qglVertex3fv( originalEdges[i].v1->pv.ToFloatPtr() );
qglColor3f( 0, 0, 1 );
qglVertex3fv( originalEdges[i].v2->pv.ToFloatPtr() );
qglEnd();
qglFlush();
}
for ( j = i+1 ; j < numOriginalEdges ; j++ ) {
optVertex_t *v1, *v2, *v3, *v4;
optVertex_t *newVert;
edgeCrossing_t *cross;
v1 = originalEdges[i].v1;
v2 = originalEdges[i].v2;
v3 = originalEdges[j].v1;
v4 = originalEdges[j].v2;
if ( !EdgesCross( v1, v2, v3, v4 ) ) {
continue;
}
// this is the only point in optimization where
// completely new points are created, and it only
// happens if there is overlapping coplanar
// geometry in the source triangles
newVert = EdgeIntersection( v1, v2, v3, v4, opt );
if ( !newVert ) {
//common->Printf( "lines %i (%i to %i) and %i (%i to %i) are colinear\n", i, v1 - optVerts, v2 - optVerts,
// j, v3 - optVerts, v4 - optVerts ); // !@#
// colinear, so add both verts of each edge to opposite
if ( VertexBetween( v3, v1, v2 ) ) {
cross = (edgeCrossing_t *)Mem_ClearedAlloc( sizeof( *cross ) );
cross->ov = v3;
cross->next = crossings[i];
crossings[i] = cross;
}
if ( VertexBetween( v4, v1, v2 ) ) {
cross = (edgeCrossing_t *)Mem_ClearedAlloc( sizeof( *cross ) );
cross->ov = v4;
cross->next = crossings[i];
crossings[i] = cross;
}
if ( VertexBetween( v1, v3, v4 ) ) {
cross = (edgeCrossing_t *)Mem_ClearedAlloc( sizeof( *cross ) );
cross->ov = v1;
cross->next = crossings[j];
crossings[j] = cross;
}
if ( VertexBetween( v2, v3, v4 ) ) {
cross = (edgeCrossing_t *)Mem_ClearedAlloc( sizeof( *cross ) );
cross->ov = v2;
cross->next = crossings[j];
crossings[j] = cross;
}
continue;
}
#if 0
if ( newVert && newVert != v1 && newVert != v2 && newVert != v3 && newVert != v4 ) {
common->Printf( "lines %i (%i to %i) and %i (%i to %i) cross at new point %i\n", i, v1 - optVerts, v2 - optVerts,
j, v3 - optVerts, v4 - optVerts, newVert - optVerts );
} else if ( newVert ) {
common->Printf( "lines %i (%i to %i) and %i (%i to %i) intersect at old point %i\n", i, v1 - optVerts, v2 - optVerts,
j, v3 - optVerts, v4 - optVerts, newVert - optVerts );
}
#endif
if ( newVert != v1 && newVert != v2 ) {
cross = (edgeCrossing_t *)Mem_ClearedAlloc( sizeof( *cross ) );
cross->ov = newVert;
cross->next = crossings[i];
crossings[i] = cross;
}
if ( newVert != v3 && newVert != v4 ) {
cross = (edgeCrossing_t *)Mem_ClearedAlloc( sizeof( *cross ) );
cross->ov = newVert;
cross->next = crossings[j];
crossings[j] = cross;
}
}
}
// now split each edge by its crossing points
// colinear edges will have duplicated edges added, but it won't hurt anything
for ( i = 0 ; i < numOriginalEdges ; i++ ) {
edgeCrossing_t *cross, *nextCross;
int numCross;
optVertex_t **sorted;
numCross = 0;
for ( cross = crossings[i] ; cross ; cross = cross->next ) {
numCross++;
}
numCross += 2; // account for originals
sorted = (optVertex_t **)Mem_Alloc( numCross * sizeof( *sorted ) );
sorted[0] = originalEdges[i].v1;
sorted[1] = originalEdges[i].v2;
j = 2;
for ( cross = crossings[i] ; cross ; cross = nextCross ) {
nextCross = cross->next;
sorted[j] = cross->ov;
Mem_Free( cross );
j++;
}
// add all possible fragment combinations that aren't divided
// by another point
for ( j = 0 ; j < numCross ; j++ ) {
for ( k = j+1 ; k < numCross ; k++ ) {
for ( l = 0 ; l < numCross ; l++ ) {
if ( sorted[l] == sorted[j] || sorted[l] == sorted[k] ) {
continue;
}
if ( sorted[j] == sorted[k] ) {
continue;
}
if ( VertexBetween( sorted[l], sorted[j], sorted[k] ) ) {
break;
}
}
if ( l == numCross ) {
//common->Printf( "line %i fragment from point %i to %i\n", i, sorted[j] - optVerts, sorted[k] - optVerts );
AddEdgeIfNotAlready( sorted[j], sorted[k] );
}
}
}
Mem_Free( sorted );
}
Mem_Free( crossings );
Mem_Free( originalEdges );
// check for duplicated edges
for ( i = 0 ; i < numOptEdges ; i++ ) {
for ( j = i+1 ; j < numOptEdges ; j++ ) {
if ( ( optEdges[i].v1 == optEdges[j].v1 && optEdges[i].v2 == optEdges[j].v2 )
|| ( optEdges[i].v1 == optEdges[j].v2 && optEdges[i].v2 == optEdges[j].v1 ) ) {
common->Printf( "duplicated optEdge\n" );
}
}
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i original edges\n", numOriginalEdges );
common->Printf( "%6i edges after splits\n", numOptEdges );
common->Printf( "%6i original vertexes\n", numOriginalVerts );
common->Printf( "%6i vertexes after splits\n", numOptVerts );
}
}
//=================================================================
/*
===================
CullUnusedVerts
Unlink any verts with no edges, so they
won't be used in the retriangulation
===================
*/
static void CullUnusedVerts( optIsland_t *island ) {
optVertex_t **prev, *vert;
int c_keep, c_free;
optEdge_t *edge;
c_keep = 0;
c_free = 0;
for ( prev = &island->verts ; *prev ; ) {
vert = *prev;
if ( !vert->edges ) {
// free it
*prev = vert->islandLink;
c_free++;
} else {
edge = vert->edges;
if ( ( edge->v1 == vert && !edge->v1link )
|| ( edge->v2 == vert && !edge->v2link ) ) {
// is is occasionally possible to get a vert
// with only a single edge when colinear optimizations
// crunch down a complex sliver
UnlinkEdge( edge, island );
// free it
*prev = vert->islandLink;
c_free++;
} else {
prev = &vert->islandLink;
c_keep++;
}
}
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i verts kept\n", c_keep );
common->Printf( "%6i verts freed\n", c_free );
}
}
/*
====================
OptimizeIsland
At this point, all needed vertexes are already in the
list, including any that were added at crossing points.
Interior and colinear vertexes will be removed, and
a new triangulation will be created.
====================
*/
static void OptimizeIsland( optIsland_t *island ) {
// add space-filling fake edges so we have a complete
// triangulation of a convex hull before optimization
AddInteriorEdges( island );
DrawEdges( island );
// determine all the possible triangles, and decide if
// the are filled or empty
BuildOptTriangles( island );
// remove interior vertexes that have filled triangles
// between all their edges
RemoveInteriorEdges( island );
DrawEdges( island );
ValidateEdgeCounts( island );
// remove vertexes that only have two colinear edges
CombineColinearEdges( island );
CullUnusedVerts( island );
DrawEdges( island );
// add new internal edges between the remaining exterior edges
// to give us a full triangulation again
AddInteriorEdges( island );
DrawEdges( island );
// determine all the possible triangles, and decide if
// the are filled or empty
BuildOptTriangles( island );
// make mapTri_t out of the filled optTri_t
RegenerateTriangles( island );
}
/*
================
AddVertexToIsland_r
================
*/
#if 0
static void AddVertexToIsland_r( optVertex_t *vert, optIsland_t *island ) {
optEdge_t *e;
// we can't just check islandLink, because the
// last vert will have a NULL
if ( vert->addedToIsland ) {
return;
}
vert->addedToIsland = true;
vert->islandLink = island->verts;
island->verts = vert;
for ( e = vert->edges ; e ; ) {
if ( !e->addedToIsland ) {
e->addedToIsland = true;
e->islandLink = island->edges;
island->edges = e;
}
if ( e->v1 == vert ) {
AddVertexToIsland_r( e->v2, island );
e = e->v1link;
continue;
}
if ( e->v2 == vert ) {
AddVertexToIsland_r( e->v1, island );
e = e->v2link;
continue;
}
common->Error( "AddVertexToIsland_r: mislinked vert" );
}
}
#endif
/*
====================
SeparateIslands
While the algorithm should theoretically handle any collection
of triangles, there are speed and stability benefits to making
it work on as small a list as possible, so separate disconnected
collections of edges and process separately.
FIXME: we need to separate the source triangles before
doing this, because PointInSourceTris() can give a bad answer if
the source list has triangles not used in the optimization
====================
*/
#if 0
static void SeparateIslands( optimizeGroup_t *opt ) {
int i;
optIsland_t island;
int numIslands;
DrawAllEdges();
numIslands = 0;
for ( i = 0 ; i < numOptVerts ; i++ ) {
if ( optVerts[i].addedToIsland ) {
continue;
}
numIslands++;
memset( &island, 0, sizeof( island ) );
island.group = opt;
AddVertexToIsland_r( &optVerts[i], &island );
OptimizeIsland( &island );
}
if ( dmapGlobals.verbose ) {
common->Printf( "%6i islands\n", numIslands );
}
}
#endif
static void DontSeparateIslands( optimizeGroup_t *opt ) {
int i;
optIsland_t island;
DrawAllEdges();
memset( &island, 0, sizeof( island ) );
island.group = opt;
// link everything together
for ( i = 0 ; i < numOptVerts ; i++ ) {
optVerts[i].islandLink = island.verts;
island.verts = &optVerts[i];
}
for ( i = 0 ; i < numOptEdges ; i++ ) {
optEdges[i].islandLink = island.edges;
island.edges = &optEdges[i];
}
OptimizeIsland( &island );
}
/*
====================
PointInSourceTris
This is a sloppy bounding box check
====================
*/
#if 0
static bool PointInSourceTris( float x, float y, float z, optimizeGroup_t *opt ) {
mapTri_t *tri;
idBounds b;
idVec3 p;
if ( !opt->material->IsDrawn() ) {
return false;
}
p[0] = x;
p[1] = y;
p[2] = z;
for ( tri = opt->triList ; tri ; tri = tri->next ) {
b.Clear();
b.AddPoint( tri->v[0].xyz );
b.AddPoint( tri->v[1].xyz );
b.AddPoint( tri->v[2].xyz );
if ( b.ContainsPoint( p ) ) {
return true;
}
}
return false;
}
#endif
/*
====================
OptimizeOptList
====================
*/
static void OptimizeOptList( optimizeGroup_t *opt ) {
optimizeGroup_t *oldNext;
// fix the t junctions among this single list
// so we can match edges
// can we avoid doing this if colinear vertexes break edges?
oldNext = opt->nextGroup;
opt->nextGroup = NULL;
FixAreaGroupsTjunctions( opt );
opt->nextGroup = oldNext;
// create the 2D vectors
dmapGlobals.mapPlanes[opt->planeNum].Normal().NormalVectors( opt->axis[0], opt->axis[1] );
AddOriginalEdges( opt );
SplitOriginalEdgesAtCrossings( opt );
#if 0
// seperate any discontinuous areas for individual optimization
// to reduce the scope of the problem
SeparateIslands( opt );
#else
DontSeparateIslands( opt );
#endif
// now free the hash verts
FreeTJunctionHash();
// free the original list and use the new one
FreeTriList( opt->triList );
opt->triList = opt->regeneratedTris;
opt->regeneratedTris = NULL;
}
/*
==================
SetGroupTriPlaneNums
Copies the group planeNum to every triangle in each group
==================
*/
void SetGroupTriPlaneNums( optimizeGroup_t *groups ) {
mapTri_t *tri;
optimizeGroup_t *group;
for ( group = groups ; group ; group = group->nextGroup ) {
for ( tri = group->triList ; tri ; tri = tri->next ) {
tri->planeNum = group->planeNum;
}
}
}
/*
===================
OptimizeGroupList
This will also fix tjunctions
===================
*/
void OptimizeGroupList( optimizeGroup_t *groupList ) {
int c_in, c_edge, c_tjunc2;
optimizeGroup_t *group;
if ( !groupList ) {
return;
}
c_in = CountGroupListTris( groupList );
// optimize and remove colinear edges, which will
// re-introduce some t junctions
for ( group = groupList ; group ; group = group->nextGroup ) {
OptimizeOptList( group );
}
c_edge = CountGroupListTris( groupList );
// fix t junctions again
FixAreaGroupsTjunctions( groupList );
FreeTJunctionHash();
c_tjunc2 = CountGroupListTris( groupList );
SetGroupTriPlaneNums( groupList );
common->Printf( "----- OptimizeAreaGroups Results -----\n" );
common->Printf( "%6i tris in\n", c_in );
common->Printf( "%6i tris after edge removal optimization\n", c_edge );
common->Printf( "%6i tris after final t junction fixing\n", c_tjunc2 );
}
/*
==================
OptimizeEntity
==================
*/
void OptimizeEntity( uEntity_t *e ) {
int i;
common->Printf( "----- OptimizeEntity -----\n" );
for ( i = 0 ; i < e->numAreas ; i++ ) {
OptimizeGroupList( e->areas[i].groups );
}
}
| [
"anastasia.kazakova@jetbrains.com"
] | anastasia.kazakova@jetbrains.com |
f0ca6f8e1c06f560791e87b3a261bd67f4004944 | 4d6bf26f4d9a43082f87e177c1a2ac6c9662c288 | /Chapter 4/Programming Challenge/16.cpp | 7a5df3a803015d0927601b01a4ddc27b7296d6c4 | [] | no_license | Miao4382/Starting-Out-with-Cplusplus | 08d13d75fdb741be59a398b76275c5ee394840ca | dd3a1eadcf403ae57a68183987fc24fbfac0517f | refs/heads/master | 2020-05-24T23:22:49.978761 | 2019-05-20T18:40:01 | 2019-05-20T18:40:01 | 187,513,299 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,480 | cpp | //16. Running the Race: The switch approach
#include <iostream>
#include <string>
using namespace std;
int main()
{
//variable definition
string runner1, runner2, runner3;
double time1, time2, time3;
//program input
cout << "Please input the name of the firt runner: ";
getline(cin, runner1);
cout << "Please input the time of the first runner: ";
cin >> time1;
cin.ignore();
cout << "Please input the name of the second runner: ";
getline(cin, runner2);
cout << "Please input the time of the second runner: ";
cin >> time2;
cin.ignore();
cout << "Please input the name of the third runner: ";
getline(cin, runner3);
cout << "Please input the time of the third runner: ";
cin >> time3;
//valid check
if (time1 > 0 && time2 > 0 && time3 > 0)
{
int flag1, flag2, flag3, flag;
flag1 = time1 < time2 ? 1 : 0;
flag2 = time1 < time3 ? 3 : 0;
flag3 = time2 < time3 ? 5 : 0;
flag = flag1 + flag2 + flag3;
switch (flag)
{
case 9: cout << "First:\t" << runner1 << "\nSecond:\t" << runner2 << "\nThird:\t" << runner3 << endl; break;
case 4: cout << "First:\t" << runner1 << "\nSecond:\t" << runner3 << "\nThird:\t" << runner2 << endl; break;
case 8: cout << "First:\t" << runner2 << "\nSecond:\t" << runner1 << "\nThird:\t" << runner3 << endl; break;
case 5: cout << "First:\t" << runner2 << "\nSecond:\t" << runner3 << "\nThird:\t" << runner1 << endl; break;
case 1: cout << "First:\t" << runner3 << "\nSecond:\t" << runner1 << "\nThird:\t" << runner2 << endl; break;
case 0: cout << "First:\t" << runner3 << "\nSecond:\t" << runner2 << "\nThird:\t" << runner1 << endl; break;
default: cout << "Invalid input!\n";
}
}
else
cout << "The time of the running should be number that greater than zero.\n";
return 0;
}
//16. Running the Race: The if/else approach
#include <iostream>
#include <string>
using namespace std;
int main()
{
//variable definition
string runner1, runner2, runner3;
double time1, time2, time3;
string max_n, mid_n, min_n;
double max, mid, min;
//program input
cout << "Please input the name of the firt runner: ";
getline(cin, runner1);
cout << "Please input the time of the first runner: ";
cin >> time1;
cin.ignore();
cout << "Please input the name of the second runner: ";
getline(cin, runner2);
cout << "Please input the time of the second runner: ";
cin >> time2;
cin.ignore();
cout << "Please input the name of the third runner: ";
getline(cin, runner3);
cout << "Please input the time of the third runner: ";
cin >> time3;
//valid check
if (time1 > 0 && time2 > 0 && time3 > 0)
{
//find out the minimum time record
min = time1;
min_n = runner1;
if (min < time2);
else
{
min = time2;
min_n = runner2;
}
if (min < time3);
else
{
min = time3;
min_n = runner3;
}
//find out the maximum time record
max = time1;
max_n = runner1;
if (max > time2);
else
{
max = time2;
max_n = runner2;
}
if (max > time3);
else
{
max = time3;
max_n = runner3;
}
//find out the medium time record
mid = time1;
mid_n = runner1;
if ((mid - max)*(mid - min) < 0);
else
{
mid = time2;
mid_n = runner2;
}
if ((mid - max)*(mid - min) < 0);
else
{
mid = time3;
mid_n = runner3;
}
//Output the result
cout << "First:\t" << min_n << "\nSecond:\t" << mid_n << "\nThird:\t" << max_n << endl;
}
else
cout << "The time of the running should be number that greater than zero.\n";
return 0;
} | [
"33183267+Miao4382@users.noreply.github.com"
] | 33183267+Miao4382@users.noreply.github.com |
18de648a52a367f367475d1351f9046fdc5c1d96 | 4754233cbcda1fad36f7a8f03906d17c9a9a90c1 | /Source/MicroKombat/EnemyAnimInstance.cpp | e171e324fea8a4da814acf175abe58aa0b4e8745 | [] | no_license | trimcao/MicroKombat | da0a948bc3fc64b8675bdbfe2ab020a6b3893b41 | cfc1d35b9fd977ac8572a0d5f8d1ad3e36d7ebd9 | refs/heads/master | 2022-12-02T02:56:22.753730 | 2020-08-18T03:11:06 | 2020-08-18T03:11:06 | 274,049,977 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 668 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "EnemyAnimInstance.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Enemy.h"
void UEnemyAnimInstance::NativeInitializeAnimation()
{
if (Pawn == nullptr)
{
Pawn = TryGetPawnOwner();
if (Pawn)
{
Enemy = Cast<AEnemy>(Pawn);
}
}
}
void UEnemyAnimInstance::UpdateAnimationProperties()
{
if (Pawn == nullptr)
{
Pawn = TryGetPawnOwner();
if (Pawn)
{
Enemy = Cast<AEnemy>(Pawn);
}
}
if (Pawn)
{
FVector Speed = Pawn->GetVelocity();
FVector LateralSpeed = FVector(Speed.X, Speed.Y, 0.f);
MovementSpeed = LateralSpeed.Size();
}
} | [
"trimcao@gmail.com"
] | trimcao@gmail.com |
75e26c7d347327285422791a049afe3848a948f6 | 3cb9bc615b9c12e1cc1f5b118b155e01108ff6e0 | /lib/Talleres/Taller 4/Cpp Code/logic.cpp | f6a0f583a3cebd24f0a1daf39b49aa75f619a9da | [] | no_license | Youngermaster/ST0247 | 1cb04f39060c602e58563a726af72f106b1799bc | c0f53e7fb7affc3058646dc5b2ea522198bc64d9 | refs/heads/master | 2020-04-21T10:34:46.173021 | 2019-06-05T01:08:13 | 2019-06-05T01:08:13 | 169,490,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,243 | cpp | #include "logic.h"
Logic::Logic()
{
this->proteins.set_name("Proteins");
this->proteins.set_limit(50000);
this->proteins.set_obligatory_elements(8);
this->flour.set_name("Flour");
this->flour.set_limit(50000);
this->flour.set_obligatory_elements(10);
this->grain.set_name("Grain");
this->grain.set_limit(50000);
this->grain.set_obligatory_elements(3);
this->toiletries.set_name("Toiletries");
this->toiletries.set_limit(50000);
this->toiletries.set_obligatory_elements(4);
this->oilsAndSauces.set_name("Oils and sauces");
this->oilsAndSauces.set_limit(50000);
this->oilsAndSauces.set_obligatory_elements(3);
this->vegetables.set_name("Vegetables");
this->vegetables.set_limit(50000);
this->vegetables.set_obligatory_elements(12);
this->optional.set_name("Optional");
core();
}
Logic::~Logic() { }
void Logic::core()
{
read_file("listacsv.csv");
vector <Product> auxiliar = proteins.get_products();
for(int iterator = 0; iterator < auxiliar.size(); iterator++)
cout << "What's up?" << endl;
}
void Logic::read_file(string path)
{
ifstream ip(path); // "listacsv.csv"
if (!ip.is_open()) cout << "ERROR: file is already open." << endl;
short int counter = 0;
string category, name, price;
while(ip.good())
{
if (counter == 0)
{
counter++;
continue;
}
getline(ip, category, ';');
getline(ip, name, ';');
getline(ip, price, '\n');
int newPrice = stoi(price);
Product newProduct(category, name, newPrice);
if (category == "Proteina")
proteins.add_product(newProduct);
else if (category == "Harina")
flour.add_product(newProduct);
else if (category == "Granos")
grain.add_product(newProduct);
else if (category == "Aseo")
toiletries.add_product(newProduct);
else if (category == "Aceite y salsa")
oilsAndSauces.add_product(newProduct);
else if (category == "Vegetales")
vegetables.add_product(newProduct);
else
optional.add_product(newProduct);
}
ip.close();
} | [
"jmyoungh@eafit.edu.co"
] | jmyoungh@eafit.edu.co |
5d9f91311f07e900644fd6638f707b8bbe2c14bd | 7e969ff50afa046cb1d42592f29e3a3954ebe401 | /HW2_full/HW2_full/Variable.cpp | b6ed367b07611bb15f0d49fc78f5e1af24fea50d | [] | no_license | ykaner/Compilers-course | 1be50de0f022b7f94111cd2d62c97de77f24829a | 306106576d2fe5eec9b7d717e0526a85fb491c8a | refs/heads/master | 2021-08-30T20:11:13.747915 | 2017-12-19T08:47:39 | 2017-12-19T08:47:39 | 110,693,064 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25 | cpp | #include "Variable.h"
| [
"yknaer12@gmail.com"
] | yknaer12@gmail.com |
10e7a1c206b2693af185ef1539e820e3a30115b0 | 1118c1eb3463ee4ec7eeb0626353882491cbfefb | /cosmo/BroadbandPower.h | 9bd7d4e7845ab786062a1771ce74dcb782abb92f | [] | no_license | igmhub/cosmo | 524df5c6d2eb383b2664dbf8952b26467320bf58 | ef4861374f48337d2b050322d4b3a278d6c16068 | refs/heads/master | 2021-05-30T02:42:17.466378 | 2015-11-26T17:40:56 | 2015-11-26T17:40:56 | 4,552,036 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | h | // Created 18-Feb-2012 by David Kirkby (University of California, Irvine) <dkirkby@uci.edu>
#ifndef COSMO_BROADBAND_POWER
#define COSMO_BROADBAND_POWER
namespace cosmo {
// Represents a broadband power spectrum P(k) proportional to (1/k)^p.
class BroadbandPower {
public:
// Creates a new broadband model P(k) = coef*PB(k,p) where PB(k,p)
// equals B(p)*(1/k)^p for kmin << k << 1/rmin, with additional terms to
// regulate 3D Fourier integrals beyond this range:
//
// PB(k,p) = B(p) exp[-(k rmin)^2] / (kmin^p + k^p)
//
// Parameters kmin and rmin should be specified in h/Mpc and Mpc/h,
// respectively, and either or both can be zero to disable the corresponding
// regulator term above.
// If r0 equals zero (the default), then B(p) = 1. A value r0 > 0 specifies
// a scale in Mpc/h used to fix B(p) so that the fluctuations of PB(k,p)
// within a top-hat window of radius r0 have a variance sigmaSq. This can
// be useful to set a "natural" relative normalization for each term but,
// in general, the values B(p) will depend on the choice of kmin, rmin.
BroadbandPower(double coef, double p,
double kmin, double rmin, double r0 = 0, double sigmaSq = 0);
virtual ~BroadbandPower();
// Returns the value of k^3/(2pi^2) P(k) for an input wavenumber k in h/Mpc.
double operator()(double kMpch) const;
private:
double _coef, _p, _kmin, _rmin, _kminp, _twopi2;
}; // BroadbandPower
} // cosmo
#endif // COSMO_BROADBAND_POWER
| [
"dkirkby@uci.edu"
] | dkirkby@uci.edu |
98f2a0ec4b53a45d4834db10a648220e08eaba5d | 2f53cc837208134f300a1e1563877a8c44be6a69 | /4/ex00/Animal.cpp | ea59d2a2b9dbcf6493eaa0b806c95be9f0f2b123 | [] | no_license | pnielly/CPP_42_Piscine | 7f72a003c9964bd1b7dc8543f0088dcb2aa1ac5f | 1d32b925bf182b04dca5f08280dab3699a7ba428 | refs/heads/master | 2023-08-26T04:41:56.349067 | 2021-10-25T13:49:31 | 2021-10-25T13:49:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Animal.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user42 <pnielly@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/31 08:15:44 by user42 #+# #+# */
/* Updated: 2021/08/01 16:05:33 by user42 ### ########.fr */
/* */
/* ************************************************************************** */
#include "Animal.hpp"
// Default constructor
Animal::Animal()
{
std::cout << "Animal created" << std::endl;
}
// Destructor
Animal::~Animal()
{
std::cout << "Animal destroyed" << std::endl;
}
// Copy
Animal::Animal(const Animal& op)
:
_type(op._type)
{
std::cout << "Animal copied" << std::endl;
}
// Assignment operator overload
Animal & Animal::operator=(const Animal& op)
{
if (this == &op)
return (*this);
this->_type = op._type;
return (*this);
}
std::string Animal::getType() const
{
return (this->_type);
}
void Animal::makeSound() const
{
std::cout << "The Animal does *Animal sound*" << std::endl;
}
| [
"pnielly@e1r8p10.42.fr"
] | pnielly@e1r8p10.42.fr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.