hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5e1a1b89a59be7719e0bb0822c0881badb6ddce5 | 9,527 | cpp | C++ | Glut Projects/Microwave Project/164 Microwave/WOW.cpp | omerwwazap/Learning-C | eb5fc80297d52a5aa4ce618dc66d4dda6a539ee3 | [
"MIT"
] | 1 | 2019-03-22T12:34:15.000Z | 2019-03-22T12:34:15.000Z | Glut Projects/Microwave Project/164 Microwave/WOW.cpp | omerwwazap/C-Projects | eb5fc80297d52a5aa4ce618dc66d4dda6a539ee3 | [
"MIT"
] | null | null | null | Glut Projects/Microwave Project/164 Microwave/WOW.cpp | omerwwazap/C-Projects | eb5fc80297d52a5aa4ce618dc66d4dda6a539ee3 | [
"MIT"
] | null | null | null | /*********
CTIS164 - Template Source Program
----------
STUDENT :
SECTION :
HOMEWORK:
----------
PROBLEMS: If your program does not function correctly,
explain here which parts are not running.
*********/
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdarg.h>
#define WINDOW_WIDTH 500
#define WINDOW_HEIGHT 500
#define TIMER_PERIOD 1000 // Period for the timer.
#define TIMER_ON 1 // 0:disable timer, 1:enable timer
#define D2R 0.0174532
//States of the progran
#define START 0
#define RUN 1
#define END 2
#define OPEN 3
#define DURATION 10
int appstate = START;
bool inStartButton = false;
int timeCounter = DURATION;
//initilize the timer function so it works sirlamasi olsun siye
void onTimer(int v);
/* Global Variables for Template File */
bool up = false, down = false, right = false, left = false;
int winWidth, winHeight; // current Window width and height
//
// to draw circle, center at (x,y)
// radius r
//
void circle(int x, int y, int r)
{
#define PI 3.1415
float angle;
glBegin(GL_POLYGON);
for (int i = 0; i < 100; i++)
{
angle = 2 * PI*i / 100;
glVertex2f(x + r*cos(angle), y + r*sin(angle));
}
glEnd();
}
void circle_wire(int x, int y, int r)
{
#define PI 3.1415
float angle;
glBegin(GL_LINE_LOOP);
for (int i = 0; i < 100; i++)
{
angle = 2 * PI*i / 100;
glVertex2f(x + r*cos(angle), y + r*sin(angle));
}
glEnd();
}
void print(int x, int y, char *string, void *font)
{
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(string);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(font, string[i]);
}
}
// display text with variables.
// vprint(-winWidth / 2 + 10, winHeight / 2 - 20, GLUT_BITMAP_8_BY_13, "ERROR: %d", numClicks);
void vprint(int x, int y, void *font, char *string, ...)
{
va_list ap;
va_start(ap, string);
char str[1024];
vsprintf_s(str, string, ap);
va_end(ap);
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(str);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(font, str[i]);
}
}
// vprint2(-50, 0, 0.35, "00:%02d", timeCounter);
void vprint2(int x, int y, float size, char *string, ...) {
va_list ap;
va_start(ap, string);
char str[1024];
vsprintf_s(str, string, ap);
va_end(ap);
glPushMatrix();
glTranslatef(x, y, 0);
glScalef(size, size, 1);
int len, i;
len = (int)strlen(str);
for (i = 0; i < len; i++)
{
glutStrokeCharacter(GLUT_STROKE_ROMAN, str[i]);
}
glPopMatrix();
}
bool checkCircle(float px, float py,//of the point
float cx, float cy, //center of the cirlce
float r)
{
float dx = px - cx;
float dy = py - cy;
float d = sqrt(dx*dx + dy*dy);
return(d <= r);
}
void diplayBackGround()
{
//label
glColor3f(0, 0, 0);
vprint(-240, 230, GLUT_BITMAP_8_BY_13, "Name Surname ");
vprint(-240, 210, GLUT_BITMAP_8_BY_13, "21702600");
vprint(-70, 200, GLUT_BITMAP_9_BY_15, "- HomeWork -");
//main container
glColor3ub(225, 230, 255);
glRectf(-200, -150, 200, 150);
glColor3ub(255, 255, 255);
glRectf(-200, -150, 200, 91);
glColor3ub(100, 130, 180);
glRectf(-200, -150, 200, -92);
glLineWidth(3);
glColor3ub(140, 170, 200);
glBegin(GL_LINES);
glVertex2f(-200, 90);
glVertex2f(200, 90);
glEnd();
glColor3ub(90, 100, 140);
glBegin(GL_LINES);
glVertex2f(-200, -91);
glVertex2f(200, -91);
glEnd();
glBegin(GL_LINE_LOOP);
glVertex2f(-200, -150);
glVertex2f(-200, 150);
glVertex2f(200, 150);
glVertex2f(200, -150);
glEnd();
glLineWidth(1);
vprint(-30, 120, GLUT_BITMAP_9_BY_15, "Microwave Inteface V1.0");
}
void displayStart()
{
glColor3ub(90, 100, 140);
circle(0, 0, 70);
if (inStartButton)
glColor3ub(255, 200, 200);
else
glColor3f(1, 1, 1);
circle(0, 0, 67);
glColor3ub(90, 100, 140);
vprint2(-50, -12, 0.25, "START");
glColor3ub(255, 255, 255);
vprint(-190, -130, GLUT_BITMAP_HELVETICA_12, "Click Start BUtton");
//glColor4f(1, 0, 0, 0.5);//transparency
//circle(-70, 0, 30);
}
void displayRun()
{
glColor3ub(90, 100, 140);
vprint2(-50, 0, 0.35, "00:%02d", timeCounter);
int width = (DURATION - timeCounter) * 30;
glColor3ub(170, 250, 140);
glRectf(-150, -70, -150 + width, -20);
}
void displayEnd()
{
glColor3ub(90, 100, 140);
vprint2(-50, 0, 0.35, "00:00");
glColor3ub(255, 150, 140);
glRectf(-150, -70, 150, -20);
glColor3f(1, 1, 1);
vprint(-190, -130, GLUT_BITMAP_HELVETICA_12, "Down Arrow To Open");
}
void displayOpen()
{
glColor3ub(90, 100, 140);
vprint2(-60, 30, 0.35, "DOOR");
vprint2(-10, -20, 0.35, "IS");
vprint2(-60, -70, 0.35, "OPEN");
glColor3f(1, 1, 1);
vprint(-190, -130, GLUT_BITMAP_HELVETICA_12, "UP Arrow to Close");
}
//
// To display onto window using OpenGL commands
//
void display() {
//
// clear window to black
//
glClearColor(1, 1, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
diplayBackGround();
switch (appstate)
{
case START:
displayStart();
break;
case RUN:
displayRun();
break;
case END:
displayEnd();
break;
case OPEN:
displayOpen();
break;
}
glutSwapBuffers();
}
//
// key function for ASCII charachters like ESC, a,b,c..,A,B,..Z
//
void onKeyDown(unsigned char key, int x, int y)
{
// exit when ESC is pressed.
if (key == 27)
exit(0);
// to refresh the window it calls display() function
glutPostRedisplay();
}
void onKeyUp(unsigned char key, int x, int y)
{
// exit when ESC is pressed.
if (key == 27)
exit(0);
// to refresh the window it calls display() function
glutPostRedisplay();
}
//
// Special Key like GLUT_KEY_F1, F2, F3,...
// Arrow Keys, GLUT_KEY_UP, GLUT_KEY_DOWN, GLUT_KEY_RIGHT, GLUT_KEY_RIGHT
//
void onSpecialKeyDown(int key, int x, int y)
{
// Write your codes here.
if (key == GLUT_KEY_DOWN && appstate == END)
appstate = OPEN;
if (key == GLUT_KEY_UP && appstate == OPEN)
appstate = START;
// to refresh the window it calls display() function
glutPostRedisplay();
}
//
// Special Key like GLUT_KEY_F1, F2, F3,...
// Arrow Keys, GLUT_KEY_UP, GLUT_KEY_DOWN, GLUT_KEY_RIGHT, GLUT_KEY_RIGHT
//
void onSpecialKeyUp(int key, int x, int y)
{
// Write your codes here.
switch (key) {
case GLUT_KEY_UP: up = false; break;
case GLUT_KEY_DOWN: down = false; break;
case GLUT_KEY_LEFT: left = false; break;
case GLUT_KEY_RIGHT: right = false; break;
}
// to refresh the window it calls display() function
glutPostRedisplay();
}
//
// When a click occurs in the window,
// It provides which button
// buttons : GLUT_LEFT_BUTTON , GLUT_RIGHT_BUTTON
// states : GLUT_UP , GLUT_DOWN
// x, y is the coordinate of the point that mouse clicked.
//
void onClick(int button, int stat, int x, int y)
{
// Write your codes here.
if (button == GLUT_LEFT_BUTTON && stat == GLUT_DOWN)
{
if (appstate == START && inStartButton)
{
appstate = RUN;
timeCounter = DURATION;
glutTimerFunc(TIMER_PERIOD, onTimer, 0); //invoke the timer
/*#if TIMER_ON == 1
// timer event
glutTimerFunc(TIMER_PERIOD, onTimer, 0);
#endif*/
}
}
if (button == GLUT_LEFT_BUTTON && stat GLUT_DOWN)
printf("%d and %d ", px, py);
// to refresh the window it calls display() function
glutPostRedisplay();
}
//
// This function is called when the window size changes.
// w : is the new width of the window in pixels.
// h : is the new height of the window in pixels.
//
void onResize(int w, int h)
{
winWidth = w;
winHeight = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-w / 2, w / 2, -h / 2, h / 2, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
display(); // refresh window.
}
void onMoveDown(int x, int y) {
// Write your codes here.
// to refresh the window it calls display() function
glutPostRedisplay();
}
// GLUT to OpenGL coordinate conversion:
// x2 = x1 - winWidth / 2
// y2 = winHeight / 2 - y1
void onMove(int x, int y) {
// Write your codes here.
int mx = x - winWidth / 2;
int my = winHeight / 2 - y;
inStartButton = checkCircle(mx, my, 0, 0, 70);
// to refresh the window it calls display() function
glutPostRedisplay();
}
#if TIMER_ON == 1
void onTimer(int v) {
if (appstate == RUN)
{
timeCounter--;
if (timeCounter > 0)
glutTimerFunc(TIMER_PERIOD, onTimer, 0);
else
appstate = END;
}
// Write your codes here.
// to refresh the window it calls display() function
glutPostRedisplay(); // display()
}
#endif
void Init() {
// Smoothing shapes
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("WOW MICREOWAVE");
glutInitWindowPosition(200, 200);
glutDisplayFunc(display);
glutReshapeFunc(onResize);
//
// keyboard registration
//
glutKeyboardFunc(onKeyDown);
glutSpecialFunc(onSpecialKeyDown);
glutKeyboardUpFunc(onKeyUp);
//
// mouse registration
//
glutMouseFunc(onClick);
glutMotionFunc(onMoveDown);
glutPassiveMotionFunc(onMove);
Init();
glutMainLoop();
} | 19.403259 | 96 | 0.622232 | omerwwazap |
5e1f2bdb10af46655c7ae0d0e833e37590f2da07 | 4,584 | cpp | C++ | archive/stan/src/test/unit/lang/generator/generate_var_type_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | archive/stan/src/test/unit/lang/generator/generate_var_type_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | archive/stan/src/test/unit/lang/generator/generate_var_type_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/lang/ast_def.cpp>
#include <stan/lang/generator.hpp>
#include <test/unit/lang/utility.hpp>
#include <gtest/gtest.h>
#include <iostream>
#include <sstream>
TEST(langGenerator, genRealVars) {
using stan::lang::scope;
using stan::lang::transformed_data_origin;
using stan::lang::function_argument_origin;
scope td_origin = transformed_data_origin;
scope fun_origin = function_argument_origin;
std::stringstream o;
o.str(std::string());
stan::lang::generate_real_var_type(td_origin, true, o);
EXPECT_EQ(1, count_matches("local_scalar_t__", o.str()));
o.str(std::string());
stan::lang::generate_real_var_type(td_origin, false, o);
EXPECT_EQ(1, count_matches("double", o.str()));
o.str(std::string());
stan::lang::generate_real_var_type(fun_origin, true, o);
EXPECT_EQ(1, count_matches("local_scalar_t__", o.str()));
o.str(std::string());
stan::lang::generate_real_var_type(fun_origin, false, o);
EXPECT_EQ(1, count_matches("local_scalar_t__", o.str()));
}
TEST(langGenerator, genArrayVars) {
using stan::lang::bare_expr_type;
using stan::lang::int_type;
using stan::lang::double_type;
using stan::lang::vector_type;
using stan::lang::row_vector_type;
using stan::lang::matrix_type;
using stan::lang::scope;
using stan::lang::transformed_data_origin;
using stan::lang::function_argument_origin;
scope td_origin = transformed_data_origin;
scope fun_origin = function_argument_origin;
std::stringstream ssReal;
std::stringstream o;
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, true, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o);
EXPECT_EQ(1, count_matches("local_scalar_t__", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, false, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o);
EXPECT_EQ(1, count_matches("double", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(fun_origin, true, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o);
EXPECT_EQ(1, count_matches("local_scalar_t__", o.str()));
ssReal.str(std::string());
o.str(std::string());
stan::lang::generate_real_var_type(fun_origin, false, ssReal);
stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o);
EXPECT_EQ(1, count_matches("local_scalar_t__", o.str()));
ssReal.str(std::string());
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(int_type()), ssReal.str(), o);
EXPECT_EQ(1, count_matches("int", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, false, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(vector_type()),ssReal.str(),o);
EXPECT_EQ(1, count_matches("Eigen::Matrix<double, Eigen::Dynamic, 1>", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, true, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(vector_type()), ssReal.str(), o);
EXPECT_EQ(1, count_matches("Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1>", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, false, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(row_vector_type()), ssReal.str(), o);
EXPECT_EQ(1, count_matches("Eigen::Matrix<double, 1, Eigen::Dynamic>", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, true, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(row_vector_type()), ssReal.str(), o);
EXPECT_EQ(1, count_matches("Eigen::Matrix<local_scalar_t__, 1, Eigen::Dynamic>", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, false, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(matrix_type()), ssReal.str(), o);
EXPECT_EQ(1, count_matches("Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>", o.str()));
ssReal.str(std::string());
stan::lang::generate_real_var_type(td_origin, true, ssReal);
o.str(std::string());
stan::lang::generate_bare_type(bare_expr_type(matrix_type()), ssReal.str(), o);
EXPECT_EQ(1, count_matches("Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic>", o.str()));
}
| 40.928571 | 107 | 0.701134 | alashworth |
5e22fe5ce3c02c8d8d86a418a7c7f39691a87119 | 13,503 | cc | C++ | ns3/ns-3.26/examples/wireless/wifi-aggregation.cc | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 7 | 2017-08-11T06:06:47.000Z | 2022-02-27T07:34:33.000Z | ns3/ns-3.26/examples/wireless/wifi-aggregation.cc | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 3 | 2017-08-11T03:04:59.000Z | 2017-09-11T14:01:14.000Z | ns3/ns-3.26/examples/wireless/wifi-aggregation.cc | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 3 | 2017-08-08T13:36:30.000Z | 2018-07-04T09:49:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 Sébastien Deronne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Sébastien Deronne <sebastien.deronne@gmail.com>
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/internet-module.h"
// This is an example that illustrates how 802.11n aggregation is configured.
// It defines 4 independant Wi-Fi networks (working on different channels).
// Each network contains one access point and one station. Each station
// continously transmits data packets to its respective AP.
//
// Network topology (numbers in parentheses are channel numbers):
//
// Network A (36) Network B (40) Network C (44) Network D (48)
// * * * * * * * *
// | | | | | | | |
// AP A STA A AP B STA B AP C STA C AP D STA D
//
// The aggregation parameters are configured differently on the 4 stations:
// - station A uses default aggregation parameter values (A-MSDU disabled, A-MPDU enabled with maximum size of 65 kB);
// - station B doesn't use aggregation (both A-MPDU and A-MSDU are disabled);
// - station C enables A-MSDU (with maximum size of 8 kB) but disables A-MPDU;
// - station C uses two-level aggregation (A-MPDU with maximum size of 32 kB and A-MSDU with maximum size of 4 kB).
//
// Packets in this simulation aren't marked with a QosTag so they
// are considered belonging to BestEffort Access Class (AC_BE).
//
// The user can select the distance between the stations and the APs and can enable/disable the RTS/CTS mechanism.
// Example: ./waf --run "wifi-aggregation --distance=10 --enableRts=0 --simulationTime=20"
//
// The output prints the throughput measured for the 4 cases/networks decribed above. When default aggregation parameters are enabled, the
// maximum A-MPDU size is 65 kB and the throughput is maximal. When aggregation is disabled, the thoughput is about the half of the
// physical bitrate as in legacy wifi networks. When only A-MSDU is enabled, the throughput is increased but is not maximal, since the maximum
// A-MSDU size is limited to 7935 bytes (whereas the maximum A-MPDU size is limited to 65535 bytes). When A-MSDU and A-MPDU are both enabled
// (= two-level aggregation), the throughput is slightly smaller than the first scenario since we set a smaller maximum A-MPDU size.
//
// When the distance is increased, the frame error rate gets higher, and the output shows how it affects the throughput for the 4 networks.
// Even through A-MSDU has less overheads than A-MPDU, A-MSDU is less robust against transmission errors than A-MPDU. When the distance is
// augmented, the throughput for the third scenario is more affected than the throughput obtained in other networks.
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("SimpleMpduAggregation");
int main (int argc, char *argv[])
{
uint32_t payloadSize = 1472; //bytes
uint64_t simulationTime = 10; //seconds
double distance = 5; //meters
bool enablePcap = 0;
CommandLine cmd;
cmd.AddValue ("payloadSize", "Payload size in bytes", payloadSize);
cmd.AddValue ("simulationTime", "Simulation time in seconds", simulationTime);
cmd.AddValue ("distance", "Distance in meters between the station and the access point", distance);
cmd.AddValue ("enablePcap", "Enable/disable pcap file generation", enablePcap);
cmd.Parse (argc, argv);
NodeContainer wifiStaNode;
wifiStaNode.Create (4);
NodeContainer wifiApNode;
wifiApNode.Create (4);
YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
phy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO);
phy.SetChannel (channel.Create ());
WifiHelper wifi;
wifi.SetStandard (WIFI_PHY_STANDARD_80211n_5GHZ);
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("HtMcs7"), "ControlMode", StringValue ("HtMcs0"));
WifiMacHelper mac;
NetDeviceContainer staDeviceA, staDeviceB, staDeviceC, staDeviceD, apDeviceA, apDeviceB, apDeviceC, apDeviceD;
Ssid ssid;
//Network A
ssid = Ssid ("network-A");
phy.Set ("ChannelNumber", UintegerValue(36));
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid));
staDeviceA = wifi.Install (phy, mac, wifiStaNode.Get(0));
mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid),
"BeaconGeneration", BooleanValue (true));
apDeviceA = wifi.Install (phy, mac, wifiApNode.Get(0));
//Network B
ssid = Ssid ("network-B");
phy.Set ("ChannelNumber", UintegerValue(40));
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"BE_MaxAmpduSize", UintegerValue (0)); //Disable A-MPDU
staDeviceB = wifi.Install (phy, mac, wifiStaNode.Get(1));
mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid),
"BeaconGeneration", BooleanValue (true));
apDeviceB = wifi.Install (phy, mac, wifiApNode.Get(1));
//Network C
ssid = Ssid ("network-C");
phy.Set ("ChannelNumber", UintegerValue(44));
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"BE_MaxAmpduSize", UintegerValue (0), //Disable A-MPDU
"BE_MaxAmsduSize", UintegerValue (7935)); //Enable A-MSDU with the highest maximum size allowed by the standard (7935 bytes)
staDeviceC = wifi.Install (phy, mac, wifiStaNode.Get(2));
mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid),
"BeaconGeneration", BooleanValue (true));
apDeviceC = wifi.Install (phy, mac, wifiApNode.Get(2));
//Network D
ssid = Ssid ("network-D");
phy.Set ("ChannelNumber", UintegerValue(48));
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"BE_MaxAmpduSize", UintegerValue (32768), //Enable A-MPDU with a smaller size than the default one
"BE_MaxAmsduSize", UintegerValue (3839)); //Enable A-MSDU with the smallest maximum size allowed by the standard (3839 bytes)
staDeviceD = wifi.Install (phy, mac, wifiStaNode.Get(3));
mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid),
"BeaconGeneration", BooleanValue (true));
apDeviceD = wifi.Install (phy, mac, wifiApNode.Get(3));
/* Setting mobility model */
MobilityHelper mobility;
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
//Set position for APs
positionAlloc->Add (Vector (0.0, 0.0, 0.0));
positionAlloc->Add (Vector (10.0, 0.0, 0.0));
positionAlloc->Add (Vector (20.0, 0.0, 0.0));
positionAlloc->Add (Vector (30.0, 0.0, 0.0));
//Set position for STAs
positionAlloc->Add (Vector (distance, 0.0, 0.0));
positionAlloc->Add (Vector (10 + distance, 0.0, 0.0));
positionAlloc->Add (Vector (20 + distance, 0.0, 0.0));
positionAlloc->Add (Vector (30 + distance, 0.0, 0.0));
//Remark: while we set these positions 10 meters apart, the networks do not interact
//and the only variable that affects transmission performance is the distance.
mobility.SetPositionAllocator (positionAlloc);
mobility.Install (wifiApNode);
mobility.Install (wifiStaNode);
/* Internet stack */
InternetStackHelper stack;
stack.Install (wifiApNode);
stack.Install (wifiStaNode);
Ipv4AddressHelper address;
address.SetBase ("192.168.1.0", "255.255.255.0");
Ipv4InterfaceContainer StaInterfaceA;
StaInterfaceA = address.Assign (staDeviceA);
Ipv4InterfaceContainer ApInterfaceA;
ApInterfaceA = address.Assign (apDeviceA);
address.SetBase ("192.168.2.0", "255.255.255.0");
Ipv4InterfaceContainer StaInterfaceB;
StaInterfaceB = address.Assign (staDeviceB);
Ipv4InterfaceContainer ApInterfaceB;
ApInterfaceB = address.Assign (apDeviceB);
address.SetBase ("192.168.3.0", "255.255.255.0");
Ipv4InterfaceContainer StaInterfaceC;
StaInterfaceC = address.Assign (staDeviceC);
Ipv4InterfaceContainer ApInterfaceC;
ApInterfaceC = address.Assign (apDeviceC);
address.SetBase ("192.168.4.0", "255.255.255.0");
Ipv4InterfaceContainer StaInterfaceD;
StaInterfaceD = address.Assign (staDeviceD);
Ipv4InterfaceContainer ApInterfaceD;
ApInterfaceD = address.Assign (apDeviceD);
/* Setting applications */
UdpServerHelper myServerA (9);
ApplicationContainer serverAppA = myServerA.Install (wifiStaNode.Get (0));
serverAppA.Start (Seconds (0.0));
serverAppA.Stop (Seconds (simulationTime + 1));
UdpClientHelper myClientA (StaInterfaceA.GetAddress (0), 9);
myClientA.SetAttribute ("MaxPackets", UintegerValue (4294967295u));
myClientA.SetAttribute ("Interval", TimeValue (Time ("0.00002"))); //packets/s
myClientA.SetAttribute ("PacketSize", UintegerValue (payloadSize));
ApplicationContainer clientAppA = myClientA.Install (wifiApNode.Get (0));
clientAppA.Start (Seconds (1.0));
clientAppA.Stop (Seconds (simulationTime + 1));
UdpServerHelper myServerB (9);
ApplicationContainer serverAppB = myServerB.Install (wifiStaNode.Get (1));
serverAppB.Start (Seconds (0.0));
serverAppB.Stop (Seconds (simulationTime + 1));
UdpClientHelper myClientB (StaInterfaceB.GetAddress (0), 9);
myClientB.SetAttribute ("MaxPackets", UintegerValue (4294967295u));
myClientB.SetAttribute ("Interval", TimeValue (Time ("0.00002"))); //packets/s
myClientB.SetAttribute ("PacketSize", UintegerValue (payloadSize));
ApplicationContainer clientAppB = myClientB.Install (wifiApNode.Get (1));
clientAppB.Start (Seconds (1.0));
clientAppB.Stop (Seconds (simulationTime + 1));
UdpServerHelper myServerC (9);
ApplicationContainer serverAppC = myServerC.Install (wifiStaNode.Get (2));
serverAppC.Start (Seconds (0.0));
serverAppC.Stop (Seconds (simulationTime + 1));
UdpClientHelper myClientC (StaInterfaceC.GetAddress (0), 9);
myClientC.SetAttribute ("MaxPackets", UintegerValue (4294967295u));
myClientC.SetAttribute ("Interval", TimeValue (Time ("0.00002"))); //packets/s
myClientC.SetAttribute ("PacketSize", UintegerValue (payloadSize));
ApplicationContainer clientAppC = myClientC.Install (wifiApNode.Get (2));
clientAppC.Start (Seconds (1.0));
clientAppC.Stop (Seconds (simulationTime + 1));
UdpServerHelper myServerD (9);
ApplicationContainer serverAppD = myServerD.Install (wifiStaNode.Get (3));
serverAppD.Start (Seconds (0.0));
serverAppD.Stop (Seconds (simulationTime + 1));
UdpClientHelper myClientD (StaInterfaceD.GetAddress (0), 9);
myClientD.SetAttribute ("MaxPackets", UintegerValue (4294967295u));
myClientD.SetAttribute ("Interval", TimeValue (Time ("0.00002"))); //packets/s
myClientD.SetAttribute ("PacketSize", UintegerValue (payloadSize));
ApplicationContainer clientAppD = myClientD.Install (wifiApNode.Get (3));
clientAppD.Start (Seconds (1.0));
clientAppD.Stop (Seconds (simulationTime + 1));
if (enablePcap)
{
phy.EnablePcap ("AP_A", apDeviceA.Get (0));
phy.EnablePcap ("STA_A", staDeviceA.Get (0));
phy.EnablePcap ("AP_B", apDeviceB.Get (0));
phy.EnablePcap ("STA_B", staDeviceB.Get (0));
phy.EnablePcap ("AP_C", apDeviceC.Get (0));
phy.EnablePcap ("STA_C", staDeviceC.Get (0));
phy.EnablePcap ("AP_D", apDeviceD.Get (0));
phy.EnablePcap ("STA_D", staDeviceD.Get (0));
}
Simulator::Stop (Seconds (simulationTime + 1));
Simulator::Run ();
Simulator::Destroy ();
/* Show results */
uint32_t totalPacketsThrough = DynamicCast<UdpServer> (serverAppA.Get (0))->GetReceived ();
double throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0);
std::cout << "Throughput with default configuration (A-MPDU aggregation enabled, 65kB): " << throughput << " Mbit/s" << '\n';
totalPacketsThrough = DynamicCast<UdpServer> (serverAppB.Get (0))->GetReceived ();
throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0);
std::cout << "Throughput with aggregation disabled: " << throughput << " Mbit/s" << '\n';
totalPacketsThrough = DynamicCast<UdpServer> (serverAppC.Get (0))->GetReceived ();
throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0);
std::cout << "Throughput with A-MPDU disabled and A-MSDU enabled (8kB): " << throughput << " Mbit/s" << '\n';
totalPacketsThrough = DynamicCast<UdpServer> (serverAppD.Get (0))->GetReceived ();
throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0);
std::cout << "Throughput with A-MPDU enabled (32kB) and A-MSDU enabled (4kB): " << throughput << " Mbit/s" << '\n';
return 0;
}
| 45.01 | 142 | 0.70451 | Aedemon |
5e2b5db8d93beff17ec7b4da13672621d6220061 | 115 | cpp | C++ | Test.cpp | KaikiasVind/CellBadger | c21adf5feec7766decfd4d89a110364d4bdfbc46 | [
"MIT"
] | null | null | null | Test.cpp | KaikiasVind/CellBadger | c21adf5feec7766decfd4d89a110364d4bdfbc46 | [
"MIT"
] | null | null | null | Test.cpp | KaikiasVind/CellBadger | c21adf5feec7766decfd4d89a110364d4bdfbc46 | [
"MIT"
] | null | null | null | #include "Test.h"
#include <QDebug>
Test::Test()
{
}
void Test::on_finished() {
qDebug() << "Finished.";
}
| 8.846154 | 28 | 0.573913 | KaikiasVind |
5e2f3a8738055071a9123ebfcca4d9e39eb96f24 | 708 | cpp | C++ | test/concurrent/test_stack_lockfree_elim_hp_stress.cpp | clearlycloudy/concurrent | 243246f3244cfaf7ffcbfc042c69980d96f988e4 | [
"MIT"
] | 9 | 2019-05-14T01:07:08.000Z | 2020-11-12T01:46:11.000Z | test/concurrent/test_stack_lockfree_elim_hp_stress.cpp | clearlycloudy/concurrent | 243246f3244cfaf7ffcbfc042c69980d96f988e4 | [
"MIT"
] | null | null | null | test/concurrent/test_stack_lockfree_elim_hp_stress.cpp | clearlycloudy/concurrent | 243246f3244cfaf7ffcbfc042c69980d96f988e4 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <thread>
#include <vector>
#include <iostream>
#include <mutex>
#include <set>
#include "catch.hpp"
#include "stack_lockfree_elim.hpp"
#include "stress_pool.hpp"
using namespace std;
TEST_CASE( "stack_lockfree_total_simple stress", "[stress]" ) {
using container_type = stack_lockfree_elim<int, trait_reclamation::hp>;
container_type p;
unsigned int num_threads = std::thread::hardware_concurrency()/2;
bool force_put_get = true;
stress_pool::stress_put_get_int<container_type, container_type::mem_reclam>( num_threads, p, force_put_get );
assert(p.check_elimination());
}
| 30.782609 | 113 | 0.748588 | clearlycloudy |
5e308377c063b426e6c5949b3a447edd4a5a4046 | 84 | hpp | C++ | TosVolume/Utils.hpp | laoo/tcmdtos | 6aa91f2e2bfe462cda8f74b5170bc52136157915 | [
"MIT"
] | null | null | null | TosVolume/Utils.hpp | laoo/tcmdtos | 6aa91f2e2bfe462cda8f74b5170bc52136157915 | [
"MIT"
] | null | null | null | TosVolume/Utils.hpp | laoo/tcmdtos | 6aa91f2e2bfe462cda8f74b5170bc52136157915 | [
"MIT"
] | null | null | null |
void extractNameExt( std::string_view src, std::array<char, 11> & nameExt );
| 16.8 | 77 | 0.666667 | laoo |
5e35b935f136f8713a74dcdeb293837b99eebafe | 432 | cc | C++ | src/sampler/halton_sampler.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 20 | 2020-06-28T03:55:40.000Z | 2022-03-08T06:00:31.000Z | src/sampler/halton_sampler.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | null | null | null | src/sampler/halton_sampler.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 1 | 2020-06-29T08:47:21.000Z | 2020-06-29T08:47:21.000Z | //
// Created by zhong on 2021/3/30.
//
#include "halton_sampler.hh"
float DR::HaltonSampler::get_1d() { return h1.get(); }
float DR::HaltonSampler::get_1d(float min, float max) {
return (max - min) * h1.get() + min;
}
std::pair<float, float> DR::HaltonSampler::get_2d() {
return {get_1d(), get_1d()};
}
std::pair<float, float> DR::HaltonSampler::get_2d(float min, float max) {
return {get_1d(min, max), get_1d(min, max)};
}
| 27 | 73 | 0.659722 | BlurryLight |
5e3b8f1ef82ff88cc2daf33ed3faa50c2eabf18f | 4,800 | cpp | C++ | plugins/deadreckoningorientation/org_osvr_filter_deadreckoningrotation.cpp | ethanpeng/OSVR-Core | 59405fc1b1a25aea051dfbba0be5171fa19b8b30 | [
"Apache-2.0"
] | 369 | 2015-03-08T03:12:41.000Z | 2022-02-08T22:15:39.000Z | plugins/deadreckoningorientation/org_osvr_filter_deadreckoningrotation.cpp | ethanpeng/OSVR-Core | 59405fc1b1a25aea051dfbba0be5171fa19b8b30 | [
"Apache-2.0"
] | 486 | 2015-03-09T13:29:00.000Z | 2020-10-16T00:41:26.000Z | plugins/deadreckoningorientation/org_osvr_filter_deadreckoningrotation.cpp | ethanpeng/OSVR-Core | 59405fc1b1a25aea051dfbba0be5171fa19b8b30 | [
"Apache-2.0"
] | 166 | 2015-03-08T12:03:56.000Z | 2021-12-03T13:56:21.000Z | /** @file
@brief Analysis plugin that performs predictive tracking for the orientation
if a specified tracker and is provided a prediction interval.
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
#include <osvr/VRPNServer/VRPNDeviceRegistration.h>
#include <osvr/Util/StringLiteralFileToString.h>
#include <vrpn_Tracker_Filter.h>
// Generated JSON header file
#include "org_osvr_filter_deadreckoningrotation_json.h"
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
// Standard includes
#include <iostream>
#include <chrono>
#include <thread>
// Anonymous namespace to avoid symbol collision
namespace {
class DeadReckoningRotation {
public:
DeadReckoningRotation(OSVR_PluginRegContext ctx, std::string const &name,
std::string const &input, int numSensors, double predictMS)
{
/// Register the VRPN device that we will be using.
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
std::string decoratedName = reg.useDecoratedName(name);
std::string localInput = "*" + input;
reg.registerDevice(new vrpn_Tracker_DeadReckoning_Rotation(
decoratedName,
reg.getVRPNConnection(),
localInput, numSensors, predictMS));
reg.setDeviceDescriptor(osvr::util::makeString(
org_osvr_filter_deadreckoningrotation_json));
// Build a new Json entry that has the correct number of
// sensors in it, rather than the default of 1.
{
Json::Reader reader;
Json::Value filterJson;
if (!reader.parse(
osvr::util::makeString(
org_osvr_filter_deadreckoningrotation_json),
filterJson)) {
throw std::logic_error("Faulty JSON file for Dead "
"Reckoning Rotation Filter - should not "
"be possible!");
}
filterJson["interfaces"]["tracker"]["count"] = numSensors;
// Corresponding filter
reg.setDeviceDescriptor(filterJson.toStyledString());
}
}
OSVR_ReturnCode update() {
// Nothing to do here - everything happens in a callback.
return OSVR_RETURN_SUCCESS;
}
private:
osvr::pluginkit::DeviceToken m_dev;
OSVR_TrackerDeviceInterface m_trackerOut;
};
class DeadReckoningRotationConstructor {
public:
/// @brief This is the required signature for a device instantiation
/// callback.
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) {
// Read the JSON data from parameters.
Json::Value root;
if (params) {
Json::Reader r;
if (!r.parse(params, root)) {
std::cerr << "Could not parse parameters!" << std::endl;
}
}
// Get the name we should use for the device
if (!root.isMember("name")) {
std::cerr << "Error: got configuration, but no name specified."
<< std::endl;
return OSVR_RETURN_FAILURE;
}
std::string name = root["name"].asString();
// Get the input device we should use to listen to
if (!root.isMember("input")) {
std::cerr << "Error: got configuration, but no input specified."
<< std::endl;
return OSVR_RETURN_FAILURE;
}
std::string input = root["input"].asString();
int numSensors = root.get("numSensors", 1).asInt();
double predictMS = root.get("predictMilliSeconds", 32).asDouble();
// OK, now that we have our parameters, create the device.
osvr::pluginkit::registerObjectForDeletion(
ctx, new DeadReckoningRotation(ctx, name, input, numSensors, predictMS * 1e-3));
return OSVR_RETURN_SUCCESS;
}
};
} // namespace
OSVR_PLUGIN(com_osvr_example_Configured) {
/// Tell the core we're available to create a device object.
osvr::pluginkit::registerDriverInstantiationCallback(
ctx, "DeadReckoningRotationTracker", new DeadReckoningRotationConstructor);
return OSVR_RETURN_SUCCESS;
}
| 33.103448 | 90 | 0.66 | ethanpeng |
5e3b92bf125508d179888bd3415413ef8e69575f | 5,217 | cpp | C++ | stm32_nn_test/image_processing.cpp | michalnand/line_follower_rl | 8e5f1a18f6c02d9de0a3b7c10f84ba8c3e958e73 | [
"MIT"
] | 2 | 2020-05-14T14:14:19.000Z | 2020-08-05T02:55:43.000Z | stm32_nn_test/image_processing.cpp | michalnand/line_follower_rl | 8e5f1a18f6c02d9de0a3b7c10f84ba8c3e958e73 | [
"MIT"
] | null | null | null | stm32_nn_test/image_processing.cpp | michalnand/line_follower_rl | 8e5f1a18f6c02d9de0a3b7c10f84ba8c3e958e73 | [
"MIT"
] | 3 | 2020-05-14T14:14:21.000Z | 2020-12-07T00:33:11.000Z | #include <image_processing.h>
void IP_FromCamera( int8_t* destination_buffer,
Camera &camera,
unsigned int destination_height,
unsigned int destination_width,
bool white_balance)
{
unsigned int size = camera.get_width()*camera.get_height();
int mean = 0;
for (unsigned int i = 0; i < size; i++)
{
int pixel = ((((uint16_t*)camera.get_buffer())[i])&0xFF00)>>8;
mean+= pixel;
}
mean = mean / size;
for (unsigned int i = 0; i < size; i++)
{
int pixel = ((((uint16_t*)camera.get_buffer())[i])&0xFF00)>>8;
int v = pixel - mean;
if (v > 127)
v = 127;
if (v < -127)
v = -127;
destination_buffer[i] = v;
}
/*
if (camera.get_width() == destination_width && camera.get_width() == destination_width)
unsigned int start_x = (camera.get_width() - destination_width)/2;
unsigned int start_y = (camera.get_height() - destination_height)/2;
int mean = 0;
if (white_balance)
{
unsigned int pixels = 0;
for (unsigned int y = 0; y < destination_height; y++)
for (unsigned int x = 0; x < destination_width; x++)
{
unsigned int idx_input = (y + start_y)*camera.get_width() + x + start_x;
int pixel = ((((uint16_t*)camera.get_buffer())[idx_input])&0xFF00)>>8;
mean+= pixel;
pixels++;
}
mean = mean / pixels;
}
unsigned int ptr = 0;
for (unsigned int y = 0; y < destination_height; y++)
for (unsigned int x = 0; x < destination_width; x++)
{
unsigned int idx_input = (y + start_y)*camera.get_width() + x + start_x;
int pixel = ((((uint16_t*)camera.get_buffer())[idx_input])&0xFF00)>>8;
int v = pixel - mean;
if (v > 127)
v = 127;
if (v < -127)
v = -127;
destination_buffer[ptr] = v;
ptr++;
}
*/
}
void IP_ToDisplay( LCD &display_,
int8_t* source_buffer,
unsigned int source_height,
unsigned int source_width,
unsigned int y_ofs,
unsigned int x_ofs)
{
unsigned int ptr = 0;
for (unsigned int y = 0; y < source_height; y++)
{
lcd.SetCursor2Draw(x_ofs, y + y_ofs);
for (unsigned int x = 0; x < source_width; x++)
{
unsigned int intensity = source_buffer[ptr] + 127;
display_.DrawPixel(intensity, intensity, intensity);
ptr++;
}
}
}
unsigned int get_xy_sat(unsigned int y, unsigned int x, unsigned int height, unsigned int width)
{
if (y >= height)
y = height-1;
if (x >= width)
x = width-1;
return y*width + x;
}
void IP_ResultToDisplay( LCD &display_,
int8_t* source_buffer,
unsigned int source_height,
unsigned int source_width,
unsigned int upscale,
unsigned int y_ofs,
unsigned int x_ofs)
{
int threshold = 5;
unsigned int ptr = 0;
for (unsigned int y = 0; y < source_height; y++)
for (unsigned int x = 0; x < source_width; x++)
{
int q00 = source_buffer[get_xy_sat(y + 0, x + 0, source_height, source_width)];
int q01 = source_buffer[get_xy_sat(y + 0, x + 1, source_height, source_width)];
int q10 = source_buffer[get_xy_sat(y + 1, x + 0, source_height, source_width)];
int q11 = source_buffer[get_xy_sat(y + 1, x + 1, source_height, source_width)];
if (q00 > threshold)
q00 = 255;
else
q00 = 0;
if (q01 > threshold)
q01 = 255;
else
q01 = 0;
if (q10 > threshold)
q10 = 255;
else
q10 = 0;
if (q11 > threshold)
q11 = 255;
else
q11 = 0;
ptr++;
for (unsigned int ky = 0; ky < upscale; ky++)
{
lcd.SetCursor2Draw(x*upscale + x_ofs, y*upscale + ky + y_ofs);
for (unsigned int kx = 0; kx < upscale; kx++)
{
int intensity = 0;
int upscale_ = upscale - 1;
intensity+= q00*(upscale_ - ky)*(upscale_ - kx);
intensity+= q01*(upscale_ - ky)*kx;
intensity+= q10*ky*(upscale_ - kx);
intensity+= q11*ky*kx;
intensity/= upscale_*upscale_;
display_.DrawPixel(intensity, intensity, intensity);
}
}
}
} | 29.982759 | 102 | 0.455626 | michalnand |
5e3d40285aa66f0d6d58feb9f7fcc4ac2dc511f9 | 1,046 | cpp | C++ | UnitTest/TestVoronoi.cpp | ArchRobison/Voromoeba | 608aeebd03f955a2180d05f310de6097c3df0c69 | [
"Apache-2.0"
] | null | null | null | UnitTest/TestVoronoi.cpp | ArchRobison/Voromoeba | 608aeebd03f955a2180d05f310de6097c3df0c69 | [
"Apache-2.0"
] | 1 | 2021-06-28T16:24:46.000Z | 2021-06-29T13:40:23.000Z | UnitTest/TestVoronoi.cpp | ArchRobison/Voromoeba | 608aeebd03f955a2180d05f310de6097c3df0c69 | [
"Apache-2.0"
] | null | null | null | #include "Voronoi.h"
#include "Region.h"
void TestVoronoi() {
NimblePixel pixels[100][100];
NimblePixMap window( 100, 100, 32, pixels, sizeof(pixels[100]) );
ConvexRegion r;
r.makeRectangle(Point(10,20),Point(90,80));
SetRegionClip(0,0,window.width(),window.height());
CompoundRegion region;
region.build(&r,&r+1);
for( int trial=0; trial<1000; ++trial ) {
static Ant ants[N_ANT_MAX];
NimblePixel color[N_ANT_MAX];
Ant* a = ants;
a->assignFirstBookend();
++a;
size_t n = 100;
for( size_t k=0; k<n; ) {
float x = RandomFloat(100);
float y = RandomFloat(100);
float dx = RandomFloat(0.001f);
float dy = RandomFloat(0.0f);
a->assign(Point(x,y),color[k]);
++a; ++k;
a->assign(Point(x+dx,y+dy),color[k]);
++a; ++k;
}
a->assignLastBookend();
++a;
DrawVoronoi( window, region, ants, a );
}
} | 29.055556 | 70 | 0.510516 | ArchRobison |
5e3eb273cb8da40252d6251aa92ee918c3093b1a | 4,907 | hpp | C++ | src/mlpack/methods/ann/layer/channel_shuffle.hpp | oblanchet/mlpack | e02ab3be544694294d2f73bd12a98d0d162ef3af | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4,216 | 2015-01-01T02:06:12.000Z | 2022-03-31T19:12:06.000Z | src/mlpack/methods/ann/layer/channel_shuffle.hpp | oblanchet/mlpack | e02ab3be544694294d2f73bd12a98d0d162ef3af | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2,621 | 2015-01-01T01:41:47.000Z | 2022-03-31T19:01:26.000Z | src/mlpack/methods/ann/layer/channel_shuffle.hpp | oblanchet/mlpack | e02ab3be544694294d2f73bd12a98d0d162ef3af | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1,972 | 2015-01-01T23:37:13.000Z | 2022-03-28T06:03:41.000Z | /**
* @file methods/ann/layer/channel_shuffle.hpp
* @author Abhinav Anand
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_LAYER_CHANNEL_SHUFFLE_HPP
#define MLPACK_METHODS_ANN_LAYER_CHANNEL_SHUFFLE_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Definition and implementation of the Channel Shuffle Layer.
*
* Channel Shuffle divides the channels/units in a tensor into groups
* and rearrange while keeping the original tensor shape.
*
* For more information, refer to the following paper,
*
* @code
* @article{zhang2018shufflenet,
* author = {Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, Jian Sun and
* Megvii Inc},
* title = {Shufflenet: An extremely efficient convolutional neural
* network for mobile devices},
* year = {2018},
* url = {https://arxiv.org/pdf/1707.01083},
* }
* @endcode
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class ChannelShuffle
{
public:
//! Create the Channel Shuffle object.
ChannelShuffle();
/**
* The constructor for the Channel Shuffle.
*
* @param inRowSize Number of input rows.
* @param inColSize Number of input columns.
* @param depth Number of input slices.
* @param group Number of groups for shuffling channels.
*/
ChannelShuffle(const size_t inRowSize,
const size_t inColSize,
const size_t depth,
const size_t groupCount);
/**
* Forward pass through the layer.
*
* @param input The input matrix.
* @param output The resulting interpolated output matrix.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output);
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards through f. Using the results from the feed
* forward pass. Since the layer does not have any learn-able parameters,
* we just have to down-sample the gradient to make its size compatible with
* the input size.
*
* @param * (input) The input matrix.
* @param gradient The computed backward gradient.
* @param output The resulting down-sampled output.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& /*input*/,
const arma::Mat<eT>& gradient,
arma::Mat<eT>& output);
//! Get the output parameter.
OutputDataType const& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType const& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! Get the row size of the input.
size_t const& InRowSize() const { return inRowSize; }
//! Modify the row size of the input.
size_t& InRowSize() { return inRowSize; }
//! Get the column size of the input.
size_t const& InColSize() const { return inColSize; }
//! Modify the column size of the input.
size_t& InColSize() { return inColSize; }
//! Get the depth of the input.
size_t const& InDepth() const { return depth; }
//! Modify the depth of the input.
size_t& InDepth() { return depth; }
//! Get the number of groups the channels is divided into.
size_t const& InGroupCount() const { return groupCount; }
//! Modify the number of groups the channels is divided into.
size_t& InGroupCount() { return groupCount; }
//! Get the shape of the input.
size_t InputShape() const
{
return inRowSize;
}
/**
* Serialize the layer.
*/
template<typename Archive>
void serialize(Archive& ar, const uint32_t /* version */);
private:
//! Locally stored row size of the input.
size_t inRowSize;
//! Locally stored column size of the input.
size_t inColSize;
//! Locally stored depth of the input.
size_t depth;
//! Locally stored the number of groups the channels is divided into.
size_t groupCount;
//! Locally stored number of input points.
size_t batchSize;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class ChannelShuffle
} // namespace ann
} // namespace mlpack
// Include implementation.
#include "channel_shuffle_impl.hpp"
#endif
| 31.455128 | 79 | 0.684736 | oblanchet |
5e3fb88c4f84c26de00af844b0df133df3c636cd | 7,365 | hpp | C++ | src/PE/utils/ordinals_lookup_tables/comctl32_dll_lookup.hpp | mkomet/LIEF | 27547aec3314177d374293130b1fd00b4487139a | [
"Apache-2.0"
] | null | null | null | src/PE/utils/ordinals_lookup_tables/comctl32_dll_lookup.hpp | mkomet/LIEF | 27547aec3314177d374293130b1fd00b4487139a | [
"Apache-2.0"
] | null | null | null | src/PE/utils/ordinals_lookup_tables/comctl32_dll_lookup.hpp | mkomet/LIEF | 27547aec3314177d374293130b1fd00b4487139a | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 - 2021 R. Thomas
* Copyright 2017 - 2021 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIEF_PE_COMCTL32_DLL_LOOKUP_H_
#define LIEF_PE_COMCTL32_DLL_LOOKUP_H_
#include <map>
namespace LIEF {
namespace PE {
static const std::map<uint32_t, const char*> comctl32_dll_lookup {
{ 0x0191, "AddMRUStringW" },
{ 0x00cf, "AttachScrollBars" },
{ 0x00d2, "CCEnableScrollBar" },
{ 0x00d1, "CCGetScrollInfo" },
{ 0x00d0, "CCSetScrollInfo" },
{ 0x0190, "CreateMRUListW" },
{ 0x0008, "CreateMappedBitmap" },
{ 0x000c, "CreatePropertySheetPage" },
{ 0x0013, "CreatePropertySheetPageA" },
{ 0x0014, "CreatePropertySheetPageW" },
{ 0x0015, "CreateStatusWindow" },
{ 0x0006, "CreateStatusWindowA" },
{ 0x0016, "CreateStatusWindowW" },
{ 0x0007, "CreateToolbar" },
{ 0x0017, "CreateToolbarEx" },
{ 0x0010, "CreateUpDownControl" },
{ 0x014b, "DPA_Clone" },
{ 0x0148, "DPA_Create" },
{ 0x0154, "DPA_CreateEx" },
{ 0x0151, "DPA_DeleteAllPtrs" },
{ 0x0150, "DPA_DeletePtr" },
{ 0x0149, "DPA_Destroy" },
{ 0x0182, "DPA_DestroyCallback" },
{ 0x0181, "DPA_EnumCallback" },
{ 0x014c, "DPA_GetPtr" },
{ 0x014d, "DPA_GetPtrIndex" },
{ 0x015b, "DPA_GetSize" },
{ 0x014a, "DPA_Grow" },
{ 0x014e, "DPA_InsertPtr" },
{ 0x0009, "DPA_LoadStream" },
{ 0x000b, "DPA_Merge" },
{ 0x000a, "DPA_SaveStream" },
{ 0x0153, "DPA_Search" },
{ 0x014f, "DPA_SetPtr" },
{ 0x0152, "DPA_Sort" },
{ 0x0157, "DSA_Clone" },
{ 0x0140, "DSA_Create" },
{ 0x0147, "DSA_DeleteAllItems" },
{ 0x0146, "DSA_DeleteItem" },
{ 0x0141, "DSA_Destroy" },
{ 0x0184, "DSA_DestroyCallback" },
{ 0x0183, "DSA_EnumCallback" },
{ 0x0142, "DSA_GetItem" },
{ 0x0143, "DSA_GetItemPtr" },
{ 0x015c, "DSA_GetSize" },
{ 0x0144, "DSA_InsertItem" },
{ 0x0145, "DSA_SetItem" },
{ 0x015a, "DSA_Sort" },
{ 0x019d, "DefSubclassProc" },
{ 0x0018, "DestroyPropertySheetPage" },
{ 0x00ce, "DetachScrollBars" },
{ 0x0019, "DllGetVersion" },
{ 0x001a, "DllInstall" },
{ 0x000f, "DrawInsert" },
{ 0x00c9, "DrawScrollBar" },
{ 0x001b, "DrawShadowText" },
{ 0x00c8, "DrawSizeBox" },
{ 0x001c, "DrawStatusText" },
{ 0x0005, "DrawStatusTextA" },
{ 0x001d, "DrawStatusTextW" },
{ 0x0193, "EnumMRUListW" },
{ 0x001e, "FlatSB_EnableScrollBar" },
{ 0x001f, "FlatSB_GetScrollInfo" },
{ 0x0020, "FlatSB_GetScrollPos" },
{ 0x0021, "FlatSB_GetScrollProp" },
{ 0x0022, "FlatSB_GetScrollPropPtr" },
{ 0x0023, "FlatSB_GetScrollRange" },
{ 0x0024, "FlatSB_SetScrollInfo" },
{ 0x0025, "FlatSB_SetScrollPos" },
{ 0x0026, "FlatSB_SetScrollProp" },
{ 0x0027, "FlatSB_SetScrollRange" },
{ 0x0028, "FlatSB_ShowScrollBar" },
{ 0x0098, "FreeMRUList" },
{ 0x0004, "GetEffectiveClientRect" },
{ 0x0029, "GetMUILanguage" },
{ 0x019b, "GetWindowSubclass" },
{ 0x002a, "HIMAGELIST_QueryInterface" },
{ 0x00cd, "HandleScrollCmd" },
{ 0x002b, "ImageList_Add" },
{ 0x002c, "ImageList_AddIcon" },
{ 0x002d, "ImageList_AddMasked" },
{ 0x002e, "ImageList_BeginDrag" },
{ 0x002f, "ImageList_CoCreateInstance" },
{ 0x0030, "ImageList_Copy" },
{ 0x0031, "ImageList_Create" },
{ 0x0032, "ImageList_Destroy" },
{ 0x0033, "ImageList_DestroyShared" },
{ 0x0034, "ImageList_DragEnter" },
{ 0x0035, "ImageList_DragLeave" },
{ 0x0036, "ImageList_DragMove" },
{ 0x0037, "ImageList_DragShowNolock" },
{ 0x0038, "ImageList_Draw" },
{ 0x0039, "ImageList_DrawEx" },
{ 0x003a, "ImageList_DrawIndirect" },
{ 0x003b, "ImageList_Duplicate" },
{ 0x003c, "ImageList_EndDrag" },
{ 0x003d, "ImageList_GetBkColor" },
{ 0x003e, "ImageList_GetDragImage" },
{ 0x003f, "ImageList_GetFlags" },
{ 0x0040, "ImageList_GetIcon" },
{ 0x0041, "ImageList_GetIconSize" },
{ 0x0042, "ImageList_GetImageCount" },
{ 0x0043, "ImageList_GetImageInfo" },
{ 0x0044, "ImageList_GetImageRect" },
{ 0x0045, "ImageList_LoadImage" },
{ 0x0046, "ImageList_LoadImageA" },
{ 0x004b, "ImageList_LoadImageW" },
{ 0x004c, "ImageList_Merge" },
{ 0x004d, "ImageList_Read" },
{ 0x004e, "ImageList_ReadEx" },
{ 0x004f, "ImageList_Remove" },
{ 0x0050, "ImageList_Replace" },
{ 0x0051, "ImageList_ReplaceIcon" },
{ 0x0052, "ImageList_Resize" },
{ 0x0053, "ImageList_SetBkColor" },
{ 0x0054, "ImageList_SetDragCursorImage" },
{ 0x0055, "ImageList_SetFilter" },
{ 0x0056, "ImageList_SetFlags" },
{ 0x0057, "ImageList_SetIconSize" },
{ 0x0058, "ImageList_SetImageCount" },
{ 0x0059, "ImageList_SetOverlayImage" },
{ 0x005a, "ImageList_Write" },
{ 0x005b, "ImageList_WriteEx" },
{ 0x0011, "InitCommonControls" },
{ 0x005c, "InitCommonControlsEx" },
{ 0x005d, "InitMUILanguage" },
{ 0x005e, "InitializeFlatSB" },
{ 0x000e, "LBItemFromPt" },
{ 0x017c, "LoadIconMetric" },
{ 0x017d, "LoadIconWithScaleDown" },
{ 0x000d, "MakeDragList" },
{ 0x0002, "MenuHelp" },
{ 0x005f, "PropertySheet" },
{ 0x0060, "PropertySheetA" },
{ 0x0061, "PropertySheetW" },
{ 0x018a, "QuerySystemGestureStatus" },
{ 0x0062, "RegisterClassNameW" },
{ 0x019c, "RemoveWindowSubclass" },
{ 0x00cc, "ScrollBar_Menu" },
{ 0x00cb, "ScrollBar_MouseMove" },
{ 0x019a, "SetWindowSubclass" },
{ 0x0003, "ShowHideMenuCtl" },
{ 0x00ca, "SizeBoxHwnd" },
{ 0x00ec, "Str_SetPtrW" },
{ 0x0158, "TaskDialog" },
{ 0x0159, "TaskDialogIndirect" },
{ 0x0063, "UninitializeFlatSB" },
{ 0x0064, "_TrackMouseEvent" },
};
}
}
#endif
| 40.690608 | 75 | 0.536456 | mkomet |
1e0f74496a38e7872122501fe6bf09da1fe91d49 | 10,227 | cc | C++ | src/common/chemistry/tests_unit/chemistry_activity_coefficients.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/common/chemistry/tests_unit/chemistry_activity_coefficients.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | src/common/chemistry/tests_unit/chemistry_activity_coefficients.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | #include <cstdlib>
#include <cmath>
#include <iostream>
#include <typeinfo>
#include <vector>
#include "UnitTest++.h"
#include "species.hh"
#include "aqueous_equilibrium_complex.hh"
#include "activity_model_factory.hh"
#include "activity_model_unit.hh"
#include "activity_model_debye_huckel.hh"
#include "activity_model.hh"
#include "chemistry_exception.hh"
/*****************************************************************************
* Common testing code
*****************************************************************************/
namespace ac = Amanzi::AmanziChemistry;
class ActivityModelTest {
public:
ActivityModelTest();
~ActivityModelTest();
void RunTest(const std::string name, double* gamma);
void set_activity_model_name(const std::string name) {
activity_model_name_ = name;
};
std::string activity_model_name(void) const {
return activity_model_name_;
};
double ionic_strength(void) {
return activity_model_->ionic_strength();
};
double tolerance(void) {
return tolerance_;
};
protected:
ac::ActivityModelFactory amf_;
private:
double tolerance_;
ac::ActivityModel* activity_model_;
std::string activity_model_name_;
ac::SpeciesArray species_;
ac::Species H_p;
ac::Species OH_m;
ac::Species Ca_pp;
ac::Species SO4_mm;
ac::Species Al_ppp;
ac::Species PO4_mmm;
std::vector<ac::AqueousEquilibriumComplex> aqueous_complexes_;
Teuchos::RCP<Amanzi::VerboseObject> vo_;
};
ActivityModelTest::ActivityModelTest()
: amf_(),
tolerance_(1.0e-5),
activity_model_name_(""),
H_p(0, "H+", 1.0, 1.0079, 9.0),
OH_m(1, "OH-", -1.0, 17.0073, 3.5),
Ca_pp(2, "Ca++", 2.0, 40.0780, 6.0),
SO4_mm(3, "SO4--", -2.0, 96.0636, 4.0),
Al_ppp(4, "Al+++", 3.0, 26.9815, 9.0),
PO4_mmm(5, "PO4---", -3.0, 94.9714, 4.0) {
// set concentrations to get ionic strength of 0.025
H_p.update(0.0005);
OH_m.update(0.0015);
Ca_pp.update(0.001);
SO4_mm.update(0.002);
Al_ppp.update(0.003);
PO4_mmm.update(0.001);
species_.push_back(H_p);
species_.push_back(OH_m);
species_.push_back(Ca_pp);
species_.push_back(SO4_mm);
species_.push_back(Al_ppp);
species_.push_back(PO4_mmm);
// TODO(bandre): should add some aqueous complexes to test ionic strength....
aqueous_complexes_.clear();
Teuchos::ParameterList plist;
vo_ = Teuchos::rcp(new Amanzi::VerboseObject("Chemistry", plist));
}
ActivityModelTest::~ActivityModelTest() {
delete activity_model_;
}
void ActivityModelTest::RunTest(const std::string name, double * gamma) {
int index = -1;
for (std::vector<ac::Species>::iterator primary = species_.begin();
primary != species_.end(); primary++) {
if (primary->name() == name) {
index = primary->identifier();
}
}
*gamma = -1.0; // final value should always be > 0
ac::ActivityModel::ActivityModelParameters parameters;
parameters.database_filename = "";
parameters.pitzer_jfunction = "";
activity_model_ = amf_.Create(activity_model_name(), parameters,
species_, aqueous_complexes_,
vo_.ptr());
activity_model_->CalculateIonicStrength(species_, aqueous_complexes_);
*gamma = activity_model_->Evaluate(species_.at(index));
}
/*!
@namespace Amanzi::AmanziChemistry::unit_tests::ActivityModel
@details Unit tests for the activity model base class, Amanzi::AmanziChemistry::ActivityModel
@test ActivityModel
*/
SUITE(amanzi_chemistry_unit_tests_ActivityModel) {
/*!
@class Amanzi::AmanziChemistry::unit_tests::ActivityModel::ActivityModel_IonicStrength
@brief ActivityModel_IonicStrength
@details Test that a the ionic strength is calculated
correctly for an arbitrary choice of 6 ions with charge of +-1,
+-2, +-3. Adjust concentrations to yield an ionic strength of
0.025.
@test ActivityModel::CalculateIonicStrength()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModel_IonicStrength) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("H+", &gamma);
// std::cout << "ionic strength: " << ionic_strength() << std::endl;
CHECK_CLOSE(0.025, ionic_strength(), tolerance());
}
} // end SUITE(amanzi_chemistry_unit_tests_ActivityModel)
/*!
@namespace Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit
@details Unit tests for class ActivityModelUnit.
- Unit activity coefficients are always 1.0 regardless of species
@f[ \gamma_i = 1.0 @f]
@test ActivityModelUnit
*/
SUITE(amanzi_chemistry_unit_tests_ActivityModelUnit) {
/*!
@brief ActivityModelUnit_H
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_H
@details Test calculation of unit activity coefficient for @f$ H^{+} @f$
@test ActivityModelUnit::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_H) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("H+", &gamma);
CHECK_EQUAL(1.0, gamma);
}
/*!
@brief ActivityModelUnit_OH
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_OH
@details Test calculation of unit activity coefficient for @f$ OH^{+} @f$
@test ActivityModelUnit::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_OH) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("OH-", &gamma);
CHECK_EQUAL(1.0, gamma);
}
/*!
@brief ActivityModelUnit_Ca
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_Ca
@details Test calculation of unit activity coefficient for @f$ Ca^{+2} @f$
@test ActivityModelUnit::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_Ca) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("Ca++", &gamma);
CHECK_EQUAL(1.0, gamma);
}
/*!
@brief ActivityModelUnit_SO4
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_SO4
@details Test calculation of unit activity coefficient for @f$ SO4^{-2} @f$
@test ActivityModelUnit::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_SO4) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("SO4--", &gamma);
CHECK_EQUAL(1.0, gamma);
}
/*!
@brief ActivityModelUnit_Al
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_Al
@details Test calculation of unit activity coefficient for @f$ Al^{+3} @f$
@test ActivityModelUnit::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_Al) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("Al+++", &gamma);
CHECK_EQUAL(1.0, gamma);
}
/*!
@brief ActivityModelUnit_PO4
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_PO4
@details Test calculation of unit activity coefficient for @f$ PO4^{-3} @f$
@test ActivityModelUnit::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_PO4) {
set_activity_model_name(ac::ActivityModelFactory::unit);
double gamma;
RunTest("PO4---", &gamma);
CHECK_EQUAL(1.0, gamma);
}
} // end SUITE(amanzi_chemistry_unit_tests_ActivityModelUnit)
/*!
@namespace Amanzi::AmanziChemistry::unit_tests::ActivityModelDebyeHuckel
@details Test the calculation of the Debye-Huckel B-dot activity
coefficients is correct.
@f[
\log \gamma _{i} =
- \frac{A_{\gamma} z_{i}^{2} \sqrt{ \bar{I} }}
{1+ \mathring{a_i} B_{\gamma } \sqrt{\bar{I}}}
+ \dot{B} \bar{I}
@f]
- Debye-Huckel: check first two digits of activity coefficients
at 25C with Langmuir, 1997, Aqueous Environmental Geochemistry,
Table 4.1 and 4.2, pg 130-131. Note, code uses slightly different
debyeA and debyeB parameters.
- source for higher number of sig figs?
- For temperature dependance, run 5-10 temperature values, then
store results in a vector and use CHECK_ARRAY_CLOSE(). Source
for temperature dependance?
@test ActivityModelDebyHuckel
*/
SUITE(amanzi_chemistry_unit_tests_ActivityModelDebyeHuckel) {
/*!
@brief ActivityModelDebyeHuckel_H
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelDebyeHuckel::ActivityModelDebyeHuckel_H
@details Test calculation of Debye-Huckel activity coefficient for @f$ H^{+} @f$
@test ActivityModelDebyeHuckel::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_H) {
set_activity_model_name(ac::ActivityModelFactory::debye_huckel);
double gamma;
RunTest("H+", &gamma);
CHECK_CLOSE(0.88, gamma, 1.0e-2);
}
/*!
@brief ActivityModelDebyeHuckel_OH
@class Amanzi::AmanziChemistry::unit_tests::ActivityModelDebyeHuckel::ActivityModelDebyeHuckel_OH
@details Test calculation of Debye-Huckel activity coefficient for @f$ OH^{-} @f$
@test ActivityModelDebyeHuckel::Evaluate()
*/
TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_OH) {
set_activity_model_name(ac::ActivityModelFactory::debye_huckel);
double gamma;
RunTest("OH-", &gamma);
CHECK_CLOSE(0.855, gamma, 1.0e-2);
}
TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_Ca) {
set_activity_model_name(ac::ActivityModelFactory::debye_huckel);
double gamma;
RunTest("Ca++", &gamma);
CHECK_CLOSE(0.57, gamma, 1.0e-2);
}
TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_SO4) {
set_activity_model_name(ac::ActivityModelFactory::debye_huckel);
double gamma;
RunTest("SO4--", &gamma);
CHECK_CLOSE(0.545, gamma, 1.0e-2);
}
TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_Al) {
set_activity_model_name(ac::ActivityModelFactory::debye_huckel);
double gamma;
RunTest("Al+++", &gamma);
CHECK_CLOSE(0.325, gamma, 1.0e-2);
}
TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_PO4) {
set_activity_model_name(ac::ActivityModelFactory::debye_huckel);
double gamma;
RunTest("PO4---", &gamma);
CHECK_CLOSE(0.25, gamma, 1.0e-2);
}
} // end SUITE(amanzi_chemistry_unit_tests_ActivityModelDebyeHuckel)
| 29.387931 | 101 | 0.702748 | ajkhattak |
1e10392a08dcf5a84d92bab4b98c0f1ec3e19d67 | 10,742 | cpp | C++ | tests/Cardano/AddressTests.cpp | alicedapp/wallet-core | 532034af30cc5a8f677c7f7b0d182e8198cf698d | [
"MIT"
] | null | null | null | tests/Cardano/AddressTests.cpp | alicedapp/wallet-core | 532034af30cc5a8f677c7f7b0d182e8198cf698d | [
"MIT"
] | null | null | null | tests/Cardano/AddressTests.cpp | alicedapp/wallet-core | 532034af30cc5a8f677c7f7b0d182e8198cf698d | [
"MIT"
] | 2 | 2020-01-08T14:28:22.000Z | 2020-01-21T15:46:52.000Z | // Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Cardano/Address.h"
#include "Cardano/Signer.h"
#include "HDWallet.h"
#include "HexCoding.h"
#include "PrivateKey.h"
#include <gtest/gtest.h>
using namespace TW;
using namespace TW::Cardano;
using namespace std;
TEST(CardanoAddress, Validation) {
// valid V2 address
ASSERT_TRUE(Address::isValid("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx"));
ASSERT_TRUE(Address::isValid("Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W"));
// valid V1 address
ASSERT_TRUE(Address::isValid("DdzFFzCqrhssmYoG5Eca1bKZFdGS8d6iag1mU4wbLeYcSPVvBNF2wRG8yhjzQqErbg63N6KJA4DHqha113tjKDpGEwS5x1dT2KfLSbSJ"));
ASSERT_TRUE(Address::isValid("DdzFFzCqrht7HGoJ87gznLktJGywK1LbAJT2sbd4txmgS7FcYLMQFhawb18ojS9Hx55mrbsHPr7PTraKh14TSQbGBPJHbDZ9QVh6Z6Di"));
// invalid checksum
ASSERT_FALSE(Address::isValid("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvm"));
// random
ASSERT_FALSE(Address::isValid("hasoiusaodiuhsaijnnsajnsaiussai"));
// empty
ASSERT_FALSE(Address::isValid(""));
}
TEST(CardanoAddress, FromString) {
{
auto address = Address("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx");
ASSERT_EQ(address.string(), "Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx");
}
{
auto address = Address("DdzFFzCqrhssmYoG5Eca1bKZFdGS8d6iag1mU4wbLeYcSPVvBNF2wRG8yhjzQqErbg63N6KJA4DHqha113tjKDpGEwS5x1dT2KfLSbSJ");
ASSERT_EQ(address.string(), "DdzFFzCqrhssmYoG5Eca1bKZFdGS8d6iag1mU4wbLeYcSPVvBNF2wRG8yhjzQqErbg63N6KJA4DHqha113tjKDpGEwS5x1dT2KfLSbSJ");
}
}
TEST(CardanoAddress, MnemonicToAddress) {
{
// Test from cardano-crypto.js; Test wallet
auto mnemonic = "cost dash dress stove morning robust group affair stomach vacant route volume yellow salute laugh";
auto wallet = HDWallet(mnemonic, "");
PrivateKey masterPrivKey = wallet.getMasterKey(TWCurve::TWCurveED25519Extended);
PrivateKey masterPrivKeyExt = wallet.getMasterKeyExtension(TWCurve::TWCurveED25519Extended);
ASSERT_EQ("a018cd746e128a0be0782b228c275473205445c33b9000a33dd5668b430b5744", hex(masterPrivKey.bytes));
ASSERT_EQ("26877cfe435fddda02409b839b7386f3738f10a30b95a225f4b720ee71d2505b", hex(masterPrivKeyExt.bytes));
{
string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano);
ASSERT_EQ("Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W", addr);
}
{
PrivateKey privKey0 = wallet.getKey(DerivationPath("m/44'/1815'/0'/0/0"));
PublicKey pubKey0 = privKey0.getPublicKey(TWPublicKeyTypeED25519Extended);
Address addr0 = Address(pubKey0);
ASSERT_EQ("Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W", addr0.string());
}
{
PrivateKey privKey1 = wallet.getKey(DerivationPath("m/44'/1815'/0'/0/1"));
PublicKey pubKey1 = privKey1.getPublicKey(TWPublicKeyTypeED25519Extended);
Address addr1 = Address(pubKey1);
ASSERT_EQ("Ae2tdPwUPEZ7dnds6ZyhQdmgkrDFFPSDh8jG9RAhswcXt1bRauNw5jczjpV", addr1.string());
}
{
PrivateKey privKey1 = wallet.getKey(DerivationPath("m/44'/1815'/0'/0/2"));
PublicKey pubKey1 = privKey1.getPublicKey(TWPublicKeyTypeED25519Extended);
Address addr1 = Address(pubKey1);
ASSERT_EQ("Ae2tdPwUPEZ8LAVy21zj4BF97iWxKCmPv12W6a18zLX3V7rZDFFVgqUBkKw", addr1.string());
}
}
{
// Tested agains AdaLite
auto mnemonicPlay1 = "youth away raise north opinion slice dash bus soldier dizzy bitter increase saddle live champion";
auto wallet = HDWallet(mnemonicPlay1, "");
string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano);
ASSERT_EQ("Ae2tdPwUPEZJYT9g1JgQWtLveUHavyRxQGi6hVzoQjct7yyCLGgk3pCyx7h", addr);
}
{
// Tested agains AdaLite
auto mnemonicPlay2 = "return custom two home gain guilt kangaroo supply market current curtain tomorrow heavy blue robot";
auto wallet = HDWallet(mnemonicPlay2, "");
string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano);
ASSERT_EQ("Ae2tdPwUPEZLtJx7LA2XZ3zzwonH9x9ieX3dMzaTBD3TfXuKczjMSjTecr1", addr);
}
{
// AdaLite Demo phrase, 12-word. AdaLite uses V1 for it, in V2 it produces different addresses.
// In AdaLite V1 addr0 is DdzFFzCqrht7HGoJ87gznLktJGywK1LbAJT2sbd4txmgS7FcYLMQFhawb18ojS9Hx55mrbsHPr7PTraKh14TSQbGBPJHbDZ9QVh6Z6Di
auto mnemonicALDemo = "civil void tool perfect avocado sweet immense fluid arrow aerobic boil flash";
auto wallet = HDWallet(mnemonicALDemo, "");
string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano);
ASSERT_EQ("Ae2tdPwUPEZJbLcD8iLgN7hVGvq66WdR4zocntRekSP97Ds3MvCfmEDjJYu", addr);
}
}
TEST(CardanoAddress, KeyHash) {
auto xpub = parse_hex("e6f04522f875c1563682ca876ddb04c2e2e3ae718e3ff9f11c03dd9f9dccf69869272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000");
auto hash = Address::keyHash(xpub);
ASSERT_EQ("a1eda96a9952a56c983d9f49117f935af325e8a6c9d38496e945faa8", hex(hash));
}
TEST(CardanoAddress, FromPublicKey) {
{
// caradano-crypto.js test
auto publicKey = PublicKey(parse_hex("e6f04522f875c1563682ca876ddb04c2e2e3ae718e3ff9f11c03dd9f9dccf69869272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000"), TWPublicKeyTypeED25519Extended);
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZCxt4UV1Uj2AMMRvg5pYPypqZowVptz3GYpK4pkcvn3EjkuNH");
}
{
// Adalite test account addr0
auto publicKey = PublicKey(parse_hex("57fd54be7b38bb8952782c2f59aa276928a4dcbb66c8c62ce44f9d623ecd5a03bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4"), TWPublicKeyTypeED25519Extended);
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W");
}
{
// Adalite test account addr1
auto publicKey = PublicKey(parse_hex("25af99056d600f7956312406bdd1cd791975bb1ae91c9d034fc65f326195fcdb247ee97ec351c0820dd12de4ca500232f73a35fe6f86778745bcd57f34d1048d"), TWPublicKeyTypeED25519Extended);
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZ7dnds6ZyhQdmgkrDFFPSDh8jG9RAhswcXt1bRauNw5jczjpV");
}
{
// Play1 addr0
auto publicKey = PublicKey(parse_hex("7cee0f30b9d536a786547dd77b35679b6830e945ffde768eb4f2a061b9dba016e513fa1290da1d22e83a41f17eed72d4489483b561fff36b9555ffdb91c430e2"), TWPublicKeyTypeED25519Extended);
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZJYT9g1JgQWtLveUHavyRxQGi6hVzoQjct7yyCLGgk3pCyx7h");
}
}
TEST(CardanoAddress, FromPrivateKey) {
{
// mnemonic Test, addr0
auto privateKey = PrivateKey(
parse_hex("b0884d248cb301edd1b34cf626ba6d880bb3ae8fd91b4696446999dc4f0b5744"),
parse_hex("309941d56938e943980d11643c535e046653ca6f498c014b88f2ad9fd6e71eff"),
parse_hex("bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4")
);
auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeED25519Extended);
ASSERT_EQ(hex(publicKey.bytes), "57fd54be7b38bb8952782c2f59aa276928a4dcbb66c8c62ce44f9d623ecd5a03bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4");
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W");
}
{
// mnemonic Play1, addr0
auto privateKey = PrivateKey(
parse_hex("a089c9423100960440ccd5b7adbd202d1ab1993a7bb30fc88b287d94016df247"),
parse_hex("da86a87f08fb15de1431a6c0ccd5ebf51c3bee81f7eaf714801bbbe4d903154a"),
parse_hex("e513fa1290da1d22e83a41f17eed72d4489483b561fff36b9555ffdb91c430e2")
);
auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeED25519Extended);
ASSERT_EQ(hex(publicKey.bytes), "7cee0f30b9d536a786547dd77b35679b6830e945ffde768eb4f2a061b9dba016e513fa1290da1d22e83a41f17eed72d4489483b561fff36b9555ffdb91c430e2");
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZJYT9g1JgQWtLveUHavyRxQGi6hVzoQjct7yyCLGgk3pCyx7h");
}
{
// from cardano-crypto.js test
auto privateKey = PrivateKey(
parse_hex("d809b1b4b4c74734037f76aace501730a3fe2fca30b5102df99ad3f7c0103e48"),
parse_hex("d54cde47e9041b31f3e6873d700d83f7a937bea746dadfa2c5b0a6a92502356c"),
parse_hex("69272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000")
);
auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeED25519Extended);
ASSERT_EQ(hex(publicKey.bytes), "e6f04522f875c1563682ca876ddb04c2e2e3ae718e3ff9f11c03dd9f9dccf69869272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000");
auto address = Address(publicKey);
ASSERT_EQ(address.string(), "Ae2tdPwUPEZCxt4UV1Uj2AMMRvg5pYPypqZowVptz3GYpK4pkcvn3EjkuNH");
}
}
TEST(CardanoAddress, PrivateKeyExtended) {
// check extended key lengths, private key 3x32 bytes, public key 64 bytes
auto privateKeyExt = PrivateKey(
parse_hex("b0884d248cb301edd1b34cf626ba6d880bb3ae8fd91b4696446999dc4f0b5744"),
parse_hex("309941d56938e943980d11643c535e046653ca6f498c014b88f2ad9fd6e71eff"),
parse_hex("bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4")
);
auto publicKeyExt = privateKeyExt.getPublicKey(TWPublicKeyTypeED25519Extended);
ASSERT_EQ(64, publicKeyExt.bytes.size());
// Non-extended: both are 32 bytes.
auto privateKeyNonext = PrivateKey(
parse_hex("b0884d248cb301edd1b34cf626ba6d880bb3ae8fd91b4696446999dc4f0b5744")
);
auto publicKeyNonext = privateKeyNonext.getPublicKey(TWPublicKeyTypeED25519);
ASSERT_EQ(32, publicKeyNonext.bytes.size());
}
TEST(CardanoAddress, FromStringNegativeInvalidString) {
try {
auto address = Address("__INVALID_ADDRESS__");
} catch (...) {
return;
}
FAIL() << "Expected exception!";
}
TEST(CardanoAddress, FromStringNegativeBadChecksum) {
try {
auto address = Address("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvm");
} catch (...) {
return;
}
FAIL() << "Expected exception!";
}
| 50.196262 | 210 | 0.756191 | alicedapp |
1e121e35fe87ebd72c78357614a7230cb0515338 | 154 | cc | C++ | common/tile/memory_subsystem/cache/cache_utils.cc | NoCModellingLab/Graphite | 1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997 | [
"MIT"
] | 94 | 2015-02-21T09:44:03.000Z | 2022-03-13T03:06:19.000Z | common/tile/memory_subsystem/cache/cache_utils.cc | NoCModellingLab/Graphite | 1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997 | [
"MIT"
] | null | null | null | common/tile/memory_subsystem/cache/cache_utils.cc | NoCModellingLab/Graphite | 1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997 | [
"MIT"
] | 36 | 2015-01-09T16:48:18.000Z | 2022-03-13T03:06:21.000Z | #include "cache_utils.h"
UInt64 computeLifetime(UInt64 birth_time, UInt64 curr_time)
{ return (curr_time > birth_time) ? (curr_time - birth_time) : 0; }
| 30.8 | 67 | 0.753247 | NoCModellingLab |
1e1a598b100bf8d0bf36c0459d2c80b53015d4d1 | 46,122 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/platform/blackberry/RenderThemeBlackBerry.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebCore/platform/blackberry/RenderThemeBlackBerry.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/platform/blackberry/RenderThemeBlackBerry.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T13:03:23.000Z | 2017-03-19T13:03:23.000Z | /*
* Copyright (C) 2006, 2007 Apple Inc.
* Copyright (C) 2009 Google Inc.
* Copyright (C) 2009, 2010, 2011, 2012, 2013 Research In Motion Limited. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include "RenderThemeBlackBerry.h"
#include "CSSValueKeywords.h"
#include "Frame.h"
#include "HTMLMediaElement.h"
#include "HostWindow.h"
#include "InputType.h"
#include "InputTypeNames.h"
#include "MediaControlElements.h"
#include "MediaPlayerPrivateBlackBerry.h"
#include "Page.h"
#include "PaintInfo.h"
#include "RenderFullScreen.h"
#include "RenderProgress.h"
#include "RenderSlider.h"
#include "RenderView.h"
#include "UserAgentStyleSheets.h"
#include <BlackBerryPlatformLog.h>
#include <BlackBerryPlatformScreen.h>
namespace WebCore {
// Sizes (unit px)
const float progressMinWidth = 16;
const float progressTextureUnitWidth = 9.0;
const float mediaControlsHeight = 44;
const float mediaBackButtonHeight = 33;
// Scale exit-fullscreen button size.
const float mediaFullscreenButtonHeightRatio = 5 / 11.0;
const float mediaFullscreenButtonWidthRatio = 3 / 11.0;
const float mediaSliderEndAdjust = 2;
const float mediaSliderTrackRadius = 3;
const float mediaSliderThumbWidth = 25;
const float mediaSliderThumbHeight = 25;
const float mediaSliderThumbRadius = 3;
const float sliderThumbWidth = 15;
const float sliderThumbHeight = 25;
// Multipliers
const unsigned paddingDivisor = 10;
const unsigned fullScreenEnlargementFactor = 2;
const float scaleFactorThreshold = 2.0;
// Slice length
const int smallSlice = 8;
const int mediumSlice = 10;
const int largeSlice = 13;
// Slider Aura, calculated from UX spec
const float auraRatio = 1.62;
// Dropdown arrow position, calculated from UX spec
const float xPositionRatio = 3;
const float yPositionRatio = 0.38;
const float widthRatio = 3;
const float heightRatio = 0.23;
// Colors
const RGBA32 focusRingPen = 0xffa3c8fe;
float RenderThemeBlackBerry::defaultFontSize = 16;
const String& RenderThemeBlackBerry::defaultGUIFont()
{
DEFINE_STATIC_LOCAL(String, fontFace, (ASCIILiteral("Slate Pro")));
return fontFace;
}
static RenderSlider* determineRenderSlider(RenderObject* object)
{
ASSERT(object->isSliderThumb());
// The RenderSlider is an ancestor of the slider thumb.
while (object && !object->isSlider())
object = object->parent();
return toRenderSlider(object);
}
static float determineFullScreenMultiplier(Element* element)
{
float fullScreenMultiplier = 1.0;
#if ENABLE(FULLSCREEN_API) && ENABLE(VIDEO)
if (element && element->document()->webkitIsFullScreen() && element->document()->webkitCurrentFullScreenElement() == toParentMediaElement(element)) {
if (Page* page = element->document()->page()) {
if (page->deviceScaleFactor() < scaleFactorThreshold)
fullScreenMultiplier = fullScreenEnlargementFactor;
// The way the BlackBerry port implements the FULLSCREEN_API for media elements
// might result in the controls being oversized, proportionally to the current page
// scale. That happens because the fullscreen element gets sized to be as big as the
// viewport size, and the viewport size might get outstretched to fit to the screen dimensions.
// To fix that, lets strips out the Page scale factor from the media controls multiplier.
float scaleFactor = element->document()->view()->hostWindow()->platformPageClient()->currentZoomFactor();
float scaleFactorFudge = 1 / page->deviceScaleFactor();
fullScreenMultiplier /= scaleFactor * scaleFactorFudge;
}
}
#endif
return fullScreenMultiplier;
}
static void drawControl(GraphicsContext* gc, const FloatRect& rect, Image* img)
{
if (!img)
return;
FloatRect srcRect(0, 0, img->width(), img->height());
gc->drawImage(img, ColorSpaceDeviceRGB, rect, srcRect);
}
static void drawThreeSliceHorizontal(GraphicsContext* gc, const IntRect& rect, Image* img, int slice)
{
if (!img)
return;
FloatSize dstSlice(rect.height() / 2, rect.height());
FloatRect srcRect(0, 0, slice, img->height());
FloatRect dstRect(rect.location(), dstSlice);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(img->width() - srcRect.width(), 0);
dstRect.move(rect.width() - dstRect.width(), 0);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect = FloatRect(slice, 0, img->width() - 2 * slice, img->height());
dstRect = FloatRect(rect.x() + dstSlice.width(), rect.y(), rect.width() - 2 * dstSlice.width(), dstSlice.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
}
static void drawThreeSliceVertical(GraphicsContext* gc, const IntRect& rect, Image* img, int slice)
{
if (!img)
return;
FloatSize dstSlice(rect.width(), rect.width() / 2);
FloatRect srcRect(0, 0, img->width(), slice);
FloatRect dstRect(rect.location(), dstSlice);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(0, img->height() - srcRect.height());
dstRect.move(0, rect.height() - dstRect.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect = FloatRect(0, slice, img->width(), img->height() - 2 * slice);
dstRect = FloatRect(rect.x(), rect.y() + dstSlice.height(), dstSlice.width(), rect.height() - 2 * dstSlice.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
}
static void drawNineSlice(GraphicsContext* gc, const IntRect& rect, double scale, Image* img, int slice)
{
if (!img)
return;
if (rect.height() * scale < 101.0)
scale = 101.0 / rect.height();
FloatSize dstSlice(slice / scale, slice / scale);
FloatRect srcRect(0, 0, slice, slice);
FloatRect dstRect(rect.location(), dstSlice);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(img->width() - srcRect.width(), 0);
dstRect.move(rect.width() - dstRect.width(), 0);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(0, img->height() - srcRect.height());
dstRect.move(0, rect.height() - dstRect.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(-(img->width() - srcRect.width()), 0);
dstRect.move(-(rect.width() - dstRect.width()), 0);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect = FloatRect(slice, 0, img->width() - 2 * slice, slice);
dstRect = FloatRect(rect.x() + dstSlice.width(), rect.y(), rect.width() - 2 * dstSlice.width(), dstSlice.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(0, img->height() - srcRect.height());
dstRect.move(0, rect.height() - dstRect.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect = FloatRect(0, slice, slice, img->height() - 2 * slice);
dstRect = FloatRect(rect.x(), rect.y() + dstSlice.height(), dstSlice.width(), rect.height() - 2 * dstSlice.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect.move(img->width() - srcRect.width(), 0);
dstRect.move(rect.width() - dstRect.width(), 0);
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
srcRect = FloatRect(slice, slice, img->width() - 2 * slice, img->height() - 2 * slice);
dstRect = FloatRect(rect.x() + dstSlice.width(), rect.y() + dstSlice.height(), rect.width() - 2 * dstSlice.width(), rect.height() - 2 * dstSlice.height());
gc->drawImage(img, ColorSpaceDeviceRGB, dstRect, srcRect);
}
static RefPtr<Image> loadImage(const char* filename)
{
RefPtr<Image> resource;
resource = Image::loadPlatformResource(filename).leakRef();
if (!resource) {
BlackBerry::Platform::logAlways(BlackBerry::Platform::LogLevelWarn, "RenderThemeBlackBerry failed to load %s.png", filename);
return 0;
}
return resource;
}
PassRefPtr<RenderTheme> RenderTheme::themeForPage(Page*)
{
static RenderTheme* theme = RenderThemeBlackBerry::create().leakRef();
return theme;
}
PassRefPtr<RenderTheme> RenderThemeBlackBerry::create()
{
return adoptRef(new RenderThemeBlackBerry());
}
RenderThemeBlackBerry::RenderThemeBlackBerry()
{
}
RenderThemeBlackBerry::~RenderThemeBlackBerry()
{
}
String RenderThemeBlackBerry::extraDefaultStyleSheet()
{
return String(themeBlackBerryUserAgentStyleSheet, sizeof(themeBlackBerryUserAgentStyleSheet));
}
#if ENABLE(VIDEO)
String RenderThemeBlackBerry::extraMediaControlsStyleSheet()
{
return String(mediaControlsBlackBerryUserAgentStyleSheet, sizeof(mediaControlsBlackBerryUserAgentStyleSheet));
}
#endif
#if ENABLE(FULLSCREEN_API)
String RenderThemeBlackBerry::extraFullScreenStyleSheet()
{
return String(mediaControlsBlackBerryFullscreenUserAgentStyleSheet, sizeof(mediaControlsBlackBerryFullscreenUserAgentStyleSheet));
}
#endif
double RenderThemeBlackBerry::caretBlinkInterval() const
{
return 0; // Turn off caret blinking.
}
void RenderThemeBlackBerry::systemFont(CSSValueID valueID, FontDescription& fontDescription) const
{
float fontSize = defaultFontSize;
// Both CSSValueWebkitControl and CSSValueWebkitSmallControl should use default font size which looks better on the controls.
if (valueID == CSSValueWebkitMiniControl) {
// Why 2 points smaller? Because that's what Gecko does. Note that we
// are assuming a 96dpi screen, which is the default value we use on Windows.
static const float pointsPerInch = 72.0f;
static const float pixelsPerInch = 96.0f;
fontSize -= (2.0f / pointsPerInch) * pixelsPerInch;
}
fontDescription.firstFamily().setFamily(defaultGUIFont());
fontDescription.setSpecifiedSize(fontSize);
fontDescription.setIsAbsoluteSize(true);
fontDescription.setGenericFamily(FontDescription::NoFamily);
fontDescription.setWeight(FontWeightNormal);
fontDescription.setItalic(false);
}
void RenderThemeBlackBerry::setButtonStyle(RenderStyle* style) const
{
Length vertPadding(int(style->fontSize() / paddingDivisor), Fixed);
style->setPaddingTop(vertPadding);
style->setPaddingBottom(vertPadding);
}
void RenderThemeBlackBerry::adjustButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
{
setButtonStyle(style);
style->setCursor(CURSOR_WEBKIT_GRAB);
}
void RenderThemeBlackBerry::adjustTextAreaStyle(StyleResolver*, RenderStyle* style, Element*) const
{
setButtonStyle(style);
}
bool RenderThemeBlackBerry::paintTextArea(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
return paintTextFieldOrTextAreaOrSearchField(object, info, rect);
}
void RenderThemeBlackBerry::adjustTextFieldStyle(StyleResolver*, RenderStyle* style, Element*) const
{
setButtonStyle(style);
}
bool RenderThemeBlackBerry::paintTextFieldOrTextAreaOrSearchField(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
ASSERT(info.context);
GraphicsContext* context = info.context;
static RefPtr<Image> bg, bgDisabled, bgHighlight;
if (!bg) {
if (BlackBerry::Platform::Graphics::Screen::primaryScreen()->displayTechnology() == BlackBerry::Platform::Graphics::OledDisplayTechnology)
bg = loadImage("core_textinput_bg_oled");
else
bg = loadImage("core_textinput_bg");
bgDisabled = loadImage("core_textinput_bg_disabled");
bgHighlight = loadImage("core_textinput_bg_highlight");
}
AffineTransform ctm = context->getCTM();
if (isEnabled(object) && bg)
drawNineSlice(context, rect, ctm.xScale(), bg.get(), smallSlice);
if (!isEnabled(object) && bgDisabled)
drawNineSlice(context, rect, ctm.xScale(), bgDisabled.get(), smallSlice);
if ((isHovered(object) || isFocused(object) || isPressed(object)) && bgHighlight)
drawNineSlice(context, rect, ctm.xScale(), bgHighlight.get(), smallSlice);
return false;
}
bool RenderThemeBlackBerry::paintTextField(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
return paintTextFieldOrTextAreaOrSearchField(object, info, rect);
}
void RenderThemeBlackBerry::adjustSearchFieldStyle(StyleResolver*, RenderStyle* style, Element*) const
{
setButtonStyle(style);
}
void RenderThemeBlackBerry::adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
{
static const float defaultControlFontPixelSize = 10;
static const float defaultCancelButtonSize = 13;
static const float minCancelButtonSize = 5;
// Scale the button size based on the font size
float fontScale = style->fontSize() / defaultControlFontPixelSize;
int cancelButtonSize = lroundf(std::max(minCancelButtonSize, defaultCancelButtonSize * fontScale));
Length length(cancelButtonSize, Fixed);
style->setWidth(length);
style->setHeight(length);
}
bool RenderThemeBlackBerry::paintSearchField(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
return paintTextFieldOrTextAreaOrSearchField(object, info, rect);
}
IntRect RenderThemeBlackBerry::convertToPaintingRect(RenderObject* inputRenderer, const RenderObject* partRenderer, LayoutRect partRect, const IntRect& localOffset) const
{
// Compute an offset between the part renderer and the input renderer.
LayoutSize offsetFromInputRenderer = -partRenderer->offsetFromAncestorContainer(inputRenderer);
// Move the rect into partRenderer's coords.
partRect.move(offsetFromInputRenderer);
// Account for the local drawing offset.
partRect.move(localOffset.x(), localOffset.y());
return pixelSnappedIntRect(partRect);
}
bool RenderThemeBlackBerry::paintSearchFieldCancelButton(RenderObject* cancelButtonObject, const PaintInfo& paintInfo, const IntRect& r)
{
Node* input = cancelButtonObject->node()->deprecatedShadowAncestorNode();
if (!input->renderer()->isBox())
return false;
RenderBox* inputRenderBox = toRenderBox(input->renderer());
LayoutRect inputContentBox = inputRenderBox->contentBoxRect();
// Make sure the scaled button stays square and will fit in its parent's box.
LayoutUnit cancelButtonSize = std::min(inputContentBox.width(), std::min<LayoutUnit>(inputContentBox.height(), r.height()));
// Calculate cancel button's coordinates relative to the input element.
// Center the button vertically. Round up though, so if it has to be one pixel off-center, it will
// be one pixel closer to the bottom of the field. This tends to look better with the text.
LayoutRect cancelButtonRect(cancelButtonObject->offsetFromAncestorContainer(inputRenderBox).width(),
inputContentBox.y() + (inputContentBox.height() - cancelButtonSize + 1) / 2, cancelButtonSize, cancelButtonSize);
IntRect paintingRect = convertToPaintingRect(inputRenderBox, cancelButtonObject, cancelButtonRect, r);
static Image* cancelImage = Image::loadPlatformResource("searchCancel").leakRef();
static Image* cancelPressedImage = Image::loadPlatformResource("searchCancelPressed").leakRef();
paintInfo.context->drawImage(isPressed(cancelButtonObject) ? cancelPressedImage : cancelImage,
cancelButtonObject->style()->colorSpace(), paintingRect);
return false;
}
void RenderThemeBlackBerry::adjustMenuListButtonStyle(StyleResolver*, RenderStyle* style, Element*) const
{
// These seem to be reasonable padding values from observation.
const int paddingLeft = 8;
const int paddingRight = 4;
const int minHeight = style->fontSize() * 2;
style->resetPadding();
style->setMinHeight(Length(minHeight, Fixed));
style->setLineHeight(RenderStyle::initialLineHeight());
style->setPaddingRight(Length(minHeight + paddingRight, Fixed));
style->setPaddingLeft(Length(paddingLeft, Fixed));
style->setCursor(CURSOR_WEBKIT_GRAB);
}
void RenderThemeBlackBerry::calculateButtonSize(RenderStyle* style) const
{
int size = style->fontSize();
Length length(size, Fixed);
if (style->appearance() == CheckboxPart || style->appearance() == RadioPart) {
style->setWidth(length);
style->setHeight(length);
return;
}
// If the width and height are both specified, then we have nothing to do.
if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
return;
if (style->width().isIntrinsicOrAuto())
style->setWidth(length);
if (style->height().isAuto())
style->setHeight(length);
}
bool RenderThemeBlackBerry::paintCheckbox(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
ASSERT(info.context);
GraphicsContext* context = info.context;
static RefPtr<Image> disabled, inactive, pressed, active, activeMark, disableMark, pressedMark;
if (!disabled) {
disabled = loadImage("core_checkbox_disabled");
inactive = loadImage("core_checkbox_inactive");
pressed = loadImage("core_checkbox_pressed");
active = loadImage("core_checkbox_active");
activeMark = loadImage("core_checkbox_active_mark");
disableMark = loadImage("core_checkbox_disabled_mark");
pressedMark = loadImage("core_checkbox_pressed_mark");
}
// Caculate where to put center checkmark.
FloatRect tmpRect(rect);
float centerX = ((float(inactive->width()) - float(activeMark->width())) / float(inactive->width()) * tmpRect.width() / 2) + tmpRect.x();
float centerY = ((float(inactive->height()) - float(activeMark->height())) / float(inactive->height()) * tmpRect.height() / 2) + tmpRect.y();
float width = float(activeMark->width()) / float(inactive->width()) * tmpRect.width();
float height = float(activeMark->height()) / float(inactive->height()) * tmpRect.height();
FloatRect centerRect(centerX, centerY, width, height);
if (isEnabled(object)) {
if (isPressed(object)) {
drawControl(context, rect, pressed.get());
if (isChecked(object)) {
drawControl(context, centerRect, pressedMark.get());
}
} else {
drawControl(context, rect, inactive.get());
if (isChecked(object)) {
drawControl(context, rect, active.get());
drawControl(context, centerRect, activeMark.get());
}
}
} else {
drawControl(context, rect, disabled.get());
if (isChecked(object))
drawControl(context, rect, disableMark.get());
}
return false;
}
void RenderThemeBlackBerry::setCheckboxSize(RenderStyle* style) const
{
calculateButtonSize(style);
}
bool RenderThemeBlackBerry::paintRadio(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
ASSERT(info.context);
GraphicsContext* context = info.context;
static RefPtr<Image> disabled, disabledDot, inactive, pressed, active, activeDot, pressedDot;
if (!disabled) {
disabled = loadImage("core_radiobutton_disabled");
disabledDot = loadImage("core_radiobutton_dot_disabled");
inactive = loadImage("core_radiobutton_inactive");
pressed = loadImage("core_radiobutton_pressed");
active = loadImage("core_radiobutton_active");
activeDot = loadImage("core_radiobutton_dot_selected");
pressedDot = loadImage("core_radiobutton_dot_pressed");
}
// Caculate where to put center circle.
FloatRect tmpRect(rect);
float centerX = ((float(inactive->width()) - float(activeDot->width())) / float(inactive->width()) * tmpRect.width() / 2)+ tmpRect.x();
float centerY = ((float(inactive->height()) - float(activeDot->height())) / float(inactive->height()) * tmpRect.height() / 2) + tmpRect.y();
float width = float(activeDot->width()) / float(inactive->width()) * tmpRect.width();
float height = float(activeDot->height()) / float(inactive->height()) * tmpRect.height();
FloatRect centerRect(centerX, centerY, width, height);
if (isEnabled(object)) {
if (isPressed(object)) {
drawControl(context, rect, pressed.get());
if (isChecked(object))
drawControl(context, centerRect, pressedDot.get());
} else {
drawControl(context, rect, inactive.get());
if (isChecked(object)) {
drawControl(context, rect, active.get());
drawControl(context, centerRect, activeDot.get());
}
}
} else {
drawControl(context, rect, disabled.get());
if (isChecked(object))
drawControl(context, rect, disabledDot.get());
}
return false;
}
void RenderThemeBlackBerry::setRadioSize(RenderStyle* style) const
{
calculateButtonSize(style);
}
// If this function returns false, WebCore assumes the button is fully decorated
bool RenderThemeBlackBerry::paintButton(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
ASSERT(info.context);
info.context->save();
GraphicsContext* context = info.context;
static RefPtr<Image> disabled, inactive, pressed;
if (!disabled) {
disabled = loadImage("core_button_disabled");
inactive = loadImage("core_button_inactive");
pressed = loadImage("core_button_pressed");
}
AffineTransform ctm = context->getCTM();
if (!isEnabled(object)) {
drawNineSlice(context, rect, ctm.xScale(), inactive.get(), largeSlice);
drawNineSlice(context, rect, ctm.xScale(), disabled.get(), largeSlice);
} else if (isPressed(object))
drawNineSlice(context, rect, ctm.xScale(), pressed.get(), largeSlice);
else
drawNineSlice(context, rect, ctm.xScale(), inactive.get(), largeSlice);
context->restore();
return false;
}
void RenderThemeBlackBerry::adjustMenuListStyle(StyleResolver* css, RenderStyle* style, Element* element) const
{
adjustMenuListButtonStyle(css, style, element);
}
static IntRect computeMenuListArrowButtonRect(const IntRect& rect)
{
// FIXME: The menu list arrow button should have a minimum and maximum width (to ensure usability) or
// scale with respect to the font size used in the menu list control or some combination of both.
return IntRect(IntPoint(rect.maxX() - rect.height(), rect.y()), IntSize(rect.height(), rect.height()));
}
bool RenderThemeBlackBerry::paintMenuList(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
ASSERT(info.context);
info.context->save();
GraphicsContext* context = info.context;
static RefPtr<Image> disabled, inactive, pressed, arrowUp, arrowUpDisabled;
if (!disabled) {
disabled = loadImage("core_button_disabled");
inactive = loadImage("core_button_inactive");
pressed = loadImage("core_button_pressed");
arrowUp = loadImage("core_dropdown_button_arrowup");
arrowUpDisabled = loadImage("core_dropdown_button_arrowup_disabled");
}
FloatRect arrowButtonRectangle(computeMenuListArrowButtonRect(rect));
float x = arrowButtonRectangle.x() + arrowButtonRectangle.width() / xPositionRatio;
float y = arrowButtonRectangle.y() + arrowButtonRectangle.height() * yPositionRatio;
float width = arrowButtonRectangle.width() / widthRatio;
float height = arrowButtonRectangle.height() * heightRatio;
FloatRect tmpRect(x, y, width, height);
AffineTransform ctm = context->getCTM();
if (!isEnabled(object)) {
drawNineSlice(context, rect, ctm.xScale(), inactive.get(), largeSlice);
drawNineSlice(context, rect, ctm.xScale(), disabled.get(), largeSlice);
drawControl(context, tmpRect, arrowUpDisabled.get());
} else if (isPressed(object)) {
drawNineSlice(context, rect, ctm.xScale(), pressed.get(), largeSlice);
drawControl(context, tmpRect, arrowUp.get());
} else {
drawNineSlice(context, rect, ctm.xScale(), inactive.get(), largeSlice);
drawControl(context, tmpRect, arrowUp.get());
}
context->restore();
return false;
}
bool RenderThemeBlackBerry::paintMenuListButton(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
return paintMenuList(object, info, rect);
}
void RenderThemeBlackBerry::adjustSliderThumbSize(RenderStyle* style, Element* element) const
{
float fullScreenMultiplier = 1;
ControlPart part = style->appearance();
if (part == MediaSliderThumbPart || part == MediaVolumeSliderThumbPart) {
RenderSlider* slider = determineRenderSlider(element->renderer());
if (slider)
fullScreenMultiplier = determineFullScreenMultiplier(toElement(slider->node()));
}
if (part == SliderThumbHorizontalPart || part == SliderThumbVerticalPart) {
style->setWidth(Length((part == SliderThumbVerticalPart ? sliderThumbHeight : sliderThumbWidth) * fullScreenMultiplier, Fixed));
style->setHeight(Length((part == SliderThumbVerticalPart ? sliderThumbWidth : sliderThumbHeight) * fullScreenMultiplier, Fixed));
} else if (part == MediaVolumeSliderThumbPart || part == MediaSliderThumbPart) {
style->setWidth(Length(mediaSliderThumbWidth * fullScreenMultiplier, Fixed));
style->setHeight(Length(mediaSliderThumbHeight * fullScreenMultiplier, Fixed));
}
}
bool RenderThemeBlackBerry::paintSliderTrack(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
const static int SliderTrackHeight = 5;
IntRect rect2;
if (object->style()->appearance() == SliderHorizontalPart) {
rect2.setHeight(SliderTrackHeight);
rect2.setWidth(rect.width());
rect2.setX(rect.x());
rect2.setY(rect.y() + (rect.height() - SliderTrackHeight) / 2);
} else {
rect2.setHeight(rect.height());
rect2.setWidth(SliderTrackHeight);
rect2.setX(rect.x() + (rect.width() - SliderTrackHeight) / 2);
rect2.setY(rect.y());
}
static Image* sliderTrack = Image::loadPlatformResource("core_progressindicator_bg").leakRef();
return paintSliderTrackRect(object, info, rect2, sliderTrack);
}
bool RenderThemeBlackBerry::paintSliderTrackRect(RenderObject* object, const PaintInfo& info, const IntRect& rect, Image* inactive)
{
ASSERT(info.context);
info.context->save();
GraphicsContext* context = info.context;
static RefPtr<Image> disabled;
if (!disabled)
disabled = loadImage("core_slider_fill_disabled");
if (rect.width() > rect.height()) {
if (isEnabled(object))
drawThreeSliceHorizontal(context, rect, inactive, mediumSlice);
else
drawThreeSliceHorizontal(context, rect, disabled.get(), (smallSlice - 1));
} else {
if (isEnabled(object))
drawThreeSliceVertical(context, rect, inactive, mediumSlice);
else
drawThreeSliceVertical(context, rect, disabled.get(), (smallSlice - 1));
}
context->restore();
return false;
}
bool RenderThemeBlackBerry::paintSliderThumb(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
ASSERT(info.context);
info.context->save();
GraphicsContext* context = info.context;
static RefPtr<Image> disabled, inactive, pressed, aura;
if (!disabled) {
disabled = loadImage("core_slider_handle_disabled");
inactive = loadImage("core_slider_handle");
pressed = loadImage("core_slider_handle_pressed");
aura = loadImage("core_slider_aura");
}
FloatRect tmpRect(rect);
float length = std::max(tmpRect.width(), tmpRect.height());
if (tmpRect.width() > tmpRect.height()) {
tmpRect.setY(tmpRect.y() - (length - tmpRect.height()) / 2);
tmpRect.setHeight(length);
} else {
tmpRect.setX(tmpRect.x() - (length - tmpRect.width()) / 2);
tmpRect.setWidth(length);
}
float auraHeight = length * auraRatio;
float auraWidth = auraHeight;
float auraX = tmpRect.x() - (auraWidth - tmpRect.width()) / 2;
float auraY = tmpRect.y() - (auraHeight - tmpRect.height()) / 2;
FloatRect auraRect(auraX, auraY, auraWidth, auraHeight);
if (!isEnabled(object)) {
// Disabled handle shrink 30%
tmpRect.move(tmpRect.width() * 0.075, tmpRect.height() * 0.075);
tmpRect.contract(tmpRect.width() * 0.15, tmpRect.height() * 0.15);
drawControl(context, tmpRect, disabled.get());
} else {
if (isPressed(object) || isHovered(object) || isFocused(object)) {
drawControl(context, tmpRect, pressed.get());
drawControl(context, auraRect, aura.get());
} else
drawControl(context, tmpRect, inactive.get());
}
context->restore();
return false;
}
void RenderThemeBlackBerry::adjustMediaControlStyle(StyleResolver*, RenderStyle* style, Element* element) const
{
float fullScreenMultiplier = determineFullScreenMultiplier(element);
HTMLMediaElement* mediaElement = toParentMediaElement(element);
if (!mediaElement)
return;
// We use multiples of mediaControlsHeight to make all objects scale evenly
Length zero(0, Fixed);
Length controlsHeight(mediaControlsHeight * fullScreenMultiplier, Fixed);
Length halfControlsWidth(mediaControlsHeight / 2 * fullScreenMultiplier, Fixed);
Length displayHeight(mediaControlsHeight / 3 * fullScreenMultiplier, Fixed);
Length volOffset(mediaControlsHeight * fullScreenMultiplier + 5, Fixed);
Length padding(mediaControlsHeight / 10 * fullScreenMultiplier, Fixed);
float fontSize = mediaControlsHeight / 3 * fullScreenMultiplier;
switch (style->appearance()) {
case MediaControlsBackgroundPart:
if (element->shadowPseudoId() == "-webkit-media-controls-placeholder")
style->setHeight(controlsHeight);
break;
case MediaPlayButtonPart:
style->setWidth(controlsHeight);
style->setHeight(controlsHeight);
break;
case MediaMuteButtonPart:
style->setWidth(controlsHeight);
style->setHeight(controlsHeight);
break;
case MediaRewindButtonPart:
// We hi-jack the Rewind Button ID to use it for the divider image
style->setWidth(halfControlsWidth);
style->setHeight(controlsHeight);
break;
case MediaEnterFullscreenButtonPart:
style->setWidth(controlsHeight);
style->setHeight(controlsHeight);
break;
case MediaExitFullscreenButtonPart:
style->setLeft(zero);
style->setWidth(controlsHeight);
style->setHeight(controlsHeight);
break;
case MediaCurrentTimePart:
case MediaTimeRemainingPart:
style->setHeight(displayHeight);
style->setPaddingRight(padding);
style->setPaddingLeft(padding);
style->setPaddingBottom(padding);
style->setFontSize(static_cast<int>(fontSize));
break;
case MediaVolumeSliderContainerPart:
style->setHeight(controlsHeight);
style->setBottom(volOffset);
break;
default:
break;
}
}
void RenderThemeBlackBerry::adjustSliderTrackStyle(StyleResolver*, RenderStyle* style, Element* element) const
{
float fullScreenMultiplier = determineFullScreenMultiplier(element);
// We use multiples of mediaControlsHeight to make all objects scale evenly
Length controlsHeight(mediaControlsHeight / 2 * fullScreenMultiplier, Fixed);
switch (style->appearance()) {
case MediaSliderPart:
case MediaVolumeSliderPart:
style->setHeight(controlsHeight);
break;
default:
break;
}
}
static bool paintMediaButton(GraphicsContext* context, const IntRect& rect, Image* image)
{
context->drawImage(image, ColorSpaceDeviceRGB, rect);
return false;
}
bool RenderThemeBlackBerry::paintMediaPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
HTMLMediaElement* mediaElement = toParentMediaElement(object);
if (!mediaElement)
return false;
static Image* mediaPlay = Image::loadPlatformResource("play").leakRef();
static Image* mediaPause = Image::loadPlatformResource("pause").leakRef();
static Image* mediaStop = Image::loadPlatformResource("stop").leakRef();
Image* nonPlayImage;
// The BlackBerry port sets the movieLoadType to LiveStream if and only if
// "stop" must be used instead of "pause".
if (mediaElement->movieLoadType() == MediaPlayer::LiveStream)
nonPlayImage = mediaStop;
else
nonPlayImage = mediaPause;
return paintMediaButton(paintInfo.context, rect, mediaElement->canPlay() ? mediaPlay : nonPlayImage);
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
// We hi-jack the Rewind Button code to use it for the divider image
bool RenderThemeBlackBerry::paintMediaRewindButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
HTMLMediaElement* mediaElement = toParentMediaElement(object);
if (!mediaElement)
return false;
if (!mediaElement->isFullscreen())
return false;
static Image* divider = Image::loadPlatformResource("divider").leakRef();
return paintMediaButton(paintInfo.context, rect, divider);
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
bool RenderThemeBlackBerry::paintMediaMuteButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
HTMLMediaElement* mediaElement = toParentMediaElement(object);
if (!mediaElement)
return false;
static Image* speaker = Image::loadPlatformResource("speaker").leakRef();
return paintMediaButton(paintInfo.context, rect, speaker);
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
bool RenderThemeBlackBerry::paintMediaFullscreenButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
HTMLMediaElement* mediaElement = toParentMediaElement(object);
if (!mediaElement)
return false;
static Image* mediaEnterFullscreen = Image::loadPlatformResource("fullscreen").leakRef();
static Image* mediaExitFullscreen = Image::loadPlatformResource("back").leakRef();
Image* buttonImage = mediaEnterFullscreen;
IntRect currentRect(rect);
#if ENABLE(FULLSCREEN_API)
if (mediaElement->document()->webkitIsFullScreen() && mediaElement->document()->webkitCurrentFullScreenElement() == mediaElement) {
buttonImage = mediaExitFullscreen;
IntRect fullscreenRect(rect.x() + (1 - mediaFullscreenButtonWidthRatio) * rect.width() / 2, rect.y() + (1 - mediaFullscreenButtonHeightRatio) * rect.height() / 2,
rect.width() * mediaFullscreenButtonWidthRatio, rect.height() * mediaFullscreenButtonHeightRatio);
currentRect = fullscreenRect;
}
#endif
return paintMediaButton(paintInfo.context, currentRect, buttonImage);
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
bool RenderThemeBlackBerry::paintMediaSliderTrack(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
HTMLMediaElement* mediaElement = toParentMediaElement(object);
if (!mediaElement)
return false;
float fullScreenMultiplier = determineFullScreenMultiplier(mediaElement);
float loaded = mediaElement->percentLoaded();
float position = mediaElement->duration() > 0 ? (mediaElement->currentTime() / mediaElement->duration()) : 0;
int intrinsicHeight = ceil(mediaSliderThumbHeight / 4);
int x = ceil(rect.x() + mediaSliderEndAdjust * fullScreenMultiplier);
int y = ceil(rect.y() + (mediaControlsHeight / 2 - intrinsicHeight) / 2 * fullScreenMultiplier + fullScreenMultiplier / 2);
int w = ceil(rect.width() - mediaSliderEndAdjust * 2 * fullScreenMultiplier);
int h = ceil(intrinsicHeight * fullScreenMultiplier);
IntRect rect2(x, y, w, h);
// We subtract a small amount from the width in the calculation below to
// prevent the played bar from poking out past the thumb accidentally.
int wPlayed = ceil((w - mediaSliderEndAdjust) * position);
// We adjust the buffered bar to make it visible to the right of the thumb.
// A small amount is subtracted from the mediaSliderThumbWidth in the first
// part of the expression to account for the fact that the slider track's
// width was shortened and x position was incremented above (to make sure
// its rounded ends get covered by the thumb).
int wLoaded = ceil((w - (mediaSliderThumbWidth - mediaSliderEndAdjust) * fullScreenMultiplier) * loaded + mediaSliderThumbWidth * fullScreenMultiplier);
IntRect played(x, y, wPlayed, h);
IntRect buffered(x, y, wLoaded > w ? w : wLoaded, h);
static Image* mediaBackground = Image::loadPlatformResource("core_slider_video_bg").leakRef();
static Image* mediaPlayer = Image::loadPlatformResource("core_slider_played_bg").leakRef();
static Image* mediaCache = Image::loadPlatformResource("core_slider_cache").leakRef();
bool result = paintSliderTrackRect(object, paintInfo, rect2, mediaBackground);
if (loaded > 0 || position > 0) {
// This is to paint buffered bar.
paintSliderTrackRect(object, paintInfo, buffered, mediaCache);
// This is to paint played part of bar (left of slider thumb) using selection color.
paintSliderTrackRect(object, paintInfo, played, mediaPlayer);
}
return result;
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
bool RenderThemeBlackBerry::paintMediaSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
static Image* disabledMediaSliderThumb = Image::loadPlatformResource("core_slider_handle_disabled").leakRef();
static Image* pressedMediaSliderThumb = Image::loadPlatformResource("core_slider_handle_pressed").leakRef();
static Image* mediaSliderThumb = Image::loadPlatformResource("core_media_handle").leakRef();
if (!isEnabled(object))
return paintMediaButton(paintInfo.context, rect, disabledMediaSliderThumb);
if (isPressed(object) || isHovered(object) || isFocused(object))
return paintMediaButton(paintInfo.context, rect, pressedMediaSliderThumb);
return paintMediaButton(paintInfo.context, rect, mediaSliderThumb);
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
bool RenderThemeBlackBerry::paintMediaVolumeSliderTrack(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
HTMLMediaElement* mediaElement = toParentMediaElement(object);
if (!mediaElement)
return false;
float fullScreenMultiplier = determineFullScreenMultiplier(mediaElement);
float volume = mediaElement->volume() > 0 ? mediaElement->volume() : 0;
int intrinsicHeight = ceil(mediaSliderThumbHeight / 4);
int x = ceil(rect.x() + (mediaControlsHeight - intrinsicHeight) / 2 * fullScreenMultiplier - fullScreenMultiplier / 2);
int y = ceil(rect.y() + (mediaControlsHeight - intrinsicHeight) / 2 * fullScreenMultiplier + fullScreenMultiplier / 2);
int w = ceil(rect.width() - (mediaControlsHeight - intrinsicHeight) * fullScreenMultiplier + fullScreenMultiplier / 2);
int h = ceil(intrinsicHeight * fullScreenMultiplier);
IntRect rect2(x, y, w, h);
IntRect volumeRect(x, y, ceil(w * volume), h);
static Image* volumeBackground = Image::loadPlatformResource("core_slider_video_bg").leakRef();
static Image* volumeBar = Image::loadPlatformResource("core_slider_played_bg").leakRef();
// This is to paint main volume slider bar.
bool result = paintSliderTrackRect(object, paintInfo, rect2, volumeBackground);
if (volume > 0) {
// This is to paint volume bar (left of volume slider thumb) using selection color.
result |= paintSliderTrackRect(object, paintInfo, volumeRect, volumeBar);
}
return result;
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
bool RenderThemeBlackBerry::paintMediaVolumeSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
#if ENABLE(VIDEO)
RenderSlider* slider = determineRenderSlider(object);
float fullScreenMultiplier = slider ? determineFullScreenMultiplier(toElement(slider->node())) : 1;
int intrinsicHeight = ceil(mediaSliderThumbHeight / 4);
int y = ceil(rect.y() + (mediaControlsHeight / 2 - intrinsicHeight / 2) / 2 * fullScreenMultiplier);
IntRect adjustedRect(rect.x(), y, rect.width(), rect.height());
return paintMediaSliderThumb(object, paintInfo, adjustedRect);
#else
UNUSED_PARAM(object);
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(rect);
return false;
#endif
}
Color RenderThemeBlackBerry::platformFocusRingColor() const
{
return focusRingPen;
}
#if ENABLE(TOUCH_EVENTS)
Color RenderThemeBlackBerry::platformTapHighlightColor() const
{
return Color(0, 168, 223, 50);
}
#endif
Color RenderThemeBlackBerry::platformActiveSelectionBackgroundColor() const
{
return Color(0, 168, 223, 50);
}
double RenderThemeBlackBerry::animationRepeatIntervalForProgressBar(RenderProgress* renderProgress) const
{
return renderProgress->isDeterminate() ? 0.0 : 0.1;
}
double RenderThemeBlackBerry::animationDurationForProgressBar(RenderProgress* renderProgress) const
{
return renderProgress->isDeterminate() ? 0.0 : 2.0;
}
bool RenderThemeBlackBerry::paintProgressTrackRect(const PaintInfo& info, const IntRect& rect, Image* image)
{
ASSERT(info.context);
info.context->save();
GraphicsContext* context = info.context;
drawThreeSliceHorizontal(context, rect, image, mediumSlice);
context->restore();
return false;
}
static void drawProgressTexture(GraphicsContext* gc, const FloatRect& rect, int n, Image* image)
{
if (!image)
return;
float finalTexturePercentage = (int(rect.width()) % int(progressTextureUnitWidth)) / progressTextureUnitWidth;
FloatSize dstSlice(progressTextureUnitWidth, rect.height() - 2);
FloatRect srcRect(1, 2, image->width() - 2, image->height() - 4);
FloatRect dstRect(FloatPoint(rect.location().x() + 1, rect.location().y() + 1), dstSlice);
for (int i = 0; i < n; i++) {
gc->drawImage(image, ColorSpaceDeviceRGB, dstRect, srcRect);
dstRect.move(dstSlice.width(), 0);
}
if (finalTexturePercentage) {
srcRect.setWidth(srcRect.width() * finalTexturePercentage * finalTexturePercentage);
dstRect.setWidth(dstRect.width() * finalTexturePercentage * finalTexturePercentage);
gc->drawImage(image, ColorSpaceDeviceRGB, dstRect, srcRect);
}
}
bool RenderThemeBlackBerry::paintProgressBar(RenderObject* object, const PaintInfo& info, const IntRect& rect)
{
if (!object->isProgress())
return true;
RenderProgress* renderProgress = toRenderProgress(object);
static Image* progressTrack = Image::loadPlatformResource("core_progressindicator_bg").leakRef();
static Image* progressBar = Image::loadPlatformResource("core_progressindicator_progress").leakRef();
static Image* progressPattern = Image::loadPlatformResource("core_progressindicator_pattern").leakRef();
static Image* progressComplete = Image::loadPlatformResource("core_progressindicator_complete").leakRef();
paintProgressTrackRect(info, rect, progressTrack);
IntRect progressRect = rect;
progressRect.setX(progressRect.x() + 1);
progressRect.setHeight(progressRect.height() - 2);
progressRect.setY(progressRect.y() + 1);
if (renderProgress->isDeterminate())
progressRect.setWidth((progressRect.width() - progressMinWidth) * renderProgress->position() + progressMinWidth - 2);
else {
// Animating
progressRect.setWidth(progressRect.width() - 2);
}
if (renderProgress->position() < 1) {
paintProgressTrackRect(info, progressRect, progressBar);
int loop = floor((progressRect.width() - 2) / progressTextureUnitWidth);
progressRect.setWidth(progressRect.width() - 2);
drawProgressTexture(info.context, progressRect, loop, progressPattern);
} else
paintProgressTrackRect(info, progressRect, progressComplete);
return false;
}
Color RenderThemeBlackBerry::platformActiveTextSearchHighlightColor() const
{
return Color(255, 150, 50); // Orange.
}
Color RenderThemeBlackBerry::platformInactiveTextSearchHighlightColor() const
{
return Color(255, 255, 0); // Yellow.
}
bool RenderThemeBlackBerry::supportsDataListUI(const AtomicString& type) const
{
#if ENABLE(DATALIST_ELEMENT)
// We support all non-popup driven types.
return type == InputTypeNames::text() || type == InputTypeNames::search() || type == InputTypeNames::url()
|| type == InputTypeNames::telephone() || type == InputTypeNames::email() || type == InputTypeNames::number()
|| type == InputTypeNames::range();
#else
return false;
#endif
}
#if ENABLE(DATALIST_ELEMENT)
IntSize RenderThemeBlackBerry::sliderTickSize() const
{
return IntSize(1, 3);
}
int RenderThemeBlackBerry::sliderTickOffsetFromTrackCenter() const
{
return -9;
}
#endif
} // namespace WebCore
| 39.086441 | 170 | 0.710659 | viewdy |
1e1a789ac10ad2cc3cb27a15f3a4ecf1decd6c1a | 979 | cpp | C++ | robot_path_planner/src/RobotPathPlannerServer.cpp | 565353780/robot-manage-ros | b39701ee709a337a03420739d2137cfeadfdde4b | [
"MIT"
] | null | null | null | robot_path_planner/src/RobotPathPlannerServer.cpp | 565353780/robot-manage-ros | b39701ee709a337a03420739d2137cfeadfdde4b | [
"MIT"
] | null | null | null | robot_path_planner/src/RobotPathPlannerServer.cpp | 565353780/robot-manage-ros | b39701ee709a337a03420739d2137cfeadfdde4b | [
"MIT"
] | null | null | null | #include <robot_path_planner/RobotPathPlannerServer.h>
bool RobotPathPlannerServer::getNavPoseVecCallback(
robot_path_planner::TargetPoseVecToNavPoseVec::Request &req,
robot_path_planner::TargetPoseVecToNavPoseVec::Response &res)
{
const std::vector<geometry_msgs::Pose>& target_pose_vec =
req.target_pose_vec;
const double& delta_rotation_angle = req.delta_rotation_angle;
const double& delta_move_dist = req.delta_move_dist;
std::vector<geometry_msgs::Pose> nav_pose_vec;
if(!robot_path_planner_.getNavPoseVec(
target_pose_vec,
delta_rotation_angle,
delta_move_dist,
nav_pose_vec))
{
std::cout << "[ERROR][RobotPathPlannerServer::getNavPoseVecCallback]\n" <<
"\t getNavPoseVec failed!\n";
return false;
}
res.nav_pose_vec = nav_pose_vec;
robot_path_planner::PoseVec nav_pose_vec_copy;
nav_pose_vec_copy.pose_vec = nav_pose_vec;
nav_pose_vec_pub_.publish(nav_pose_vec_copy);
return true;
}
| 29.666667 | 78 | 0.758938 | 565353780 |
1e1e9e92763ae05ea620dcc4d1a2933f0a45c678 | 7,886 | cpp | C++ | libnavi/src/BinderClient.cpp | rm-medina/agl-service-navigation | b9fa50ad33af4c3425d7198beaa63b783da2f62c | [
"Apache-2.0"
] | null | null | null | libnavi/src/BinderClient.cpp | rm-medina/agl-service-navigation | b9fa50ad33af4c3425d7198beaa63b783da2f62c | [
"Apache-2.0"
] | null | null | null | libnavi/src/BinderClient.cpp | rm-medina/agl-service-navigation | b9fa50ad33af4c3425d7198beaa63b783da2f62c | [
"Apache-2.0"
] | 4 | 2017-12-12T03:59:55.000Z | 2019-03-12T19:47:26.000Z | // Copyright 2017 AW SOFTWARE CO.,LTD
// Copyright 2017 AISIN AW CO.,LTD
#include <cstring>
#include "BinderClient.h"
#include "JsonRequestGenerator.h"
#include "JsonResponseAnalyzer.h"
#include "traces.h"
/**
* @brief constructor
*/
BinderClient::BinderClient() : navicoreListener(nullptr)
{
requestMng = new RequestManage();
}
/**
* @brief Destructor
*/
BinderClient::~BinderClient()
{
delete requestMng;
}
/**
* @brief Connect with the Binder server
*/
bool BinderClient::ConnectServer(std::string url, naviapi::NavicoreListener* listener)
{
this->navicoreListener = listener;
if( !requestMng->Connect(url.c_str(), this))
{
TRACE_ERROR("cannot connect to binding service.\n");
return false;
}
return true;
}
/**
* @brief Call Genivi's GetPosition via Binder and get the result
*/
void BinderClient::NavicoreGetPosition(const std::vector< int32_t >& valuesToReturn)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
std::string req_json = JsonRequestGenerator::CreateRequestGetPosition(valuesToReturn);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_GETPOSITION, req_json.c_str()) )
{
TRACE_DEBUG("navicore_getposition success.\n");
}
else
{
TRACE_ERROR("navicore_getposition failed.\n");
}
}
}
/**
* @brief Get route handle
*/
void BinderClient::NavicoreGetAllRoutes()
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
std::string req_json = JsonRequestGenerator::CreateRequestGetAllRoutes();
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_GETALLROUTES, req_json.c_str()) )
{
TRACE_DEBUG("navicore_getallroutes success.\n");
}
else
{
TRACE_ERROR("navicore_getallroutes failed.\n");
}
}
}
/**
* @brief Generate route handle
*/
void BinderClient::NavicoreCreateRoute(const uint32_t& sessionHandle)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
uint32_t session = requestMng->GetSessionHandle();
std::string req_json = JsonRequestGenerator::CreateRequestCreateRoute(&session);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_CREATEROUTE, req_json.c_str()) )
{
TRACE_DEBUG("navicore_createroute success.\n");
}
else
{
TRACE_ERROR("navicore_createroute failed.\n");
}
}
}
/**
* @brief Pause demo
*/
void BinderClient::NavicorePauseSimulation(const uint32_t& sessionHandle)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
uint32_t session = requestMng->GetSessionHandle();
std::string req_json = JsonRequestGenerator::CreateRequestPauseSimulation(&session);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_PAUSESIMULATION, req_json.c_str()) )
{
TRACE_DEBUG("navicore_pausesimulationmode success.\n");
}
else
{
TRACE_ERROR("navicore_pausesimulationmode failed.\n");
}
}
}
/**
* @brief Simulation mode setting
*/
void BinderClient::NavicoreSetSimulationMode(const uint32_t& sessionHandle, const bool& activate)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
uint32_t session = requestMng->GetSessionHandle();
std::string req_json = JsonRequestGenerator::CreateRequestSetSimulationMode(&session, &activate);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_SETSIMULATIONMODE, req_json.c_str()) )
{
TRACE_DEBUG("navicore_setsimulationmode success.\n");
}
else
{
TRACE_ERROR("navicore_setsimulationmode failed.\n");
}
}
}
/**
* @brief Delete route information
*/
void BinderClient::NavicoreCancelRouteCalculation(const uint32_t& sessionHandle, const uint32_t& routeHandle)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
uint32_t session = requestMng->GetSessionHandle();
std::string req_json = JsonRequestGenerator::CreateRequestCancelRouteCalculation(&session, &routeHandle);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_CANCELROUTECALCULATION, req_json.c_str()) )
{
TRACE_DEBUG("navicore_cancelroutecalculation success.\n");
}
else
{
TRACE_ERROR("navicore_cancelroutecalculation failed.\n");
}
}
}
/**
* @brief Destination setting
*/
void BinderClient::NavicoreSetWaypoints(const uint32_t& sessionHandle, const uint32_t& routeHandle, const bool& startFromCurrentPosition, const std::vector<naviapi::Waypoint>& waypointsList)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
uint32_t session = requestMng->GetSessionHandle();
uint32_t route = requestMng->GetRouteHandle();
std::string req_json = JsonRequestGenerator::CreateRequestSetWaypoints(&session, &route,
&startFromCurrentPosition, &waypointsList);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_SETWAYPOINTS, req_json.c_str()) )
{
TRACE_DEBUG("navicore_setwaypoints success.\n");
}
else
{
TRACE_ERROR("navicore_setwaypoints failed.\n");
}
}
}
/**
* @brief Route calculation processing
*/
void BinderClient::NavicoreCalculateRoute(const uint32_t& sessionHandle, const uint32_t& routeHandle)
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
uint32_t session = requestMng->GetSessionHandle();
uint32_t route = requestMng->GetRouteHandle();
std::string req_json = JsonRequestGenerator::CreateRequestCalculateroute(&session, &route);
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_CALCULATEROUTE, req_json.c_str()) )
{
TRACE_DEBUG("navicore_calculateroute success.\n");
}
else
{
TRACE_ERROR("navicore_calculateroute failed.\n");
}
}
}
/**
* @brief Retrieve session information
* @return Map of session information
*/
void BinderClient::NavicoreGetAllSessions()
{
// Check if it is connected
if( requestMng->IsConnect() )
{
// JSON request generation
std::string req_json = JsonRequestGenerator::CreateRequestGetAllSessions();
// Send request
if( requestMng->CallBinderAPI(API_NAME, VERB_GETALLSESSIONS, req_json.c_str()) )
{
TRACE_DEBUG("navicore_getallsessions success.\n");
}
else
{
TRACE_ERROR("navicore_getallsessions failed.\n");
}
}
}
void BinderClient::OnReply(struct json_object* reply)
{
struct json_object* requestObject = nullptr;
json_object_object_get_ex(reply, "request", &requestObject);
struct json_object* infoObject = nullptr;
json_object_object_get_ex(requestObject, "info", &infoObject);
const char* info = json_object_get_string(infoObject);
char tmpVerb[256];
strcpy(tmpVerb, info);
// Create a new JSON response
const char* json_str = json_object_to_json_string_ext(reply, JSON_C_TO_STRING_PRETTY);
std::string response_json = std::string( json_str );
if (strcmp(VERB_GETALLSESSIONS, tmpVerb) == 0)
{
std::map<uint32_t, std::string> ret = JsonResponseAnalyzer::AnalyzeResponseGetAllSessions(response_json);
// keep session handle
requestMng->SetSessionHandle( ret.begin()->first );
this->navicoreListener->getAllSessions_reply(ret);
}
else if (strcmp(VERB_GETPOSITION, tmpVerb) == 0)
{
std::map< int32_t, naviapi::variant > ret = JsonResponseAnalyzer::AnalyzeResponseGetPosition(response_json);
this->navicoreListener->getPosition_reply(ret);
}
else if (strcmp(VERB_GETALLROUTES, tmpVerb) == 0)
{
std::vector< uint32_t > ret = JsonResponseAnalyzer::AnalyzeResponseGetAllRoutes(response_json);
// route handle
if(ret.size() > 0)
{
requestMng->SetRouteHandle(ret[0]);
}
this->navicoreListener->getAllRoutes_reply(ret);
}
else if (strcmp(VERB_CREATEROUTE, tmpVerb) == 0)
{
uint32_t ret = JsonResponseAnalyzer::AnalyzeResponseCreateRoute(response_json);
// keep route handle
requestMng->SetRouteHandle(ret);
this->navicoreListener->createRoute_reply(ret);
}
}
| 24.955696 | 190 | 0.731676 | rm-medina |
1e1fa20d104929410e212682c30692a0aeafa0d6 | 487 | hpp | C++ | PP/concepts/pointer_to_member.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | 3 | 2019-07-12T23:12:24.000Z | 2019-09-05T07:57:45.000Z | PP/concepts/pointer_to_member.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | PP/concepts/pointer_to_member.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | #pragma once
#include <PP/compose.hpp>
#include <PP/get_type.hpp>
#include <PP/overloaded.hpp>
#include <PP/remove_cv.hpp>
namespace PP
{
PP_CIA is_pointer_to_member =
compose(overloaded(
[]<typename T, typename Class>(type_t<T Class::*>)
{
return true;
},
[](auto&&)
{
return false;
}),
remove_cv);
PP_CONCEPT1(pointer_to_member)
}
| 21.173913 | 66 | 0.49692 | Petkr |
1e22bc5a4a712c75a0841744a4254fd788f83564 | 48,889 | cpp | C++ | src/mongo/db/s/resharding/resharding_txn_cloner_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/resharding/resharding_txn_cloner_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/resharding/resharding_txn_cloner_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <boost/optional/optional_io.hpp>
#include <vector>
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/cancelable_operation_context.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/logical_session_cache_noop.h"
#include "mongo/db/persistent_task_store.h"
#include "mongo/db/pipeline/process_interface/shardsvr_process_interface.h"
#include "mongo/db/repl/storage_interface_impl.h"
#include "mongo/db/repl/wait_for_majority_service.h"
#include "mongo/db/s/resharding/resharding_server_parameters_gen.h"
#include "mongo/db/s/resharding/resharding_txn_cloner.h"
#include "mongo/db/s/resharding/resharding_txn_cloner_progress_gen.h"
#include "mongo/db/s/shard_server_test_fixture.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/session_catalog_mongod.h"
#include "mongo/db/session_txn_record_gen.h"
#include "mongo/db/transaction_participant.h"
#include "mongo/db/vector_clock_metadata_hook.h"
#include "mongo/executor/network_interface_factory.h"
#include "mongo/executor/thread_pool_task_executor.h"
#include "mongo/idl/server_parameter_test_util.h"
#include "mongo/rpc/metadata/egress_metadata_hook_list.h"
#include "mongo/s/catalog/sharding_catalog_client_mock.h"
#include "mongo/s/catalog/type_shard.h"
#include "mongo/s/catalog_cache_loader_mock.h"
#include "mongo/s/database_version.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/concurrency/thread_pool.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace mongo {
namespace {
class ReshardingTxnClonerTest : public ShardServerTestFixture {
void setUp() {
// Don't call ShardServerTestFixture::setUp so we can install a mock catalog cache loader.
ShardingMongodTestFixture::setUp();
replicationCoordinator()->alwaysAllowWrites(true);
serverGlobalParams.clusterRole = ClusterRole::ShardServer;
_clusterId = OID::gen();
ShardingState::get(getServiceContext())->setInitialized(kTwoShardIdList[0], _clusterId);
auto mockLoader = std::make_unique<CatalogCacheLoaderMock>();
// The config database's primary shard is always config, and it is always sharded.
mockLoader->setDatabaseRefreshReturnValue(
DatabaseType{NamespaceString::kConfigDb.toString(),
ShardId::kConfigServerId,
DatabaseVersion::makeFixed()});
// The config.transactions collection is always unsharded.
mockLoader->setCollectionRefreshReturnValue(
{ErrorCodes::NamespaceNotFound, "collection not found"});
CatalogCacheLoader::set(getServiceContext(), std::move(mockLoader));
uassertStatusOK(
initializeGlobalShardingStateForMongodForTest(ConnectionString(kConfigHostAndPort)));
configTargeterMock()->setFindHostReturnValue(kConfigHostAndPort);
for (const auto& shardId : kTwoShardIdList) {
auto shardTargeter = RemoteCommandTargeterMock::get(
uassertStatusOK(shardRegistry()->getShard(operationContext(), shardId))
->getTargeter());
shardTargeter->setFindHostReturnValue(makeHostAndPort(shardId));
}
WaitForMajorityService::get(getServiceContext()).startup(getServiceContext());
// onStepUp() relies on the storage interface to create the config.transactions table.
repl::StorageInterface::set(getServiceContext(),
std::make_unique<repl::StorageInterfaceImpl>());
MongoDSessionCatalog::onStepUp(operationContext());
LogicalSessionCache::set(getServiceContext(), std::make_unique<LogicalSessionCacheNoop>());
}
void tearDown() {
WaitForMajorityService::get(getServiceContext()).shutDown();
ShardServerTestFixture::tearDown();
}
/**
* Override the CatalogClient to make CatalogClient::getAllShards automatically return the
* expected shards. We cannot mock the network responses for the ShardRegistry reload, since the
* ShardRegistry reload is done over DBClient, not the NetworkInterface, and there is no
* DBClientMock analogous to the NetworkInterfaceMock.
*/
std::unique_ptr<ShardingCatalogClient> makeShardingCatalogClient() {
class StaticCatalogClient final : public ShardingCatalogClientMock {
public:
StaticCatalogClient(std::vector<ShardId> shardIds) : _shardIds(std::move(shardIds)) {}
StatusWith<repl::OpTimeWith<std::vector<ShardType>>> getAllShards(
OperationContext* opCtx, repl::ReadConcernLevel readConcern) override {
std::vector<ShardType> shardTypes;
for (const auto& shardId : _shardIds) {
const ConnectionString cs = ConnectionString::forReplicaSet(
shardId.toString(), {makeHostAndPort(shardId)});
ShardType sType;
sType.setName(cs.getSetName());
sType.setHost(cs.toString());
shardTypes.push_back(std::move(sType));
};
return repl::OpTimeWith<std::vector<ShardType>>(shardTypes);
}
private:
const std::vector<ShardId> _shardIds;
};
return std::make_unique<StaticCatalogClient>(kTwoShardIdList);
}
protected:
const UUID kDefaultReshardingId = UUID::gen();
const std::vector<ShardId> kTwoShardIdList{_myShardName, {"otherShardName"}};
const std::vector<ReshardingSourceId> kTwoSourceIdList = {
{kDefaultReshardingId, _myShardName}, {kDefaultReshardingId, ShardId("otherShardName")}};
const std::vector<DurableTxnStateEnum> kDurableTxnStateEnumValues = {
DurableTxnStateEnum::kPrepared,
DurableTxnStateEnum::kCommitted,
DurableTxnStateEnum::kAborted,
DurableTxnStateEnum::kInProgress};
std::vector<boost::optional<DurableTxnStateEnum>> getDurableTxnStatesAndBoostNone() {
std::vector<boost::optional<DurableTxnStateEnum>> statesAndBoostNone = {boost::none};
for (auto state : kDurableTxnStateEnumValues) {
statesAndBoostNone.push_back(state);
}
return statesAndBoostNone;
}
BSONObj makeTxn(boost::optional<DurableTxnStateEnum> multiDocTxnState = boost::none) {
auto txn = SessionTxnRecord(
makeLogicalSessionIdForTest(), 0, repl::OpTime(Timestamp::min(), 0), Date_t());
txn.setState(multiDocTxnState);
return txn.toBSON();
}
LogicalSessionId getTxnRecordLsid(BSONObj txnRecord) {
return SessionTxnRecord::parse(IDLParserErrorContext("ReshardingTxnClonerTest"), txnRecord)
.getSessionId();
}
std::vector<BSONObj> makeSortedTxns(int numTxns) {
std::vector<BSONObj> txns;
for (int i = 0; i < numTxns; i++) {
txns.emplace_back(makeTxn());
}
std::sort(txns.begin(), txns.end(), [this](BSONObj a, BSONObj b) {
return getTxnRecordLsid(a).toBSON().woCompare(getTxnRecordLsid(b).toBSON()) < 0;
});
return txns;
}
void onCommandReturnTxnBatch(std::vector<BSONObj> firstBatch,
CursorId cursorId,
bool isFirstBatch) {
onCommand([&](const executor::RemoteCommandRequest& request) {
return CursorResponse(
NamespaceString::kSessionTransactionsTableNamespace, cursorId, firstBatch)
.toBSON(isFirstBatch ? CursorResponse::ResponseType::InitialResponse
: CursorResponse::ResponseType::SubsequentResponse);
});
}
void onCommandReturnTxns(std::vector<BSONObj> firstBatch, std::vector<BSONObj> secondBatch) {
CursorId cursorId(0);
if (secondBatch.size() > 0) {
cursorId = 123;
}
onCommand([&](const executor::RemoteCommandRequest& request) {
return CursorResponse(
NamespaceString::kSessionTransactionsTableNamespace, cursorId, firstBatch)
.toBSON(CursorResponse::ResponseType::InitialResponse);
});
if (secondBatch.size() == 0) {
return;
}
onCommand([&](const executor::RemoteCommandRequest& request) {
return CursorResponse(NamespaceString::kSessionTransactionsTableNamespace,
CursorId{0},
secondBatch)
.toBSON(CursorResponse::ResponseType::SubsequentResponse);
});
}
void seedTransactionOnRecipient(LogicalSessionId sessionId,
TxnNumber txnNum,
bool multiDocTxn) {
auto opCtx = operationContext();
opCtx->setLogicalSessionId(sessionId);
opCtx->setTxnNumber(txnNum);
if (multiDocTxn) {
opCtx->setInMultiDocumentTransaction();
}
MongoDOperationContextSession ocs(opCtx);
auto txnParticipant = TransactionParticipant::get(opCtx);
ASSERT(txnParticipant);
if (multiDocTxn) {
txnParticipant.beginOrContinue(
opCtx, {txnNum}, false /* autocommit */, true /* startTransaction */);
} else {
txnParticipant.beginOrContinue(
opCtx, {txnNum}, boost::none /* autocommit */, boost::none /* startTransaction */);
}
}
void checkTxnHasBeenUpdated(LogicalSessionId sessionId, TxnNumber txnNum) {
DBDirectClient client(operationContext());
// The same logical session entry may be inserted more than once by a test case, so use a
// $natural sort to find the most recently inserted entry.
FindCommandRequest findCmd{NamespaceString::kRsOplogNamespace};
findCmd.setFilter(BSON(repl::OplogEntryBase::kSessionIdFieldName << sessionId.toBSON()));
findCmd.setSort(BSON("$natural" << -1));
auto bsonOplog = client.findOne(std::move(findCmd));
ASSERT(!bsonOplog.isEmpty());
auto oplogEntry = repl::MutableOplogEntry::parse(bsonOplog).getValue();
ASSERT_EQ(oplogEntry.getTxnNumber().get(), txnNum);
ASSERT_BSONOBJ_EQ(oplogEntry.getObject(), BSON("$sessionMigrateInfo" << 1));
ASSERT_BSONOBJ_EQ(oplogEntry.getObject2().get(), BSON("$incompleteOplogHistory" << 1));
ASSERT(oplogEntry.getOpType() == repl::OpTypeEnum::kNoop);
auto bsonTxn =
client.findOne(NamespaceString::kSessionTransactionsTableNamespace,
BSON(SessionTxnRecord::kSessionIdFieldName << sessionId.toBSON()));
ASSERT(!bsonTxn.isEmpty());
auto txn = SessionTxnRecord::parse(
IDLParserErrorContext("resharding config transactions cloning test"), bsonTxn);
ASSERT_EQ(txn.getTxnNum(), txnNum);
ASSERT_EQ(txn.getLastWriteOpTime(), oplogEntry.getOpTime());
}
void checkTxnHasNotBeenUpdated(LogicalSessionId sessionId, TxnNumber txnNum) {
auto opCtx = operationContext();
opCtx->setLogicalSessionId(sessionId);
MongoDOperationContextSession ocs(opCtx);
auto txnParticipant = TransactionParticipant::get(opCtx);
DBDirectClient client(operationContext());
auto bsonOplog =
client.findOne(NamespaceString::kRsOplogNamespace,
BSON(repl::OplogEntryBase::kSessionIdFieldName << sessionId.toBSON()));
ASSERT_BSONOBJ_EQ(bsonOplog, {});
ASSERT_EQ(txnParticipant.getActiveTxnNumberAndRetryCounter().getTxnNumber(), txnNum);
}
boost::optional<ReshardingTxnClonerProgress> getTxnCloningProgress(
const ReshardingSourceId& sourceId) {
DBDirectClient client(operationContext());
auto progressDoc = client.findOne(
NamespaceString::kReshardingTxnClonerProgressNamespace,
BSON(ReshardingTxnClonerProgress::kSourceIdFieldName << sourceId.toBSON()));
if (progressDoc.isEmpty()) {
return boost::none;
}
return ReshardingTxnClonerProgress::parse(
IDLParserErrorContext("ReshardingTxnClonerProgress"), progressDoc);
}
boost::optional<LogicalSessionId> getProgressLsid(const ReshardingSourceId& sourceId) {
auto progressDoc = getTxnCloningProgress(sourceId);
return progressDoc ? boost::optional<LogicalSessionId>(progressDoc->getProgress())
: boost::none;
}
std::shared_ptr<executor::ThreadPoolTaskExecutor> makeTaskExecutorForCloner() {
// The ReshardingTxnCloner expects there to already be a Client associated with the thread
// from the thread pool. We set up the ThreadPoolTaskExecutor identically to how the
// recipient's primary-only service is set up.
ThreadPool::Options threadPoolOptions;
threadPoolOptions.maxThreads = 1;
threadPoolOptions.threadNamePrefix = "TestReshardCloneConfigTransactions-";
threadPoolOptions.poolName = "TestReshardCloneConfigTransactionsThreadPool";
threadPoolOptions.onCreateThread = [](const std::string& threadName) {
Client::initThread(threadName.c_str());
auto* client = Client::getCurrent();
AuthorizationSession::get(*client)->grantInternalAuthorization(client);
{
stdx::lock_guard<Client> lk(*client);
client->setSystemOperationKillableByStepdown(lk);
}
};
auto hookList = std::make_unique<rpc::EgressMetadataHookList>();
hookList->addHook(std::make_unique<rpc::VectorClockMetadataHook>(getServiceContext()));
auto executor = std::make_shared<executor::ThreadPoolTaskExecutor>(
std::make_unique<ThreadPool>(std::move(threadPoolOptions)),
executor::makeNetworkInterface(
"TestReshardCloneConfigTransactionsNetwork", nullptr, std::move(hookList)));
executor->startup();
return executor;
}
std::shared_ptr<MongoProcessInterface> makeMongoProcessInterface() {
return std::make_shared<ShardServerProcessInterface>(
Grid::get(getServiceContext())->getExecutorPool()->getFixedExecutor());
}
ExecutorFuture<void> runCloner(
ReshardingTxnCloner& cloner,
std::shared_ptr<executor::ThreadPoolTaskExecutor> executor,
std::shared_ptr<executor::ThreadPoolTaskExecutor> cleanupExecutor,
boost::optional<CancellationToken> customCancelToken = boost::none) {
// Allows callers to control the cancellation of the cloner's run() function when specified.
auto cancelToken = customCancelToken.is_initialized()
? customCancelToken.get()
: operationContext()->getCancellationToken();
auto cancelableOpCtxExecutor = std::make_shared<ThreadPool>([] {
ThreadPool::Options options;
options.poolName = "TestReshardCloneConfigTransactionsCancelableOpCtxPool";
options.minThreads = 1;
options.maxThreads = 1;
return options;
}());
CancelableOperationContextFactory opCtxFactory(cancelToken, cancelableOpCtxExecutor);
// There isn't a guarantee that the reference count to `executor` has been decremented after
// .run() returns. We schedule a trivial task on the task executor to ensure the callback's
// destructor has run. Otherwise `executor` could end up outliving the ServiceContext and
// triggering an invariant due to the task executor's thread having a Client still.
return cloner
.run(executor,
cleanupExecutor,
cancelToken,
std::move(opCtxFactory),
makeMongoProcessInterface())
.thenRunOn(executor)
.onCompletion([](auto x) { return x; });
}
void makeInProgressTxn(OperationContext* opCtx, LogicalSessionId lsid, TxnNumber txnNumber) {
opCtx->setInMultiDocumentTransaction();
opCtx->setLogicalSessionId(std::move(lsid));
opCtx->setTxnNumber(txnNumber);
MongoDOperationContextSession ocs(opCtx);
auto txnParticipant = TransactionParticipant::get(opCtx);
txnParticipant.beginOrContinue(
opCtx, {txnNumber}, false /* autocommit */, true /* startTransaction */);
txnParticipant.unstashTransactionResources(opCtx, "insert");
txnParticipant.stashTransactionResources(opCtx);
}
repl::OpTime makePreparedTxn(OperationContext* opCtx,
LogicalSessionId lsid,
TxnNumber txnNumber) {
opCtx->setInMultiDocumentTransaction();
opCtx->setLogicalSessionId(std::move(lsid));
opCtx->setTxnNumber(txnNumber);
MongoDOperationContextSession ocs(opCtx);
auto txnParticipant = TransactionParticipant::get(opCtx);
txnParticipant.beginOrContinue(
opCtx, {txnNumber}, false /* autocommit */, true /* startTransaction */);
txnParticipant.unstashTransactionResources(opCtx, "prepareTransaction");
// The transaction machinery cannot store an empty locker.
{ Lock::GlobalLock globalLock(opCtx, MODE_IX); }
auto opTime = [opCtx] {
TransactionParticipant::SideTransactionBlock sideTxn{opCtx};
WriteUnitOfWork wuow{opCtx};
auto opTime = repl::getNextOpTime(opCtx);
wuow.release();
opCtx->recoveryUnit()->abortUnitOfWork();
opCtx->lockState()->endWriteUnitOfWork();
return opTime;
}();
txnParticipant.prepareTransaction(opCtx, opTime);
txnParticipant.stashTransactionResources(opCtx);
return opTime;
}
void abortTxn(OperationContext* opCtx, LogicalSessionId lsid, TxnNumber txnNumber) {
opCtx->setInMultiDocumentTransaction();
opCtx->setLogicalSessionId(std::move(lsid));
opCtx->setTxnNumber(txnNumber);
MongoDOperationContextSession ocs(opCtx);
auto txnParticipant = TransactionParticipant::get(opCtx);
txnParticipant.beginOrContinue(
opCtx, {txnNumber}, false /* autocommit */, boost::none /* startTransaction */);
txnParticipant.unstashTransactionResources(opCtx, "abortTransaction");
txnParticipant.abortTransaction(opCtx);
txnParticipant.stashTransactionResources(opCtx);
}
Timestamp getLatestOplogTimestamp(OperationContext* opCtx) {
DBDirectClient client(opCtx);
FindCommandRequest findRequest{NamespaceString::kRsOplogNamespace};
findRequest.setSort(BSON("ts" << -1));
findRequest.setLimit(1);
auto cursor = client.find(findRequest);
ASSERT_TRUE(cursor->more());
const auto oplogEntry = cursor->next();
return oplogEntry.getField("ts").timestamp();
}
std::vector<repl::DurableOplogEntry> findOplogEntriesNewerThan(OperationContext* opCtx,
Timestamp ts) {
std::vector<repl::DurableOplogEntry> result;
PersistentTaskStore<repl::OplogEntryBase> store(NamespaceString::kRsOplogNamespace);
store.forEach(opCtx, BSON("ts" << BSON("$gt" << ts)), [&](const auto& oplogEntry) {
result.emplace_back(
unittest::assertGet(repl::DurableOplogEntry::parse(oplogEntry.toBSON())));
return true;
});
return result;
}
boost::optional<SessionTxnRecord> findSessionRecord(OperationContext* opCtx,
const LogicalSessionId& lsid) {
boost::optional<SessionTxnRecord> result;
PersistentTaskStore<SessionTxnRecord> store(
NamespaceString::kSessionTransactionsTableNamespace);
store.forEach(opCtx,
BSON(SessionTxnRecord::kSessionIdFieldName << lsid.toBSON()),
[&](const auto& sessionTxnRecord) {
result.emplace(sessionTxnRecord);
return false;
});
return result;
}
void checkGeneratedNoop(const repl::DurableOplogEntry& foundOp,
const LogicalSessionId& lsid,
TxnNumber txnNumber,
const std::vector<StmtId>& stmtIds) {
ASSERT_EQ(OpType_serializer(foundOp.getOpType()),
OpType_serializer(repl::OpTypeEnum::kNoop))
<< foundOp;
ASSERT_EQ(foundOp.getSessionId(), lsid) << foundOp;
ASSERT_EQ(foundOp.getTxnNumber(), txnNumber) << foundOp;
ASSERT(foundOp.getStatementIds() == stmtIds) << foundOp;
// The oplog entry must have o2 and fromMigrate set or SessionUpdateTracker will ignore it.
ASSERT_TRUE(foundOp.getObject2());
ASSERT_TRUE(foundOp.getFromMigrate());
}
void checkSessionTxnRecord(const SessionTxnRecord& sessionTxnRecord,
const repl::DurableOplogEntry& foundOp) {
ASSERT_EQ(sessionTxnRecord.getSessionId(), foundOp.getSessionId())
<< sessionTxnRecord.toBSON() << ", " << foundOp;
ASSERT_EQ(sessionTxnRecord.getTxnNum(), foundOp.getTxnNumber())
<< sessionTxnRecord.toBSON() << ", " << foundOp;
ASSERT_EQ(sessionTxnRecord.getLastWriteOpTime(), foundOp.getOpTime())
<< sessionTxnRecord.toBSON() << ", " << foundOp;
ASSERT_EQ(sessionTxnRecord.getLastWriteDate(), foundOp.getWallClockTime())
<< sessionTxnRecord.toBSON() << ", " << foundOp;
}
private:
static HostAndPort makeHostAndPort(const ShardId& shardId) {
return HostAndPort(str::stream() << shardId << ":123");
}
RAIIServerParameterControllerForTest controller{"reshardingTxnClonerProgressBatchSize", 1};
};
TEST_F(ReshardingTxnClonerTest, MergeTxnNotOnRecipient) {
for (auto state : getDurableTxnStatesAndBoostNone()) {
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber txnNum = 3;
auto txn = SessionTxnRecord(sessionId, txnNum, repl::OpTime(), Date_t::now());
txn.setState(state);
onCommandReturnTxns({txn.toBSON()}, {});
auto status = future.getNoThrow();
ASSERT_OK(status) << (state ? DurableTxnState_serializer(*state) : "retryable write");
checkTxnHasBeenUpdated(sessionId, txnNum);
}
}
TEST_F(ReshardingTxnClonerTest, MergeUnParsableTxn) {
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber txnNum = 3;
onCommandReturnTxns({SessionTxnRecord(sessionId, txnNum, repl::OpTime(), Date_t::now())
.toBSON()
.removeField(SessionTxnRecord::kSessionIdFieldName)},
{});
auto status = future.getNoThrow();
ASSERT_EQ(status, static_cast<ErrorCodes::Error>(40414));
}
TEST_F(ReshardingTxnClonerTest, MergeNewTxnOverMultiDocTxn) {
for (auto state : getDurableTxnStatesAndBoostNone()) {
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber donorTxnNum = 3;
TxnNumber recipientTxnNum = donorTxnNum - 1;
seedTransactionOnRecipient(sessionId, recipientTxnNum, true);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
auto txn = SessionTxnRecord(sessionId, donorTxnNum, repl::OpTime(), Date_t::now());
txn.setState(state);
onCommandReturnTxns({txn.toBSON()}, {});
auto status = future.getNoThrow();
ASSERT_OK(status) << (state ? DurableTxnState_serializer(*state) : "retryable write");
checkTxnHasBeenUpdated(sessionId, donorTxnNum);
}
}
TEST_F(ReshardingTxnClonerTest, MergeNewTxnOverRetryableWriteTxn) {
for (auto state : getDurableTxnStatesAndBoostNone()) {
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber donorTxnNum = 3;
TxnNumber recipientTxnNum = donorTxnNum - 1;
seedTransactionOnRecipient(sessionId, recipientTxnNum, false);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
auto txn = SessionTxnRecord(sessionId, donorTxnNum, repl::OpTime(), Date_t::now());
txn.setState(state);
onCommandReturnTxns({txn.toBSON()}, {});
auto status = future.getNoThrow();
ASSERT_OK(status) << (state ? DurableTxnState_serializer(*state) : "retryable write");
checkTxnHasBeenUpdated(sessionId, donorTxnNum);
}
}
TEST_F(ReshardingTxnClonerTest, MergeCurrentTxnOverRetryableWriteTxn) {
for (auto state : getDurableTxnStatesAndBoostNone()) {
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber txnNum = 3;
seedTransactionOnRecipient(sessionId, txnNum, false);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
auto txn = SessionTxnRecord(sessionId, txnNum, repl::OpTime(), Date_t::now());
txn.setState(state);
onCommandReturnTxns({txn.toBSON()}, {});
auto status = future.getNoThrow();
ASSERT_OK(status) << (state ? DurableTxnState_serializer(*state) : "retryable write");
checkTxnHasBeenUpdated(sessionId, txnNum);
}
}
TEST_F(ReshardingTxnClonerTest, MergeCurrentTxnOverMultiDocTxn) {
for (auto state : getDurableTxnStatesAndBoostNone()) {
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber txnNum = 3;
seedTransactionOnRecipient(sessionId, txnNum, true);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
auto txn = SessionTxnRecord(sessionId, txnNum, repl::OpTime(), Date_t::now());
txn.setState(state);
onCommandReturnTxns({txn.toBSON()}, {});
auto status = future.getNoThrow();
ASSERT_OK(status) << (state ? DurableTxnState_serializer(*state) : "retryable write");
checkTxnHasNotBeenUpdated(sessionId, txnNum);
}
}
TEST_F(ReshardingTxnClonerTest, MergeOldTxnOverTxn) {
for (auto state : getDurableTxnStatesAndBoostNone()) {
const auto sessionId = makeLogicalSessionIdForTest();
TxnNumber recipientTxnNum = 3;
TxnNumber donorTxnNum = recipientTxnNum - 1;
seedTransactionOnRecipient(sessionId, recipientTxnNum, false);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
auto txn = SessionTxnRecord(sessionId, donorTxnNum, repl::OpTime(), Date_t::now());
txn.setState(state);
onCommandReturnTxns({txn.toBSON()}, {});
auto status = future.getNoThrow();
ASSERT_OK(status) << (state ? DurableTxnState_serializer(*state) : "retryable write");
checkTxnHasNotBeenUpdated(sessionId, recipientTxnNum);
}
}
TEST_F(ReshardingTxnClonerTest, MergeMultiDocTransactionAndRetryableWrite) {
const auto sessionIdRetryableWrite = makeLogicalSessionIdForTest();
const auto sessionIdMultiDocTxn = makeLogicalSessionIdForTest();
TxnNumber txnNum = 3;
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
auto sessionRecordRetryableWrite =
SessionTxnRecord(sessionIdRetryableWrite, txnNum, repl::OpTime(), Date_t::now());
auto sessionRecordMultiDocTxn =
SessionTxnRecord(sessionIdMultiDocTxn, txnNum, repl::OpTime(), Date_t::now());
sessionRecordMultiDocTxn.setState(DurableTxnStateEnum::kAborted);
onCommandReturnTxns({sessionRecordRetryableWrite.toBSON(), sessionRecordMultiDocTxn.toBSON()},
{});
auto status = future.getNoThrow();
ASSERT_OK(status);
checkTxnHasBeenUpdated(sessionIdRetryableWrite, txnNum);
checkTxnHasBeenUpdated(sessionIdMultiDocTxn, txnNum);
}
/**
* Test that the ReshardingTxnCloner stops processing batches when canceled via cancelToken.
*/
TEST_F(ReshardingTxnClonerTest, ClonerOneBatchThenCanceled) {
const auto txns = makeSortedTxns(4);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto opCtxToken = operationContext()->getCancellationToken();
auto cancelSource = CancellationSource(opCtxToken);
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommand([&](const executor::RemoteCommandRequest& request) {
cancelSource.cancel();
return CursorResponse(NamespaceString::kSessionTransactionsTableNamespace,
CursorId{123},
std::vector<BSONObj>(txns.begin(), txns.begin() + 2))
.toBSON(CursorResponse::ResponseType::InitialResponse);
});
auto status = future.getNoThrow();
ASSERT_EQ(status.code(), ErrorCodes::CallbackCanceled);
}
TEST_F(ReshardingTxnClonerTest, ClonerStoresProgressSingleBatch) {
const auto txns = makeSortedTxns(2);
const auto lastLsid = getTxnRecordLsid(txns.back());
{
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[1]));
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
onCommandReturnTxnBatch(txns, CursorId{0}, true /* isFirstBatch */);
auto status = future.getNoThrow();
ASSERT_OK(status);
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), lastLsid);
}
// Repeat with a different shard to verify multiple progress docs can exist at once for a
// resharding operation.
{
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), lastLsid);
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[0], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
onCommandReturnTxnBatch(txns, CursorId{0}, true /* isFirstBatch */);
auto status = future.getNoThrow();
ASSERT_OK(status);
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[0]), lastLsid);
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), lastLsid);
}
// Verify each progress document is scoped to a single resharding operation.
ASSERT_FALSE(getTxnCloningProgress(ReshardingSourceId(UUID::gen(), kTwoShardIdList[0])));
ASSERT_FALSE(getTxnCloningProgress(ReshardingSourceId(UUID::gen(), kTwoShardIdList[1])));
}
TEST_F(ReshardingTxnClonerTest, ClonerStoresProgressMultipleBatches) {
const auto txns = makeSortedTxns(4);
const auto firstLsid = getTxnRecordLsid(txns[1]);
const auto lastLsid = getTxnRecordLsid(txns.back());
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[1]));
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto cancelSource = CancellationSource(operationContext()->getCancellationToken());
auto future = runCloner(cloner, executor, executor, cancelSource.token());
// The progress document is updated asynchronously after the session record is updated. We fake
// the cloning operation being canceled to inspect the progress document after the first batch
// has been processed.
onCommandReturnTxnBatch(std::vector<BSONObj>(txns.begin(), txns.begin() + 2),
CursorId{123},
true /* isFirstBatch */);
onCommand([&](const executor::RemoteCommandRequest& request) {
// Simulate a stepdown.
cancelSource.cancel();
// With a non-mock network, disposing of the pipeline upon cancellation would also cancel
// the original request.
return Status{ErrorCodes::CallbackCanceled, "Simulate cancellation"};
});
auto status = future.getNoThrow();
ASSERT_EQ(status, ErrorCodes::CallbackCanceled);
// After the first batch, the progress document should contain the lsid of the last document in
// that batch.
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), firstLsid);
// Now we run the cloner again and give it the remaining documents.
future = runCloner(cloner, executor, executor);
onCommandReturnTxnBatch(
std::vector<BSONObj>(txns.begin() + 1, txns.end()), CursorId{0}, false /* isFirstBatch */);
status = future.getNoThrow();
ASSERT_OK(status);
// After the second and final batch, the progress document should have been updated to the final
// overall lsid.
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), lastLsid);
}
TEST_F(ReshardingTxnClonerTest, ClonerStoresProgressResume) {
const auto txns = makeSortedTxns(4);
const auto firstLsid = getTxnRecordLsid(txns.front());
const auto lastLsid = getTxnRecordLsid(txns.back());
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[1]));
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
auto cancelSource = CancellationSource(operationContext()->getCancellationToken());
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommandReturnTxnBatch({txns.front()}, CursorId{123}, true /* isFirstBatch */);
// Simulate the cloning operation being canceled as the batch was being filled.
onCommand([&](const executor::RemoteCommandRequest& request) {
// The progress document is updated asynchronously after the session record is updated but
// is guaranteed to have been updated before the next getMore request is sent.
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), firstLsid);
// Simulate a stepdown.
cancelSource.cancel();
// With a non-mock network, disposing of the pipeline upon cancellation would also cancel
// the original request.
return Status{ErrorCodes::CallbackCanceled, "Simulate cancellation"};
});
auto status = future.getNoThrow();
ASSERT_EQ(status, ErrorCodes::CallbackCanceled);
// The stored progress should be unchanged.
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), firstLsid);
// Simulate a resume on the new primary by creating a new fetcher that resumes after the lsid in
// the progress document.
future = runCloner(cloner, executor, executor);
BSONObj cmdObj;
onCommand([&](const executor::RemoteCommandRequest& request) {
cmdObj = request.cmdObj.getOwned();
return CursorResponse(NamespaceString::kSessionTransactionsTableNamespace,
CursorId{0},
std::vector<BSONObj>(txns.begin() + 1, txns.end()))
.toBSON(CursorResponse::ResponseType::InitialResponse);
});
status = future.getNoThrow();
ASSERT_OK(status);
// The aggregation request should include the progress lsid to resume from.
ASSERT_STRING_CONTAINS(cmdObj.toString(), firstLsid.toBSON().toString());
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), lastLsid);
for (const auto& txn : txns) {
// Note 0 is the default txnNumber used for txn records made by makeSortedTxns()
checkTxnHasBeenUpdated(getTxnRecordLsid(txn), 0);
}
// Simulate a resume after a rollback of an update to the progress document by creating a new
// fetcher that resumes at the lsid from the first progress document. This verifies cloning is
// idempotent on the cloning shard.
cloner.updateProgressDocument_forTest(operationContext(), firstLsid);
future = runCloner(cloner, executor, executor);
onCommand([&](const executor::RemoteCommandRequest& request) {
cmdObj = request.cmdObj.getOwned();
return CursorResponse(NamespaceString::kSessionTransactionsTableNamespace,
CursorId{0},
std::vector<BSONObj>(txns.begin() + 1, txns.end()))
.toBSON(CursorResponse::ResponseType::InitialResponse);
});
status = future.getNoThrow();
ASSERT_OK(status);
// The aggregation request should have included the previous progress lsid to resume from.
ASSERT_STRING_CONTAINS(cmdObj.toString(), firstLsid.toBSON().toString());
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
ASSERT_EQ(*getProgressLsid(kTwoSourceIdList[1]), lastLsid);
for (const auto& txn : txns) {
// Note 0 is the default txnNumber used for txn records made by makeSortedTxns()
checkTxnHasBeenUpdated(getTxnRecordLsid(txn), 0);
}
}
TEST_F(ReshardingTxnClonerTest, ClonerDoesNotUpdateProgressOnEmptyBatch) {
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[0], Timestamp::max());
auto future = runCloner(cloner, executor, executor);
onCommandReturnTxnBatch({}, CursorId{0}, true /* isFirstBatch */);
auto status = future.getNoThrow();
ASSERT_OK(status);
ASSERT_FALSE(getTxnCloningProgress(kTwoSourceIdList[0]));
}
TEST_F(ReshardingTxnClonerTest, WaitsOnPreparedTxnAndAutomaticallyRetries) {
auto lsid = makeLogicalSessionIdForTest();
TxnNumber existingTxnNumber = 100;
auto opTime = makePreparedTxn(operationContext(), lsid, existingTxnNumber);
TxnNumber incomingTxnNumber = existingTxnNumber + 1;
auto sessionTxnRecord = SessionTxnRecord{lsid, incomingTxnNumber, repl::OpTime{}, Date_t{}};
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
CancellationSource cancelSource;
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommandReturnTxns({sessionTxnRecord.toBSON()}, {});
ASSERT_FALSE(future.isReady());
// Wait a little bit to increase the likelihood that the cloner has blocked on the prepared
// transaction before the transaction is aborted.
ASSERT_OK(
executor->sleepFor(Milliseconds{200}, CancellationToken::uncancelable()).getNoThrow());
ASSERT_FALSE(future.isReady());
abortTxn(operationContext(), lsid, existingTxnNumber);
ASSERT_OK(future.getNoThrow());
{
auto foundOps = findOplogEntriesNewerThan(operationContext(), opTime.getTimestamp());
ASSERT_GTE(foundOps.size(), 2U);
// The first oplog entry is from aborting the prepared transaction via abortTxn().
// The second oplog entry is from the session txn record being updated by
// ReshardingTxnCloner.
checkGeneratedNoop(foundOps[1], lsid, incomingTxnNumber, {kIncompleteHistoryStmtId});
auto sessionTxnRecord = findSessionRecord(operationContext(), lsid);
ASSERT_TRUE(bool(sessionTxnRecord));
checkSessionTxnRecord(*sessionTxnRecord, foundOps[1]);
}
}
TEST_F(ReshardingTxnClonerTest, CancelableWhileWaitingOnPreparedTxn) {
auto lsid = makeLogicalSessionIdForTest();
TxnNumber existingTxnNumber = 100;
makePreparedTxn(operationContext(), lsid, existingTxnNumber);
ON_BLOCK_EXIT([&] { abortTxn(operationContext(), lsid, existingTxnNumber); });
TxnNumber incomingTxnNumber = existingTxnNumber + 1;
auto sessionTxnRecord = SessionTxnRecord{lsid, incomingTxnNumber, repl::OpTime{}, Date_t{}};
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
CancellationSource cancelSource;
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommandReturnTxns({sessionTxnRecord.toBSON()}, {});
ASSERT_FALSE(future.isReady());
// Wait a little bit to increase the likelihood that the applier has blocked on the prepared
// transaction before the cancellation source is canceled.
ASSERT_OK(
executor->sleepFor(Milliseconds{200}, CancellationToken::uncancelable()).getNoThrow());
ASSERT_FALSE(future.isReady());
cancelSource.cancel();
ASSERT_EQ(future.getNoThrow(), ErrorCodes::CallbackCanceled);
}
TEST_F(ReshardingTxnClonerTest,
WaitsOnInProgressInternalTxnForRetryableWriteAndAutomaticallyRetries) {
auto retryableWriteLsid = makeLogicalSessionIdForTest();
TxnNumber retryableWriteTxnNumber = 100;
auto internalTxnLsid = makeLogicalSessionIdWithTxnNumberAndUUIDForTest(retryableWriteLsid,
retryableWriteTxnNumber);
TxnNumber internalTxnTxnNumber = 1;
makeInProgressTxn(operationContext(), internalTxnLsid, internalTxnTxnNumber);
auto lastOplogTs = getLatestOplogTimestamp(operationContext());
auto sessionTxnRecord =
SessionTxnRecord{retryableWriteLsid, retryableWriteTxnNumber, repl::OpTime{}, Date_t{}};
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
CancellationSource cancelSource;
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommandReturnTxns({sessionTxnRecord.toBSON()}, {});
ASSERT_FALSE(future.isReady());
// Wait a little bit to increase the likelihood that the cloner has blocked on the in progress
// internal transaction before the transaction is aborted.
ASSERT_OK(
executor->sleepFor(Milliseconds{200}, CancellationToken::uncancelable()).getNoThrow());
ASSERT_FALSE(future.isReady());
abortTxn(operationContext(), internalTxnLsid, internalTxnTxnNumber);
ASSERT_OK(future.getNoThrow());
{
auto foundOps = findOplogEntriesNewerThan(operationContext(), lastOplogTs);
ASSERT_GTE(foundOps.size(), 1U);
// The first oplog entry is from the session txn record being updated by
// ReshardingTxnCloner.
checkGeneratedNoop(
foundOps[0], retryableWriteLsid, retryableWriteTxnNumber, {kIncompleteHistoryStmtId});
auto sessionTxnRecord = findSessionRecord(operationContext(), retryableWriteLsid);
ASSERT_TRUE(bool(sessionTxnRecord));
checkSessionTxnRecord(*sessionTxnRecord, foundOps[0]);
}
}
TEST_F(ReshardingTxnClonerTest,
WaitsOnPreparedInternalTxnForRetryableWriteAndAutomaticallyRetries) {
auto retryableWriteLsid = makeLogicalSessionIdForTest();
TxnNumber retryableWriteTxnNumber = 100;
auto internalTxnLsid = makeLogicalSessionIdWithTxnNumberAndUUIDForTest(retryableWriteLsid,
retryableWriteTxnNumber);
TxnNumber internalTxnTxnNumber = 1;
auto opTime = makePreparedTxn(operationContext(), internalTxnLsid, internalTxnTxnNumber);
auto sessionTxnRecord =
SessionTxnRecord{retryableWriteLsid, retryableWriteTxnNumber, repl::OpTime{}, Date_t{}};
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
CancellationSource cancelSource;
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommandReturnTxns({sessionTxnRecord.toBSON()}, {});
ASSERT_FALSE(future.isReady());
// Wait a little bit to increase the likelihood that the cloner has blocked on the in progress
// internal transaction before the transaction is aborted.
ASSERT_OK(
executor->sleepFor(Milliseconds{200}, CancellationToken::uncancelable()).getNoThrow());
ASSERT_FALSE(future.isReady());
abortTxn(operationContext(), internalTxnLsid, internalTxnTxnNumber);
ASSERT_OK(future.getNoThrow());
{
auto foundOps = findOplogEntriesNewerThan(operationContext(), opTime.getTimestamp());
ASSERT_GTE(foundOps.size(), 2U);
// The first oplog entry is from aborting the prepared internal transaction via abortTxn().
// The second oplog entry is from the session txn record being updated by
// ReshardingTxnCloner.
checkGeneratedNoop(
foundOps[1], retryableWriteLsid, retryableWriteTxnNumber, {kIncompleteHistoryStmtId});
auto sessionTxnRecord = findSessionRecord(operationContext(), retryableWriteLsid);
ASSERT_TRUE(bool(sessionTxnRecord));
checkSessionTxnRecord(*sessionTxnRecord, foundOps[1]);
}
}
TEST_F(ReshardingTxnClonerTest, CancelableWhileWaitingOnInProgressInternalTxnForRetryableWrite) {
auto retryableWriteLsid = makeLogicalSessionIdForTest();
TxnNumber retryableWriteTxnNumber = 100;
auto internalTxnLsid = makeLogicalSessionIdWithTxnNumberAndUUIDForTest(retryableWriteLsid,
retryableWriteTxnNumber);
TxnNumber internalTxnTxnNumber = 1;
makeInProgressTxn(operationContext(), internalTxnLsid, internalTxnTxnNumber);
ON_BLOCK_EXIT([&] { abortTxn(operationContext(), internalTxnLsid, internalTxnTxnNumber); });
auto sessionTxnRecord =
SessionTxnRecord{retryableWriteLsid, retryableWriteTxnNumber, repl::OpTime{}, Date_t{}};
auto executor = makeTaskExecutorForCloner();
ReshardingTxnCloner cloner(kTwoSourceIdList[1], Timestamp::max());
CancellationSource cancelSource;
auto future = runCloner(cloner, executor, executor, cancelSource.token());
onCommandReturnTxns({sessionTxnRecord.toBSON()}, {});
ASSERT_FALSE(future.isReady());
// Wait a little bit to increase the likelihood that the applier has blocked on the prepared
// transaction before the cancellation source is canceled.
ASSERT_OK(
executor->sleepFor(Milliseconds{200}, CancellationToken::uncancelable()).getNoThrow());
ASSERT_FALSE(future.isReady());
cancelSource.cancel();
ASSERT_EQ(future.getNoThrow(), ErrorCodes::CallbackCanceled);
}
} // namespace
} // namespace mongo
| 43.456889 | 100 | 0.687128 | benety |
1e23c7e9b68399b53521befc967c550549b44b9d | 3,505 | hpp | C++ | src/sagl/parser/eval.hpp | lggruspe/ibex | 43cdd950c8db533e9e5b350375e1288744dc6e7e | [
"MIT"
] | null | null | null | src/sagl/parser/eval.hpp | lggruspe/ibex | 43cdd950c8db533e9e5b350375e1288744dc6e7e | [
"MIT"
] | 1 | 2020-03-31T11:30:17.000Z | 2020-03-31T11:30:17.000Z | src/sagl/parser/eval.hpp | lggruspe/ibex | 43cdd950c8db533e9e5b350375e1288744dc6e7e | [
"MIT"
] | null | null | null | #pragma once
#include "parser.hpp"
#include <cassert>
#include <iostream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
struct ParseTree {
using Tree = std::unique_ptr<ParseTree>;
std::vector<Tree> children;
const std::string label;
const std::string value;
ParseTree(const std::string& label, const std::string& value = "")
: label(label)
, value(value)
{}
};
struct SyntaxError {
char const* what() const { return "syntax error"; }
};
static inline std::ostream& operator<<(
std::ostream& out,
std::unique_ptr<ParseTree>& node)
{
if (node == nullptr) {
return out << "nil";
}
if (!node->children.empty()) {
out << "(";
}
out << node->value;
for (auto& child: node->children) {
out << " " << child;
}
if (!node->children.empty()) {
out << ")";
}
return out;
}
using Context = std::vector<std::unique_ptr<ParseTree>>;
struct ParseTreeCallback: public parser::BaseCallback<Context> {
using Sentence = std::vector<std::string>;
using Rule = std::pair<std::string, Sentence>;
std::vector<Rule> rules;
auto accept(bool acc)
{
if (!acc) {
throw SyntaxError();
}
std::multimap<std::string, Sentence> grammar_rules;
for (const auto& rule: rules) {
grammar_rules.insert(rule);
}
return std::make_pair(rules[0].first, grammar_rules);
}
bool handle_shift(const std::pair<std::string, std::string>& lookahead)
{
const auto& [tok, lex] = lookahead;
state.push_back(std::make_unique<ParseTree>(tok, lex));
return true;
}
bool handle_reduce(const Rule& rule)
{
auto node = std::make_unique<ParseTree>(rule.first);
std::vector<decltype(node)> children;
for (int i = 0; i < (int)(rule.second.size()); ++i) {
children.push_back(std::move(state.back()));
state.pop_back();
}
while (!children.empty()) {
node->children.push_back(std::move(children.back()));
children.pop_back();
}
state.push_back(std::move(node));
append_rule(rule);
return true;
}
void append_rule(const Rule& rule)
{
if (rule.first == "Rule") {
if (rule.second == Sentence{"Lhs", "arrow", "Rhs", "dot"}) {
assert(state.back()->children.size() == 4);
auto* lhs = state.back()->children[0].get();
auto* rhs = state.back()->children[2].get();
assert(lhs && lhs->label == "Lhs");
assert(rhs && rhs->label == "Rhs");
rules.push_back(Rule(get_lhs(lhs), fold(rhs)));
}
}
}
private:
Sentence fold(ParseTree* t) const
{
if (t->children.empty()) {
return Sentence();
}
assert(t->children.size() == 2);
assert(t->children[0]->label == "Rhs");
assert(t->children[1]->label == "identifier");
Sentence current = fold(t->children[0].get());
current.push_back(t->children[1]->value);
return current;
}
std::string get_lhs(ParseTree* lhs) const
{
assert(lhs->label == "Lhs");
assert(lhs->children.size() == 1);
auto* child = lhs->children.front().get();
assert(child->label == "identifier");
assert(child->children.empty());
return child->value;
}
};
| 27.382813 | 75 | 0.54465 | lggruspe |
1e27b7a31fe10820d62803f251fd0de1f490c82f | 5,434 | cc | C++ | src/ledger/bin/storage/fake/fake_ledger_storage.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | src/ledger/bin/storage/fake/fake_ledger_storage.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | null | null | null | src/ledger/bin/storage/fake/fake_ledger_storage.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2019 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 "src/ledger/bin/storage/fake/fake_ledger_storage.h"
#include <lib/async/cpp/task.h>
#include "src/ledger/bin/storage/fake/fake_page_storage.h"
namespace storage {
namespace fake {
DelayingCallbacksManager::DelayingCallbacksManager() = default;
DelayingCallbacksManager::~DelayingCallbacksManager() = default;
class DelayIsSyncedCallbackFakePageStorage : public storage::fake::FakePageStorage {
public:
explicit DelayIsSyncedCallbackFakePageStorage(
ledger::Environment* environment, DelayingCallbacksManager* delaying_callbacks_manager,
storage::PageId id)
: storage::fake::FakePageStorage(environment, id),
delaying_callbacks_manager_(delaying_callbacks_manager) {}
DelayIsSyncedCallbackFakePageStorage(const DelayIsSyncedCallbackFakePageStorage&) = delete;
DelayIsSyncedCallbackFakePageStorage& operator=(const DelayIsSyncedCallbackFakePageStorage&) =
delete;
~DelayIsSyncedCallbackFakePageStorage() override = default;
// Unblocks the call of |IsSynced| callback for the given page.
void CallIsSyncedCallback() {
storage::fake::FakePageStorage::IsSynced(std::move(is_synced_callback_));
}
// FakePageStorage:
void IsSynced(fit::function<void(ledger::Status, bool)> callback) override {
if (!delaying_callbacks_manager_->ShouldDelayIsSyncedCallback(page_id_)) {
storage::fake::FakePageStorage::IsSynced(std::move(callback));
return;
}
is_synced_callback_ = std::move(callback);
}
void IsEmpty(fit::function<void(ledger::Status, bool)> callback) override {
callback(ledger::Status::OK, true);
}
bool IsOnline() override { return false; }
private:
fit::function<void(ledger::Status, bool)> is_synced_callback_;
DelayingCallbacksManager* delaying_callbacks_manager_;
};
FakeLedgerStorage::FakeLedgerStorage(ledger::Environment* environment)
: environment_(environment) {}
FakeLedgerStorage::~FakeLedgerStorage() = default;
void FakeLedgerStorage::ListPages(
fit::function<void(storage::Status, std::set<storage::PageId>)> callback) {
FXL_NOTREACHED() << "Maybe implement this later on if needed?";
}
void FakeLedgerStorage::CreatePageStorage(
storage::PageId page_id,
fit::function<void(ledger::Status, std::unique_ptr<storage::PageStorage>)> callback) {
create_page_calls.push_back(std::move(page_id));
callback(ledger::Status::IO_ERROR, nullptr);
}
void FakeLedgerStorage::GetPageStorage(
storage::PageId page_id,
fit::function<void(ledger::Status, std::unique_ptr<storage::PageStorage>)> callback) {
get_page_calls.push_back(page_id);
async::PostTask(
environment_->dispatcher(), [this, callback = std::move(callback), page_id]() mutable {
if (should_get_page_fail) {
callback(ledger::Status::PAGE_NOT_FOUND, nullptr);
} else {
auto fake_page_storage =
std::make_unique<DelayIsSyncedCallbackFakePageStorage>(environment_, this, page_id);
// If the page was opened before, restore the previous sync state.
fake_page_storage->set_synced(synced_pages_.find(page_id) != synced_pages_.end());
page_storages_[std::move(page_id)] = fake_page_storage.get();
callback(ledger::Status::OK, std::move(fake_page_storage));
}
});
}
void FakeLedgerStorage::DeletePageStorage(storage::PageIdView /*page_id*/,
fit::function<void(ledger::Status)> callback) {
delete_page_storage_callback = std::move(callback);
}
void FakeLedgerStorage::ClearCalls() {
create_page_calls.clear();
get_page_calls.clear();
page_storages_.clear();
}
void FakeLedgerStorage::DelayIsSyncedCallback(storage::PageIdView page_id, bool delay_callback) {
if (delay_callback) {
pages_with_delayed_callback.insert(page_id.ToString());
} else {
pages_with_delayed_callback.erase(page_id.ToString());
}
}
bool FakeLedgerStorage::ShouldDelayIsSyncedCallback(storage::PageIdView page_id) {
return pages_with_delayed_callback.find(page_id.ToString()) != pages_with_delayed_callback.end();
}
void FakeLedgerStorage::CallIsSyncedCallback(storage::PageIdView page_id) {
auto it = page_storages_.find(page_id.ToString());
FXL_CHECK(it != page_storages_.end());
it->second->CallIsSyncedCallback();
}
void FakeLedgerStorage::set_page_storage_synced(storage::PageIdView page_id, bool is_synced) {
storage::PageId page_id_string = page_id.ToString();
if (is_synced) {
synced_pages_.insert(page_id_string);
} else {
auto it = synced_pages_.find(page_id_string);
if (it != synced_pages_.end()) {
synced_pages_.erase(it);
}
}
FXL_CHECK(page_storages_.find(page_id_string) != page_storages_.end());
page_storages_[page_id_string]->set_synced(is_synced);
}
void FakeLedgerStorage::set_page_storage_offline_empty(storage::PageIdView page_id,
bool is_offline_empty) {
storage::PageId page_id_string = page_id.ToString();
if (is_offline_empty) {
offline_empty_pages_.insert(page_id_string);
} else {
auto it = offline_empty_pages_.find(page_id_string);
if (it != offline_empty_pages_.end()) {
offline_empty_pages_.erase(it);
}
}
}
} // namespace fake
} // namespace storage
| 36.965986 | 100 | 0.732241 | winksaville |
1e29cfa4d348c84cf27091e453660aa740bd11c3 | 25,126 | cpp | C++ | examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/printing/printing.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 471 | 2019-06-26T09:59:09.000Z | 2022-03-30T04:59:42.000Z | examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/printing/printing.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/printing/printing.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 317 | 2017-06-20T19:57:17.000Z | 2020-09-16T10:28:30.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: samples/printing.cpp
// Purpose: Printing demo for wxWidgets
// Author: Julian Smart
// Modified by: Francesco Montorsi
// Created: 1995
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#include "wx/log.h"
#endif
#if !wxUSE_PRINTING_ARCHITECTURE
#error "You must set wxUSE_PRINTING_ARCHITECTURE to 1 in setup.h, and recompile the library."
#endif
#include <ctype.h>
#include "wx/metafile.h"
#include "wx/print.h"
#include "wx/printdlg.h"
#include "wx/image.h"
#include "wx/accel.h"
#if wxUSE_POSTSCRIPT
#include "wx/generic/printps.h"
#include "wx/generic/prntdlgg.h"
#endif
#if wxUSE_GRAPHICS_CONTEXT
#include "wx/graphics.h"
#endif
#ifdef __WXMAC__
#include "wx/osx/printdlg.h"
#endif
#include "printing.h"
#ifndef wxHAS_IMAGES_IN_RESOURCES
#include "../sample.xpm"
#endif
// Global print data, to remember settings during the session
wxPrintData *g_printData = NULL;
// Global page setup data
wxPageSetupDialogData* g_pageSetupData = NULL;
// ----------------------------------------------------------------------------
// MyApp
// ----------------------------------------------------------------------------
IMPLEMENT_APP(MyApp)
bool MyApp::OnInit(void)
{
if ( !wxApp::OnInit() )
return false;
wxInitAllImageHandlers();
// init global objects
// -------------------
g_printData = new wxPrintData;
// You could set an initial paper size here
#if 0
g_printData->SetPaperId(wxPAPER_LETTER); // for Americans
g_printData->SetPaperId(wxPAPER_A4); // for everyone else
#endif
g_pageSetupData = new wxPageSetupDialogData;
// copy over initial paper size from print record
(*g_pageSetupData) = *g_printData;
// Set some initial page margins in mm.
g_pageSetupData->SetMarginTopLeft(wxPoint(15, 15));
g_pageSetupData->SetMarginBottomRight(wxPoint(15, 15));
// init local GUI objects
// ----------------------
#if 0
wxImage image( wxT("test.jpg") );
image.SetAlpha();
int i,j;
for (i = 0; i < image.GetWidth(); i++)
for (j = 0; j < image.GetHeight(); j++)
image.SetAlpha( i, j, 50 );
m_bitmap = image;
#endif
m_angle = 30;
m_testFont.Create(10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
// Create the main frame window
// ----------------------------
MyFrame* frame = new MyFrame((wxFrame *) NULL, wxT("wxWidgets Printing Demo"),
wxPoint(0, 0), wxSize(400, 400));
frame->Centre(wxBOTH);
frame->Show();
return true;
}
int MyApp::OnExit()
{
delete g_printData;
delete g_pageSetupData;
return wxApp::OnExit();
}
void MyApp::Draw(wxDC&dc)
{
// This routine just draws a bunch of random stuff on the screen so that we
// can check that different types of object are being drawn consistently
// between the screen image, the print preview image (at various zoom
// levels), and the printed page.
dc.SetBackground(*wxWHITE_BRUSH);
// dc.Clear();
dc.SetFont(m_testFont);
// dc.SetBackgroundMode(wxTRANSPARENT);
dc.SetPen(*wxBLACK_PEN);
dc.SetBrush(*wxLIGHT_GREY_BRUSH);
dc.DrawRectangle(0, 0, 230, 350);
dc.DrawLine(0, 0, 229, 349);
dc.DrawLine(229, 0, 0, 349);
dc.SetBrush(*wxTRANSPARENT_BRUSH);
dc.SetBrush(*wxCYAN_BRUSH);
dc.SetPen(*wxRED_PEN);
dc.DrawRoundedRectangle(0, 20, 200, 80, 20);
dc.DrawText( wxT("Rectangle 200 by 80"), 40, 40);
dc.SetPen( wxPen(*wxBLACK, 0, wxPENSTYLE_DOT_DASH) );
dc.DrawEllipse(50, 140, 100, 50);
dc.SetPen(*wxRED_PEN);
dc.DrawText( wxT("Test message: this is in 10 point text"), 10, 180);
#if wxUSE_UNICODE
const char *test = "Hebrew שלום -- Japanese (日本語)";
wxString tmp = wxConvUTF8.cMB2WC( test );
dc.DrawText( tmp, 10, 200 );
#endif
wxPoint points[5];
points[0].x = 0;
points[0].y = 0;
points[1].x = 20;
points[1].y = 0;
points[2].x = 20;
points[2].y = 20;
points[3].x = 10;
points[3].y = 20;
points[4].x = 10;
points[4].y = -20;
dc.DrawPolygon( 5, points, 20, 250, wxODDEVEN_RULE );
dc.DrawPolygon( 5, points, 50, 250, wxWINDING_RULE );
dc.DrawArc( 20, 330, 40, 300, 20, 300 );
{
wxDCBrushChanger changeBrush(dc, *wxTRANSPARENT_BRUSH);
dc.DrawArc( 60, 330, 80, 300, 60, 300 );
}
dc.DrawEllipticArc( 80, 250, 60, 30, 0.0, 270.0 );
points[0].x = 150;
points[0].y = 250;
points[1].x = 180;
points[1].y = 250;
points[2].x = 180;
points[2].y = 220;
points[3].x = 200;
points[3].y = 220;
dc.DrawSpline( 4, points );
wxString str;
int i = 0;
str.Printf( wxT("---- Text at angle %d ----"), i );
dc.DrawRotatedText( str, 100, 300, i );
i = m_angle;
str.Printf( wxT("---- Text at angle %d ----"), i );
dc.DrawRotatedText( str, 100, 300, i );
wxIcon my_icon = wxICON(sample);
dc.DrawIcon( my_icon, 100, 100);
if (m_bitmap.IsOk())
dc.DrawBitmap( m_bitmap, 10, 10 );
#if wxUSE_GRAPHICS_CONTEXT
wxGraphicsContext *gc = NULL;
wxPrinterDC *printer_dc = wxDynamicCast( &dc, wxPrinterDC );
if (printer_dc)
gc = wxGraphicsContext::Create( *printer_dc );
wxWindowDC *window_dc = wxDynamicCast( &dc, wxWindowDC );
if (window_dc)
gc = wxGraphicsContext::Create( *window_dc );
#ifdef __WXMSW__
wxEnhMetaFileDC *emf_dc = wxDynamicCast( &dc, wxEnhMetaFileDC );
if (emf_dc)
gc = wxGraphicsContext::Create( *emf_dc );
#endif
if (gc)
{
// make a path that contains a circle and some lines, centered at 100,100
gc->SetPen( *wxRED_PEN );
wxGraphicsPath path = gc->CreatePath();
path.AddCircle( 50.0, 50.0, 50.0 );
path.MoveToPoint(0.0, 50.0);
path.AddLineToPoint(100.0, 50.0);
path.MoveToPoint(50.0, 0.0);
path.AddLineToPoint(50.0, 100.0 );
path.CloseSubpath();
path.AddRectangle(25.0, 25.0, 50.0, 50.0);
gc->StrokePath(path);
// draw some text
wxString text("Text by wxGraphicsContext");
gc->SetFont( m_testFont, *wxBLACK );
gc->DrawText(text, 25.0, 60.0);
// draw rectangle around the text
double w, h, d, el;
gc->GetTextExtent(text, &w, &h, &d, &el);
gc->SetPen( *wxBLACK_PEN );
gc->DrawRectangle(25.0, 60.0, w, h);
delete gc;
}
#endif
}
// ----------------------------------------------------------------------------
// MyFrame
// ----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(wxID_EXIT, MyFrame::OnExit)
EVT_MENU(wxID_PRINT, MyFrame::OnPrint)
EVT_MENU(wxID_PREVIEW, MyFrame::OnPrintPreview)
EVT_MENU(WXPRINT_PAGE_SETUP, MyFrame::OnPageSetup)
EVT_MENU(wxID_ABOUT, MyFrame::OnPrintAbout)
#if wxUSE_POSTSCRIPT
EVT_MENU(WXPRINT_PRINT_PS, MyFrame::OnPrintPS)
EVT_MENU(WXPRINT_PREVIEW_PS, MyFrame::OnPrintPreviewPS)
EVT_MENU(WXPRINT_PAGE_SETUP_PS, MyFrame::OnPageSetupPS)
#endif
#ifdef __WXMAC__
EVT_MENU(WXPRINT_PAGE_MARGINS, MyFrame::OnPageMargins)
#endif
EVT_MENU(WXPRINT_ANGLEUP, MyFrame::OnAngleUp)
EVT_MENU(WXPRINT_ANGLEDOWN, MyFrame::OnAngleDown)
EVT_MENU_RANGE(WXPRINT_FRAME_MODAL_APP,
WXPRINT_FRAME_MODAL_NON,
MyFrame::OnPreviewFrameModalityKind)
wxEND_EVENT_TABLE()
MyFrame::MyFrame(wxFrame *frame, const wxString&title, const wxPoint&pos, const wxSize&size)
: wxFrame(frame, wxID_ANY, title, pos, size)
{
m_canvas = NULL;
m_previewModality = wxPreviewFrame_AppModal;
#if wxUSE_STATUSBAR
// Give us a status line
CreateStatusBar(2);
SetStatusText(wxT("Printing demo"));
#endif // wxUSE_STATUSBAR
// Load icon and bitmap
SetIcon( wxICON( sample) );
// Make a menubar
wxMenu *file_menu = new wxMenu;
file_menu->Append(wxID_PRINT, wxT("&Print..."), wxT("Print"));
file_menu->Append(WXPRINT_PAGE_SETUP, wxT("Page Set&up..."), wxT("Page setup"));
#ifdef __WXMAC__
file_menu->Append(WXPRINT_PAGE_MARGINS, wxT("Page Margins..."), wxT("Page margins"));
#endif
file_menu->Append(wxID_PREVIEW, wxT("Print Pre&view"), wxT("Preview"));
wxMenu * const menuModalKind = new wxMenu;
menuModalKind->AppendRadioItem(WXPRINT_FRAME_MODAL_APP, "&App modal");
menuModalKind->AppendRadioItem(WXPRINT_FRAME_MODAL_WIN, "&Window modal");
menuModalKind->AppendRadioItem(WXPRINT_FRAME_MODAL_NON, "&Not modal");
file_menu->AppendSubMenu(menuModalKind, "Preview frame &modal kind");
#if wxUSE_ACCEL
// Accelerators
wxAcceleratorEntry entries[1];
entries[0].Set(wxACCEL_CTRL, (int) 'V', wxID_PREVIEW);
wxAcceleratorTable accel(1, entries);
SetAcceleratorTable(accel);
#endif
#if wxUSE_POSTSCRIPT
file_menu->AppendSeparator();
file_menu->Append(WXPRINT_PRINT_PS, wxT("Print PostScript..."), wxT("Print (PostScript)"));
file_menu->Append(WXPRINT_PAGE_SETUP_PS, wxT("Page Setup PostScript..."), wxT("Page setup (PostScript)"));
file_menu->Append(WXPRINT_PREVIEW_PS, wxT("Print Preview PostScript"), wxT("Preview (PostScript)"));
#endif
file_menu->AppendSeparator();
file_menu->Append(WXPRINT_ANGLEUP, wxT("Angle up\tAlt-U"), wxT("Raise rotated text angle"));
file_menu->Append(WXPRINT_ANGLEDOWN, wxT("Angle down\tAlt-D"), wxT("Lower rotated text angle"));
file_menu->AppendSeparator();
file_menu->Append(wxID_EXIT, wxT("E&xit"), wxT("Exit program"));
wxMenu *help_menu = new wxMenu;
help_menu->Append(wxID_ABOUT, wxT("&About"), wxT("About this demo"));
wxMenuBar *menu_bar = new wxMenuBar;
menu_bar->Append(file_menu, wxT("&File"));
menu_bar->Append(help_menu, wxT("&Help"));
// Associate the menu bar with the frame
SetMenuBar(menu_bar);
// create the canvas
// -----------------
m_canvas = new MyCanvas(this, wxPoint(0, 0), wxSize(100, 100),
wxRETAINED|wxHSCROLL|wxVSCROLL);
// Give it scrollbars: the virtual canvas is 20 * 50 = 1000 pixels in each direction
m_canvas->SetScrollbars(20, 20, 50, 50);
}
void MyFrame::OnExit(wxCommandEvent& WXUNUSED(event))
{
Close(true /*force closing*/);
}
void MyFrame::OnPrint(wxCommandEvent& WXUNUSED(event))
{
wxPrintDialogData printDialogData(* g_printData);
wxPrinter printer(&printDialogData);
MyPrintout printout(this, wxT("My printout"));
if (!printer.Print(this, &printout, true /*prompt*/))
{
if (wxPrinter::GetLastError() == wxPRINTER_ERROR)
{
wxLogError(wxT("There was a problem printing. Perhaps your current printer is not set correctly?"));
}
else
{
wxLogMessage(wxT("You canceled printing"));
}
}
else
{
(*g_printData) = printer.GetPrintDialogData().GetPrintData();
}
}
void MyFrame::OnPrintPreview(wxCommandEvent& WXUNUSED(event))
{
// Pass two printout objects: for preview, and possible printing.
wxPrintDialogData printDialogData(* g_printData);
wxPrintPreview *preview =
new wxPrintPreview(new MyPrintout(this), new MyPrintout(this), &printDialogData);
if (!preview->IsOk())
{
delete preview;
wxLogError(wxT("There was a problem previewing.\nPerhaps your current printer is not set correctly?"));
return;
}
wxPreviewFrame *frame =
new wxPreviewFrame(preview, this, wxT("Demo Print Preview"), wxPoint(100, 100), wxSize(600, 650));
frame->Centre(wxBOTH);
frame->InitializeWithModality(m_previewModality);
frame->Show();
}
void MyFrame::OnPageSetup(wxCommandEvent& WXUNUSED(event))
{
(*g_pageSetupData) = *g_printData;
wxPageSetupDialog pageSetupDialog(this, g_pageSetupData);
pageSetupDialog.ShowModal();
(*g_printData) = pageSetupDialog.GetPageSetupDialogData().GetPrintData();
(*g_pageSetupData) = pageSetupDialog.GetPageSetupDialogData();
}
#if wxUSE_POSTSCRIPT
void MyFrame::OnPrintPS(wxCommandEvent& WXUNUSED(event))
{
wxPrintDialogData printDialogData(* g_printData);
wxPostScriptPrinter printer(&printDialogData);
MyPrintout printout(this, wxT("My printout"));
printer.Print(this, &printout, true/*prompt*/);
(*g_printData) = printer.GetPrintDialogData().GetPrintData();
}
void MyFrame::OnPrintPreviewPS(wxCommandEvent& WXUNUSED(event))
{
// Pass two printout objects: for preview, and possible printing.
wxPrintDialogData printDialogData(* g_printData);
wxPrintPreview *preview = new wxPrintPreview(new MyPrintout(this), new MyPrintout(this), &printDialogData);
wxPreviewFrame *frame =
new wxPreviewFrame(preview, this, wxT("Demo Print Preview"), wxPoint(100, 100), wxSize(600, 650));
frame->Centre(wxBOTH);
frame->Initialize();
frame->Show();
}
void MyFrame::OnPageSetupPS(wxCommandEvent& WXUNUSED(event))
{
(*g_pageSetupData) = * g_printData;
wxGenericPageSetupDialog pageSetupDialog(this, g_pageSetupData);
pageSetupDialog.ShowModal();
(*g_printData) = pageSetupDialog.GetPageSetupDialogData().GetPrintData();
(*g_pageSetupData) = pageSetupDialog.GetPageSetupDialogData();
}
#endif
#ifdef __WXMAC__
void MyFrame::OnPageMargins(wxCommandEvent& WXUNUSED(event))
{
(*g_pageSetupData) = *g_printData;
wxMacPageMarginsDialog pageMarginsDialog(this, g_pageSetupData);
pageMarginsDialog.ShowModal();
(*g_printData) = pageMarginsDialog.GetPageSetupDialogData().GetPrintData();
(*g_pageSetupData) = pageMarginsDialog.GetPageSetupDialogData();
}
#endif
void MyFrame::OnPrintAbout(wxCommandEvent& WXUNUSED(event))
{
(void)wxMessageBox(wxT("wxWidgets printing demo\nAuthor: Julian Smart"),
wxT("About wxWidgets printing demo"), wxOK|wxCENTRE);
}
void MyFrame::OnAngleUp(wxCommandEvent& WXUNUSED(event))
{
wxGetApp().IncrementAngle();
m_canvas->Refresh();
}
void MyFrame::OnAngleDown(wxCommandEvent& WXUNUSED(event))
{
wxGetApp().DecrementAngle();
m_canvas->Refresh();
}
void MyFrame::OnPreviewFrameModalityKind(wxCommandEvent& event)
{
m_previewModality = static_cast<wxPreviewFrameModalityKind>(
wxPreviewFrame_AppModal +
(event.GetId() - WXPRINT_FRAME_MODAL_APP));
}
// ----------------------------------------------------------------------------
// MyCanvas
// ----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow)
// EVT_PAINT(MyCanvas::OnPaint)
wxEND_EVENT_TABLE()
MyCanvas::MyCanvas(wxFrame *frame, const wxPoint&pos, const wxSize&size, long style)
: wxScrolledWindow(frame, wxID_ANY, pos, size, style)
{
SetBackgroundColour(*wxWHITE);
}
//void MyCanvas::OnPaint(wxPaintEvent& WXUNUSED(evt))
void MyCanvas::OnDraw(wxDC& dc)
{
//wxPaintDC dc(this);
wxGetApp().Draw(dc);
}
// ----------------------------------------------------------------------------
// MyPrintout
// ----------------------------------------------------------------------------
bool MyPrintout::OnPrintPage(int page)
{
wxDC *dc = GetDC();
if (dc)
{
if (page == 1)
DrawPageOne();
else if (page == 2)
DrawPageTwo();
// Draw page numbers at top left corner of printable area, sized so that
// screen size of text matches paper size.
MapScreenSizeToPage();
dc->DrawText(wxString::Format(wxT("PAGE %d"), page), 0, 0);
return true;
}
else
return false;
}
bool MyPrintout::OnBeginDocument(int startPage, int endPage)
{
if (!wxPrintout::OnBeginDocument(startPage, endPage))
return false;
return true;
}
void MyPrintout::GetPageInfo(int *minPage, int *maxPage, int *selPageFrom, int *selPageTo)
{
*minPage = 1;
*maxPage = 2;
*selPageFrom = 1;
*selPageTo = 2;
}
bool MyPrintout::HasPage(int pageNum)
{
return (pageNum == 1 || pageNum == 2);
}
void MyPrintout::DrawPageOne()
{
// You might use THIS code if you were scaling graphics of known size to fit
// on the page. The commented-out code illustrates different ways of scaling
// the graphics.
// We know the graphic is 230x350. If we didn't know this, we'd need to
// calculate it.
wxCoord maxX = 230;
wxCoord maxY = 350;
// This sets the user scale and origin of the DC so that the image fits
// within the paper rectangle (but the edges could be cut off by printers
// that can't print to the edges of the paper -- which is most of them. Use
// this if your image already has its own margins.
// FitThisSizeToPaper(wxSize(maxX, maxY));
// wxRect fitRect = GetLogicalPaperRect();
// This sets the user scale and origin of the DC so that the image fits
// within the page rectangle, which is the printable area on Mac and MSW
// and is the entire page on other platforms.
// FitThisSizeToPage(wxSize(maxX, maxY));
// wxRect fitRect = GetLogicalPageRect();
// This sets the user scale and origin of the DC so that the image fits
// within the page margins as specified by g_PageSetupData, which you can
// change (on some platforms, at least) in the Page Setup dialog. Note that
// on Mac, the native Page Setup dialog doesn't let you change the margins
// of a wxPageSetupDialogData object, so you'll have to write your own dialog or
// use the Mac-only wxMacPageMarginsDialog, as we do in this program.
FitThisSizeToPageMargins(wxSize(maxX, maxY), *g_pageSetupData);
wxRect fitRect = GetLogicalPageMarginsRect(*g_pageSetupData);
// This sets the user scale and origin of the DC so that the image appears
// on the paper at the same size that it appears on screen (i.e., 10-point
// type on screen is 10-point on the printed page) and is positioned in the
// top left corner of the page rectangle (just as the screen image appears
// in the top left corner of the window).
// MapScreenSizeToPage();
// wxRect fitRect = GetLogicalPageRect();
// You could also map the screen image to the entire paper at the same size
// as it appears on screen.
// MapScreenSizeToPaper();
// wxRect fitRect = GetLogicalPaperRect();
// You might also wish to do you own scaling in order to draw objects at
// full native device resolution. In this case, you should do the following.
// Note that you can use the GetLogicalXXXRect() commands to obtain the
// appropriate rect to scale to.
// MapScreenSizeToDevice();
// wxRect fitRect = GetLogicalPageRect();
// Each of the preceding Fit or Map routines positions the origin so that
// the drawn image is positioned at the top left corner of the reference
// rectangle. You can easily center or right- or bottom-justify the image as
// follows.
// This offsets the image so that it is centered within the reference
// rectangle defined above.
wxCoord xoff = (fitRect.width - maxX) / 2;
wxCoord yoff = (fitRect.height - maxY) / 2;
OffsetLogicalOrigin(xoff, yoff);
// This offsets the image so that it is positioned at the bottom right of
// the reference rectangle defined above.
// wxCoord xoff = (fitRect.width - maxX);
// wxCoord yoff = (fitRect.height - maxY);
// OffsetLogicalOrigin(xoff, yoff);
wxGetApp().Draw(*GetDC());
}
void MyPrintout::DrawPageTwo()
{
// You might use THIS code to set the printer DC to ROUGHLY reflect
// the screen text size. This page also draws lines of actual length
// 5cm on the page.
// Compare this to DrawPageOne(), which uses the really convenient routines
// from wxPrintout to fit the screen image onto the printed page. This page
// illustrates how to do all the scaling calculations yourself, if you're so
// inclined.
wxDC *dc = GetDC();
// Get the logical pixels per inch of screen and printer
int ppiScreenX, ppiScreenY;
GetPPIScreen(&ppiScreenX, &ppiScreenY);
int ppiPrinterX, ppiPrinterY;
GetPPIPrinter(&ppiPrinterX, &ppiPrinterY);
// This scales the DC so that the printout roughly represents the screen
// scaling. The text point size _should_ be the right size but in fact is
// too small for some reason. This is a detail that will need to be
// addressed at some point but can be fudged for the moment.
float scale = (float)((float)ppiPrinterX/(float)ppiScreenX);
// Now we have to check in case our real page size is reduced (e.g. because
// we're drawing to a print preview memory DC)
int pageWidth, pageHeight;
int w, h;
dc->GetSize(&w, &h);
GetPageSizePixels(&pageWidth, &pageHeight);
// If printer pageWidth == current DC width, then this doesn't change. But w
// might be the preview bitmap width, so scale down.
float overallScale = scale * (float)(w/(float)pageWidth);
dc->SetUserScale(overallScale, overallScale);
// Calculate conversion factor for converting millimetres into logical
// units. There are approx. 25.4 mm to the inch. There are ppi device units
// to the inch. Therefore 1 mm corresponds to ppi/25.4 device units. We also
// divide by the screen-to-printer scaling factor, because we need to
// unscale to pass logical units to DrawLine.
// Draw 50 mm by 50 mm L shape
float logUnitsFactor = (float)(ppiPrinterX/(scale*25.4));
float logUnits = (float)(50*logUnitsFactor);
dc->SetPen(* wxBLACK_PEN);
dc->DrawLine(50, 250, (long)(50.0 + logUnits), 250);
dc->DrawLine(50, 250, 50, (long)(250.0 + logUnits));
dc->SetBackgroundMode(wxTRANSPARENT);
dc->SetBrush(*wxTRANSPARENT_BRUSH);
{ // GetTextExtent demo:
wxString words[7] = { wxT("This "), wxT("is "), wxT("GetTextExtent "),
wxT("testing "), wxT("string. "), wxT("Enjoy "), wxT("it!") };
wxCoord w, h;
long x = 200, y= 250;
wxFont fnt(15, wxSWISS, wxNORMAL, wxNORMAL);
dc->SetFont(fnt);
for (int i = 0; i < 7; i++)
{
wxString word = words[i];
word.Remove( word.Len()-1, 1 );
dc->GetTextExtent(word, &w, &h);
dc->DrawRectangle(x, y, w, h);
dc->GetTextExtent(words[i], &w, &h);
dc->DrawText(words[i], x, y);
x += w;
}
}
dc->SetFont(wxGetApp().GetTestFont());
dc->DrawText(wxT("Some test text"), 200, 300 );
// TESTING
int leftMargin = 20;
int rightMargin = 20;
int topMargin = 20;
int bottomMargin = 20;
int pageWidthMM, pageHeightMM;
GetPageSizeMM(&pageWidthMM, &pageHeightMM);
float leftMarginLogical = (float)(logUnitsFactor*leftMargin);
float topMarginLogical = (float)(logUnitsFactor*topMargin);
float bottomMarginLogical = (float)(logUnitsFactor*(pageHeightMM - bottomMargin));
float rightMarginLogical = (float)(logUnitsFactor*(pageWidthMM - rightMargin));
dc->SetPen(* wxRED_PEN);
dc->DrawLine( (long)leftMarginLogical, (long)topMarginLogical,
(long)rightMarginLogical, (long)topMarginLogical);
dc->DrawLine( (long)leftMarginLogical, (long)bottomMarginLogical,
(long)rightMarginLogical, (long)bottomMarginLogical);
WritePageHeader(this, dc, wxT("A header"), logUnitsFactor);
}
// Writes a header on a page. Margin units are in millimetres.
bool MyPrintout::WritePageHeader(wxPrintout *printout, wxDC *dc, const wxString&text, float mmToLogical)
{
#if 0
static wxFont *headerFont = (wxFont *) NULL;
if (!headerFont)
{
headerFont = wxTheFontList->FindOrCreateFont(16, wxSWISS, wxNORMAL, wxBOLD);
}
dc->SetFont(headerFont);
#endif
int pageWidthMM, pageHeightMM;
printout->GetPageSizeMM(&pageWidthMM, &pageHeightMM);
wxUnusedVar(pageHeightMM);
int leftMargin = 10;
int topMargin = 10;
int rightMargin = 10;
float leftMarginLogical = (float)(mmToLogical*leftMargin);
float topMarginLogical = (float)(mmToLogical*topMargin);
float rightMarginLogical = (float)(mmToLogical*(pageWidthMM - rightMargin));
wxCoord xExtent, yExtent;
dc->GetTextExtent(text, &xExtent, &yExtent);
float xPos = (float)(((((pageWidthMM - leftMargin - rightMargin)/2.0)+leftMargin)*mmToLogical) - (xExtent/2.0));
dc->DrawText(text, (long)xPos, (long)topMarginLogical);
dc->SetPen(* wxBLACK_PEN);
dc->DrawLine( (long)leftMarginLogical, (long)(topMarginLogical+yExtent),
(long)rightMarginLogical, (long)topMarginLogical+yExtent );
return true;
}
| 32.0894 | 116 | 0.641646 | madanagopaltcomcast |
1e2ab834a1ae1626cd4b9e080ba22a4dc2028d6b | 608 | cpp | C++ | NOI[OpenJudge]/1.13/1.13.12.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | NOI[OpenJudge]/1.13/1.13.12.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | NOI[OpenJudge]/1.13/1.13.12.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | //Code By HeRaNO
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int x[11], y[11];
int gcd(int a, int b)
{
if (b == 0)return a;
else return gcd(b, a % b);
}
void jia(int n, int m)
{
int k = y[n] * y[m] / gcd(y[n], y[m]);
x[n] = x[n] * (k / y[n]);
x[m] = x[m] * (k / y[m]);
x[n] = x[n] + x[m];
y[n] = k;
int ys = gcd(x[n], y[n]);
x[n] /= ys;
y[n] /= ys;
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)scanf("%d/%d", &x[i], &y[i]);
for (int i = 2; i <= n; i++)jia(i, i - 1);
if (y[n] == 1)cout << x[n];
else cout << x[n] << "/" << y[n];
return 0;
}
| 16.432432 | 58 | 0.457237 | HeRaNO |
1e2b0c6287b7d20bdcb81c4159cf97e0a266831b | 3,072 | cpp | C++ | code/console/duino/osal_duino_sysconsole.cpp | iocafe/eosal | e71239d4d6600c5e14f71a5434c2d56901c7bee8 | [
"MIT"
] | 1 | 2020-04-28T23:26:32.000Z | 2020-04-28T23:26:32.000Z | code/console/duino/osal_duino_sysconsole.cpp | iocafe/eosal | e71239d4d6600c5e14f71a5434c2d56901c7bee8 | [
"MIT"
] | null | null | null | code/console/duino/osal_duino_sysconsole.cpp | iocafe/eosal | e71239d4d6600c5e14f71a5434c2d56901c7bee8 | [
"MIT"
] | 1 | 2021-06-18T06:03:44.000Z | 2021-06-18T06:03:44.000Z | /**
@file console/duino/osal_duino_sysconsole.c
@brief Operating system default console IO.
@author Pekka Lehtikoski
@version 1.0
@date 26.4.2021
The osal_sysconsole_write() function writes text to the console or serial port designated
for debug output, and the osal_sysconsole_read() prosesses input from system console or
serial port.
Copyright 2020 Pekka Lehtikoski. This file is part of the eosal and shall only be used,
modified, and distributed under the terms of the project licensing. By continuing to use, modify,
or distribute this file you indicate that you have read the license and understand and accept
it fully.
****************************************************************************************************
*/
#include "eosal.h"
#ifdef OSAL_ARDUINO
#if OSAL_CONSOLE
/**
****************************************************************************************************
@brief Initialize system console.
@anchor osal_sysconsole_initialize
The osal_sysconsole_initialize() function should do any initialization necessary to use the
system console, for example to set serial port.
@return None
****************************************************************************************************
*/
void osal_sysconsole_initialize(
void)
{
}
#if OSAL_PROCESS_CLEANUP_SUPPORT
/**
****************************************************************************************************
@brief Shut down system console.
@anchor osal_sysconsole_shutdown
The osal_sysconsole_shutdown() function restores console state as it was.
@return None
****************************************************************************************************
*/
void osal_sysconsole_shutdown(
void)
{
}
#endif
/**
****************************************************************************************************
@brief Write text to system console.
@anchor osal_sysconsole_write
The osal_sysconsole_write() function writes a string to the default console o fthe process, if any.
@param text Pointer to string to write.
@return Pointer to the allocated memory block, or OS_NULL if the function failed (out of
memory).
****************************************************************************************************
*/
void osal_sysconsole_write(
const os_char *text)
{
Serial.write(text);
Serial.flush();
}
/**
****************************************************************************************************
@brief Read character from system console.
@anchor osal_sysconsole_run
The osal_sysconsole_read() function reads the input from system console. If there are any
input, the callbacks monitoring the input from this console will get called.
@return UTF32 character or 0 if none.
****************************************************************************************************
*/
os_uint osal_sysconsole_read(
void)
{
if (Serial.available())
{
return Serial.read();
}
return 0;
}
#endif
#endif
| 27.428571 | 101 | 0.516602 | iocafe |
1e2d13ac8bc4481b41902a0b91138e16ac003f56 | 1,427 | cpp | C++ | src/viewer/GlErrors.cpp | serserar/ModelConverter | 23e6237a347dc959de191d4cc378defb0a9d044b | [
"MIT"
] | null | null | null | src/viewer/GlErrors.cpp | serserar/ModelConverter | 23e6237a347dc959de191d4cc378defb0a9d044b | [
"MIT"
] | null | null | null | src/viewer/GlErrors.cpp | serserar/ModelConverter | 23e6237a347dc959de191d4cc378defb0a9d044b | [
"MIT"
] | null | null | null | /* -*- c++ -*- */
/////////////////////////////////////////////////////////////////////////////
//
// GlErrors.cpp -- Copyright (c) 2006-2007 David Henry
// last modification: jan. 24, 2007
//
// This code is licenced under the MIT license.
//
// This software is provided "as is" without express or implied
// warranties. You may freely copy and compile this source into
// applications you distribute provided that the copyright text
// below is included in the resulting source code.
//
// OpenGL error management.
//
/////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif // _WIN32
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
#include "GlErrors.h"
using std::cerr;
using std::endl;
// -------------------------------------------------------------------------
// checkOpenGLErrors
//
// Print the last OpenGL error code. @file is the filename where the
// function has been called, @line is the line number. You should use
// this function like this:
// checkOpenGLErrors (__FILE__, __LINE__);
// -------------------------------------------------------------------------
GLenum
checkOpenGLErrors (const char *file, int line)
{
GLenum errCode = glGetError ();
if (errCode != GL_NO_ERROR)
cerr << "(GL) " << file << " (" << line << "): "
<< gluErrorString (errCode) << endl;
return errCode;
}
| 26.924528 | 77 | 0.537491 | serserar |
1e35abe759f50e9a5cb976bc75ffd4aa1dedfa94 | 1,595 | cpp | C++ | src/RDP/Unity/main.cpp | RoboticsDevelopmentProjects/spp-base-library | f8e1be763da49fd226b708e5aeeaaccc2ef37246 | [
"MIT"
] | null | null | null | src/RDP/Unity/main.cpp | RoboticsDevelopmentProjects/spp-base-library | f8e1be763da49fd226b708e5aeeaaccc2ef37246 | [
"MIT"
] | null | null | null | src/RDP/Unity/main.cpp | RoboticsDevelopmentProjects/spp-base-library | f8e1be763da49fd226b708e5aeeaaccc2ef37246 | [
"MIT"
] | null | null | null | #include "Unity.h"
#include <ros/ros.h>
#if 0
#include <ros/ros.h>
#include <std_msgs/Empty.h>
int main(int argc, char *argv[]){
ros::init(argc, argv, "Unity");
ros::NodeHandle node;
ros::Publisher pub = node.advertise<std_msgs::Empty>("startSpeechRecognition", 100);
ros::Rate loopRate(5);
for(int i=0; i < 3; i++){
loopRate.sleep();
}
//while(ros::ok()){
std_msgs::Empty msg;
pub.publish(msg);
ROS_INFO("publish startSpeechRecognition");
ros::spinOnce();
loopRate.sleep();
//}
return 0;
}
#else
int main(int argc, char *argv[]){
Unity unity(argc, argv);
#ifdef SHARE_DIR
ROS_INFO("defined share_dir = %s", SHARE_DIR);
#else
ROS_INFO("not defined share_dir");
#endif
//ROS_INFO("CATKIN_PACKAGE_SHARE = %s",SHARE_DIR);
sleep(5);
unity.startSpeechRecognition();
unity.startUserRecognition();
while(ros::ok()) unity.statusUpdate();
}
#endif
/*
#include "ros/ros.h"
#include "RDP/AddTwoInts.h"
#include <cstdlib>
int main(int argc, char **argv)
{
ros::init(argc, argv, "add_two_ints_client");
if (argc != 3)
{
ROS_INFO("usage: add_two_ints_client X Y");
return 1;
}
ros::NodeHandle n;
ros::ServiceClient client = n.serviceClient<RDP::AddTwoInts>("add_two_ints");
RDP::AddTwoInts srv;
srv.request.a = atoll(argv[1]);
srv.request.b = atoll(argv[2]);
if (client.call(srv))
{
ROS_INFO("Sum: %ld", (long int)srv.response.sum);
}
else
{
ROS_ERROR("Failed to call service add_two_ints");
return 1;
}
return 0;
}
*/
| 19.45122 | 88 | 0.618182 | RoboticsDevelopmentProjects |
1e36a8ebc3a60f0c5cf24d7a032cd323d6003877 | 2,673 | cpp | C++ | deprecated_old_files/deprecated_workspace_pkgs/move_base_tf/src/move_base_odom.cpp | Torreshan/TurtleBot | c6ae948364f82f505581dad2ee2dceb95fdcfba8 | [
"MIT"
] | 1 | 2019-01-31T13:13:03.000Z | 2019-01-31T13:13:03.000Z | deprecated_old_files/deprecated_workspace_pkgs/move_base_tf/src/move_base_odom.cpp | Torreshan/TurtleBot | c6ae948364f82f505581dad2ee2dceb95fdcfba8 | [
"MIT"
] | null | null | null | deprecated_old_files/deprecated_workspace_pkgs/move_base_tf/src/move_base_odom.cpp | Torreshan/TurtleBot | c6ae948364f82f505581dad2ee2dceb95fdcfba8 | [
"MIT"
] | 1 | 2019-01-14T16:24:05.000Z | 2019-01-14T16:24:05.000Z | #include <ros/ros.h>
#include <tf/tf.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Pose2D.h>
#include <nav_msgs/Odometry.h>
#include <math.h>
geometry_msgs::Pose2D current_pose;
void odomCallback(const nav_msgs::OdometryConstPtr& msg)
{
// linear position
current_pose.x = msg->pose.pose.position.x;
current_pose.y = msg->pose.pose.position.y;
// quaternion to RPY conversion
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
// angular position
current_pose.theta = yaw;
pub_pose2d.publish(current_pose);
}
int main(int argc, char **argv)
{
const double PI = 3.14159265358979323846;
ROS_INFO("start");
ros::init(argc, argv, "move_pub");
ros::NodeHandle n;
ros::Publisher pub_pose2d = n.advertise("turtlebot_pose2d", 1);
ros::Subscriber sub_odometry = n.subscribe("odom", 1, odomCallback);
ros::Publisher movement_pub = n.advertise("cmd_vel",1); //for sensors the value after , should be higher to get a more accurate result (queued)
ros::Rate rate(10); //the larger the value, the "smoother" , try value of 1 to see "jerk" movement
//move forward
ROS_INFO("move forward");
ros::Time start = ros::Time::now();
while(ros::ok() && current_pose.x < 1.5) {
geometry_msgs::Twist move; //velocity controls
move.linear.x = 0.2; //speed value m/s
move.angular.z = 0;
movement_pub.publish(move);
ros::spinOnce();
rate.sleep();
}
//turn right
ROS_INFO("turn right");
ros::Time start_turn = ros::Time::now();
while(ros::ok() && current_pose.theta > -PI/2)
{
geometry_msgs::Twist move;
//velocity controls
move.linear.x = 0; //speed value m/s
move.angular.z = -0.3;
movement_pub.publish(move);
ros::spinOnce();
rate.sleep();
}
//move forward again
ROS_INFO("move forward");
ros::Time start2 = ros::Time::now();
while(ros::ok() && current_pose.y > -1.5)
{
geometry_msgs::Twist move;
//velocity controls
move.linear.x = 0.2; //speed value m/s
move.angular.z = 0;
movement_pub.publish(move);
ros::spinOnce();
rate.sleep();
}
// just stop
while(ros::ok()) {
geometry_msgs::Twist move;
move.linear.x = 0;
move.angular.z = 0;
movement_pub.publish(move);
ros::spinOnce();
rate.sleep();
}
return 0;
}
| 26.73 | 147 | 0.605312 | Torreshan |
1e380c5622561779bd3440e733a1cf5ec7ffc016 | 29,728 | cpp | C++ | videowidget.cpp | Svensational/TrackIt | 7dc9d24ce4a7fb7ed79f0f915027316d9b225cb1 | [
"MIT"
] | null | null | null | videowidget.cpp | Svensational/TrackIt | 7dc9d24ce4a7fb7ed79f0f915027316d9b225cb1 | [
"MIT"
] | null | null | null | videowidget.cpp | Svensational/TrackIt | 7dc9d24ce4a7fb7ed79f0f915027316d9b225cb1 | [
"MIT"
] | null | null | null | #include "videowidget.h"
#include <iostream>
#include <QtCore/QTimer>
#include <QtGui/QFileDialog>
#include <QtGui/QFormLayout>
#include <QtGui/QLabel>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtGui/QSpinBox>
#include <QtGui/QWheelEvent>
#include <opencv2/core/core.hpp>
#include <GL/glext.h>
#include "datawidget.h"
#include "object.h"
inline int getNearestPOT(int n) {
int m = 1;
while (m<n) {
m*=2;
}
return m;
}
VideoWidget::VideoWidget(DataWidget * data, QWidget * parent) :
QGLWidget(parent),
autoZoom(true),
showCenterLines(true),
createBoxFlag(false),
createKeyboxFlag(false),
videoSize(QSize()),
zoom(1.0),
texCoords(QSizeF(1.0, 1.0)),
currentTexture(0),
currentFrame(0),
selectedObj(NULL),
selectedBBox(NULL),
hitArea(NONE),
data(data),
cacheEnabled(true),
cacheSize(45)
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(showNextFrame()));
setMouseTracking(true);
}
/** The framerate is obtained from the openCV \ref capture
*/
double VideoWidget::getFramerate() {
return capture.get(CV_CAP_PROP_FPS);
}
/** The corresponding object is retrieved from the DataWidget. The \ref
* selectedBBox is updated as well.
* \sa void selectionChanged(int id)
*/
void VideoWidget::changeSelection(int id) {
if (!selectedObj || selectedObj->getID()!=id) {
selectedObj = data->getObject(id);
if (selectedObj) {
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
}
else {
selectedBBox = NULL;
}
updateGL();
}
}
/** Internally the \ref createBoxFlag is set and the cursor is set to a
* crosshair. If a virtual box exists it gets converted to a single box instead
* and if a box exists for the last frame it gets copied instead, so it should
* be easier to create consistent boxes.
* \sa void createKeyBBox()
*/
void VideoWidget::createBBox() {
if (!selectedObj || createBoxFlag) {
// cancel already started creation
createBoxFlag = false;
unsetCursor();
emit boxCreationStarted(false);
return;
}
BBox currentBBox = selectedObj->getBBox(currentFrame);
if (currentBBox.type) {
// it's a existing box
currentBBox.type = BBox::SINGLE;
selectedObj->addBBox(currentBBox);
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
emit boxCreationStarted(false);
emit updateActions();
}
else {
// no box present
BBox * previousBBox = selectedObj->getBBoxPointer(currentFrame-1);
if (previousBBox) {
// preceding box present
selectedObj->addBBox(BBox(currentFrame,
previousBBox->rect,
selectedObj->getID(),
BBox::SINGLE));
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
emit boxCreationStarted(false);
emit updateActions();
}
else {
// really nothing present
createBoxFlag = true;
setCursor(Qt::CrossCursor);
}
}
updateGL();
}
/** Internally the \ref createKeyboxFlag is set and the cursor is set to a
* crosshair. If a virtual box exists it gets converted to a key box instead
* and if a box exists before it gets copied instead.
* \sa void createBBox()
*/
void VideoWidget::createKeyBBox() {
if (!selectedObj || createKeyboxFlag) {
createKeyboxFlag = false;
unsetCursor();
emit boxCreationStarted(false);
return;
}
BBox currentBBox = selectedObj->getBBox(currentFrame);
if (currentBBox.type) {
// it's a existing box
currentBBox.type = BBox::KEYBOX;
selectedObj->addBBox(currentBBox);
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
emit boxCreationStarted(false);
emit updateActions();
}
else {
// no box present
BBox * previousBBox = selectedObj->getPrecedingBBoxPointer(currentFrame);
if (previousBBox) {
// preceding box present
selectedObj->addBBox(BBox(currentFrame,
previousBBox->rect,
selectedObj->getID(),
BBox::KEYBOX));
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
emit boxCreationStarted(false);
emit updateActions();
}
else {
// really nothing present
createKeyboxFlag = true;
setCursor(Qt::CrossCursor);
}
}
updateGL();
}
/** The GL states are set and a default projection is defined.
*/
void VideoWidget::initializeGL() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glLineStipple(1, 0xF0F0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 1.0, 0.0, -5.0, 5.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/** Internally a small QRect is created, moved to every handles position and
* checked for containment of the \a pos
* \note The \a pos has to be in video coordinates!
*/
VideoWidget::Hitarea VideoWidget::isHit(QRect const & rect, QPoint const & pos) const {
QRect handle(QPoint(0, 0), QSize(9, 9)/zoom);
handle.moveCenter(rect.topLeft());
if (handle.contains(pos)) {
return TOPLEFT;
}
handle.moveCenter(rect.topRight());
if (handle.contains(pos)) {
return TOPRIGHT;
}
handle.moveCenter(rect.bottomLeft());
if (handle.contains(pos)) {
return BOTTOMLEFT;
}
handle.moveCenter(rect.bottomRight());
if (handle.contains(pos)) {
return BOTTOMRIGHT;
}
handle.moveCenter(QPoint(rect.center().x(), rect.top()));
if (handle.contains(pos)) {
return TOP;
}
handle.moveCenter(QPoint(rect.left(), rect.center().y()));
if (handle.contains(pos)) {
return LEFT;
}
handle.moveCenter(QPoint(rect.right(), rect.center().y()));
if (handle.contains(pos)) {
return RIGHT;
}
handle.moveCenter(QPoint(rect.center().x(), rect.bottom()));
if (handle.contains(pos)) {
return BOTTOM;
}
if (rect.contains(pos)) {
return CENTER;
}
return NONE;
}
/** If \ref hitArea is defined the according edge/corner of the box gets moved.
* Else the cursor gets updated via updateCursor().
*/
void VideoWidget::mouseMoveEvent(QMouseEvent * event) {
if (selectedBBox) {
const QPoint delta = event->pos()/zoom - hitPos;
hitPos = event->pos()/zoom;
switch (hitArea) {
case TOPLEFT:
selectedBBox->rect.setTopLeft(selectedBBox->rect.topLeft()+delta);
break;
case TOP:
selectedBBox->rect.setTop(selectedBBox->rect.top()+delta.y());
break;
case TOPRIGHT:
selectedBBox->rect.setTopRight(selectedBBox->rect.topRight()+delta);
break;
case LEFT:
selectedBBox->rect.setLeft(selectedBBox->rect.left()+delta.x());
break;
case CENTER:
selectedBBox->rect.moveCenter(selectedBBox->rect.center()+delta);
break;
case RIGHT:
selectedBBox->rect.setRight(selectedBBox->rect.right()+delta.x());
break;
case BOTTOMLEFT:
selectedBBox->rect.setBottomLeft(selectedBBox->rect.bottomLeft()+delta);
break;
case BOTTOM:
selectedBBox->rect.setBottom(selectedBBox->rect.bottom()+delta.y());
break;
case BOTTOMRIGHT:
selectedBBox->rect.setBottomRight(selectedBBox->rect.bottomRight()+delta);
break;
default:
updateCursor();
break;
}
}
event->ignore();
if (hitArea) {
updateData();
}
}
/** If \ref createBoxFlag or \ref createKeyboxFlag is set a new zero sized
* bounding box gets created at the \a events position and \ref hitArea is set
* to \ref BOTTOMRIGHT so a following move event will resize the box.\n
* Else, if a BBox is currently selected the corresponding \ref Hitarea is
* determined.\n
* If a unselected BBox or nothing gets hit the \ref selectedObj and \ref
* selectedBBox are updated.
*/
void VideoWidget::mousePressEvent(QMouseEvent * event) {
hitArea = NONE;
hitPos = event->pos()/zoom;
if (createBoxFlag || createKeyboxFlag) {
BBox bbox(currentFrame,
QRect(hitPos, QSize(1, 1)),
selectedObj->getID(),
createBoxFlag?BBox::SINGLE:BBox::KEYBOX);
selectedObj->addBBox(bbox);
updateData();
hitArea = BOTTOMRIGHT;
createBoxFlag = false;
createKeyboxFlag = false;
emit boxCreationStarted(false);
emit updateActions();
}
else {
// check whether and where the selected BBox was hit
if (selectedBBox) {
hitArea = isHit(selectedBBox->rect, hitPos);
}
if (!hitArea) {
bboxes = data->getBBoxes(currentFrame);
int i = bboxes.size();
bool hit = false;
while (!hit && i>0) {
hit = bboxes.at(--i).rect.contains(hitPos);
}
if (hit) {
selectedObj = data->getObject(bboxes.at(i).objectID);
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
emit selectionChanged(bboxes.at(i).objectID);
updateCursor();
}
else {
selectedObj = NULL;
selectedBBox = NULL;
emit selectionChanged(-1);
}
}
}
event->ignore();
updateGL();
}
/** \ref hitArea is set to \ref NONE and created boxes get normalized
*/
void VideoWidget::mouseReleaseEvent(QMouseEvent * event) {
hitArea = NONE;
// correct wrong BBs
if (selectedBBox && !selectedBBox->rect.isValid()) {
selectedBBox->rect = selectedBBox->rect.normalized();
}
event->accept();
}
/** If the video doesn't exists nothing happens, else it is opened without any
* further prompt into the openCV \ref capture and a VideofileInfo gets
* screated and sent to the DataWidget.
*/
void VideoWidget::openRequest(QString openFilename) {
QString filename = openFilename;
if (!QFile::exists(filename)) {
filename = QFileDialog::getOpenFileName(this,
tr("Linked video file couldn't be found"),
filename,
tr("Videos (*.avi *.mpg);;All files (*.*)"));
if (filename.isEmpty()) {
return;
}
}
capture.open(filename.toStdString());
if (!capture.isOpened()) {
QMessageBox::warning(this,
tr("Unable to open video"),
tr("The file\n\"")+filename+tr("\"\ncouldn't be opened as a video!"));
return;
}
videoSize.setWidth(capture.get(CV_CAP_PROP_FRAME_WIDTH));
videoSize.setHeight(capture.get(CV_CAP_PROP_FRAME_HEIGHT));
resizeTexture();
setZoom(1.0);
emit maxFramesChanged(capture.get(CV_CAP_PROP_FRAME_COUNT));
data->setVFInfo(VideofileInfo(filename.section('/', -1),
capture.get(CV_CAP_PROP_FRAME_COUNT),
videoSize));
// Just to make sure everything updates
currentFrame = -1;
clearFrameCache();
emit currentFrameChanged(1);
seek(0);
}
/** The filename is asked from the user via a QFileDialog and the video is
* opened using \ref openRequest
*/
void VideoWidget::openVideoFile() {
QString filename = QFileDialog::getOpenFileName(this,
tr("Open video file"),
QString(),
tr("Videos (*.avi *.mpg *.mpeg *.mp4 *.m4v *.mkv *.flv *.wmv);;All files (*.*)"));
if (filename.isEmpty()) {
return;
}
QDir::setCurrent(filename.section('/', 0, -2));
openRequest(filename);
}
/** First the current video frame gets rendered, then the currently visible
* bounding boxes and the selected object.
* \sa void renderCurrentFrame() const
* \sa void renderBBox(BBox const & bbox, bool active) const
* \sa void renderSelectedObject() const
*/
void VideoWidget::paintGL() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 1.0, 0.0, -5.0, 5.0);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
renderCurrentFrame();
glLoadIdentity();
glOrtho(0.5f, videoSize.width()+0.5f, videoSize.height()+0.5f, 0.5f, -5.0f, 5.0f);
foreach (BBox const & bbox, bboxes) {
if (!selectedObj || bbox.objectID != selectedObj->getID()) {
renderBBox(bbox);
}
}
renderSelectedObject();
}
/** The \ref timer gets started with a interval according to the videos FPS and
* \ref playToggled gets emitted with true.
* \note the \ref timer timeout signal is connected to showNextFrame()
*/
void VideoWidget::play(bool play) {
if (capture.isOpened()) {
if (play) {
timer->start(1000.0/capture.get(CV_CAP_PROP_FPS));
}
else {
timer->stop();
}
emit playToggled(play);
}
else {
emit playToggled(false);
}
}
/** The color gets chosen according to \a active
*/
void VideoWidget::renderBBox(BBox const & bbox, bool active) const {
// create Array holding the bbox vertices:
int theBox[16] = { bbox.rect.left(), bbox.rect.bottom(),
bbox.rect.right(), bbox.rect.bottom(),
bbox.rect.right(), bbox.rect.top(),
bbox.rect.left(), bbox.rect.top(),
bbox.rect.left(), bbox.rect.center().y(),
bbox.rect.center().x(), bbox.rect.bottom(),
bbox.rect.right(), bbox.rect.center().y(),
bbox.rect.center().x(), bbox.rect.top()};
//render outlines
glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
if (active) {
glLineWidth(4.5f);
}
else {
glLineWidth(3.5f);
}
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_INT, 0, &theBox);
glDrawArrays(GL_LINE_LOOP, 0, 4);
if (active && (bbox.type==BBox::SINGLE || bbox.type==BBox::KEYBOX)) {
glPointSize(9.0f);
glDrawArrays(GL_POINTS, 0, 8);
}
//render box
switch (bbox.type) {
case BBox::SINGLE:
glColor4ub(102, 194, 165, 255);
break;
case BBox::KEYBOX:
glColor4ub(252, 141, 98, 255);
break;
case BBox::VIRTUAL:
glColor4ub(141, 160, 203, 255);
break;
default:
break;
}
if (active) {
glLineWidth(2.5f);
}
else {
glLineWidth(1.5f);
}
glDrawArrays(GL_LINE_LOOP, 0, 4);
if (active && (bbox.type==BBox::SINGLE || bbox.type==BBox::KEYBOX)) {
glPointSize(7.0f);
glDrawArrays(GL_POINTS, 0, 8);
}
glDisableClientState(GL_VERTEX_ARRAY);
}
/** The object is represented by a white line connecting the center of all of
* its BBoxes. The selected box is also rendered as a fat box with visible
* handles and a white point at its center to clarify its position on the white
* line.
* \sa void renderCenterline() const
* \sa void renderBBox(BBox const & bbox, bool active = false) const
*/
void VideoWidget::renderSelectedObject() const {
if (!selectedObj) {
return;
}
if (showCenterLines){
renderCenterline();
}
// now paint BBox
BBox bbox = selectedObj->getBBox(currentFrame);
if (bbox.type) {
glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
glPointSize(9.0f);
glBegin(GL_POINTS);
glVertex2f(bbox.rect.center().x(), bbox.rect.center().y());
glEnd();
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glPointSize(7.0f);
glBegin(GL_POINTS);
glVertex2f(bbox.rect.center().x(), bbox.rect.center().y());
glEnd();
renderBBox(bbox, true);
}
}
/** The centerline connects the centers of all bounding boxes to represent an object
*/
void VideoWidget::renderCenterline() const {
int prevFrameNumber;
QPoint prevCenter;
// Paint Centerlines:
// set color for background lines
glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
glLineWidth(3.5f);
for (int pass=0; pass<2; ++pass) {
// paint solid lines
prevFrameNumber = selectedObj->firstBBox().framenumber;
prevCenter = selectedObj->firstBBox().rect.center();
glBegin(GL_LINES);
foreach (BBox const & bbox, selectedObj->getBBoxes()) {
if (bbox.type==BBox::SINGLE && bbox.framenumber==prevFrameNumber+1) {
glVertex2f(prevCenter.x(), prevCenter.y());
glVertex2f(bbox.rect.center().x(), bbox.rect.center().y());
}
prevFrameNumber = bbox.framenumber;
prevCenter = bbox.rect.center();
}
glEnd();
// paint stippled lines
prevFrameNumber = selectedObj->firstBBox().framenumber;
prevCenter = selectedObj->firstBBox().rect.center();
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINES);
foreach (BBox const & bbox, selectedObj->getBBoxes()) {
if (bbox.type==BBox::KEYBOX) {
glVertex2f(prevCenter.x(), prevCenter.y());
glVertex2f(bbox.rect.center().x(), bbox.rect.center().y());
}
prevFrameNumber = bbox.framenumber;
prevCenter = bbox.rect.center();
}
glEnd();
glDisable(GL_LINE_STIPPLE);
// set color for foreground lines (2nd pass)
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glLineWidth(1.5f);
}
}
/** Since the frame is saved in a GL texture simply a view filling quad with the
* said texture is rendered.
* \note Since the texture is ensured to have power of two dimensions the
* texture coordinates don't reach to 1.0 but to \ref texCoords.
*/
void VideoWidget::renderCurrentFrame() const {
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, texCoords.height());
glVertex2f(0.0f, 1.0f);
glTexCoord2f(texCoords.width(), texCoords.height());
glVertex2f(1.0f, 1.0f);
glTexCoord2f(texCoords.width(), 0.0f);
glVertex2f(1.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(0.0f, 0.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
}
/** Simply updates the viewport to the new \a width and \a height.
*/
void VideoWidget::resizeGL(int width, int height) {
glViewport(0, 0, width, height);
}
/** The width and height are powers of two to support legacy video systems.
* The Coordinate of the loose edge of the actual image data is saved in \ref
* texCoords for rendering.
*/
void VideoWidget::resizeTexture() {
const int widthPOT = getNearestPOT(videoSize.width());
const int heightPOT = getNearestPOT(videoSize.height());
texCoords = QSizeF(videoSize.width()/float(widthPOT), videoSize.height()/float(heightPOT));
glEnable(GL_TEXTURE_2D);
glDeleteTextures(1, ¤tTexture);
glGenTextures(1, ¤tTexture);
glBindTexture(GL_TEXTURE_2D, currentTexture);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, widthPOT, heightPOT, 0, GL_BGR, GL_UNSIGNED_BYTE, 0);
glDisable(GL_TEXTURE_2D);
}
/** seek: loads frames to show into texture.
* cacheSize frames before actual frame are cached to achieve better scrollback performance
* This is where framecaching is done: it consists of 6 cases:
* 1) cache is empty -> refill.
* 2) the frame requested is in the cache -> just show.
* 3) the frame is consecutively following the one in the cache (happens often)
-> cache new one, delete smallest one.
* 4) closer to the start than cache is big -> clear cache and refill from start.
* 5) from new frame backward towards cache is the stuff..
* 6) not in cache-> empty cache and refill
*/
void VideoWidget::seek(int frame) {
cv::Mat cvImage;
const int nextFrame = capture.get(CV_CAP_PROP_POS_FRAMES);
const int maxFrames = capture.get(CV_CAP_PROP_FRAME_COUNT);
if (frame == currentFrame){
updateGL();
return;
}
if ((frame < 0) || (frame >= maxFrames)) {
play(false);
return;
}
//calculate memory usage:
if (!cacheEnabled) {
if (frame != nextFrame) {
capture.set(CV_CAP_PROP_POS_FRAMES, frame);
}
currentFrame = frame;
emit currentFrameChanged(currentFrame);
capture >> cvImage;
updateTexture(cvImage);
hitArea = NONE;
updateData();
updateGL();
}else{
int firstElementIdx = fCache.lowerBound(0).key();
int lastElementIdx = (fCache.end()-1).key();
// if cache is empty fill,
if (fCache.isEmpty()){
if (frame-cacheSize < 0){
capture.set(CV_CAP_PROP_POS_FRAMES, 0);
for (int i=0; i<cacheSize; i++){
capture >> cvImage; // todo: refine into single line
fCache.insert(i,cvImage.clone());
}
}else{
capture.set(CV_CAP_PROP_POS_FRAMES, frame-cacheSize);
for (int i=frame-cacheSize; i<=frame; i++){
capture >> cvImage; // todo: refine into single line
fCache.insert(i,cvImage.clone());
}
}
updateTexture(fCache.value(frame));
// if cache is hit:
}else if ( (firstElementIdx <= frame)
&& (lastElementIdx >= frame)){
updateTexture(fCache.value(frame));
// if it's in cache+1 (happens often because +1 frame!):
}else if (frame == lastElementIdx+1){
// * load new frame, put it to last position of cache, delete the first in the cache
if(!(capture.get(CV_CAP_PROP_POS_FRAMES) == frame)){
capture.set(CV_CAP_PROP_POS_FRAMES, frame);
}
capture >> cvImage;
fCache.insert(frame, cvImage.clone());
updateTexture(fCache.value(frame));
fCache.remove(firstElementIdx);
// if too close to beginning to put everything in frame..
}else if (frame - cacheSize < 0){
// * delete cache and refill;
clearFrameCache();
seek(frame);
return;
// already some frames cached.....
}else if ((frame-cacheSize > firstElementIdx) &&
(frame-cacheSize < lastElementIdx)){
// delete frames from first frame to frame-cacheSize,
// set counter to last Cache Element+1 and add frames from there up to frame
if(!(capture.get(CV_CAP_PROP_POS_FRAMES) == lastElementIdx+1)){
capture.set(CV_CAP_PROP_POS_FRAMES, lastElementIdx+1);
}
for (int i=lastElementIdx+1; i<=frame; i++){
capture >> cvImage;
fCache.insert(i, cvImage.clone());
}
for (int i=firstElementIdx; i<frame-cacheSize; i++){
fCache.remove(i); // < remove unneeded beginning of cache
}
updateTexture(fCache.value(frame));
// totally not in cache, also old stuff not..
}else {
clearFrameCache();
seek(frame);
return;
}
//std::cout << "Cachesize: " << fCache.size() << " elements. \n";
currentFrame=frame;
emit currentFrameChanged(currentFrame);
hitArea=NONE;
updateData();
updateGL();
}
}
/** If \ref autoZoom is set the zoom is adjusted, too.
* @sa void setZoom(qreal newZoom)
*/
void VideoWidget::setAvailableSize(QSize newSize) {
if (availableSize != newSize) {
availableSize = newSize;
if (autoZoom && availableSize.isValid() && videoSize.isValid()) {
setZoom(qMin(availableSize.width()/float(videoSize.width()),
availableSize.height()/float(videoSize.height())));
}
}
}
/** Also emits signal \ref zoomChanged(float zoom)
*/
void VideoWidget::setZoom(qreal newZoom) {
zoom = qBound(0.1, newZoom, 2.0);
emit zoomChanged(zoom);
resize(videoSize*zoom);
}
/** Simply calls seek(currentFrame+1)
* @sa void seek(int frame)
*/
void VideoWidget::showNextFrame() {
/*
const int nextFrame = capture.get(CV_CAP_PROP_POS_FRAMES);
const int maxFrames = capture.get(CV_CAP_PROP_FRAME_COUNT);
if (nextFrame >= maxFrames) {
play(false);
return;
}
currentFrame = nextFrame;
emit currentFrameChanged(currentFrame);
cv::Mat cvImage;
capture >> cvImage;
updateTexture(cvImage);
hitArea = NONE;
updateData();
updateGL();
*/
seek(currentFrame+1);
}
/** Simply calls seek(currentFrame-1)
* @sa void seek(int frame)
*/
void VideoWidget::showPreviousFrame() {
/*
capture.set(CV_CAP_PROP_POS_FRAMES, currentFrame-1.0);
showNextFrame();
*/
seek(currentFrame-1);
}
/** If it's over a handle of the selected box it gets changed to a resize cursor
* else it's reset to the default cursor.
*/
void VideoWidget::updateCursor() {
if (selectedBBox) {
switch (isHit(selectedBBox->rect, hitPos)) {
case TOPLEFT:
setCursor(Qt::SizeFDiagCursor);
break;
case TOP:
setCursor(Qt::SizeVerCursor);
break;
case TOPRIGHT:
setCursor(Qt::SizeBDiagCursor);
break;
case LEFT:
setCursor(Qt::SizeHorCursor);
break;
case CENTER:
setCursor(Qt::SizeAllCursor);
break;
case RIGHT:
setCursor(Qt::SizeHorCursor);
break;
case BOTTOMLEFT:
setCursor(Qt::SizeBDiagCursor);
break;
case BOTTOM:
setCursor(Qt::SizeVerCursor);
break;
case BOTTOMRIGHT:
setCursor(Qt::SizeFDiagCursor);
break;
default:
unsetCursor();
break;
}
}
else {
unsetCursor();
}
}
/** This should be done whenever the data changes and the cached pointers could
* be invalid.
*/
void VideoWidget::updateData() {
bboxes = data->getBBoxes(currentFrame);
if (selectedObj) {
selectedBBox = selectedObj->getBBoxPointer(currentFrame);
}
updateGL();
}
/** \note OpenCV uses BGR, OpenGL uses RGB.
*/
void VideoWidget::updateTexture(cv::Mat const & mat) const {
glEnable(GL_TEXTURE_2D);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mat.cols, mat.rows, GL_BGR, GL_UNSIGNED_BYTE, (GLubyte*)mat.data);
glDisable(GL_TEXTURE_2D);
}
/** Scroll up: Zoom in - Scroll down: Zoom out
* \note The zoom factor is saved in \ref zoom and is clamped to [0.1, 2.0]
*/
void VideoWidget::wheelEvent(QWheelEvent * event) {
if (event->modifiers().testFlag(Qt::ControlModifier)) {
emit zoomChangedManually(false);
setZoom(zoom+event->delta()/1200.0);
event->accept();
}
else {
event->ignore();
}
}
/** The video also gets resized to fit the available size
*/
void VideoWidget::zoomFit(bool checked) {
if (autoZoom != checked) {
autoZoom = checked;
if (availableSize.isValid() && videoSize.isValid()) {
setZoom(qMin(availableSize.width()/float(videoSize.width()),
availableSize.height()/float(videoSize.height())));
}
}
}
void VideoWidget::zoomIn() {
emit zoomChangedManually(false);
setZoom(zoom+0.1);
}
void VideoWidget::zoomOut() {
emit zoomChangedManually(false);
setZoom(zoom-0.1);
}
void VideoWidget::zoomReset() {
emit zoomChangedManually(false);
setZoom(1.0);
}
void VideoWidget::toggleCache(){
if (cacheEnabled){
cacheEnabled = false;
clearFrameCache();
std::cout << "Cache is now disabled." << std::endl;
}else{
cacheEnabled = true;
clearFrameCache();
std::cout << "Cache is now enabled." << std::endl;
}
}
void VideoWidget::setCacheProperties(){
int size;
if (videoSize.isValid()){
size = (int)((float)cacheSize*(float)videoSize.width()*(float)videoSize.height()*3.0/(1024.0*1024.0));
cacheSizeFactor = (float)(videoSize.width()*videoSize.height());
}else{
size=0;
cacheSizeFactor=0.0;
}
QDialog * cacheSettingsWidget = new QDialog();
QFormLayout * settingsLayout = new QFormLayout(cacheSettingsWidget);
QSpinBox * cacheSizeBox = new QSpinBox();
QLabel * sizeInMb = new QLabel(QString::number(size) + QString(" MB"));
QLabel * newSizeLabel = new QLabel();
QPushButton *okBut = new QPushButton(tr("Ok"));
QPushButton *cancelBut = new QPushButton(tr("Cancel"));
cacheSettingsWidget->setWindowTitle(tr("Set Cache Size properties"));
cacheSizeBox->setMinimum(5);
cacheSizeBox->setValue(cacheSize);
connect(cacheSizeBox, SIGNAL(valueChanged(int)), this, SLOT(setCacheSizeText(int)));
connect(this, SIGNAL(cacheSizeChanged(QString)), newSizeLabel, SLOT(setText(QString)));
connect(cancelBut, SIGNAL(clicked()), cacheSettingsWidget, SLOT(reject()));
connect(okBut, SIGNAL(clicked()), cacheSettingsWidget, SLOT(accept()));
settingsLayout->addRow("Current Cache size: ", sizeInMb);
settingsLayout->addRow("Cache size in Frames:", cacheSizeBox);
settingsLayout->addRow("New cache size:", newSizeLabel);
settingsLayout->addRow(okBut, cancelBut);
setCacheSizeText(cacheSize);
if (cacheSettingsWidget->exec() == QDialog::Accepted){
setCacheSize(cacheSizeBox->value());
}
cacheSettingsWidget->deleteLater();
}
/** The cahce also gets cleared
*/
void VideoWidget::setCacheSize(int newSize){
cacheSize = newSize;
clearFrameCache();
}
void VideoWidget::setCacheSizeText(int size){
emit cacheSizeChanged(QString::number((int)(((float)size *cacheSizeFactor *3.0)/(1024.0*1024.0)))+ QString(" MB"));
}
void VideoWidget::clearFrameCache(){
fCache.clear();
}
void VideoWidget::toggleCenterlines(){
showCenterLines = !showCenterLines;
updateGL();
}
| 30.806218 | 133 | 0.623856 | Svensational |
1e3b07d31cedae760548d839efa3e6f79d63eb23 | 13,976 | cpp | C++ | src/core/Common.cpp | BlauHimmel/Hikari | 38746e5d03a8e106a346a6f792f3093034a576bb | [
"MIT"
] | 11 | 2018-11-22T03:07:10.000Z | 2022-03-31T15:51:29.000Z | src/core/Common.cpp | BlauHimmel/Hikari | 38746e5d03a8e106a346a6f792f3093034a576bb | [
"MIT"
] | 2 | 2019-02-14T15:05:42.000Z | 2019-07-26T06:07:13.000Z | src/core/Common.cpp | BlauHimmel/Hikari | 38746e5d03a8e106a346a6f792f3093034a576bb | [
"MIT"
] | 4 | 2018-12-18T12:40:07.000Z | 2022-03-31T15:51:31.000Z | #include <core\Common.hpp>
#include <core\Object.hpp>
#include <core\Vector.hpp>
#if defined(__PLATFORM_LINUX__)
#include <malloc.h>
#endif
#if defined(__PLATFORM_WINDOWS__)
#include <windows.h>
#endif
#if defined(__PLATFORM_MACOS__)
#include <sys/sysctl.h>
#endif
NAMESPACE_BEGIN
int GetCoreCount()
{
return int(std::thread::hardware_concurrency());
}
std::string Indent(const std::string & String, int Amount)
{
std::istringstream ISS(String);
std::ostringstream OSS;
std::string Spacer(Amount, ' ');
bool FirstLine = true;
for (std::string Line; std::getline(ISS, Line); )
{
if (!FirstLine)
{
OSS << Spacer;
}
OSS << Line;
if (!ISS.eof())
{
OSS << endl;
}
FirstLine = false;
}
return OSS.str();
}
std::string ToLower(const std::string & String)
{
std::function<char(char)> ToLower = [&](char C)
{
return char(tolower(int(C)));
};
std::string Result;
Result.resize(String.size());
std::transform(String.begin(), String.end(), Result.begin(), ToLower);
return Result;
}
bool ToBool(const std::string & String)
{
std::string Value = ToLower(String);
if (Value == "false")
{
return false;
}
else if (Value == "true")
{
return true;
}
else
{
throw HikariException("Could not parse boolean value \"%s\"", String);
}
}
int ToInt(const std::string & String)
{
char * pEnd = nullptr;
int Result = int(strtol(String.c_str(), &pEnd, 10));
if (*pEnd != '\0')
{
throw HikariException("Could not parse integer value \"%s\"", String);
}
return Result;
}
unsigned int ToUInt(const std::string & String)
{
char * pEnd = nullptr;
unsigned int Result = unsigned int(strtoul(String.c_str(), &pEnd, 10));
if (*pEnd != '\0')
{
throw HikariException("Could not parse integer value \"%s\"", String);
}
return Result;
}
float ToFloat(const std::string & String)
{
char * pEnd = nullptr;
float Result = float(strtof(String.c_str(), &pEnd));
if (*pEnd != '\0')
{
throw HikariException("Could not parse floating point value \"%s\"", String);
}
return Result;
}
Eigen::Vector3f ToVector3f(const std::string & String)
{
std::vector<std::string> Tokens = Tokenize(String);
if (Tokens.size() != 3)
{
throw HikariException("Expected 3 values");
}
Eigen::Vector3f Result;
for (int i = 0; i < 3; ++i)
{
Result[i] = ToFloat(Tokens[i]);
}
return Result;
}
std::vector<std::string> Tokenize(const std::string & String, const std::string & Delim, bool bIncludeEmpty)
{
std::string::size_type LastPos = 0, Pos = String.find_first_of(Delim, LastPos);
std::vector<std::string> Tokens;
while (LastPos != std::string::npos)
{
if (Pos != LastPos || bIncludeEmpty)
{
Tokens.push_back(String.substr(LastPos, Pos - LastPos));
}
LastPos = Pos;
if (LastPos != std::string::npos)
{
LastPos += 1;
Pos = String.find_first_of(Delim, LastPos);
}
}
return Tokens;
}
bool EndsWith(const std::string & String, const std::string & Ending)
{
if (Ending.size() > String.size())
{
return false;
}
return std::equal(Ending.rbegin(), Ending.rend(), String.rbegin());
}
std::string TimeString(double Time, bool bPrecise)
{
if (std::isnan(Time) || std::isinf(Time))
{
return "inf";
}
std::string Suffix = "ms";
if (Time > 1000)
{
Time /= 1000; Suffix = "s";
if (Time > 60)
{
Time /= 60; Suffix = "m";
if (Time > 60)
{
Time /= 60; Suffix = "h";
if (Time > 24)
{
Time /= 24; Suffix = "d";
}
}
}
}
std::ostringstream OS;
OS << std::setprecision(bPrecise ? 4 : 1) << std::fixed << Time << Suffix;
return OS.str();
}
std::string MemString(size_t Size, bool bPrecise)
{
double Value = double(Size);
const char * pSuffixes[] =
{
"B", "KiB", "MiB", "GiB", "TiB", "PiB"
};
int Suffix = 0;
while (Suffix < 5 && Value > 1024.0)
{
Value /= 1024.0; ++Suffix;
}
std::ostringstream OS;
OS << std::setprecision(Suffix == 0 ? 0 : (bPrecise ? 4 : 1)) << std::fixed << Value << " " << pSuffixes[Suffix];
return OS.str();
}
Color3f Clamp(Color3f Value, Color3f Min, Color3f Max)
{
return Color3f(
Clamp(Value[0], Min[0], Max[0]),
Clamp(Value[1], Min[1], Max[1]),
Clamp(Value[2], Min[2], Max[2])
);
}
Color4f Clamp(Color4f Value, Color4f Min, Color4f Max)
{
return Color4f(
Clamp(Value[0], Min[0], Max[0]),
Clamp(Value[1], Min[1], Max[1]),
Clamp(Value[2], Min[2], Max[2]),
Clamp(Value[3], Min[3], Max[3])
);
}
Color3f Lerp(float T, const Color3f & V1, const Color3f & V2)
{
return (1.0f - T) * V1 + T * V2;
}
Color4f Lerp(float T, const Color4f & V1, const Color4f & V2)
{
return (1.0f - T) * V1 + T * V2;
}
float EvalCubicInterpolate1D(
float X,
const float * pValues,
int Size,
float Min,
float Max,
bool bExtrapolate
)
{
/* Give up when given an out-of-range or NaN argument */
if (!(X >= Min && X <= Max) && !bExtrapolate)
{
return 0.0f;
}
/* Transform X so that knots lie at integer positions */
float T = ((X - Min) * (Size - 1)) / (Max - Min);
/* Find the index of the left knot in the queried subinterval, be
robust to cases where T lies exactly on the right endpoint */
int K = std::max(int(0), std::min(int(T), Size - 2));
float F0 = pValues[K], F1 = pValues[K + 1];
float D0, D1;
/* Approximate the derivatives */
if (K > 0)
{
D0 = 0.5f * (pValues[K + 1] - pValues[K - 1]);
}
else
{
D0 = pValues[K + 1] - pValues[K];
}
if (K + 2 < Size)
{
D1 = 0.5f * (pValues[K + 2] - pValues[K]);
}
else
{
D1 = pValues[K + 1] - pValues[K];
}
/* Compute the relative position within the interval */
T = T - float(K);
float T2 = T * T, T3 = T2 * T;
return (2.0f * T3 - 3.0f * T2 + 1) * F0 +
(-2.0f * T3 + 3.0f * T2) * F1 +
(T3 - 2.0f * T2 + T) * D0 +
(T3 - T2) * D1;
}
float EvalCubicInterpolate2D(
const Point2f & P,
const float * pValues,
const Point2i & Size,
const Point2f & Min,
const Point2f & Max,
bool bExtrapolate
)
{
float KnotWeights[2][4];
Point2i Knot;
/* Compute interpolation weights separately for each dimension */
for (int Dim = 0; Dim < 2; ++Dim)
{
float * pWeights = KnotWeights[Dim];
/* Give up when given an out-of-range or NaN argument */
if (!(P[Dim] >= Min[Dim] && P[Dim] <= Max[Dim]) && !bExtrapolate)
{
return 0.0f;
}
/* Transform P so that knots lie at integer positions */
float T = ((P[Dim] - Min[Dim]) * float(Size[Dim] - 1)) / (Max[Dim] - Min[Dim]);
/* Find the index of the left knot in the queried subinterval, be
robust to cases where 't' lies exactly on the right endpoint */
Knot[Dim] = std::min(int(T), Size[Dim] - 2);
/* Compute the relative position within the interval */
T = T - float(Knot[Dim]);
/* Compute node weights */
float T2 = T * T, T3 = T2 * T;
pWeights[0] = 0.0f;
pWeights[1] = 2.0f * T3 - 3.0f * T2 + 1;
pWeights[2] = -2.0f * T3 + 3.0f * T2;
pWeights[3] = 0.0f;
/* Derivative weights */
float D0 = T3 - 2.0f * T2 + T, D1 = T3 - T2;
/* Turn derivative weights into node weights using
an appropriate chosen finite differences stencil */
if (Knot[Dim] > 0)
{
pWeights[2] += 0.5f * D0;
pWeights[0] -= 0.5f * D0;
}
else
{
pWeights[2] += D0;
pWeights[1] -= D0;
}
if (Knot[Dim] + 2 < Size[Dim])
{
pWeights[3] += 0.5f * D1;
pWeights[1] -= 0.5f * D1;
}
else
{
pWeights[2] += D1;
pWeights[1] -= D1;
}
}
float Result = 0.0f;
for (int y = -1; y <= 2; y++)
{
float WY = KnotWeights[1][y + 1];
for (int x = -1; x <= 2; x++)
{
float WXY = KnotWeights[0][x + 1] * WY;
if (WXY == 0)
{
continue;
}
int Pos = (Knot[1] + y) * Size[0] + Knot[0] + x;
Result += pValues[Pos] * WXY;
}
}
return Result;
}
float EvalCubicInterpolate3D(
const Point3f & P,
const float * pValues,
const Point3i & Size,
const Point3f & Min,
const Point3f & Max,
bool bExtrapolate
)
{
float KnotWeights[3][4];
Point3i Knot;
/* Compute interpolation weights separately for each dimension */
for (int Dim = 0; Dim < 3; ++Dim)
{
float * pWeights = KnotWeights[Dim];
/* Give up when given an out-of-range or NaN argument */
if (!(P[Dim] >= Min[Dim] && P[Dim] <= Max[Dim]) && !bExtrapolate)
{
return 0.0f;
}
/* Transform P so that knots lie at integer positions */
float T = ((P[Dim] - Min[Dim]) * float(Size[Dim] - 1)) / (Max[Dim] - Min[Dim]);
/* Find the index of the left knot in the queried subinterval, be
robust to cases where 'T' lies exactly on the right endpoint */
Knot[Dim] = std::min(int(T), Size[Dim] - 2);
/* Compute the relative position within the interval */
T = T - float(Knot[Dim]);
/* Compute node weights */
float T2 = T * T, T3 = T2 * T;
pWeights[0] = 0.0f;
pWeights[1] = 2.0f * T3 - 3.0f * T2 + 1.0f;
pWeights[2] = -2.0f * T3 + 3.0f * T2;
pWeights[3] = 0.0f;
/* Derivative weights */
float D0 = T3 - 2.0f * T2 + T, D1 = T3 - T2;
/* Turn derivative weights into node weights using
an appropriate chosen finite differences stencil */
if (Knot[Dim] > 0)
{
pWeights[2] += 0.5f * D0;
pWeights[0] -= 0.5f * D0;
}
else
{
pWeights[2] += D0;
pWeights[1] -= D0;
}
if (Knot[Dim] + 2 < Size[Dim])
{
pWeights[3] += 0.5f * D1;
pWeights[1] -= 0.5f * D1;
}
else
{
pWeights[2] += D1;
pWeights[1] -= D1;
}
}
float Result = 0.0f;
for (int z = -1; z <= 2; z++)
{
float WZ = KnotWeights[2][z + 1];
for (int y = -1; y <= 2; y++)
{
float WYZ = KnotWeights[1][y + 1] * WZ;
for (int x = -1; x <= 2; x++)
{
float WXYZ = KnotWeights[0][x + 1] * WYZ;
if (WXYZ == 0)
{
continue;
}
int Pos = ((Knot[2] + z) * Size[1] + (Knot[1] + y)) * Size[0] + Knot[0] + x;
Result += pValues[Pos] * WXYZ;
}
}
}
return Result;
}
Vector3f SphericalDirection(float Theta, float Phi)
{
float SinTheta, CosTheta, SinPhi, CosPhi;
SinCos(Theta, &SinTheta, &CosTheta);
SinCos(Phi, &SinPhi, &CosPhi);
return Vector3f(
SinTheta * CosPhi,
SinTheta * SinPhi,
CosTheta
);
}
Point2f SphericalCoordinates(const Vector3f & Dir)
{
Point2f Result(
std::acos(Dir.z()),
std::atan2(Dir.y(), Dir.x())
);
if (Result.y() < 0)
{
Result.y() += 2.0f * float(M_PI);
}
return Result;
}
float FresnelDielectric(float CosThetaI, float Eta, float InvEta, float & CosThetaT)
{
if (Eta == 1.0f)
{
CosThetaT = -CosThetaI;
return 0.0f;
}
/* Using Snell's law, calculate the squared sine of the
angle between the normal and the transmitted ray */
float Scale = (CosThetaI > 0.0f) ? InvEta : Eta;
float CosThetaTSqr = 1.0f - (1.0f - CosThetaI * CosThetaI) * (Scale * Scale);
/* Check for total internal reflection */
if (CosThetaTSqr <= 0.0f)
{
CosThetaT = 0.0f;
return 1.0f;
}
/* Find the absolute cosines of the incident/transmitted rays */
float CosThetaII = std::abs(CosThetaI);
float CosThetaTT = std::sqrt(CosThetaTSqr);
float Rs = (CosThetaII - Eta * CosThetaTT)
/ (CosThetaII + Eta * CosThetaTT);
float Rp = (Eta * CosThetaII - CosThetaTT)
/ (Eta * CosThetaII + CosThetaTT);
CosThetaT = (CosThetaI > 0.0f) ? -CosThetaTT : CosThetaTT;
/* No polarization -- return the unpolarized reflectance */
return 0.5f * (Rs * Rs + Rp * Rp);
}
Color3f FresnelConductor(float CosThetaI, const Color3f & Eta, const Color3f & EtaK)
{
float CosThetaI2 = CosThetaI * CosThetaI;
float SinThetaI2 = 1.0f - CosThetaI2;
Color3f Eta2 = Eta * Eta;
Color3f EtaK2 = EtaK * EtaK;
Color3f T0 = Eta2 - EtaK2 - Color3f(SinThetaI2);
Color3f A2PlusB2 = (T0 * T0 + 4.0f * Eta2 * EtaK2).cwiseSqrt();
Color3f T1 = A2PlusB2 + Color3f(CosThetaI2);
Color3f A = (0.5f * (A2PlusB2 + T0)).cwiseSqrt();
Color3f T2 = 2.0f * CosThetaI * A;
Color3f Rs = (T1 - T2).cwiseQuotient(T1 + T2);
Color3f T3 = CosThetaI2 * A2PlusB2 + Color3f(SinThetaI2 * SinThetaI2);
Color3f T4 = T2 * SinThetaI2;
Color3f Rp = Rs * (T3 - T4).cwiseQuotient(T3 + T4);
return 0.5f * (Rp + Rs);
}
float ApproxFresnelDiffuseReflectance(float Eta)
{
/**
* An evalution of the accuracy led
* to the following scheme, which cherry-picks
* fits from two papers where they are best.
*/
if (Eta < 1.0f)
{
/* Fit by Egan and Hilgeman (1973). Works
reasonably well for "normal" IOR values (<2).
Max rel. error in 1.0 - 1.5 : 0.1%
Max rel. error in 1.5 - 2 : 0.6%
Max rel. error in 2.0 - 5 : 9.5%
*/
return -1.4399f * (Eta * Eta) + 0.7099f * Eta + 0.6681f + 0.0636f / Eta;
}
else
{
/* Fit by d'Eon and Irving (2011)
*
* Maintains a good accuracy even for
* unrealistic IOR values.
*
* Max rel. error in 1.0 - 2.0 : 0.1%
* Max rel. error in 2.0 - 10.0 : 0.2%
*/
float InvEta = 1.0f / Eta,
InvEta2 = InvEta * InvEta,
InvEta3 = InvEta2 * InvEta,
InvEta4 = InvEta3 * InvEta,
InvEta5 = InvEta4 * InvEta;
return 0.919317f - 3.4793f * InvEta
+ 6.75335f * InvEta2
- 7.80989f * InvEta3
+ 4.98554f * InvEta4
- 1.36881f * InvEta5;
}
}
void CoordinateSystem(const Vector3f & Va, Vector3f & Vb, Vector3f & Vc)
{
if (std::abs(Va.x()) > std::abs(Va.y()))
{
float InvLen = 1.0f / std::sqrt(Va.x() * Va.x() + Va.z() * Va.z());
Vc = Vector3f(Va.z() * InvLen, 0.0f, -Va.x() * InvLen);
}
else
{
float InvLen = 1.0f / std::sqrt(Va.y() * Va.y() + Va.z() * Va.z());
Vc = Vector3f(0.0f, Va.z() * InvLen, -Va.y() * InvLen);
}
Vb = Vc.cross(Va);
}
Vector3f Reflect(const Vector3f & Wi)
{
return Vector3f(-Wi.x(), -Wi.y(), Wi.z());
}
Vector3f Refract(const Vector3f & Wi, float CosThetaT, float Eta, float InvEta)
{
float Scale = -(CosThetaT < 0.0f ? InvEta : Eta);
return Vector3f(Scale * Wi.x(), Scale * Wi.y(), CosThetaT);
}
Vector3f Reflect(const Vector3f & Wi, const Vector3f & M)
{
return 2.0f * Wi.dot(M) * M - Wi;
}
Vector3f Refract(const Vector3f & Wi, const Vector3f & M, float CosThetaT, float Eta, float InvEta)
{
Eta = (CosThetaT < 0.0f ? InvEta : Eta);
return M * (Wi.dot(M) * Eta + CosThetaT) - Wi * Eta;
}
filesystem::resolver * GetFileResolver()
{
static std::unique_ptr<filesystem::resolver> pResolver(new filesystem::resolver());
return pResolver.get();
}
NAMESPACE_END
| 22.009449 | 114 | 0.607112 | BlauHimmel |
1e4168f58d211abc3e375778731a52f68592f23a | 112,298 | cpp | C++ | 01.Firmware/components/FabGL/examples/VGA/MultitaskingCPM/src/BDOS.cpp | POMIN-163/xbw | ebda2fb925ec54e48e806ba1c3cd4e04a7b25368 | [
"Apache-2.0"
] | 5 | 2022-02-14T03:12:57.000Z | 2022-03-06T11:58:31.000Z | 01.Firmware/components/FabGL/examples/VGA/MultitaskingCPM/src/BDOS.cpp | POMIN-163/xbw | ebda2fb925ec54e48e806ba1c3cd4e04a7b25368 | [
"Apache-2.0"
] | null | null | null | 01.Firmware/components/FabGL/examples/VGA/MultitaskingCPM/src/BDOS.cpp | POMIN-163/xbw | ebda2fb925ec54e48e806ba1c3cd4e04a7b25368 | [
"Apache-2.0"
] | 4 | 2022-02-23T07:00:59.000Z | 2022-03-10T03:58:11.000Z | /*
Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
Copyright (c) 2019-2021 Fabrizio Di Vittorio.
All rights reserved.
* Please contact fdivitto2013@gmail.com if you need a commercial license.
* This library and related software is available under GPL v3.
FabGL 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.
FabGL 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 FabGL. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/stat.h>
#include "BDOS.h"
#pragma GCC optimize ("O2")
// Disc Parameter Block (DPB) - common to all disks
// configuration;
// block size: 2K
// disk space: 0x7fff * 2K = 67106816 bytes (TODO)
const DiscParameterBlock commonDiscParameterBlock = {
.spt = 255, // Number of 128-byte records per track
.bsh = 4, // Block shift. 3 => 1k, 4 => 2k, 5 => 4k....
.blm = 0xF, // Block mask. 7 => 1k, 0Fh => 2k, 1Fh => 4k...
.exm = 0, // Extent mask, see later
.dsm = 0x7fff, // (no. of blocks on the disc)-1. max 0x7fff : TODO may change by the total disk space
.drm = 9998, // (no. of directory entries)-1
.al0 = 0, // Directory allocation bitmap, first byte
.al1 = 0, // Directory allocation bitmap, second byte
.cks = 0x8000, // Checksum vector size, 0 or 8000h for a fixed disc. No. directory entries/4, rounded up.
.off = 0, // Offset, number of reserved tracks
.psh = 0, // Physical sector shift, 0 => 128-byte sectors 1 => 256-byte sectors 2 => 512-byte sectors...
.phm = 0, // Physical sector mask, 0 => 128-byte sectors 1 => 256-byte sectors 3 => 512-byte sectors...
};
// Disk Parameter Header (DPH)
const DiscParameterHeader discParameterHeader = {
.XLT = 0,
.dummy = { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.MF = 0,
.DPB = DPB_ADDR,
.CSV = 0,
.ALV = 0,
.DIRBCB = 0,
.DTABCB = 0,
.HASH = 0xFFFF,
.HBANK = 0,
};
BDOS::BDOS(HAL * hal, BIOS * bios)
: m_HAL(hal),
m_BIOS(bios),
m_printerEchoEnabled(false),
m_auxStream(nullptr),
m_consoleReadyChar(0),
m_readHistoryItem(0),
m_writeHistoryItem(0),
m_searchPath(nullptr)
{
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS started\r\n");
#endif
// initialize zero page to zero
m_HAL->fillMem(0x0000, 0, 256);
// reset open file cache
for (int i = 0; i < CPMMAXFILES; ++i)
m_openFileCache[i].file = nullptr;
for (int i = 0; i < MAXDRIVERS; ++i)
m_currentDir[i] = strdup("");
// unknown SCB value
SCB_setByte(SCB_UNKNOWN1_B, 0x07);
// base address of BDOS
SCB_setWord(SCB_BDOSBASE_W, BDOS_ENTRY);
// SCB BDOS version
SCB_setByte(SCB_BDOSVERSION_B, 0x31);
// SCB address (undocumented)
SCB_setWord(SCB_SCBADDR_W, SCB_ADDR);
// console width and height
SCB_setByte(SCB_CONSOLEWIDTH_B, m_HAL->getTerminalColumns() - 1); // width - 1 (so 80 columns becomes 79)
SCB_setByte(SCB_CONSOLEPAGELENGTH_B, m_HAL->getTerminalRows());
// address of 128 byte buffer
SCB_setWord(SCB_BNKBUF, BDOS_BUFADDR);
// common base address (makes the system looked as "banked")
SCB_setWord(SCB_COMMONBASEADDR_W, SYSTEM_ADDR);
// SCB default logical to physical device assignments
m_BIOS->assignPhysicalDevice(LOGICALDEV_CONIN, PHYSICALDEV_KBD); // console input -- KBD
m_BIOS->assignPhysicalDevice(LOGICALDEV_CONOUT, PHYSICALDEV_CRT); // console output -- CRT
m_BIOS->assignPhysicalDevice(LOGICALDEV_AUXIN, PHYSICALDEV_UART1); // aux input -- UART1
m_BIOS->assignPhysicalDevice(LOGICALDEV_AUXOUT, PHYSICALDEV_UART1); // aux output -- UART1
m_BIOS->assignPhysicalDevice(LOGICALDEV_LIST, PHYSICALDEV_LPT); // list -- LPT
// current disk is A
setCurrentDrive(0);
// current user is 0
setCurrentUser(0);
// current user is 0
SCB_setByte(SCB_CURRENTUSER_B, 0);
// BDOS entry in SCB
SCB_setWord(SCB_TOPOFUSERTPA_W, BDOS_ENTRY);
// BDOS entry
m_HAL->writeByte(PAGE0_BDOS, 0xC3); // CPU opcode: JP
m_HAL->writeWord(PAGE0_OSBASE, BDOS_ENTRY);
// BDOS exit
m_HAL->writeByte(BDOS_ENTRY, 0xC9); // CPU opcode: RET
// BIOS entry
m_HAL->writeByte(PAGE0_WSTART, 0xC3); // CPU opcode: JP
m_HAL->writeWord(PAGE0_WSTARTADDR, BIOS_ENTRY + 3); // BIOS WBOOT function
// BIOS jump table
for (int i = 0; i < 33; ++i) {
m_HAL->writeByte(BIOS_ENTRY + i * 3 + 0, 0xC3); // CPU opcode: JP
m_HAL->writeWord(BIOS_ENTRY + i * 3 + 1, BIOS_RETS + i); // address of related BIOS exit (RET opcode)
}
// BIOS exits
for (int i = 0; i < 33; ++i)
m_HAL->writeByte(BIOS_RETS + i, 0xC9); // CPU opcode: RET
// Disc Parameter Block (DPB) - common to all disks
m_HAL->copyMem(DPB_ADDR, &commonDiscParameterBlock, sizeof(DiscParameterBlock));
// Disk Parameter Header (DPH)
m_HAL->copyMem(DPH_ADDR, &discParameterHeader, sizeof(DiscParameterHeader));
// invalidate cached directory label flags
memset(m_cachedDirLabelFlags, 0xff, MAXDRIVERS);
// default search drivers
SCB_setByte(SCB_DRIVESEARCHCHAIN0_B, 0); // first search on mount path of current drive
SCB_setByte(SCB_DRIVESEARCHCHAIN1_B, 1); // second search on mount path of drive A
SCB_setByte(SCB_DRIVESEARCHCHAIN2_B, 0xFF); // end marker
// reset write protect disk word
m_writeProtectWord = 0;
// allocate console (BDOS 10) input buffer history
for (int i = 0; i < CCP_HISTORY_DEPTH; ++i) {
m_history[i] = (char*) malloc(CCP_HISTORY_LINEBUFFER_LEN);
m_history[i][0] = 0;
}
// code to execute every CPU step
m_HAL->onCPUStep = [&]() {
// BIOS call?
if (m_HAL->CPU_getPC() >= BIOS_RETS && m_HAL->CPU_getPC() <= BIOS_RETS + 33)
m_BIOS->processBIOS(m_HAL->CPU_getPC() - BIOS_RETS);
// BDOS call?
if (m_HAL->CPU_getPC() == BDOS_ENTRY)
processBDOS();
};
/*
consoleOutFmt("STACK : 0x%04X\r\n", STACK_ADDR);
consoleOutFmt("BDOS : 0x%04X\r\n", BDOS_ENTRY);
consoleOutFmt("BIOS : 0x%04X\r\n", BIOS_ENTRY);
consoleOutFmt("DPB : 0x%04X\r\n", DPB_ADDR);
consoleOutFmt("DPH : 0x%04X\r\n", DPH_ADDR);
consoleOutFmt("SCB_PG : 0x%04X\r\n", SCB_PAGEADDR);
consoleOutFmt("SCB : 0x%04X\r\n", SCB_ADDR);
consoleOutFmt("BDOS_BUFADDR : 0x%04X\r\n", BDOS_BUFADDR);
consoleOutFmt("CHRTBL_ADDR : 0x%04X\r\n", CHRTBL_ADDR);
//*/
// get ready to exec CCP
resetProgramEnv();
}
BDOS::~BDOS()
{
for (int i = 0; i < MAXDRIVERS; ++i)
free(m_currentDir[i]);
for (int i = 0; i < CCP_HISTORY_DEPTH; ++i)
free(m_history[i]);
free(m_searchPath);
m_HAL->releaseMem(0, 65535);
}
bool BDOS::isDir(uint16_t FCBaddr)
{
return m_HAL->compareMem(FCBaddr + FCB_T1, DIRECTORY_EXT, 3) == 0;
}
// user: 0..15
void BDOS::setCurrentUser(int user)
{
user = user & 0xF;
SCB_setByte(SCB_CURRENTUSER_B, user);
m_HAL->writeByte(PAGE0_CURDRVUSR, (m_HAL->readByte(PAGE0_CURDRVUSR) & 0x0F) | (user << 4));
}
// user: 0..15
int BDOS::getCurrentUser()
{
return SCB_getByte(SCB_CURRENTUSER_B) & 0xF;
}
char const * BDOS::getCurrentDir()
{
int drive = getCurrentDrive(); // default drive
return m_currentDir[drive];
}
char const * BDOS::getCurrentDir(int drive)
{
return m_currentDir[drive];
}
// drive: 0 = A, 15 = P
void BDOS::setCurrentDrive(int drive)
{
drive = drive & 0xF;
if (m_HAL->getDriveMountPath(drive)) {
SCB_setByte(SCB_CURRENTDISK_B, drive);
m_HAL->writeByte(PAGE0_CURDRVUSR, (m_HAL->readByte(PAGE0_CURDRVUSR) & 0xF0) | drive);
}
}
// drive: 0 = A, 15 = P
int BDOS::getCurrentDrive()
{
return SCB_getByte(SCB_CURRENTDISK_B) & 0xF;
}
// if "str" contains a drive specification return true ("A:", "B:"...) and set *drive
// otherwise return false and set *drive with the default drive
// str can be nullptr
bool BDOS::strToDrive(char const * str, int * drive)
{
*drive = getCurrentDrive();
auto slen = str ? strlen(str) : 0;
if (slen >= 2 && isalpha(str[0]) && str[1] == ':') {
// has drive specificator
*drive = toupper(str[0]) - 'A';
return true;
}
return false;
}
bool BDOS::strToDrive(uint16_t str, int * drive)
{
*drive = getCurrentDrive();
auto slen = str ? m_HAL->strLen(str) : 0;
if (slen >= 2 && isalpha(m_HAL->readByte(str)) && m_HAL->readByte(str + 1) == ':') {
// has drive specificator
*drive = toupper(m_HAL->readByte(str)) - 'A';
return true;
}
return false;
}
// if errfunc > -1 then call doError setting A=L=0xFF and H=B=0x04 registers (Invalid Drive)
bool BDOS::checkDrive(int drive, int errfunc)
{
bool valid = drive >= 0 && drive < MAXDRIVERS && m_HAL->getDriveMountPath(drive) != nullptr;
if (!valid) {
if (errfunc > -1) {
doError(0xFF, 0x04, "CP/M Error on %c: Invalid Drive\r\nFunction %d\r\n", 'A' + drive, errfunc);
} else {
consoleOutStr("Invalid Drive\r\n");
}
}
return valid;
}
void BDOS::setSearchPath(char const * path)
{
if (m_searchPath)
free(m_searchPath);
m_searchPath = strdup(path);
}
char const * BDOS::getSearchPath()
{
return m_searchPath;
}
// load, process parameters and run the specified program (with parameters)
// cmdline can also be located at same position of PAGE0_DMA
void BDOS::runCommand(uint16_t cmdline)
{
// find file name length
auto filenameEnd = m_HAL->findChar(cmdline, ' ');
if (!filenameEnd)
filenameEnd = cmdline + m_HAL->strLen(cmdline);
auto filenameLen = filenameEnd - cmdline;
int drive;
bool driveSpecified = strToDrive(cmdline, &drive);
if (driveSpecified) {
// has drive specificator
cmdline += 2;
filenameLen -= 2;
}
if (!checkDrive(drive, -1))
return;
int searchOrder = SCB_getByte(SCB_CCPFLAGS2_B) >> SCB_CCPFLAGS2_FILESEARCHORDER_BIT;
int searchCount = (searchOrder == SCB_CCPFLAGS2_FILESEARCHORDER_COM ? 1 : 2);
for (int i = 0; i < searchCount; ++i) {
char afilename[filenameLen + 4];
m_HAL->copyMem(afilename, cmdline, filenameLen);
afilename[filenameLen] = 0;
bool hasExtension = strrchr(afilename, '.');
if (!hasExtension) {
// hasn't extension, add ".COM" or ".SUB" depending on searchOrder
bool trySUB = (i == 0 && searchOrder == SCB_CCPFLAGS2_FILESEARCHORDER_SUB_COM) || (i == 1 && searchOrder == SCB_CCPFLAGS2_FILESEARCHORDER_COM_SUB);
strcat(afilename, trySUB ? ".SUB" : ".COM");
}
if (execProgram(drive, afilename, filenameEnd)) {
// success
return;
}
if (hasExtension)
break;
}
// file not found, show error message only when is not in "cold start" mode (trying to execute PROFILE.SUB)
if (SCB_testBit(SCB_CCPFLAGS3_B, SCB_CCPFLAGS3_COLDSTART)) {
consoleOutStr(cmdline, m_HAL->readByte(filenameEnd));
consoleOutChar('?');
}
}
// load and exec specified program (.COM or .SUB)
// filename is relative path. execProgram tries to load it from following places:
// - current directory of specified drive
// - mount path (root dir) of drivers in SCB_DRIVESEARCHCHAIN#_B
bool BDOS::execProgram(int drive, char const * filename, uint16_t parameters)
{
#if MSGDEBUG & DEBUG_BDOS
char params[m_HAL->strLen(parameters) + 1];
m_HAL->copyStr(params, parameters);
m_HAL->logf("execProgram: drive=%d filename=\"%s\" params=\"%s\"\r\n", drive, filename, params);
#endif
bool isSUB = strstr(filename, ".SUB");
if (isSUB) {
// make sure the ".SUB" file exists
setBrowserAtDrive(drive);
if (!m_fileBrowser.exists(filename, false))
return false; // sub not found
}
auto afilename = isSUB ? "SUBMIT.COM" : filename;
FILE * fr = nullptr;
// try current directory
char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(m_currentDir[drive]) + 1 + strlen(afilename) + 1];
strcpy(fullpath, m_HAL->getDriveMountPath(drive));
strcat(fullpath, "/");
if (m_currentDir[drive] && strlen(m_currentDir[drive]) > 0) {
strcat(fullpath, m_currentDir[drive]);
strcat(fullpath, "/");
}
strcat(fullpath, afilename);
fr = fopen(fullpath, "rb");
if (fr == nullptr) {
// not found, if m_searchPath is specified then search in specified paths, otherwise look into drivers specified by SCB_DRIVESEARCHCHAIN#_B
if (m_searchPath) {
// try paths in m_searchPath
for (char const * p = m_searchPath, * next = nullptr; fr == nullptr && p != nullptr; p = next) {
// bypass ';' and spaces
while (isspace(*p) || *p == ';')
++p;
// look head for start of next path
next = strchr(p, ';');
// get drive
int drive = toupper(*p) - 'A';
if (m_HAL->getDriveMountPath(drive)) {
p += 2; // bypass drive specificator
auto pathlen = next ? next - p : strlen(p); // this path length
char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + pathlen + 1 + strlen(afilename) + 1];
strcpy(fullpath, m_HAL->getDriveMountPath(drive));
strcat(fullpath, "/");
strncat(fullpath, p, pathlen);
strcat(fullpath, "/");
strcat(fullpath, afilename);
fr = fopen(fullpath, "rb");
}
}
} else {
// try mount paths of drivers in SCB_DRIVESEARCHCHAIN#_B
for (int searchdrive = 0; fr == nullptr && searchdrive < 4; ++searchdrive) {
int drv = SCB_getByte(SCB_DRIVESEARCHCHAIN0_B + searchdrive);
if (drv == 0xFF)
break;
drive = (drv == 0 ? getCurrentDrive() : drv - 1);
char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(afilename) + 1];
strcpy(fullpath, m_HAL->getDriveMountPath(drive));
strcat(fullpath, "/");
strcat(fullpath, afilename);
fr = fopen(fullpath, "rb");
}
}
}
if (!fr) {
// file not found
return false;
}
fseek(fr, 0, SEEK_END);
size_t size = ftell(fr);
fseek(fr, 0, SEEK_SET);
if (size > getTPASize()) {
// out of memory
fclose(fr);
return false;
}
// Copy program parameters into default DMA
// Must be done here, because parameters may lay on TPA!
auto tail = parameters;
auto ptr = PAGE0_DMA;
m_HAL->writeByte(ptr, m_HAL->strLen(tail)); // first byte is the parameters length
if (isSUB) {
// is submit "filename" goes to the parameters side
m_HAL->writeByte(ptr, m_HAL->readByte(ptr) + 1 + strlen(filename));
++ptr;
m_HAL->writeByte(ptr++ , ' ');
while (*filename)
m_HAL->writeByte(ptr++, *filename++);
} else
++ptr;
m_HAL->copyStr(ptr, tail);
auto dest = TPA_ADDR;
while (size--)
m_HAL->writeByte(dest++, fgetc(fr));
fclose(fr);
// set drive number where the program was loaded
m_HAL->writeByte(PAGE0_LOADDRIVE, drive + 1); // 1 = A
execLoadedProgram(size);
return true;
}
void BDOS::resetProgramEnv()
{
// Reset Multi Sector Count
SCB_setByte(SCB_MULTISECTORCOUNT_B, 1);
// Output delimiter
SCB_setByte(SCB_OUTPUTDELIMETER_B, '$');
// DMA Address
SCB_setWord(SCB_CURRENTDMAADDR_W, PAGE0_DMA);
// Console mode
SCB_setWord(SCB_CONSOLEMODE_W, 0);
// Error mode
SCB_setByte(SCB_ERRORMODE_B, 0);
// Reset error drive
SCB_setByte(SCB_ERRORDRIVE_B, 0);
}
// executes the program at TPA_ADDR
void BDOS::execLoadedProgram(size_t size)
{
resetProgramEnv();
// fills default FCBs
parseParams();
// does this COM contains RSXs? (0xC9 = RET)
if (m_HAL->readByte(TPA_ADDR) == 0xC9 && size > 0xFF) {
// yes, relocate them
processRSXCOM();
}
// run
m_HAL->CPU_pushStack(PAGE0_WSTART); // push PAGE0_WSTART as return address into the stack
m_HAL->CPU_exec(TPA_ADDR, 0xFFFF);
// remove RSXs that can be removed
removeRSX();
// this restores BDOS and BIOS entries (for BDOS also takes care of RSX)
m_BIOS->BIOS_call_WBOOT();
// release unused memory
m_HAL->releaseMem(TPA_ADDR, getTPATop());
}
uint16_t BDOS::getTPASize()
{
return getTPATop() - TPA_ADDR;
}
uint16_t BDOS::getTPATop()
{
return m_HAL->readWord(PAGE0_OSBASE) - 6;
}
// the loaded COM contains zero or more RSXs
// - execute pre-initialization code
// - move and relocate RSXs
// - move program from (TPA_ADDR + 0x100) to TPA_ADDR
void BDOS::processRSXCOM()
{
// execute pre-initialization code
m_HAL->CPU_pushStack(0xFFFF); // RET will interrupt execution
m_HAL->CPU_exec(TPA_ADDR + COMHEAD_INIT, 0xFFFF);
// load RSXs
int rsxRecords = m_HAL->readByte(TPA_ADDR + COMHEAD_RSXCOUNT);
if (m_HAL->readByte(TPA_ADDR + 256) == 0xC9) {
// the main program is just a RET. This file contains just RSXs.
// (see special case at page 1-26, paragraph 2, of CP/M 3 Programmers's Guide).
SCB_setBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_NULLRSX);
}
for (int i = 0; i < rsxRecords; ++i) {
uint16_t rsxRecordAddr = TPA_ADDR + COMHEAD_RSXRECORDS + i * 16;
if (m_HAL->readByte(rsxRecordAddr + RSXRECORD_NONBANK) == 0x00) { // non banked flag: here we act as banked system (we already have some BDOS funcs)
uint16_t codepos = m_HAL->readWord(rsxRecordAddr + RSXRECORD_OFFSET);
uint16_t codelen = m_HAL->readWord(rsxRecordAddr + RSXRECORD_CODELEN);
loadRSX(TPA_ADDR + codepos, codelen);
}
}
// move main program
uint16_t proglen = m_HAL->readWord(TPA_ADDR + COMHEAD_LEN);
m_HAL->moveMem(TPA_ADDR, TPA_ADDR + 0x100, proglen);
}
void BDOS::loadRSX(uint16_t imageAddr, int imageLen)
{
#if MSGDEBUG & DEBUG_BDOS
char const * rsxName[8];
m_HAL->copyMem(rsxName, imageAddr + RSXPREFIX_NAME, 8);
m_HAL->logf("loadRSX \"%8s\"\r\n", rsxName);
#endif
// first RSX
uint16_t firstRSXaddr = m_HAL->readWord(PAGE0_OSBASE) - RSXPREFIX_START;
// calculate new RSX position
uint16_t thisRSXaddr = (firstRSXaddr - imageLen) & 0xFF00; // page aligned
// set next module address
m_HAL->writeWord(imageAddr + RSXPREFIX_NEXT, m_HAL->readWord(PAGE0_OSBASE));
// set prev module address
m_HAL->writeWord(imageAddr + RSXPREFIX_PREV, PAGE0_BDOS);
// redirect base entry
m_HAL->writeWord(PAGE0_OSBASE, thisRSXaddr + RSXPREFIX_START);
// update SCB MXTPA field
SCB_setWord(SCB_TOPOFUSERTPA_W, m_HAL->readWord(PAGE0_OSBASE));
// set next module "prev" field, if not original BDOS
if (firstRSXaddr + RSXPREFIX_START != BDOS_ENTRY)
m_HAL->writeWord(firstRSXaddr + RSXPREFIX_PREV, m_HAL->readWord(PAGE0_OSBASE));
// copy and relocate RSX
uint16_t relmapAddr = imageAddr + imageLen;
int offset = (thisRSXaddr >> 8) - 1;
for (int i = 0; i < imageLen; ++i) {
if (m_HAL->readByte(relmapAddr + i / 8) & (1 << (7 - (i % 8))))
m_HAL->writeByte(thisRSXaddr + i, m_HAL->readByte(imageAddr + i) + offset);
else
m_HAL->writeByte(thisRSXaddr + i, m_HAL->readByte(imageAddr + i));
}
}
void BDOS::removeRSX()
{
uint16_t rsxAddr = m_HAL->readWord(PAGE0_OSBASE) - RSXPREFIX_START;
while (rsxAddr + RSXPREFIX_START != BDOS_ENTRY && rsxAddr != 0 && rsxAddr != 65535 - 6) {
uint16_t rsxPrev = m_HAL->readWord(rsxAddr + RSXPREFIX_PREV);
uint16_t rsxNext = m_HAL->readWord(rsxAddr + RSXPREFIX_NEXT);
// can remove?
if (m_HAL->readByte(rsxAddr + RSXPREFIX_REMOVE) == 0xFF && !SCB_testBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_NULLRSX)) {
// yes, remove this RSX
#if MSGDEBUG & DEBUG_BDOS
char const * rsxName[8];
m_HAL->copyMem(rsxName, rsxAddr + RSXPREFIX_NAME, 8);
m_HAL->logf("removeRSX \"%8s\"\r\n", rsxName);
#endif
// update "next" field of previous RSX
if (rsxPrev == PAGE0_BDOS) {
// previous is PAGE0_BDOS (0x0005), update this address
m_HAL->writeWord(PAGE0_OSBASE, rsxNext);
// update SCB MXTPA field
SCB_setWord(SCB_TOPOFUSERTPA_W, m_HAL->readWord(PAGE0_OSBASE));
} else {
// previous is another RSX, update its next field
m_HAL->writeWord(rsxPrev - RSXPREFIX_START + RSXPREFIX_NEXT, rsxNext);
}
// update "prev" field of next RSX
if (rsxNext != BDOS_ENTRY) {
m_HAL->writeWord(rsxNext - RSXPREFIX_START + RSXPREFIX_PREV, rsxPrev);
}
}
// just in case: remove RSX only flag, so it will be removed next time
SCB_clearBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_NULLRSX);
// next RSX
rsxAddr = rsxNext - RSXPREFIX_START;
}
}
// return true when there is at least one RSX in memory
bool BDOS::RSXInstalled()
{
return SCB_getWord(SCB_TOPOFUSERTPA_W) != BDOS_ENTRY;
}
bool BDOS::BDOSAddrChanged()
{
return m_HAL->readWord(PAGE0_OSBASE) != BDOS_ENTRY;
}
bool BDOS::BIOSAddrChanged()
{
return m_HAL->readWord(PAGE0_WSTARTADDR) != (BIOS_ENTRY + 3);
}
// set A, L, B, H CPU registers in one step
void BDOS::CPUsetALBH(uint8_t A, uint8_t L, uint8_t B, uint8_t H)
{
m_HAL->CPU_writeRegByte(Z80_A, A);
m_HAL->CPU_writeRegByte(Z80_L, L);
m_HAL->CPU_writeRegByte(Z80_B, B);
m_HAL->CPU_writeRegByte(Z80_H, H);
}
void BDOS::CPUsetALBH(uint8_t AL, uint8_t BH)
{
CPUsetALBH(AL, AL, BH, BH);
}
// set HL and BA (H=hi byte,L=lo byte, B=hi byte, A=lo byte)
void BDOS::CPUsetHLBA(uint16_t HL, uint16_t BA)
{
m_HAL->CPU_writeRegWord(Z80_HL, HL);
m_HAL->CPU_writeRegByte(Z80_A, BA & 0xFF);
m_HAL->CPU_writeRegByte(Z80_B, BA >> 8);
}
void BDOS::BDOS_call(uint16_t * BC, uint16_t * DE, uint16_t * HL, uint16_t * AF)
{
m_HAL->CPU_writeRegWord(Z80_BC, *BC);
m_HAL->CPU_writeRegWord(Z80_DE, *DE);
m_HAL->CPU_writeRegWord(Z80_HL, *HL);
m_HAL->CPU_writeRegWord(Z80_AF, *AF);
// has the BDOS been changed?
if (m_HAL->readWord(PAGE0_OSBASE) != BDOS_ENTRY) {
// yes, you have to call BDOS using CPU execution
// set return address (it is important that is it inside TPA, some RSX check it)
uint16_t retAddr = 0x100; // as if calling from 0x100 (like it is CPP)
m_HAL->CPU_pushStack(retAddr); // RET will interrupt execution
m_HAL->CPU_exec(PAGE0_BDOS, retAddr);
} else {
// no, you can directly call BDOS function here
processBDOS();
}
*BC = m_HAL->CPU_readRegWord(Z80_BC);
*DE = m_HAL->CPU_readRegWord(Z80_DE);
*HL = m_HAL->CPU_readRegWord(Z80_HL);
*AF = m_HAL->CPU_readRegWord(Z80_AF);
}
int BDOS::BDOS_callConsoleIn()
{
uint16_t BC = 0x0001, DE = 0, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
int BDOS::BDOS_callConsoleStatus()
{
uint16_t BC = 0x000B, DE = 0, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
int BDOS::BDOS_callDirectConsoleIO(int mode)
{
uint16_t BC = 0x0006, DE = mode, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
void BDOS::BDOS_callConsoleOut(char c)
{
uint16_t BC = 0x0002, DE = c, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
}
// str must end with '0'
// maxChars can be 0 (entire length of "str")
void BDOS::BDOS_callOutputString(char const * str, uint16_t workBufAddr, size_t workBufSize, size_t maxChars)
{
auto slen = strlen(str);
if (maxChars > 0 && slen > maxChars)
slen = maxChars;
while (slen > 0) {
auto len = fabgl::tmin<size_t>(workBufSize - 1, slen);
m_HAL->copyMem(workBufAddr, str, len);
m_HAL->writeByte(workBufAddr + len, SCB_getByte(SCB_OUTPUTDELIMETER_B));
uint16_t BC = 0x0009, DE = workBufAddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
slen -= len;
str += len;
}
}
void BDOS::BDOS_callOutputString(uint16_t str)
{
uint16_t BC = 0x0009, DE = str, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
}
// if addr = 0x0000, then use PAGE0_DMA as input buffer
void BDOS::BDOS_callReadConsoleBuffer(uint16_t addr)
{
uint16_t BC = 0x000A, DE = addr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
}
void BDOS::BDOS_callSystemReset()
{
uint16_t BC = 0x0000, DE = 0, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
}
// ret HL value
int BDOS::BDOS_callParseFilename(uint16_t PFCBaddr)
{
uint16_t BC = 0x0098, DE = PFCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return HL;
}
// ret HL value
int BDOS::BDOS_callSearchForFirst(uint16_t FCBaddr)
{
uint16_t BC = 0x0011, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return HL;
}
// ret HL value
int BDOS::BDOS_callSearchForNext()
{
uint16_t BC = 0x0012, DE = 0, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return HL;
}
// ret A value
int BDOS::BDOS_callDeleteFile(uint16_t FCBaddr)
{
uint16_t BC = 0x0013, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
// ret A value
int BDOS::BDOS_callRenameFile(uint16_t FCBaddr)
{
uint16_t BC = 0x0017, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
// ret HA value
int BDOS::BDOS_callOpenFile(uint16_t FCBaddr)
{
uint16_t BC = 0x000F, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return (AF >> 8) | (HL & 0xFF00);
}
// ret HA value
int BDOS::BDOS_callMakeFile(uint16_t FCBaddr)
{
uint16_t BC = 0x0016, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return (AF >> 8) | (HL & 0xFF00);
}
// ret A value
int BDOS::BDOS_callCloseFile(uint16_t FCBaddr)
{
uint16_t BC = 0x0010, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
// ret A value
int BDOS::BDOS_callReadSequential(uint16_t FCBaddr)
{
uint16_t BC = 0x0014, DE = FCBaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
void BDOS::BDOS_callSetDMAAddress(uint16_t DMAaddr)
{
uint16_t BC = 0x001A, DE = DMAaddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
}
int BDOS::BDOS_callCopyFile(uint16_t srcFullPathAddr, uint16_t dstPathAddr, bool overwrite, bool display)
{
uint16_t BC = (overwrite ? 0x0100 : 0) | (display ? 0x0200 : 0) | 0x00D4;
uint16_t DE = dstPathAddr;
uint16_t HL = srcFullPathAddr;
uint16_t AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
int BDOS::BDOS_callChangeCurrentDirectory(uint16_t pathAddr)
{
uint16_t BC = 0x00D5, DE = pathAddr, HL = 0, AF = 0;
BDOS_call(&BC, &DE, &HL, &AF);
return AF >> 8;
}
// ret = true, program end
void BDOS::processBDOS()
{
// register C contains the BDOS function to execute
int func = m_HAL->CPU_readRegByte(Z80_C);
switch (func) {
// 0 (0x00) : System Reset
case 0x00:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: System Reset\r\n", func);
#endif
BDOS_systemReset();
break;
// 1 (0x01) : Console Input
case 0x01:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Console Input\r\n", func);
#endif
BDOS_consoleInput();
break;
// 2 (0x02) : Console output
case 0x02:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Console output\r\n", func);
#endif
BDOS_consoleOutput();
break;
// 3 (0x03) : Aux input
case 0x03:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Aux input\r\n", func);
#endif
BDOS_auxInput();
break;
// 4 (0x04) : Aux output
case 0x04:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Aux output\r\n", func);
#endif
BDOS_auxOutput();
break;
// 5 (0x05) : LST output
case 0x05:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: LST output\r\n", func);
#endif
BDOS_lstOutput();
break;
// 6 (0x06) : Direct Console IO
case 0x06:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Direct Console IO\r\n", func);
#endif
BDOS_directConsoleIO();
break;
// 7 (0x07) : Aux input status
case 0x07:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Aux input status\r\n", func);
#endif
BDOS_auxInputStatus();
break;
// 8 (0x08) : Aux output status
case 0x08:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Aux output status\r\n", func);
#endif
BDOS_auxOutputStatus();
break;
// 9 (0x09) : Output string
case 0x09:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Output string\r\n", func);
#endif
BDOS_outputString();
break;
// 10 (0x0A) : Read console buffer
case 0x0A:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Read console buffer\r\n", func);
#endif
BDOS_readConsoleBuffer();
break;
// 11 (0x0B) : Console status
case 0x0B:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Console status\r\n", func);
#endif
BDOS_getConsoleStatus();
break;
// 12 (0x0C) : Return version number
case 0x0C:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Return version number\r\n", func);
#endif
BDOS_returnVersionNumber();
break;
// 13 (0x0D) : Reset disk system
case 0x0D:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Reset disk system\r\n", func);
#endif
BDOS_resetDiskSystem();
break;
// 14 (0x0E) : Select disk
case 0x0E:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Select disk\r\n", func);
#endif
BDOS_selectDisk();
break;
// 15 (0x0F) : Open file
case 0x0F:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Open file\r\n", func);
#endif
BDOS_openFile();
break;
// 16 (0x10) : Close file
case 0x10:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Close file\r\n", func);
#endif
BDOS_closeFile();
break;
// 17 (0x11) : Search for first
case 0x11:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Search for first\r\n", func);
#endif
BDOS_searchForFirst();
break;
// 18 (0x12) : Search for next
case 0x12:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Search for next\r\n", func);
#endif
BDOS_searchForNext();
break;
// 19 (0x13) : Delete file
case 0x13:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Delete file\r\n", func);
#endif
BDOS_deleteFile();
break;
// 20 (0x14) : Read sequential
case 0x14:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Read sequential\r\n", func);
#endif
BDOS_readSequential();
break;
// 21 (0x15) : Write sequential
case 0x15:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Write sequential\r\n", func);
#endif
BDOS_writeSequential();
break;
// 22 (0x16) : Create file / Create Directory
case 0x16:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Create file/dir\r\n", func);
#endif
BDOS_makeFile();
break;
// 23 (0x17) : Rename file
case 0x17:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Rename file\r\n", func);
#endif
BDOS_renameFile();
break;
// 24 (0x18) : Return login vector
case 0x18:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Return login vector\r\n", func);
#endif
BDOS_returnLoginVector();
break;
// 25 (0x19) : Return current disk
case 0x19:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Return current disk\r\n", func);
#endif
BDOS_returnCurrentDisk();
break;
// 26 (0x1A) : Set DMA address
case 0x1A:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set DMA address\r\n", func);
#endif
BDOS_setDMAAddress();
break;
// 27 (0x1B) : Get Addr (Alloc)
case 0x1B:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get Addr (Alloc)\r\n", func);
#endif
BDOS_getAddr();
break;
// 28 (0x1C) : Write protect disk
case 0x1C:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Write protect disk\r\n", func);
#endif
BDOS_writeProtectDisk();
break;
// 29 (0x1D) : Get read only vector
case 0x1D:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get read only vector\r\n", func);
#endif
BDOS_getReadOnlyVector();
break;
// 30 (0x1E) : Set File Attributes
case 0x1E:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set File Attributes\r\n", func);
#endif
BDOS_setFileAttributes();
break;
// 31 (0x1F) : Get DPB address (Disc Parameter Block)
case 0x1F:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get DPB address\r\n", func);
#endif
BDOS_getDPBAddress();
break;
// 32 (0x20) : Get/set user number
case 0x20:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: get/set user number\r\n", func);
#endif
BDOS_getSetUserCode();
break;
// 33 (0x21) : Random access read record
case 0x21:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Random access read record\r\n", func);
#endif
BDOS_readRandom();
break;
// 34 (0x22) : Random access write record
case 0x22:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Random access write record\r\n", func);
#endif
BDOS_writeRandom();
break;
// 35 (0x23) : Compute file size
case 0x23:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Compute file size\r\n", func);
#endif
BDOS_computeFileSize();
break;
// 36 (0x24) : Set random record
case 0x24:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set random record\r\n", func);
#endif
BDOS_setRandomRecord();
break;
// 37 (0x25) : Reset drive
case 0x25:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Reset drive\r\n", func);
#endif
BDOS_resetDrive();
break;
// 38 (0x26) : Access drive
case 0x26:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Access drive\r\n", func);
#endif
BDOS_accessDrive();
break;
// 39 (0x27) : Free drive
case 0x27:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Free drive\r\n", func);
#endif
BDOS_freeDrive();
break;
// 40 (0x28) : Write random with zero fill
case 0x28:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Write random with zero fill\r\n", func);
#endif
BDOS_writeRandomZeroFill();
break;
// 41 (0x29) : Test and write record
case 0x29:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Test and write record\r\n", func);
#endif
BDOS_testAndWriteRecord();
break;
// 42 (0x2A) : Lock record
case 0x2A:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Lock record\r\n", func);
#endif
BDOS_lockRecord();
break;
// 43 (0x2B) : Unock record
case 0x2B:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Unock record\r\n", func);
#endif
BDOS_unlockRecord();
break;
// 44 (0x2C) : Set multi-sector count
case 0x2C:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set multi-sector count\r\n", func);
#endif
BDOS_setMultiSectorCount();
break;
// 45 (0x2D) : Set error mode
case 0x2D:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set error mode\r\n", func);
#endif
BDOS_setErrorMode();
break;
// 46 (0x2E) : Get disk free space
case 0x2E:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get disk free space\r\n", func);
#endif
BDOS_getDiskFreeSpace();
break;
// 47 (0x2F) : Chain to program
case 0x2F:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Chain to program\r\n", func);
#endif
BDOS_chainToProgram();
break;
// 48 (0x30) : Flush buffers
case 0x30:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Flush buffers\r\n", func);
#endif
BDOS_flushBuffers();
break;
// 49 (0x31) : Get/set system control block
case 0x31:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get/set system control block\r\n", func);
#endif
BDOS_getSetSystemControlBlock();
break;
// 50 (0x32) : Direct BIOS call
case 0x32:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Direct BIOS call\r\n", func);
#endif
BDOS_directBIOSCall();
break;
// 59 (0x3B) : Load overlay
case 0x3B:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Load overlay\r\n", func);
#endif
BDOS_loadOverlay();
break;
// 60 (0x3C) : Call System Resident Extension
case 0x3C:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Call System Resident Extension\r\n", func);
#endif
BDOS_callResidentSystemExtension();
break;
// 98 (0x62) : Free Blocks
case 0x62:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Free Blocks\r\n", func);
#endif
BDOS_freeBlocks();
break;
// 99 (0x63) : Truncate file
case 0x63:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Truncate file\r\n", func);
#endif
BDOS_truncateFile();
break;
// 100 (0x64) : Set Directory Label
case 0x64:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set Directory Label\r\n", func);
#endif
BDOS_setDirectoryLabel();
break;
// 101 (0x65) : Return directory label data
case 0x65:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Return directory label data\r\n", func);
#endif
BDOS_returnDirLabelData();
break;
// 102 (0x66) : Read file date stamps and password mode
case 0x66:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Read file date stamps and password mode\r\n", func);
#endif
BDOS_readFileDateStamps();
break;
// 104 (0x68) : Set date and time
case 0x68:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set date and time\r\n", func);
#endif
BDOS_setDateTime();
break;
// 105 (0x69) : Get date and time
case 0x69:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get date and time\r\n", func);
#endif
BDOS_getDateTime();
break;
// 108 (0x6C) : Get/Set program return code
case 0x6C:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get/Set program return code\r\n", func);
#endif
BDOS_getSetProgramReturnCode();
break;
// 109 (0x6D) : Set or get console mode
case 0x6D:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Set or get console mode\r\n", func);
#endif
BDOS_getSetConsoleMode();
break;
// 110 (0x6E) : Get set output delimiter
case 0x6E:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Get set output delimiter\r\n", func);
#endif
BDOS_getSetOutputDelimiter();
break;
// 111 (0x6F) : Print block
case 0x6F:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Print block\r\n", func);
#endif
BDOS_printBlock();
break;
// 112 (0x6F) : List block
case 0x70:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: List block\r\n", func);
#endif
BDOS_listBlock();
break;
// 152 (0x98) : Parse filename
case 0x98:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Parse filename\r\n", func);
#endif
BDOS_parseFilename();
break;
// 212 (0xD4) : Copy file (specific of this BDOS implementation)
case 0xD4:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Copy file\r\n", func);
#endif
BDOS_copyFile();
break;
// 213 (0xD5) : Change current directory (specific of this BDOS implementation)
case 0xD5:
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS %d: Change current directory\r\n", func);
#endif
BDOS_changeCurrentDirectory();
break;
default:
#if MSGDEBUG & DEBUG_ERRORS
m_HAL->logf("BDOS %d: Unsupported\r\n", func);
#endif
break;
}
}
// this overload check Error Mode field and can display or abort application
void BDOS::doError(uint8_t A, uint8_t H, const char * format, ...)
{
SCB_setByte(SCB_ERRORDRIVE_B, getCurrentDrive());
if (isDefaultErrorMode()) {
m_HAL->CPU_stop();
SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFD);
}
if (isDefaultErrorMode() || isDisplayReturnErrorMode()) {
va_list ap;
va_start(ap, format);
int size = vsnprintf(nullptr, 0, format, ap) + 1;
if (size > 0) {
va_end(ap);
va_start(ap, format);
char buf[size + 1];
vsnprintf(buf, size, format, ap);
consoleOutStr(buf);
}
va_end(ap);
}
CPUsetALBH(A, H);
}
// BDOS 0 (0x00)
void BDOS::BDOS_systemReset()
{
// jump to PAGE0_WSTART
m_HAL->CPU_setPC(PAGE0_WSTART);
}
// BDOS 1 (0x01)
void BDOS::BDOS_consoleInput()
{
uint8_t c = consoleIn();
CPUsetALBH(c, 0);
}
// BDOS 2 (0x02)
void BDOS::BDOS_consoleOutput()
{
char c = m_HAL->CPU_readRegByte(Z80_E);
consoleOutChar(c);
}
// BDOS 3 (0x03)
void BDOS::BDOS_auxInput()
{
int c = 0;
if (m_auxStream) {
while (!m_auxStream->available())
;
c = m_auxStream->read();
}
CPUsetALBH(c, 0);
}
// BDOS 4 (0x04)
void BDOS::BDOS_auxOutput()
{
if (m_auxStream) {
m_auxStream->write(m_HAL->CPU_readRegByte(Z80_E));
}
}
// BDOS 5 (0x05)
void BDOS::BDOS_lstOutput()
{
lstOut(m_HAL->CPU_readRegByte(Z80_E));
}
// BDOS 6 (0x06)
void BDOS::BDOS_directConsoleIO()
{
uint8_t v = m_HAL->CPU_readRegByte(Z80_E);
if (v == 0xFF) {
// return input char. If no char return 0
uint8_t v = rawConsoleAvailable() ? rawConsoleIn() : 0;
CPUsetALBH(v, 0);
} else if (v == 0xFE) {
// return status. 0 = no char avail, ff = char avail
uint8_t v = rawConsoleAvailable() ? 0xFF : 0;
CPUsetALBH(v, 0);
} else if (v == 0xFD) {
// return input char (suspend)
uint8_t v = rawConsoleIn();
CPUsetALBH(v, 0);
} else {
// send "v" con console
m_BIOS->BIOS_call_CONOUT(v);
}
}
// BDOS 7 (0x07)
void BDOS::BDOS_auxInputStatus()
{
int v = 0;
if (m_auxStream && m_auxStream->available())
v = 0xFF;
CPUsetALBH(v, 0);
}
// BDOS 8 (0x08)
void BDOS::BDOS_auxOutputStatus()
{
// always ready!
CPUsetALBH(0xFF, 0);
}
// BDOS 9 (0x09)
void BDOS::BDOS_outputString()
{
uint16_t addr = m_HAL->CPU_readRegWord(Z80_DE);
char delim = SCB_getByte(SCB_OUTPUTDELIMETER_B);
consoleOutStr(addr, delim);
}
// BDOS 10 (0x0A)
void BDOS::BDOS_readConsoleBuffer()
{
uint16_t bufAddrParam = m_HAL->CPU_readRegWord(Z80_DE);
uint16_t bufAddr = (bufAddrParam ? bufAddrParam : PAGE0_DMA);
int mx = fabgl::tmax<int>(1, m_HAL->readByte(bufAddr));
LineEditor ed(nullptr);
if (bufAddrParam == 0) {
char str[m_HAL->strLen(bufAddr) + 1];
m_HAL->copyStr(str, bufAddr + 2);
ed.typeText(str);
}
ed.onRead = [&](int * c) {
*c = m_BIOS->BIOS_call_CONIN();
};
ed.onWrite = [&](int c) {
m_BIOS->BIOS_call_CONOUT(c);
};
ed.onChar = [&](int * c) {
switch (*c) {
case ASCII_CTRLC:
if (isDisableCTRLCExit() == false) {
*c = ASCII_CR;
SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE);
m_HAL->CPU_stop();
}
break;
case ASCII_LF: // aka CTRL-J
*c = ASCII_CR;
break;
case ASCII_CTRLP:
switchPrinterEchoEnabled();
break;
}
};
ed.onSpecialChar = [&](LineEditorSpecialChar sc) {
switch (sc) {
case LineEditorSpecialChar::CursorUp:
{
char const * txt = getPrevHistoryItem();
if (txt)
ed.setText(txt);
break;
}
case LineEditorSpecialChar::CursorDown:
{
char const * txt = getNextHistoryItem();
if (txt)
ed.setText(txt);
break;
}
}
};
ed.onCarriageReturn = [&](int * op) {
m_BIOS->BIOS_call_CONOUT(ASCII_CR); // bdos 10 always echoes even CR
*op = 1; // on carriage return just perform end editing (without new line)
};
ed.edit(mx);
auto len = strlen(ed.get());
m_HAL->writeByte(bufAddr + 1, len);
m_HAL->copyMem(bufAddr + 2, ed.get(), len);
if (m_printerEchoEnabled)
lstOut(ed.get());
// save into history
saveIntoConsoleHistory(ed.get());
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("BDOS 10: Read console buffer - EXIT\r\n");
#endif
}
// BDOS 11 (0x0B)
void BDOS::BDOS_getConsoleStatus()
{
int ret = 0;
if (isFUNC11CTRLCOnlyMode()) {
if (rawConsoleDirectAvailable()) {
// ret 0x01 only if CTRL-C has been typed
m_consoleReadyChar = rawConsoleDirectIn();
if (m_consoleReadyChar == ASCII_CTRLC)
ret = 0x01;
}
} else if (rawConsoleAvailable()) {
// ret 0x01 for any char
ret = 0x01;
}
CPUsetALBH(ret, 0);
}
// BDOS 12 (0x0C)
void BDOS::BDOS_returnVersionNumber()
{
// A=L=0x31 => 3.1 - CP/M Plus
// B=H=0x00 => 8080, CP/M
CPUsetALBH(0x31, 0);
}
// BDOS 13 (0x0D)
void BDOS::BDOS_resetDiskSystem()
{
// reset DMA to 0x0080
SCB_setWord(SCB_CURRENTDMAADDR_W, PAGE0_DMA);
// current disk is A
setCurrentDrive(0);
// current user is 0
setCurrentUser(0);
// multi sector count
SCB_setByte(SCB_MULTISECTORCOUNT_B, 1);
// reset write protect disk word
m_writeProtectWord = 0;
CPUsetALBH(0x00, 0x00);
}
// BDOS 14 (0x0E)
void BDOS::BDOS_selectDisk()
{
int drive = m_HAL->CPU_readRegByte(Z80_E);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" drive=%c\r\n", 'A' + drive);
#endif
if (!checkDrive(drive, 14))
return;
setCurrentDrive(drive);
CPUsetALBH(0x00, 0x00);
}
// generate a 32 bit hash for the filename and drive number
// djb2 hashing algorithm
// TODO: collisions exist, so it could be better to find another way to handle open files caching!
uint32_t BDOS::filenameHash(uint16_t FCBaddr)
{
uint32_t hash = (5381 << 5) + 5381 + getDriveFromFCB(FCBaddr);
for (int i = FCB_F1; i <= FCB_T3; ++i)
hash = (hash << 5) + hash + (m_HAL->readByte(FCBaddr + i) & 0x7f);
return hash;
}
// ret nullptr if not found
FILE * BDOS::getFileFromCache(uint16_t FCBaddr)
{
const uint32_t hash = filenameHash(FCBaddr);
for (int i = 0; i < CPMMAXFILES; ++i)
if (hash == m_openFileCache[i].filenameHash && m_openFileCache[i].file) {
#if MSGDEBUG & DEBUG_BDOS
// check for hash failure
for (int j = 0; j < 11; ++j) {
if (m_openFileCache[i].filename[j] != (m_HAL->readByte(FCBaddr + FCB_F1 + j) & 0x7f)) {
// fail!
HAL::logf("Hash failure!! \"");
for (int k = 0; k < 11; ++k)
HAL::logf("%c", m_HAL->readByte(FCBaddr + FCB_F1 + k) & 0x7f);
HAL::logf("\" <> \"%s\"\r\n", m_openFileCache[i].filename);
m_HAL->abort(AbortReason::GeneralFailure);
}
}
#endif
return m_openFileCache[i].file;
}
return nullptr;
}
void BDOS::addFileToCache(uint16_t FCBaddr, FILE * file)
{
if (file) {
const uint32_t hash = filenameHash(FCBaddr);
int idx = -1;
for (int i = 0; i < CPMMAXFILES; ++i)
if (m_openFileCache[i].file == nullptr) {
idx = i;
break;
}
if (idx == -1) {
// no more free items, close one (@TODO: chose a better algorithm!)
idx = rand() % CPMMAXFILES;
fclose(m_openFileCache[idx].file);
}
m_openFileCache[idx].file = file;
m_openFileCache[idx].filenameHash = hash;
#if MSGDEBUG & DEBUG_BDOS
for (int i = 0; i < 11; ++i)
m_openFileCache[idx].filename[i] = m_HAL->readByte(FCBaddr + FCB_F1 + i) & 0x7f;
m_openFileCache[idx].filename[11] = 0;
HAL::logf("addFileToCache handle=%p name=\"%s\" idx=%d\r\n", file, m_openFileCache[idx].filename, idx);
#endif
}
}
void BDOS::removeFileFromCache(FILE * file)
{
for (int i = 0; i < CPMMAXFILES; ++i)
if (m_openFileCache[i].file == file) {
m_openFileCache[i].file = nullptr;
return;
}
}
int BDOS::getOpenFilesCount()
{
int ret = 0;
for (int i = 0; i < CPMMAXFILES; ++i)
if (m_openFileCache[i].file)
++ret;
return ret;
}
void BDOS::closeAllFiles()
{
for (int i = 0; i < CPMMAXFILES; ++i)
if (m_openFileCache[i].file) {
fclose(m_openFileCache[i].file);
m_openFileCache[i].file = nullptr;
}
}
// create:
// false = file must exist otherwise returns nullptr
// true = file mustn't exist otherwise returns nullptr
// tempext:
// false = let FCB specified extension
// true = replace extension with $$$
// files are always open as read/write
// err:
// 0 = no err
// 1 = invalid drive
// 2 = file not found or already exists
FILE * BDOS::openFile(uint16_t FCBaddr, bool create, bool tempext, int errFunc, int * err)
{
*err = 0;
// already open?
if (!tempext) {
auto f = getFileFromCache(FCBaddr);
if (f) {
if (create) {
// create a file that is already open: close it before!
removeFileFromCache(f);
fclose(f);
} else
return f;
}
}
int drive = getDriveFromFCB(FCBaddr);
if (!checkDrive(drive, errFunc)) {
*err = 1;
return nullptr;
}
setBrowserAtDrive(drive);
char filename[13];
getFilenameFromFCB(FCBaddr, filename);
strToUpper(filename);
if (tempext) {
// replace extension with '$$$'
char * p = strchr(filename, '.');
if (p)
*p = 0;
strcat(filename, ".$$$");
}
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" openFile %s\r\n", filename);
#endif
int fullpathLen = m_fileBrowser.getFullPath(filename);
char fullpath[fullpathLen];
m_fileBrowser.getFullPath(filename, fullpath, fullpathLen);
FILE * f = nullptr;
if (create) {
if (m_fileBrowser.exists(filename, false))
*err = 2;
else
f = fopen(fullpath, "w+b");
} else {
if (!m_fileBrowser.exists(filename, false))
*err = 2;
else
f = fopen(fullpath, "r+b");
}
if (f)
addFileToCache(FCBaddr, f);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" handle = %p\r\n", f);
#endif
return f;
}
void BDOS::closeFile(uint16_t FCBaddr)
{
auto f = getFileFromCache(FCBaddr);
if (f) {
removeFileFromCache(f);
fclose(f);
}
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("closeFile %p\r\n", f);
#endif
}
// BDOS 15 (0x0F)
void BDOS::BDOS_openFile()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int err;
FILE * f = openFile(FCBaddr, false, false, 15, &err);
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
if (m_HAL->readByte(FCBaddr + FCB_CR) == 0xFF) {
// last record byte count requested (put byte count into FCB_CR itself)
m_HAL->writeByte(FCBaddr + FCB_CR, (size / 16384) % 128);
}
// set record count (of current extent)
m_HAL->writeByte(FCBaddr + FCB_RC, fabgl::tmin<size_t>((size + 127) / 128, 128));
// reset position to 0
// note: EX (FCB_EX) is not reset, it should be done by the application
// should it be done for S2 and CR also?
m_HAL->writeByte(FCBaddr + FCB_S2, 0);
m_HAL->writeByte(FCBaddr + FCB_CR, 0);
CPUsetALBH(0x00, 0x00);
} else {
doError(0xFF, 0x01, "CP/M Error opening file, I/O Error\r\nFunction 15\r\n");
}
}
// BDOS 16 (0x10)
void BDOS::BDOS_closeFile()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
closeFile(FCBaddr);
CPUsetALBH(0x00, 0x00);
}
// BDOS 17 (0x11)
void BDOS::BDOS_searchForFirst()
{
m_fileSearchState.FCB = m_HAL->CPU_readRegWord(Z80_DE);
m_fileSearchState.DMA = SCB_getWord(SCB_CURRENTDMAADDR_W);
searchFirst(&m_fileSearchState);
// update SCB fields
SCB_setWord(SCB_DCNT_W, m_fileSearchState.index << 2);
SCB_setWord(SCB_SEARCHA_W, m_fileSearchState.FCB);
SCB_setByte(SCB_SEARCHL_B, m_fileSearchState.getAllFiles ? 0x00 : 0x0F);
if (m_fileSearchState.errCode == 0) {
// 0: file found
CPUsetALBH(m_fileSearchState.retCode, 0x00);
} else if (m_fileSearchState.errCode == 1) {
// 1: no files
CPUsetALBH(0xFF, 0x00);
} else {
// 2: invalid drive
doError(0xFF, 0x04, "CP/M Error, Invalid Drive\r\nFunction 17\r\n");
}
}
// BDOS 18 (0x12)
void BDOS::BDOS_searchForNext()
{
m_fileSearchState.DMA = SCB_getWord(SCB_CURRENTDMAADDR_W); // necessary? May it be changed between BDOS 17 and 18?
searchNext(&m_fileSearchState);
// update SCB fields
SCB_setWord(SCB_DCNT_W, m_fileSearchState.index << 2);
SCB_setWord(SCB_SEARCHA_W, m_fileSearchState.FCB);
if (m_fileSearchState.errCode == 0) {
// 0: file found
CPUsetALBH(m_fileSearchState.retCode, 0x00);
} else {
// 1: no more files
CPUsetALBH(0xFF, 0x00);
}
}
// BDOS 19 (0x13)
void BDOS::BDOS_deleteFile()
{
FileSearchState state;
state.DMA = BDOS_BUFADDR;
state.FCB = m_HAL->CPU_readRegWord(Z80_DE);
searchFirst(&state);
if (state.errCode == 1) {
// no items
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" no items\r\n");
#endif
CPUsetALBH(0xFF, 0x00);
} else if (state.errCode == 2) {
// invalid drive
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" invalid drive\r\n");
#endif
doError(0xFF, 0x04, "CP/M Error, Invalid Drive\r\nFunction 19\r\n");
} else { // r == 0, file found
while (state.errCode == 0) {
uint16_t FCBaddr = state.DMA + 32 * state.retCode;
bool isDirFlag = isDir(FCBaddr);
if (isDirFlag) {
// replace "[D]" with " "
m_HAL->fillMem(FCBaddr + 9, ' ', 3);
}
char filename[13];
getFilenameFromFCB(FCBaddr, filename);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" filename=%s\r\n", filename);
#endif
// m_fileBrowser already positioned by searchFirst()
m_fileBrowser.remove(filename);
searchNext(&state);
}
CPUsetALBH(0x00, 0x00);
}
}
// BDOS 20 (0x14)
void BDOS::BDOS_readSequential()
{
uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W);
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int err;
FILE * f = openFile(FCBaddr, false, false, 20, &err);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" FCB_EX=%d FCB_S2=%d FCB_CR=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_EX), m_HAL->readByte(FCBaddr + FCB_S2), m_HAL->readByte(FCBaddr + FCB_CR), f);
#endif
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
// go to position identified by FCB_EX, FCB_S2 and FCB_CR
size_t pos = getPosFCB(FCBaddr);
fseek(f, pos, SEEK_SET);
int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B);
int bytesCount = recCount * 128;
int bytesRead = 0;
for (; bytesRead < bytesCount; ++bytesRead) {
int c = fgetc(f);
if (c == EOF)
break;
m_HAL->writeByte(DMAaddr + bytesRead, c);
}
// fill missing bytes
for (int i = bytesRead; i < bytesCount; ++i)
m_HAL->writeByte(DMAaddr + i, 0x1A);
auto r = (bytesRead + 127) / 128; // r = number of records read
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" pos=%d reccount=%d read=%d\r\n", (int)pos, recCount, (int)r);
#endif
// update position
setPosFCB(FCBaddr, pos + r * 128);
if (r < recCount) {
// EOF (H=B=number of records read)
CPUsetALBH(0x01, r);
} else {
// all ok
CPUsetALBH(0x00, 0x00);
}
} else {
doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 20\r\n");
}
}
// BDOS 21 (0x15)
void BDOS::BDOS_writeSequential()
{
uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W);
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int err;
FILE * f = openFile(FCBaddr, false, false, 21, &err);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" FCB_EX=%d FCB_S2=%d FCB_CR=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_EX), m_HAL->readByte(FCBaddr + FCB_S2), m_HAL->readByte(FCBaddr + FCB_CR), f);
#endif
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
// go to position identified by FCB_EX, FCB_S2 and FCB_CR
size_t pos = getPosFCB(FCBaddr);
fseek(f, pos, SEEK_SET);
int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B);
int bytesCount = recCount * 128;
int bytesWritten = 0;
for (; bytesWritten < bytesCount; ++bytesWritten) {
int e = fputc(m_HAL->readByte(DMAaddr + bytesWritten), f);
if (e == EOF)
break;
}
auto r = (bytesWritten + 127) / 128;
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" pos=%d reccount=%d wrote=%d\r\n", (int)pos, recCount, (int)r);
#endif
// update position
setPosFCB(FCBaddr, pos + r * 128);
if (r < recCount) {
// no available data block (H=B=number of records written)
CPUsetALBH(0x02, r);
} else {
// all ok
CPUsetALBH(0x00, 0x00);
}
} else {
doError(0xFF, 0x01, "CP/M Error writing file, I/O Error\r\nFunction 21\r\n");
}
}
// err:
// 0 = no err
// 1 = invalid drive
// 2 = dir already exists
void BDOS::createDir(uint16_t FCBaddr, int errFunc, int * err)
{
*err = 0;
int drive = getDriveFromFCB(FCBaddr);
if (!checkDrive(drive, errFunc)) {
*err = 1;
return;
}
setBrowserAtDrive(drive);
char dirname[13];
getFilenameFromFCB(FCBaddr, dirname);
if (m_fileBrowser.exists(dirname, false)) {
*err = 2;
return;
}
m_fileBrowser.makeDirectory(dirname);
}
// BDOS 22 (0x16)
// if bit 7 of FCB drive is set then create a directory instead of a file (CP/M 86 v4)
void BDOS::BDOS_makeFile()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
bool createDirFlag = m_HAL->readByte(FCBaddr) & 0x80;
int err;
FILE * f = nullptr;
if (createDirFlag) {
// create directory
createDir(FCBaddr, 22, &err);
} else {
f = openFile(FCBaddr, true, false, 22, &err);
}
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file already exists
doError(0xFF, 0x08, "CP/M Error, File/Dir already exists\r\nFunction 22\r\n");
return;
}
if (f) {
// all ok
// reset position to 0
m_HAL->writeByte(FCBaddr + FCB_EX, 0);
m_HAL->writeByte(FCBaddr + FCB_S2, 0);
m_HAL->writeByte(FCBaddr + FCB_CR, 0);
CPUsetALBH(0x00, 0x00);
} else if (createDirFlag){
// creatre directory ok
CPUsetALBH(0x00, 0x00);
} else {
// other non hardware error
CPUsetALBH(0xFF, 0x00);
}
}
// BDOS 23 (0x17)
void BDOS::BDOS_renameFile()
{
uint16_t FCBaddr_old = m_HAL->CPU_readRegWord(Z80_DE);
uint16_t FCBaddr_new = FCBaddr_old + 16;
char filename_old[13];
getFilenameFromFCB(FCBaddr_old, filename_old);
char filename_new[13];
getFilenameFromFCB(FCBaddr_new, filename_new);
int drive = getDriveFromFCB(FCBaddr_old);
if (!checkDrive(drive, 23))
return;
setBrowserAtDrive(drive);
if (m_fileBrowser.exists(filename_new, false)) {
// new file already exists
doError(0xFF, 0x08, "CP/M Error, File already exists\r\nFunction 23\r\n");
} else if (!m_fileBrowser.exists(filename_old, false)) {
// orig file not found
CPUsetALBH(0xFF, 0x00); // non fatal error
} else {
// all ok
m_fileBrowser.rename(filename_old, filename_new);
CPUsetALBH(0x00, 0x00);
}
}
// BDOS 24 (0x18)
void BDOS::BDOS_returnLoginVector()
{
uint16_t loginVector = 0;
for (int i = 0; i < MAXDRIVERS; ++i)
if (m_HAL->getDriveMountPath(i))
loginVector |= 1 << i;
m_HAL->CPU_writeRegWord(Z80_HL, loginVector);
}
// BDOS 25 (0x19)
void BDOS::BDOS_returnCurrentDisk()
{
uint8_t drive = getCurrentDrive();
CPUsetALBH(drive, 0);
}
// BDOS 26 (0x1A)
void BDOS::BDOS_setDMAAddress()
{
SCB_setWord(SCB_CURRENTDMAADDR_W, m_HAL->CPU_readRegWord(Z80_DE));
}
// BDOS 27 (0x1B)
void BDOS::BDOS_getAddr()
{
// not implemented, returns always error
m_HAL->CPU_writeRegWord(Z80_HL, 0xFFFF);
}
// BDOS 28 (0x1C)
void BDOS::BDOS_writeProtectDisk()
{
m_writeProtectWord |= 1 << getCurrentDrive();
}
// BDOS 29 (0x1D)
void BDOS::BDOS_getReadOnlyVector()
{
m_HAL->CPU_writeRegWord(Z80_HL, m_writeProtectWord);
}
// BDOS 30 (0x1E)
void BDOS::BDOS_setFileAttributes()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int drive = getDriveFromFCB(FCBaddr);
if (!checkDrive(drive, 30))
return;
char filename[13];
getFilenameFromFCB(FCBaddr, filename);
setBrowserAtDrive(drive);
if (m_fileBrowser.exists(filename, false)) {
// sets last record byte count?
if ((m_HAL->readByte(FCBaddr + FCB_F6) & 0x80) != 0 && m_HAL->readByte(FCBaddr + FCB_CR) > 0) {
// yes, set the exact file size
int byteCount = m_HAL->readByte(FCBaddr + FCB_CR); // last record byte count (0 = 128 => don't truncate!)
// get file size
auto fileSize = m_fileBrowser.fileSize(filename);
// adjust file size
fileSize = ((fileSize + 127) / 128 - 1) * 128 + byteCount;
m_fileBrowser.truncate(filename, fileSize);
}
CPUsetALBH(0x00, 0x00);
} else {
// file not found
CPUsetALBH(0xFF, 0x00);
}
}
// BDOS 31 (0x1F)
void BDOS::BDOS_getDPBAddress()
{
CPUsetHLBA(DPB_ADDR, DPB_ADDR);
}
// BDOS 32 (0x20)
void BDOS::BDOS_getSetUserCode()
{
uint8_t user = m_HAL->CPU_readRegByte(Z80_E);
if (user == 0xFF) {
uint8_t user = SCB_getByte(SCB_CURRENTUSER_B);
CPUsetALBH(user, 0);
} else {
SCB_setByte(SCB_CURRENTUSER_B, user & 0xF);
}
}
// BDOS 33 (0x21)
void BDOS::BDOS_readRandom()
{
uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W);
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int err;
FILE * f = openFile(FCBaddr, false, false, 33, &err);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" FCB_R0=%d FCB_R1=%d FCB_R2=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_R0), m_HAL->readByte(FCBaddr + FCB_R1), m_HAL->readByte(FCBaddr + FCB_R2), f);
#endif
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
// go to position identified by R0, R1, R2
size_t pos = getAbsolutePosFCB(FCBaddr);
fseek(f, pos, SEEK_SET);
int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B);
int bytesCount = recCount * 128;
int bytesRead = 0;
for (; bytesRead < bytesCount; ++bytesRead) {
int c = fgetc(f);
if (c == EOF)
break;
m_HAL->writeByte(DMAaddr + bytesRead, c);
}
// fill missing bytes
for (int i = bytesRead; i < bytesCount; ++i)
m_HAL->writeByte(DMAaddr + i, 0x1A);
auto r = (bytesRead + 127) / 128; // r = number of records read
// reposition at the start of this record
fseek(f, pos, SEEK_SET);
setPosFCB(FCBaddr, pos);
if (r == 0) {
// EOF
CPUsetALBH(0x01, 0x00);
} else {
// ok
CPUsetALBH(0x00, 0x00);
}
} else {
doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 33\r\n");
}
}
// BDOS 34 (0x22)
void BDOS::BDOS_writeRandom()
{
uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W);
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int err;
FILE * f = openFile(FCBaddr, false, false, 34, &err);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" FCB_R0=%d FCB_R1=%d FCB_R2=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_R0), m_HAL->readByte(FCBaddr + FCB_R1), m_HAL->readByte(FCBaddr + FCB_R2), f);
#endif
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
// go to position identified by R0, R1, R2
size_t pos = getAbsolutePosFCB(FCBaddr);
fseek(f, pos, SEEK_SET);
int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B);
int bytesCount = recCount * 128;
int bytesWritten = 0;
for (; bytesWritten < bytesCount; ++bytesWritten) {
int e = fputc(m_HAL->readByte(DMAaddr + bytesWritten), f);
if (e == EOF)
break;
}
// reposition at the start of this record
fseek(f, pos, SEEK_SET);
setPosFCB(FCBaddr, pos);
CPUsetALBH(0x00, 0x00);
} else {
doError(0xFF, 0x01, "CP/M Error writing file, I/O Error\r\nFunction 34\r\n");
}
}
// BDOS 35 (0x23)
void BDOS::BDOS_computeFileSize()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int err;
FILE * f = openFile(FCBaddr, false, false, 35, &err);
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
closeFile(FCBaddr);
setAbsolutePosFCB(FCBaddr, size);
CPUsetALBH(0x00, 0x00);
} else {
doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 35\r\n");
}
}
// BDOS 36 (0x24)
void BDOS::BDOS_setRandomRecord()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
// TODO: is it really necessary to open file?
int err;
FILE * f = openFile(FCBaddr, false, false, 36, &err);
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (f) {
// go to position identified by FCB_EX, FCB_S2 and FCB_CR
size_t pos = getPosFCB(FCBaddr);
setAbsolutePosFCB(FCBaddr, pos); // set r0, r1 and r2
} else {
doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 36\r\n");
}
}
// BDOS 37 (0x25)
void BDOS::BDOS_resetDrive()
{
uint16_t driveVector = m_HAL->CPU_readRegWord(Z80_DE);
for (int i = 0; i < MAXDRIVERS; ++i) {
if (driveVector & (1 << i)) {
// reset drive "i"
m_writeProtectWord &= ~(1 << i); // restore read/only flag
}
}
}
// BDOS 38 (0x26)
void BDOS::BDOS_accessDrive()
{
// not implemented (MP/M only)
CPUsetALBH(0x00, 0x00);
}
// BDOS 39 (0x27)
void BDOS::BDOS_freeDrive()
{
// not implemented (MP/M only)
CPUsetALBH(0x00, 0x00);
}
// BDOS 40 (0x28)
void BDOS::BDOS_writeRandomZeroFill()
{
// because we don't allocate "blocks", this has just the same behaviour of write random
BDOS_writeRandom();
}
// BDOS 41 (0x29)
void BDOS::BDOS_testAndWriteRecord()
{
// not implemented (MP/M II only)
CPUsetALBH(0xFF, 0x00);
}
// BDOS 42 (0x2A)
void BDOS::BDOS_lockRecord()
{
// not implemented (MP/M II only)
CPUsetALBH(0x00, 0x00);
}
// BDOS 43 (0x2B)
void BDOS::BDOS_unlockRecord()
{
// not implemented (MP/M II only)
CPUsetALBH(0x00, 0x00);
}
// BDOS 44 (0x2C)
void BDOS::BDOS_setMultiSectorCount()
{
uint8_t v = m_HAL->CPU_readRegByte(Z80_E);
SCB_setByte(SCB_MULTISECTORCOUNT_B, v);
if (v >= 1 && v <= 128)
CPUsetALBH(0x00, 0x00);
else
CPUsetALBH(0xFF, 0x00);
}
// BDOS 45 (0x2D)
void BDOS::BDOS_setErrorMode()
{
SCB_setByte(SCB_ERRORMODE_B, m_HAL->CPU_readRegByte(Z80_E));
}
// BDOS 46 (0x2E)
void BDOS::BDOS_getDiskFreeSpace()
{
int drive = m_HAL->CPU_readRegByte(Z80_E);
if (!checkDrive(drive, 46))
return;
setBrowserAtDrive(drive);
int64_t total = 0, used = 0;
m_fileBrowser.getFSInfo(m_fileBrowser.getCurrentDriveType(), 0, &total, &used);
uint32_t free = (uint32_t) fabgl::tmin<int64_t>((total - used) / 128, 2147483647); // 2147483648 = 2^24 * 128 - 1 = 2^31 - 1
uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W);
m_HAL->writeByte(DMAaddr + 0, free & 0xFF);
m_HAL->writeByte(DMAaddr + 1, (free >> 8) & 0xFF);
m_HAL->writeByte(DMAaddr + 2, (free >> 16) & 0xFF);
CPUsetALBH(0x00, 0x00);
}
// BDOS 47 (0x2F)
void BDOS::BDOS_chainToProgram()
{
int chainFlag = m_HAL->CPU_readRegByte(Z80_E);
if (chainFlag == 0xFF)
SCB_setBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_CHAINCHANGEDU); // initializes the default drive and user number to the current program values
else
SCB_clearBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_CHAINCHANGEDU); // set default values (previous)
SCB_setBit(SCB_CCPFLAGS1_B, SCB_CCOFLAGS1_CHAININING);
m_HAL->CPU_stop();
}
// BDOS 48 (0x30)
void BDOS::BDOS_flushBuffers()
{
// nothing to do, files are implicitely flushed
}
// BDOS 49 (0x31)
void BDOS::BDOS_getSetSystemControlBlock()
{
uint8_t q_offset = m_HAL->readByte(m_HAL->CPU_readRegWord(Z80_DE) + 0);
uint8_t q_set = m_HAL->readByte(m_HAL->CPU_readRegWord(Z80_DE) + 1);
uint8_t q_value_b = m_HAL->readByte(m_HAL->CPU_readRegWord(Z80_DE) + 2);
uint16_t q_value_w = m_HAL->readWord(m_HAL->CPU_readRegWord(Z80_DE) + 2);
// dynamic fields
switch (q_offset) {
// Console Column Position
case SCB_CONSOLECOLPOS_B:
{
int row, col;
m_HAL->getTerminalCursorPos(&col, &row);
SCB_setByte(SCB_CONSOLECOLPOS_B, col - 1);
break;
}
}
if (q_set == 0) {
// Read byte at offset into A, and word at offset into HL.
CPUsetHLBA(SCB_getWord(q_offset), SCB_getWord(q_offset));
} else if (q_set == 0x0FF) {
// Write byte
SCB_setByte(q_offset, q_value_b);
} else if (q_set == 0x0FE) {
// Write word
SCB_setWord(q_offset, q_value_w);
}
}
// BDOS 50 (0x32)
void BDOS::BDOS_directBIOSCall()
{
uint16_t PBaddr = m_HAL->CPU_readRegWord(Z80_DE);
m_HAL->CPU_writeRegByte(Z80_A, m_HAL->readByte(PBaddr + 1));
m_HAL->CPU_writeRegByte(Z80_C, m_HAL->readByte(PBaddr + 2));
m_HAL->CPU_writeRegByte(Z80_B, m_HAL->readByte(PBaddr + 3));
m_HAL->CPU_writeRegByte(Z80_E, m_HAL->readByte(PBaddr + 4));
m_HAL->CPU_writeRegByte(Z80_D, m_HAL->readByte(PBaddr + 5));
m_HAL->CPU_writeRegByte(Z80_L, m_HAL->readByte(PBaddr + 6));
m_HAL->CPU_writeRegByte(Z80_H, m_HAL->readByte(PBaddr + 7));
m_BIOS->processBIOS(m_HAL->readByte(PBaddr + 0));
m_HAL->writeByte(PBaddr + 1, m_HAL->CPU_readRegByte(Z80_A));
m_HAL->writeByte(PBaddr + 2, m_HAL->CPU_readRegByte(Z80_C));
m_HAL->writeByte(PBaddr + 3, m_HAL->CPU_readRegByte(Z80_B));
m_HAL->writeByte(PBaddr + 4, m_HAL->CPU_readRegByte(Z80_E));
m_HAL->writeByte(PBaddr + 5, m_HAL->CPU_readRegByte(Z80_D));
m_HAL->writeByte(PBaddr + 6, m_HAL->CPU_readRegByte(Z80_L));
m_HAL->writeByte(PBaddr + 7, m_HAL->CPU_readRegByte(Z80_H));
}
// BDOS 59 (0x3B)
// Always present, even when LOADER is not loaded
void BDOS::BDOS_loadOverlay()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
removeRSX();
if (FCBaddr == 0x0000) {
// invalid FCB
CPUsetALBH(0xFE, 0x00);
return;
}
uint16_t loadAddr = m_HAL->readByte(FCBaddr + FCB_R0) | (m_HAL->readByte(FCBaddr + FCB_R1) << 8);
int err;
FILE * f = openFile(FCBaddr, false, false, 59, &err);
if (err == 1) {
// invalid drive
return; // doError already called
}
if (err == 2) {
// file not found
CPUsetALBH(0xFF, 0x00);
return;
}
if (!f) {
doError(0xFF, 0x09, "CP/M Invalid FCB\r\nFunction 59\r\n");
return;
}
// is PRL?
if (hasExt(FCBaddr, "PRL")) {
// TODO
#if MSGDEBUG & DEBUG_ERRORS
m_HAL->logf("Unsupported load PRL in BDS 59\r\n");
#endif
CPUsetALBH(0xFF, 0x00);
} else {
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
fseek(f, 0, SEEK_SET);
if (size > getTPASize()) {
// no enough memory
CPUsetALBH(0xFE, 0x00);
closeFile(FCBaddr);
return;
}
int c;
while ((c = fgetc(f)) != EOF)
m_HAL->writeByte(loadAddr++, c);
CPUsetALBH(0x00, 0x00);
}
closeFile(FCBaddr);
}
// BDOS 60 (0x3C)
void BDOS::BDOS_callResidentSystemExtension()
{
CPUsetALBH(0xFF, 0x00);
}
// BDOS 98 (0x62)
void BDOS::BDOS_freeBlocks()
{
CPUsetALBH(0x00, 0x00);
}
// BDOS 99 (0x63)
void BDOS::BDOS_truncateFile()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int drive = getDriveFromFCB(FCBaddr);
if (!checkDrive(drive, 99))
return;
char filename[13];
getFilenameFromFCB(FCBaddr, filename);
setBrowserAtDrive(drive);
if (m_fileBrowser.exists(filename, false)) {
// copy "absolute pos"+128 bytes
// round to blocks (newlen should be already 128 bytes aligned)
// +1 because r0,r1,r2 indicates "last" block, not the required size
size_t newlen = 128 * ((getAbsolutePosFCB(FCBaddr) + 127) / 128 + 1);
if (m_fileBrowser.truncate(filename, newlen))
CPUsetALBH(0x00, 0x00);
else
doError(0xFF, 0x01, "CP/M I/O Error\r\nFunction 99\r\n");
} else {
doError(0xFF, 0x00, "CP/M Error, File Not Found\r\nFunction 99\r\n");
}
}
// Directory label is implemented using a (hidden) file named DIRLABEL_FILENAME
// located at the root of mount point. That file contains the FCB (32 bytes) specified by func 100.
// drive: 0 = A, 1 = B...
void BDOS::writeDirectoryLabel(int drive, uint16_t FCBaddr, int errfunc)
{
// we need update datetime in SCB
m_BIOS->updateSCBFromHALDateTime();
uint8_t wFCB[32] = {0};
// read creation date if any
if (readDirectoryLabel(drive, 0, wFCB) == 0) {
// there isn't an existing label
m_HAL->copyMem(wFCB + FCB_TS1, SCB_ADDR + SCB_DATEDAYS_W, 4); // copy creation date from SCB
}
// copy label name and flags from FCB to wFCB
m_HAL->copyMem(wFCB + FCB_F1, FCBaddr + FCB_F1, 12);
// adjust some FCB fields
wFCB[FCB_DR] = 0x20; // directory label flag
wFCB[FCB_EX] |= 1; // directory label exists
m_cachedDirLabelFlags[drive] = wFCB[FCB_EX];
// set update date
m_HAL->copyMem(wFCB + FCB_TS2, SCB_ADDR + SCB_DATEDAYS_W, 4); // copy update date from SCB
char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(DIRLABEL_FILENAME) + 1];
strcpy(fullpath, m_HAL->getDriveMountPath(drive));
strcat(fullpath, "/");
strcat(fullpath, DIRLABEL_FILENAME);
auto f = fopen(fullpath, "wb");
fwrite(wFCB, 1, 32, f);
fclose(f);
}
// FCB buffer musts have space for at least 32 bytes
// drive: 0 = A, 1 = B...
// ret: directory label flags or 0
// notes:
// - if FCBaddr is 0, it is not used.
// - if FCB is nullptr, it is not used.
uint8_t BDOS::readDirectoryLabel(int drive, uint16_t FCBaddr, uint8_t * FCB)
{
m_cachedDirLabelFlags[drive] = 0;
char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(DIRLABEL_FILENAME) + 1];
strcpy(fullpath, m_HAL->getDriveMountPath(drive));
strcat(fullpath, "/");
strcat(fullpath, DIRLABEL_FILENAME);
auto f = fopen(fullpath, "rb");
if (f) {
for (int i = 0; i < 32; ++i) {
int c = fgetc(f);
if (FCBaddr)
m_HAL->writeByte(FCBaddr + i, c);
if (FCB)
FCB[i] = c;
if (i == FCB_EX)
m_cachedDirLabelFlags[drive] = c;
}
fclose(f);
}
return m_cachedDirLabelFlags[drive];
}
// use readDirectoryLabel() if not cached, otherwise returns cached value
uint8_t BDOS::getDirectoryLabelFlags(int drive)
{
if (m_cachedDirLabelFlags[drive] == 0xFF) {
// no cached flags, read directory label
return readDirectoryLabel(drive, 0, nullptr);
}
return m_cachedDirLabelFlags[drive];
}
// BDOS 100 (0x64)
void BDOS::BDOS_setDirectoryLabel()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int drive = getDriveFromFCB(FCBaddr) & 0x0F;
if (!checkDrive(drive, 100))
return;
writeDirectoryLabel(drive, FCBaddr, 100);
CPUsetALBH(0x00, 0x00);
}
// BDOS 101 (0x65)
void BDOS::BDOS_returnDirLabelData()
{
uint16_t FCBaddr = BDOS_BUFADDR;
int drive = m_HAL->CPU_readRegByte(Z80_E);
uint8_t flags = readDirectoryLabel(drive, FCBaddr, nullptr);
CPUsetALBH(flags, 0x00);
}
// BDOS 102 (0x66)
void BDOS::BDOS_readFileDateStamps()
{
uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE);
int drive = getDriveFromFCB(FCBaddr);
if (!checkDrive(drive, 102))
return;
setBrowserAtDrive(drive);
char filename[13];
getFilenameFromFCB(FCBaddr, filename);
if (!m_fileBrowser.exists(filename, false)) {
CPUsetALBH(0xFF, 0x00);
return;
}
auto dirLabelFlags = getDirectoryLabelFlags(drive);
m_HAL->writeByte(FCBaddr + 12, 0); // TODO: no password
m_HAL->fillMem(FCBaddr + 24, 0, 4);
m_HAL->fillMem(FCBaddr + 28, 0, 4);
if (dirLabelFlags & DIRLABELFLAGS_EXISTS) {
int year, month, day, hour, minutes, seconds;
DateTime dt;
if (dirLabelFlags & DIRLABELFLAGS_CREATE) {
m_fileBrowser.fileCreationDate(filename, &year, &month, &day, &hour, &minutes, &seconds);
dt.set(year, month, day, hour, minutes, seconds);
m_HAL->copyMem(FCBaddr + 24, &dt, 4);
} else if (dirLabelFlags & DIRLABELFLAGS_ACCESS) {
m_fileBrowser.fileAccessDate(filename, &year, &month, &day, &hour, &minutes, &seconds);
dt.set(year, month, day, hour, minutes, seconds);
m_HAL->copyMem(FCBaddr + 24, &dt, 4);
}
if (dirLabelFlags & DIRLABELFLAGS_UPDATE) {
m_fileBrowser.fileUpdateDate(filename, &year, &month, &day, &hour, &minutes, &seconds);
dt.set(year, month, day, hour, minutes, seconds);
m_HAL->copyMem(FCBaddr + 28, &dt, 4);
}
}
CPUsetALBH(0x00, 0x00);
}
// BDOS 104 (0x68)
void BDOS::BDOS_setDateTime()
{
// put into SCB the date from [DE]
uint16_t DATaddr = m_HAL->CPU_readRegWord(Z80_DE);
SCB_setWord(SCB_DATEDAYS_W, m_HAL->readWord(DATaddr + 0));
SCB_setByte(SCB_HOUR_B, m_HAL->readByte(DATaddr + 2));
SCB_setByte(SCB_MINUTES_B, m_HAL->readByte(DATaddr + 3));
SCB_setByte(SCB_SECONDS_B, 0);
// ask bios to update datetime from SCB
m_BIOS->updateHALDateTimeFromSCB();
}
// BDOS 105 (0x69)
void BDOS::BDOS_getDateTime()
{
// ask bios to update SCB
m_BIOS->updateSCBFromHALDateTime();
// put into [DE] and A the content of datetime SCB fields
uint16_t DATaddr = m_HAL->CPU_readRegWord(Z80_DE);
m_HAL->writeWord(DATaddr + 0, SCB_getWord(SCB_DATEDAYS_W));
m_HAL->writeByte(DATaddr + 2, SCB_getByte(SCB_HOUR_B));
m_HAL->writeByte(DATaddr + 3, SCB_getByte(SCB_MINUTES_B));
CPUsetALBH(SCB_getByte(SCB_SECONDS_B), 0);
}
// 108 (0x6C)
void BDOS::BDOS_getSetProgramReturnCode()
{
uint16_t code = m_HAL->CPU_readRegWord(Z80_DE);
if (code == 0xFFFF) {
// get
m_HAL->CPU_writeRegWord(Z80_HL, SCB_getWord(SCB_PROGRAMRETCODE_W));
} else {
// set
SCB_setWord(SCB_PROGRAMRETCODE_W, code);
}
}
// BDOS 109 (0x6D)
void BDOS::BDOS_getSetConsoleMode()
{
uint16_t newval = m_HAL->CPU_readRegWord(Z80_DE);
if (newval == 0xFFFF) {
// get
m_HAL->CPU_writeRegWord(Z80_HL, SCB_getWord(SCB_CONSOLEMODE_W));
} else {
// set
SCB_setWord(SCB_CONSOLEMODE_W, newval);
}
}
// BDOS 110 (0x6E)
void BDOS::BDOS_getSetOutputDelimiter()
{
if (m_HAL->CPU_readRegWord(Z80_DE) == 0xFFFF) {
// get
uint8_t delim = SCB_getByte(SCB_OUTPUTDELIMETER_B);
CPUsetALBH(delim, 0);
} else {
// set
SCB_setByte(SCB_OUTPUTDELIMETER_B, m_HAL->CPU_readRegByte(Z80_E));
}
}
// 111 (0x6F)
void BDOS::BDOS_printBlock()
{
uint16_t CCB = m_HAL->CPU_readRegWord(Z80_DE); // CCB = Character Control Block
uint16_t str = m_HAL->readWord(CCB);
auto len = m_HAL->readWord(CCB + 2);
while (len--)
consoleOutChar(m_HAL->readByte(str++));
}
// 112 (0x70)
void BDOS::BDOS_listBlock()
{
uint16_t CCB = m_HAL->CPU_readRegWord(Z80_DE); // CCB = Character Control Block
uint16_t str = m_HAL->readWord(CCB);
auto len = m_HAL->readWord(CCB + 2);
while (len--)
lstOut(m_HAL->readByte(str++));
}
// 152 (0x98)
void BDOS::BDOS_parseFilename()
{
uint16_t PFCB = m_HAL->CPU_readRegWord(Z80_DE); // PFCB = Parse Filename Control Block
uint16_t strAddr = m_HAL->readWord(PFCB);
uint16_t FCBaddr = m_HAL->readWord(PFCB + 2);
m_HAL->fillMem(FCBaddr, 0, 36);
m_HAL->fillMem(FCBaddr + 16, ' ', 8); // blanks on password field
auto next = filenameToFCB(strAddr, FCBaddr, nullptr, nullptr);
// skip trailing blanks
while (m_HAL->readByte(next) != 0 && isspace(m_HAL->readByte(next)))
++next;
// return value (HL) is 0 to indicate "end of input", otherwise it is the address of next delimiter
uint16_t ret = 0x0000;
char nextChar = m_HAL->readByte(next);
if (nextChar != 0 && nextChar != ASCII_CR)
ret = strAddr + (next - strAddr);
m_HAL->CPU_writeRegWord(Z80_HL, ret);
}
// only searchingName can have wildcards
bool BDOS::fileMatchWithWildCards(char const * searchingName, char const * testingName)
{
auto searchingNameLen = strlen(searchingName);
for (int i = 0; i < searchingNameLen; ++i) {
if (searchingName[i] == '*') {
// wildcard '*', bypass all chars until "." or end of testing name
for (++testingName; *testingName && *testingName != '.'; ++testingName)
;
} else if (searchingName[i] == '?' || toupper(searchingName[i]) == toupper(*testingName)) {
// matching char
++testingName;
} else
return false; // fail
}
return true;
}
void BDOS::copyFile(FILE * src, FILE * dst)
{
void * buffer = malloc(COPYFILE_BUFFERSIZE);
while (true) {
auto r = fread(buffer, 1, COPYFILE_BUFFERSIZE, src);
if (r == 0)
break;
fwrite(buffer, 1, r, dst);
}
free(buffer);
}
// return true if filename has specified extension (without ".")
bool BDOS::hasExt(char const * filename, char const * ext)
{
auto p = strchr(filename, '.');
if (!p)
return strlen(ext) == 0;
++p;
return strcasecmp(p, ext) == 0;
}
bool BDOS::hasExt(uint16_t FCBaddr, char const * ext)
{
return m_HAL->compareMem(FCBaddr + FCB_T1, ext, 3) == 0;
}
void BDOS::strToUpper(char * str)
{
for (; *str; ++str)
*str = toupper(*str);
}
// Creates an absolute path (including mounting path) from a relative or disk-relative path.
//
// path can be:
// nullptr or empty => absolute path point to current directory of current drive
// \ => absolute path point to root directory of current drive
// drive: => absolute path point to current directory of specified drive
// drive:\ => absolute path point to root directory of specified drive
// something => absolute path point to current directory of current drive + '/' + something
// \something => absolute path point to root directory of current drive + '/' + something
// drive:something => absolute path point to current directory of specified drive + '/' + something
// drive:\something => absolute path point to root directory of specifie drive + '/' + something
// notes:
// - "something" can be a single name or multiple names separated by '/' or '\'
// - separators can be '/' or '\'
// - result buffer must be deallocated using free()
// returns:
// nullptr => invalid drive
char * BDOS::createAbsolutePath(uint16_t pathAddr, bool insertMountPath, int * drive)
{
char * path = nullptr;
auto pathLen = pathAddr ? m_HAL->strLen(pathAddr) : 0;
char pathStorage[pathLen + 1];
if (pathLen > 0) {
m_HAL->copyStr(pathStorage, pathAddr);
path = pathStorage;
strToUpper(path);
}
// bypass spaces
while (path && isspace(*path))
++path;
// source drive (if any, otherwise strToDrive() uses default drive)
int srcDrive;
if (strToDrive(path, &srcDrive))
path += 2;
if (!checkDrive(srcDrive)) {
// fail, invalid drive (message already shown by checkDrive())
return nullptr;
}
if (drive)
*drive = srcDrive;
// source is relative or absolute path?
bool srcIsAbsolute = path && strlen(path) > 0 && (path[0] == '\\' || path[0] == '/');
if (srcIsAbsolute)
++path; // bypass separator
// build source absolute path
char * srcAbsPath;
if (srcIsAbsolute) {
srcAbsPath = strdup(path);
} else {
// concatenate current directory and specified path
auto specPathLen = path ? strlen(path) : 0;
auto curdir = getCurrentDir(srcDrive);
srcAbsPath = (char*) malloc(strlen(curdir) + 1 + specPathLen + 1);
strcpy(srcAbsPath, curdir);
if (path && specPathLen > 0) {
if (curdir && strlen(curdir) > 0)
strcat(srcAbsPath, "/");
strcat(srcAbsPath, path);
}
}
fabgl::replacePathSep(srcAbsPath, '/');
// handle ".." (previous directory)
processPrevDirMarks(srcAbsPath);
if (!insertMountPath) {
// do not insert mounting path
return srcAbsPath;
}
// build source actual path (mount path + absolute path)
auto srcMountPath = m_HAL->getDriveMountPath(srcDrive);
char * srcActualPath = (char*) malloc(strlen(srcMountPath) + 1 + strlen(srcAbsPath) + 1);
strcpy(srcActualPath, srcMountPath);
if (strlen(srcAbsPath) > 0) {
strcat(srcActualPath, "/");
strcat(srcActualPath, srcAbsPath);
}
free(srcAbsPath);
return srcActualPath;
}
// process ".." marks, removing previous directory from the path
// "AAA/../BBB" => "BBB"
// "AAA/.." => ""
// "AAA/BBB/.." => "AAA"
// "AAA/BBB/../CCC" => "AAA/CCC"
// "AAA/BBB/../.." => ""
// "AAA/BBB/../CCC/../DDD" => "AAA/DDD"
// "AAA/BBB/CCC/../.." => "AAA"
// "AAA/BBB/CCC/../../DDD" => "AAA/DDD"
// 012345678901234567890
void BDOS::processPrevDirMarks(char * path)
{
int p = 0;
for (; path[p]; ++p) {
if (path[p] == '/' && path[p + 1] == '.' && path[p + 2] == '.') {
// found "/.." pattern
// search beginning of previous dir
int b = p - 1;
while (b >= 0 && path[b] != '/')
--b;
++b;
// removes from "b" to "p"
p += 3;
if (path[p] == '/')
++p;
memmove(path + b, path + p, strlen(path + p) + 1);
p = b - 2;
if (p < 0)
p = -1;
} else if (path[p] == '.' && path[p + 1] == '.') {
// found ".." pattern
// just remove (eventually even additional '/')
int b = p;
while (path[b] == '.' || path[b] == '/')
++b;
memmove(path + p, path + b, strlen(path + b) + 1);
p = -1;
}
}
if (path[p - 1] == '/')
path[p - 1] = 0;
}
// 212 (0xD4) : Copy file (specific of this BDOS implementation)
// HL : zero terminated string which specify "path + filename" of source
// DE : zero terminated string which specify "path + [filename]" of destination
// B : mode flags:
// bit 0 : 0 = fail if destination exists 1 = overwrite if destination exists
// bit 1 : 0 = don't show copied files 1 = show copied files
// ret:
// A = 0 -> success
// A = 1 -> fail, source doesn't exist
// A = 2 -> fail, destination path doesn't exist
// A = 3 -> fail, destination already exist
// A = 4 -> fail, source and dest are the same file
// notes:
// * supports '?' and '*' wildcards
void BDOS::BDOS_copyFile()
{
auto srcFullPathAddr = m_HAL->CPU_readRegWord(Z80_HL);
auto dstPathAddr = m_HAL->CPU_readRegWord(Z80_DE);
bool overwrite = (m_HAL->CPU_readRegByte(Z80_B) & 1);
bool display = (m_HAL->CPU_readRegByte(Z80_B) & 2);
auto srcActualPath = createAbsolutePath(srcFullPathAddr);
if (!srcActualPath) {
// fail, source doesn't exist
free(srcActualPath);
CPUsetALBH(1, 0);
return;
}
// break source path and filename path
char * srcFilename = strrchr(srcActualPath, '/');
*srcFilename = 0;
++srcFilename;
auto dstActualPath = createAbsolutePath(dstPathAddr);
if (!dstActualPath) {
// fail, dest desn't exist
free(srcActualPath);
free(dstActualPath);
CPUsetALBH(2, 0);
return;
}
// is dest path a directory?
// @TODO: what about SPIFFS?
struct stat statbuf;
bool destIsDir = stat(dstActualPath, &statbuf) == 0 && S_ISDIR(statbuf.st_mode);
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("overwrite = %s \r\n", overwrite ? "YES" : "NO");
m_HAL->logf("srcActualPath = \"%s\" \r\n", srcActualPath);
m_HAL->logf("dstActualPath = \"%s\" \r\n", dstActualPath);
#endif
int copied = 0;
if (m_fileBrowser.setDirectory(srcActualPath)) {
for (int i = 0; i < m_fileBrowser.count(); ++i) {
auto diritem = m_fileBrowser.get(i);
if (!diritem->isDir && fileMatchWithWildCards(srcFilename, diritem->name)) {
// name match
// compose dest path
char * dstActualFullPath;
if (destIsDir) {
// destination is a directory, append source filename
dstActualFullPath = (char *) malloc(strlen(dstActualPath) + 1 + strlen(diritem->name) + 1);
strcpy(dstActualFullPath, dstActualPath);
strcat(dstActualFullPath, "/");
strcat(dstActualFullPath, diritem->name);
} else {
// destination is a file
dstActualFullPath = strdup(dstActualPath);
}
// compose source path
auto srcActualFullPath = (char *) malloc(strlen(srcActualPath) + 1 + strlen(diritem->name) + 1);
strcpy(srcActualFullPath, srcActualPath);
strcat(srcActualFullPath, "/");
strcat(srcActualFullPath, diritem->name);
// source and dest are the same file?
if (strcasecmp(dstActualFullPath, srcActualFullPath) == 0) {
// yes...
free(dstActualFullPath);
free(srcActualFullPath);
copied = -3;
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" source and dest are the same file\r\n");
#endif
break;
}
if (!overwrite) {
// fail if dest already exists
FILE * f = fopen(dstActualFullPath, "rb");
if (f) {
fclose(f);
free(dstActualFullPath);
free(srcActualFullPath);
copied = -1;
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" file already exists\r\n");
#endif
break;
}
}
// try to open dest file
FILE * dstFile = fopen(dstActualFullPath, "wb");
if (!dstFile) {
// fail, dest path doesn't exist
free(dstActualFullPath);
free(srcActualFullPath);
copied = -2;
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf(" dest path doesn't exist\r\n");
#endif
break;
}
#if MSGDEBUG & DEBUG_BDOS
m_HAL->logf("copying \"%s\" to \"%s\" \r\n", srcActualFullPath, dstActualFullPath);
#endif
// open source file (always exists)
FILE * srcFile = fopen(srcActualFullPath, "rb");
// copy files
copyFile(srcFile, dstFile);
if (display) {
consoleOutStr(diritem->name);
consoleOutStr("\r\n");
}
// cleanup
fclose(srcFile);
fclose(dstFile);
free(srcActualFullPath);
free(dstActualFullPath);
++copied;
}
}
}
// cleanup buffers
free(srcActualPath);
free(dstActualPath);
if (copied == 0) {
// no source file
m_HAL->CPU_writeRegByte(Z80_A, 1);
} else if (copied > 0) {
// at least one copied
m_HAL->CPU_writeRegByte(Z80_A, 0);
} else if (copied == -1) {
// overwrite = false and at least one file already exists
m_HAL->CPU_writeRegByte(Z80_A, 3);
} else if (copied == -2) {
// destination path doesn't exist
m_HAL->CPU_writeRegByte(Z80_A, 2);
} else if (copied == -3) {
// source and dest are the same
m_HAL->CPU_writeRegByte(Z80_A, 4);
}
}
// 213 (0xD5) : Change current directory (specific of this BDOS implementation)
// DE : zero terminated string which specify "path" of new current directory
// ret:
// A = 0 -> success
// A = 1 -> fail, dir doesn't exist
// path can be:
// empty (first byte = 0) => set root as current directory of current disk
// \ => set root as current directory of current disk
// disk:\ => set root as current directory of specified disk
// something => set current dir + something as current directory of current disk
// ...and so on...
void BDOS::BDOS_changeCurrentDirectory()
{
uint16_t pathAddr = m_HAL->CPU_readRegWord(Z80_DE);
int drive;
auto actualPath = createAbsolutePath(pathAddr, true, &drive);
if (!actualPath) {
// fail, dir doesn't exist
CPUsetALBH(1, 0);
return;
}
if (m_fileBrowser.setDirectory(actualPath)) {
// success, remove mount path
auto mountPathLen = strlen(m_HAL->getDriveMountPath(drive));
if (mountPathLen == strlen(actualPath)) {
// root dir optimization
m_currentDir[drive][0] = 0;
free(actualPath);
} else {
memmove(actualPath, actualPath + mountPathLen + 1, strlen(actualPath) - mountPathLen + 1);
free(m_currentDir[drive]);
m_currentDir[drive] = actualPath;
}
CPUsetALBH(0, 0);
} else {
// fail, dir doesn't exist
free(actualPath);
CPUsetALBH(1, 0);
}
}
// fills R0, R1 and R2 of FCB with pos
// pos is in bytes (up aligned to 128 bytes)
void BDOS::setAbsolutePosFCB(uint16_t FCBaddr, size_t pos)
{
auto blk = (pos + 127) / 128; // number of blocks
m_HAL->writeByte(FCBaddr + FCB_R0, blk & 0xff);
m_HAL->writeByte(FCBaddr + FCB_R1, (blk >> 8) & 0xff);
m_HAL->writeByte(FCBaddr + FCB_R2, (blk >> 16) & 0xff);
}
// return pos (in bytes) from R0, R1 and R2 of FCB
size_t BDOS::getAbsolutePosFCB(uint16_t FCBaddr)
{
return 128 * (m_HAL->readByte(FCBaddr + FCB_R0) | (m_HAL->readByte(FCBaddr + FCB_R1) << 8) | (m_HAL->readByte(FCBaddr + FCB_R2) << 16));
}
// fills EX, S2 and CR of FPC with pos
// pos is in bytes (down aligned to 128 bytes)
void BDOS::setPosFCB(uint16_t FCBaddr, size_t pos)
{
m_HAL->writeByte(FCBaddr + FCB_EX, (pos % 524288) / 16384); // extent, low byte
m_HAL->writeByte(FCBaddr + FCB_S2, (pos / 524288)); // extent, high byte
m_HAL->writeByte(FCBaddr + FCB_CR, (pos % 16384) / 128); // cr (current record)
}
// return pos (in bytes) from EX, S2 and CR
size_t BDOS::getPosFCB(uint16_t FCBaddr)
{
return m_HAL->readByte(FCBaddr + FCB_EX) * 16384 + m_HAL->readByte(FCBaddr + FCB_S2) * 524288 + m_HAL->readByte(FCBaddr + FCB_CR) * 128;
}
// convert 11 bytes filename (8+3) of FCB to normal string (filename + '.' + ext)
void BDOS::getFilenameFromFCB(uint16_t FCBaddr, char * filename)
{
for (int i = 0; i < 11; ++i) {
char c = m_HAL->readByte(FCBaddr + 1 + i) & 0x7f;
if (i < 8) {
if (c == ' ') {
i = 7;
continue;
}
} else if (i == 8) {
if (c != ' ') {
*filename++ = '.';
} else
break;
} else { // i > 8
if (c == ' ')
break;
}
*filename++ = c;
}
*filename = 0;
}
// general form is:
// {d:}filename{.typ}{;password}
// extract drive ("A:", "B:"...) and filename and fill the FCB
// expand jolly '*' if present
// eliminates leading spaces
// FCB must be initialized with blanks and zeros (where necessary) before call filenameToFCB() because only specified fields are actually filled
// passwordAddr:
// nullptr => copy password into FCB
// pointer => put address of password into *passwordAddr
// passwordLen:
// set only when passwordAddr is not nullptr
// ret. next char after the filename (zero or a delimiter)
uint16_t BDOS::filenameToFCB(uint16_t filename, uint16_t FCB, uint16_t * passwordAddr, uint8_t * passwordLen)
{
// bypass leading spaces
while (m_HAL->readByte(filename) != 0 && isspace(m_HAL->readByte(filename)))
++filename;
// drive specified?
int drive;
if (strToDrive(filename, &drive)) {
m_HAL->writeByte(FCB + FCB_DR, drive + 1); // 1 = A
filename += 2;
} else
m_HAL->writeByte(FCB + FCB_DR, 0); // 0 = default drive
// calc filename size
int filenameSize = 0;
while (m_HAL->readByte(filename + filenameSize) != 0 && !isspace(m_HAL->readByte(filename + filenameSize)))
++filenameSize;
char filenameStr[filenameSize + 1];
m_HAL->copyMem(filenameStr, filename, filenameSize);
filenameStr[filenameSize] = 0;
char filename11[11];
auto sep = expandFilename(filenameStr, filename11, false);
m_HAL->copyMem(FCB + 1, filename11, 11);
auto sepAddr = filename + (sep - filenameStr);
if (sep[0] == ';' && isalnum(sep[1])) {
// extract password
++sep; ++sepAddr;
if (passwordAddr) {
*passwordAddr = sepAddr;
for (*passwordLen = 0; *passwordLen < 8 && !isFileDelimiter(*sep); ++*passwordLen) {
++sep; ++sepAddr;
}
} else {
for (int i = 0; i < 8; ++i) {
m_HAL->writeByte(FCB + 16 + i, isFileDelimiter(*sep) ? ' ' : toupper(*sep));
++sep; ++sepAddr;
}
}
} else if (passwordAddr) {
*passwordAddr = 0;
*passwordLen = 0;
}
return sepAddr;
}
// convert filename to 11 bytes (8+3)
// expands '*' with '?' on filename and file type
// ret. next char after the filename (zero or a delimiter)
char const * BDOS::expandFilename(char const * filename, char * expandedFilename, bool isDir)
{
memset(expandedFilename, ' ', 11);
if (strcmp(filename, "..") == 0) {
expandedFilename[0] = '.';
expandedFilename[1] = '.';
filename += 2;
} else if (strcmp(filename, ".") == 0) {
expandedFilename[0] = '.';
++filename;
} else {
for (int i = 0; i < 11;) {
if (i <= 8 && *filename == '.') {
i = 8;
} else if (*filename == '*') {
// expand jolly '*'..
if (i < 8) {
// ..on filename
for (; i < 8; ++i)
expandedFilename[i] = '?';
} else {
// ..on file type
for (; i < 11; ++i)
expandedFilename[i] = '?';
}
} else if (isFileDelimiter(*filename) || *filename < 32) {
break;
} else {
expandedFilename[i] = toupper(*filename);
++i;
}
++filename;
}
}
if (isDir)
memcpy(expandedFilename + 8, DIRECTORY_EXT, 3);
return filename;
}
int BDOS::getDriveFromFCB(uint16_t FCBaddr)
{
int rawdrive = m_HAL->readByte(FCBaddr + FCB_DR) & 0x1F; // 0x1F allows 0..16 range
if (rawdrive == 0)
return getCurrentDrive();
else
return rawdrive - 1;
}
bool BDOS::isFileDelimiter(char c)
{
return (c == 0x00 || // null
c == 0x20 || // space
c == 0x0D || // return
c == 0x09 || // tab
c == 0x3A || // :
c == 0x2E || // .
c == 0x3B || // ;
c == 0x3D || // =
c == 0x2C || // ,
c == 0x5B || // [
c == 0x5D || // ]
c == 0x3C || // <
c == 0x3E || // >
c == 0x7C); // |
}
// parse parameters in PAGE0_DMA (0x0080) and fills FCB1 and FCB2
void BDOS::parseParams()
{
m_HAL->fillMem(PAGE0_FCB1, 0, 36); // reset default FCB1 (this will reset up to 0x80, not included)
m_HAL->fillMem(PAGE0_FCB1 + FCB_F1, 32, 11); // blanks on filename of FCB1
m_HAL->fillMem(PAGE0_FCB2 + FCB_F1, 32, 11); // blanks on filename of FCB2
int len = m_HAL->readByte(PAGE0_DMA);
if (len > 1) {
uint16_t tailAddr = PAGE0_DMA + 2; // +2 to bypass params size and first space
// file 1
uint16_t passAddr;
uint8_t passLen;
auto next = filenameToFCB(tailAddr, PAGE0_FCB1, &passAddr, &passLen);
if (passAddr && passLen > 0) {
m_HAL->writeWord(PAGE0_FCB1PASSADDR_W, passAddr);
m_HAL->writeByte(PAGE0_FCB1PASSLEN, passLen);
}
// file 2
if (next) {
filenameToFCB(next, PAGE0_FCB2, &passAddr, &passLen);
if (passAddr && passLen > 0) {
m_HAL->writeWord(PAGE0_FCB2PASSADDR_W, passAddr);
m_HAL->writeByte(PAGE0_FCB2PASSLEN, passLen);
}
}
}
}
void BDOS::setBrowserAtDrive(int drive)
{
char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(m_currentDir[drive]) + 1];
strcpy(fullpath, m_HAL->getDriveMountPath(drive));
if (m_currentDir[drive] && strlen(m_currentDir[drive]) > 0) {
strcat(fullpath, "/");
strcat(fullpath, m_currentDir[drive]);
}
m_fileBrowser.setDirectory(fullpath);
}
// state->FCB and state->DMA must be initialized before searchFirst() call
void BDOS::searchFirst(FileSearchState * state)
{
state->index = -1;
state->extIndex = -1;
state->size = 0;
state->returnSFCB = false;
state->getAllFiles = (m_HAL->readByte(state->FCB + FCB_DR) == '?');
state->getAllExtents = (m_HAL->readByte(state->FCB + FCB_EX) == '?');
int drive = state->getAllFiles ? getCurrentDrive() : getDriveFromFCB(state->FCB);
if (m_HAL->getDriveMountPath(drive)) {
state->dirLabelFlags = getDirectoryLabelFlags(drive);
state->hasDirLabel = (state->dirLabelFlags != 0xFF && (state->dirLabelFlags & DIRLABELFLAGS_EXISTS));
setBrowserAtDrive(drive);
searchNext(state);
} else {
// invalid drive
state->errCode = 2;
}
}
void BDOS::searchNextFillDMA_FCB(FileSearchState * state, bool isFirst, char const * filename11)
{
// write file info into DMA
uint16_t DMA = state->DMA;
if (isFirst) {
m_HAL->fillMem(DMA, 0, 32);
m_HAL->writeByte(DMA + FCB_USR, 0); // user number 0 TODO
m_HAL->copyMem(DMA + FCB_F1, filename11, 11);
// reset extent number
m_HAL->writeByte(DMA + FCB_EX, 0); // extent lo [EX]
m_HAL->writeByte(DMA + FCB_S2, 0); // extent hi [S2]
} else {
// increment extent number
m_HAL->writeByte(DMA + FCB_EX, m_HAL->readByte(DMA + FCB_EX) + 1); // extent lo [EX]
if (m_HAL->readByte(DMA + FCB_EX) == 32) {
m_HAL->writeByte(DMA + FCB_EX, 0);
m_HAL->writeByte(DMA + FCB_S2, m_HAL->readByte(DMA + FCB_S2) + 1); // extent hi [S2]
}
}
// RC
m_HAL->writeByte(DMA + FCB_RC, fabgl::tmin((state->size + 127) / 128, 128));
int extentSize = m_HAL->readByte(DMA + FCB_RC) * 128;
// S1 (Last Record Byte Count)
if (extentSize < 16383 && state->size != extentSize) {
// not using the full extent space, so this is the last extent
m_HAL->writeByte(DMA + FCB_S1, state->size % 128);
} else // extentSize >= 16383
m_HAL->writeByte(DMA + FCB_S1, 0);
// D0-D15
// because each allocation block is 2K and we have a lot of blocks
// then each block pointer needs 16 bits (two bytes)
m_HAL->fillMem(DMA + FCB_AL, 0, 16);
int requiredBlocks = (extentSize + 2047) / 2048;
for (int i = 0; i < requiredBlocks; ++i) {
// set dummy 0xffff block pointer
m_HAL->writeByte(DMA + FCB_AL + i * 2 + 0, 0xff);
m_HAL->writeByte(DMA + FCB_AL + i * 2 + 1, 0xff);
}
// other extents of this reply appair as deleted
m_HAL->fillMem(DMA + 32, 0xE5, 96);
state->size -= extentSize;
}
void BDOS::searchNextFillDMA_SFCB(FileSearchState * state)
{
uint16_t DMA = state->DMA;
m_HAL->fillMem(DMA + 96, 0, 32);
m_HAL->writeByte(DMA + 96 + 0, 0x21);
m_HAL->copyMem(DMA + 96 + 1, &state->createOrAccessDate, 4);
m_HAL->copyMem(DMA + 96 + 5, &state->updateDate, 4);
m_HAL->writeByte(DMA + 96 + 9, 0);
m_HAL->writeByte(DMA + 96 + 10, 0);
}
bool BDOS::searchNextFillDMA_DirLabel(FileSearchState * state)
{
uint16_t DMA = state->DMA;
if (readDirectoryLabel(getCurrentDrive(), DMA, nullptr) & 0x01) {
// directory label exists
m_HAL->fillMem(DMA + 32, 0xE5, 96);
searchNextFillDMA_SFCB(state); // SFCB of directory label!
return true;
}
return false;
}
void BDOS::searchNext(FileSearchState * state)
{
while (true) {
if (state->getAllFiles && state->returnSFCB) {
// just return SFCB of the matched file
searchNextFillDMA_SFCB(state);
state->returnSFCB = false;
state->errCode = 0;
state->retCode = 3; // get fourth FCB
return;
} else if ((state->getAllFiles || state->getAllExtents) && state->size > 0) {
// still returning previous file, more extents need to be returned
searchNextFillDMA_FCB(state, false, nullptr);
if (state->hasDirLabel)
searchNextFillDMA_SFCB(state);
state->errCode = 0;
state->retCode = 0;
return;
} else {
// return a new file
if (state->hasDirLabel && state->extIndex == -1 && state->getAllFiles && searchNextFillDMA_DirLabel(state)) {
// get directory label as first extent
state->extIndex += 1;
state->returnSFCB = true; // directory label has its own datestamp (unused?)
state->retCode = 0;
state->errCode = 0;
return;
}
state->index += 1;
state->extIndex += 1;
if (state->index >= m_fileBrowser.count()) {
// no more files
state->errCode = 1;
return;
}
char const * filename = m_fileBrowser.get(state->index)->name;
char filename11[11];
expandFilename(filename, filename11, m_fileBrowser.get(state->index)->isDir);
bool match = true;
if (!state->getAllFiles) {
// does the search match?
char searchingStrg[11];
m_HAL->copyMem(searchingStrg, state->FCB + 1, 11);
char const * searching = searchingStrg;
char const * filename11ptr = filename11;
for (int i = 0; i < 11; ++i, ++searching, ++filename11ptr) {
if (*searching != '?' && toupper(*searching) != *filename11ptr) {
match = false;
break;
}
}
}
if (match) {
// file found
// get file size
state->size = (int) m_fileBrowser.fileSize(filename);
searchNextFillDMA_FCB(state, true, filename11);
if (state->hasDirLabel) {
// get file date stamps
int year = 0, month = 0, day = 0, hour = 0, minutes = 0, seconds = 0;
if (state->dirLabelFlags & DIRLABELFLAGS_CREATE)
m_fileBrowser.fileCreationDate(filename, &year, &month, &day, &hour, &minutes, &seconds);
if (state->dirLabelFlags & DIRLABELFLAGS_ACCESS)
m_fileBrowser.fileAccessDate(filename, &year, &month, &day, &hour, &minutes, &seconds);
state->createOrAccessDate.set(year, month, day, hour, minutes, seconds);
year = month = day = hour = minutes = seconds = 0;
if (state->dirLabelFlags & DIRLABELFLAGS_UPDATE)
m_fileBrowser.fileUpdateDate(filename, &year, &month, &day, &hour, &minutes, &seconds);
state->updateDate.set(year, month, day, hour, minutes, seconds);
searchNextFillDMA_SFCB(state);
state->returnSFCB = true;
}
state->retCode = 0;
state->errCode = 0;
return;
}
}
}
}
// don't care about m_consoleReadyChar
uint8_t BDOS::rawConsoleDirectIn()
{
return m_BIOS->BIOS_call_CONIN();
}
// don't care about m_consoleReadyChar
bool BDOS::rawConsoleDirectAvailable()
{
return m_BIOS->BIOS_call_CONST() != 0;
}
// always blocking
uint8_t BDOS::rawConsoleIn()
{
uint8_t r;
if (m_consoleReadyChar != 0) {
r = m_consoleReadyChar;
m_consoleReadyChar = 0;
} else {
r = rawConsoleDirectIn();
}
return r;
}
bool BDOS::rawConsoleAvailable()
{
return m_consoleReadyChar != 0 || rawConsoleDirectAvailable();
}
// output "c" to console
// - check for CTRL-P (if enabled)
// - check (and stop) for CTRL-S / CTRL-Q (if enabled)
// - echoes to LST (if enabled)
// - check for CTRL-C (if enabled)
// - expand TAB (if enabled)
void BDOS::consoleOutChar(uint8_t c)
{
bool rawConsole = isRawConsoleOutMode();
bool checkCTRLP = !rawConsole;
bool checkCTRLC = !isDisableCTRLCExit();
bool checkStopScroll = !isDisableStopScroll();
// user typed ctrl chars?
if ((checkCTRLP || checkCTRLC || checkStopScroll) && rawConsoleAvailable()) {
uint8_t tc = rawConsoleIn();
// CTRL-P?
if (checkCTRLP && tc == ASCII_CTRLP) {
switchPrinterEchoEnabled();
}
// CTRL-C?
else if (checkCTRLC && tc == ASCII_CTRLC) {
m_HAL->CPU_stop();
SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE);
}
// CTRL-S?
else if (checkStopScroll && tc == ASCII_CTRLS) {
// wait for CTRL-Q
while ((tc = rawConsoleIn()) != ASCII_CTRLQ) {
// CTRL-P is also checked here
if (checkCTRLP && tc == ASCII_CTRLP)
switchPrinterEchoEnabled();
// CTRL-C is also checked here
if (checkCTRLC && tc == ASCII_CTRLC) {
m_HAL->CPU_stop();
SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE);
break;
}
}
} else
m_consoleReadyChar = tc; // reinject character
}
if (c == ASCII_TAB && rawConsole == false) {
// expand TAB to 8 spaces
for (int i = 0; i < 8; ++i) {
m_BIOS->BIOS_call_CONOUT(' ');
if (m_printerEchoEnabled)
lstOut(' ');
}
} else {
m_BIOS->BIOS_call_CONOUT(c);
if (rawConsole == false && m_printerEchoEnabled)
lstOut(c);
}
}
uint8_t BDOS::consoleIn()
{
uint8_t c = 0;
while (true) {
c = rawConsoleIn();
switch (c) {
// TAB (expand to 8 spaces)
case ASCII_TAB:
for (int i = 0; i < 8; ++i) {
m_BIOS->BIOS_call_CONOUT(' ');
if (m_printerEchoEnabled)
lstOut(' ');
}
break;
// CTRL-P, switch on/off printer echo
case ASCII_CTRLP:
if (isDisableStopScroll() == false) { // isDisableStopScroll() disables also CTRL-P
switchPrinterEchoEnabled();
continue; // reloop
}
break;
// CTRL-C, terminate program
case ASCII_CTRLC:
if (isDisableCTRLCExit() == false) {
m_HAL->CPU_stop();
SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE);
}
break;
// CTRL-S/CTRL-Q (stop scroll and wait for CTRL-Q)
case ASCII_CTRLS:
if (!isDisableStopScroll()) {
while ((c = rawConsoleIn()) != ASCII_CTRLQ) {
// CTRL-P is also checked here
if (c == ASCII_CTRLP)
switchPrinterEchoEnabled();
// CTRL-C is also checked here
if (c == ASCII_CTRLC && isDisableCTRLCExit() == false) {
m_HAL->CPU_stop();
SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE);
return c;
}
m_BIOS->BIOS_call_CONOUT(ASCII_BEL);
}
continue; // reloop
}
break;
// others, echo
default:
m_BIOS->BIOS_call_CONOUT(c);
if (m_printerEchoEnabled)
lstOut(c);
break;
}
break; // exit loop
}
return c;
}
void BDOS::lstOut(uint8_t c)
{
m_BIOS->BIOS_call_LIST(c);
}
void BDOS::lstOut(char const * str)
{
while (*str)
lstOut(*str++);
}
// print until "delimeter"
void BDOS::consoleOutStr(char const * str, char delimiter)
{
while (*str != delimiter)
consoleOutChar(*str++);
}
// print until "delimiter"
void BDOS::consoleOutStr(uint16_t addr, char delimiter)
{
char c;
while ((c = m_HAL->readByte(addr++)) != delimiter)
consoleOutChar(c);
}
void BDOS::consoleOutFmt(const char * format, ...)
{
va_list ap;
va_start(ap, format);
int size = vsnprintf(nullptr, 0, format, ap) + 1;
if (size > 0) {
va_end(ap);
va_start(ap, format);
char buf[size + 1];
vsnprintf(buf, size, format, ap);
consoleOutStr(buf);
}
va_end(ap);
}
void BDOS::saveIntoConsoleHistory(char const * str)
{
if (str && strlen(str) > 0) {
int prevIndex = m_writeHistoryItem > 0 ? m_writeHistoryItem - 1 : CCP_HISTORY_DEPTH - 1;
if (strcmp(m_history[prevIndex], str) != 0) {
strcpy(m_history[m_writeHistoryItem], str);
++m_writeHistoryItem;
if (m_writeHistoryItem == CCP_HISTORY_DEPTH)
m_writeHistoryItem = 0;
}
m_readHistoryItem = m_writeHistoryItem;
}
/*
for (int i = 0; i < CCP_HISTORY_DEPTH; ++i)
m_HAL->logf("%d: \"%s\"\r\n", i, m_history[i]);
//*/
}
char const * BDOS::getPrevHistoryItem()
{
--m_readHistoryItem;
if (m_readHistoryItem < 0)
m_readHistoryItem = CCP_HISTORY_DEPTH - 1;
return m_history[m_readHistoryItem];
}
char const * BDOS::getNextHistoryItem()
{
++m_readHistoryItem;
if (m_readHistoryItem == CCP_HISTORY_DEPTH)
m_readHistoryItem = 0;
return m_history[m_readHistoryItem];
}
void BDOS::SCB_setBit(int field, int bitmask)
{
SCB_setByte(field, SCB_getByte(field) | bitmask);
}
void BDOS::SCB_clearBit(int field, int bitmask)
{
SCB_setByte(field, SCB_getByte(field) & ~bitmask);
}
bool BDOS::SCB_testBit(int field, int bitmask)
{
return (SCB_getByte(field) & bitmask) != 0;
}
void BDOS::SCB_setByte(int field, uint8_t value)
{
m_HAL->writeByte(SCB_ADDR + field, value);
}
uint8_t BDOS::SCB_getByte(int field)
{
return m_HAL->readByte(SCB_ADDR + field);
}
void BDOS::SCB_setWord(int field, uint16_t value)
{
m_HAL->writeWord(SCB_ADDR + field, value);
}
uint16_t BDOS::SCB_getWord(int field)
{
return m_HAL->readWord(SCB_ADDR + field);
}
| 25.833448 | 171 | 0.623012 | POMIN-163 |
1e420b0407854e8f026b8e07ba0a6796441cbb1e | 6,541 | cpp | C++ | Source/ArchQOR/x86/Assembler/BatchCPU/i586CPU.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/ArchQOR/x86/Assembler/BatchCPU/i586CPU.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/ArchQOR/x86/Assembler/BatchCPU/i586CPU.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //i586CPU.cpp
// Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>
// Copyright (c) Querysoft Limited 2013
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Implement i586 Assembler intrinsics for x86PC platform
#include "ArchQOR.h"
#if ( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
#include "ArchQOR/x86/Assembler/BatchCPU/i586CPU.h"
//------------------------------------------------------------------------------
namespace nsArch
{
namespace nsx86
{
//--------------------------------------------------------------------------------
Ci586CPU::Ci586CPU( CCodeGeneratorBase* codeGenerator ) : Ci486CPU( codeGenerator )
{
}
//--------------------------------------------------------------------------------
Ci586CPU::~Ci586CPU() __QCMP_THROW
{
}
//------------------------------------------------------------------------------
//Compares the 64-bit value in EDX:EAX with the memory operand (Pentium).
//
// If the values are equal, then this instruction stores the 64-bit value
// in ECX:EBX into the memory operand and sets the zero flag. Otherwise,
// this instruction copies the 64-bit memory operand into the EDX:EAX
// registers and clears the zero flag.
void Ci586CPU::cmpxchg8b( const CMem& dst )
{
_emitInstruction( INST_CMPXCHG8B, &dst );
}
//------------------------------------------------------------------------------
//Read Time-Stamp Counter (Pentium).
void Ci586CPU::rdtsc()
{
_emitInstruction( INST_RDTSC );
}
//------------------------------------------------------------------------------
//Read Time-Stamp Counter and Processor ID (New).
void Ci586CPU::rdtscp()
{
_emitInstruction( INST_RDTSCP );
}
//------------------------------------------------------------------------------
#if ( QOR_ARCH_WORDSIZE == 64 )
//Convert DWord to QWord (Sign Extend).
//
// RAX <- Sign Extend EAX
void Ci586CPU::cdqe()
{
_emitInstruction( INST_CDQE );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//Compares the 128-bit value in RDX:RAX with the memory operand (X64).
//
// If the values are equal, then this instruction stores the 128-bit value
// in RCX:RBX into the memory operand and sets the zero flag. Otherwise,
// this instruction copies the 128-bit memory operand into the RDX:RAX
// registers and clears the zero flag.
void Ci586CPU::cmpxchg16b( const CMem& dst )
{
_emitInstruction( INST_CMPXCHG16B, &dst );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Move DWord to QWord with sign-extension.
void Ci586CPU::movsxd( const CGPReg& dst, const CGPReg& src )
{
_emitInstruction( INST_MOVSXD, &dst, &src );
}
//------------------------------------------------------------------------------
//Move DWord to QWord with sign-extension.
// @overload
void Ci586CPU::movsxd( const CGPReg& dst, const CMem& src )
{
_emitInstruction( INST_MOVSXD, &dst, &src );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Load ECX/RCX QWORDs from DS:[ESI/RSI] to RAX.
void Ci586CPU::rep_lodsq()
{
_emitInstruction( INST_REP_LODSQ );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Move ECX/RCX QWORDs from DS:[ESI/RSI] to ES:[EDI/RDI].
void Ci586CPU::rep_movsq()
{
_emitInstruction( INST_REP_MOVSQ );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Fill ECX/RCX QWORDs at ES:[EDI/RDI] with RAX.
void Ci586CPU::rep_stosq()
{
_emitInstruction( INST_REP_STOSQ );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Repeated find nonmatching QWORDs in ES:[EDI/RDI] and DS:[ESI/RDI].
void Ci586CPU::repe_cmpsq()
{
_emitInstruction( INST_REPE_CMPSQ );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Find non-RAX QWORD starting at ES:[EDI/RDI].
void Ci586CPU::repe_scasq()
{
_emitInstruction( INST_REPE_SCASQ );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Repeated find nonmatching QWORDs in ES:[EDI/RDI] and DS:[ESI/RDI].
void Ci586CPU::repne_cmpsq()
{
_emitInstruction( INST_REPNE_CMPSQ );
}
#endif //
#if ( QOR_ARCH_WORDSIZE == 64 )
//------------------------------------------------------------------------------
//Find RAX, starting at ES:[EDI/RDI].
void Ci586CPU::repne_scasq()
{
_emitInstruction( INST_REPNE_SCASQ );
}
#endif //
//--------------------------------------------------------------------------------
CPentiumFPU::CPentiumFPU( Cx86CPUCore& refCPU ) : C486FPU( refCPU )
{
}
//--------------------------------------------------------------------------------
CPentiumFPU::~CPentiumFPU()
{
}
}//nsx86
}//nsArch
#endif//( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
| 34.067708 | 85 | 0.541202 | mfaithfull |
1e4407c4faf59b2aef39e4ece8e4bcfba39571b6 | 19,167 | cpp | C++ | SYEngine/Engine/SceneManager/EntityManager/ComponentManager/Component/Rendering/SkeletalModel.cpp | FrankMejzlik/syengine | 27929bbea5e05d1b1ce97abe408c5a90f29ab4dc | [
"MIT"
] | 1 | 2022-02-14T18:39:49.000Z | 2022-02-14T18:39:49.000Z | SYEngine/Engine/SceneManager/EntityManager/ComponentManager/Component/Rendering/SkeletalModel.cpp | FrankMejzlik/syengine | 27929bbea5e05d1b1ce97abe408c5a90f29ab4dc | [
"MIT"
] | null | null | null | SYEngine/Engine/SceneManager/EntityManager/ComponentManager/Component/Rendering/SkeletalModel.cpp | FrankMejzlik/syengine | 27929bbea5e05d1b1ce97abe408c5a90f29ab4dc | [
"MIT"
] | null | null | null | //
//#include "SkeletalModel.h"
//
//using namespace SYE;
//
//glm::mat3 aiMatrix3x3ToGlm(const aiMatrix3x3 &from)
//{
// glm::mat3 to = std::move(glm::mat4(1.0f));
// //the a,b,c,d in assimp is the row ; the 1,2,3,4 is the column
// to[0][0] = from.a1; to[1][0] = from.a2; to[2][0] = from.a3;
// to[0][1] = from.b1; to[1][1] = from.b2; to[2][1] = from.b3;
// to[0][2] = from.c1; to[1][2] = from.c2; to[2][2] = from.c3;
//
// return to;
//}
//
//glm::mat4 aiMatrix4x4ToGlm(const aiMatrix4x4 &from)
//{
// glm::mat4 to = std::move(glm::mat4(1.0f));
// //the a,b,c,d in assimp is the row ; the 1,2,3,4 is the column
// to[0][0] = from.a1; to[1][0] = from.a2; to[2][0] = from.a3; to[3][0] = from.a4;
// to[0][1] = from.b1; to[1][1] = from.b2; to[2][1] = from.b3; to[3][1] = from.b4;
// to[0][2] = from.c1; to[1][2] = from.c2; to[2][2] = from.c3; to[3][2] = from.c4;
// to[0][3] = from.d1; to[1][3] = from.d2; to[2][3] = from.d3; to[3][3] = from.d4;
// return to;
//}
//
///* Adds a new Bone */
//void VertexBoneData::AddBoneData(unsigned int BoneID, float Weight)
//{
// for (unsigned int i = 0; i < NUM_BONES_PER_VERTEX; ++i)
// if (Weights[i] == 0.0)
// {
// IDs[i] = BoneID;
// Weights[i] = Weight;
// return;
// }
//}
//
//
//BoneInfo::BoneInfo()
//{
// BoneOffset = glm::mat4(0.0f);
// FinalTransformation = glm::mat4(0.0f);
//}
//
//
//VertexBoneData::VertexBoneData()
//{
// Reset();
//}
//
//void VertexBoneData::Reset()
//{
// for (unsigned int i = 0; i < NUM_BONES_PER_VERTEX; ++i)
// {
// IDs[i] = 0;
// Weights[i] = 0;
// }
//}
//
///* Init */
//SkeletalModel::SkeletalModel(Entity* pOwnerEntity, const std::map< int, std::unique_ptr<BaseModule> >& subModulesConstRef, std::array< std::map<size_t, Component*>, COMPONENTS_NUM_SLOTS>& primaryComponentSlots)
// //Model(pOwnerEntity, subModulesConstRef, primaryComponentSlots)
//{
// m_Importer = new Assimp::Importer();
//
// m_VAO = 0;
// for (unsigned int i = 0; i < (unsigned long long)eVertexBufferType::NUM_VBs; ++i)
// {
// m_Buffers[i] = 0;
// }
// m_NumBones = 0;
// m_pScene = NULL;
//
// _type = eType::SKELETAL_MODEL;
//}
//
//SkeletalModel::~SkeletalModel()
//{
// Clear();
//}
//
//void SkeletalModel::Clear()
//{
// /* Deletes VBOs */
// if (m_Buffers[0] != 0)
// glDeleteBuffers(NUM_VBs, m_Buffers);
// /* Deletes VAO */
// if (m_VAO != 0)
// {
// glDeleteVertexArrays(1, &m_VAO);
// m_VAO = 0;
// }
//}
//
//
//void SkeletalModel::LoadModelFromFile(std::string_view fileName)
//{
// /* Deletes the previous loaded mesh(if it exists) */
// Clear();
//
// /* Create the VAO */
// glGenVertexArrays(1, &m_VAO);
// glBindVertexArray(m_VAO);
//
// /* Create VBOs for vertices attributes */
// glGenBuffers(NUM_VBs, m_Buffers);
//
// /* Return value */
// bool ret = false;
//
// m_pScene = m_Importer->ReadFile(fileName.data(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals);
//
// if (m_pScene)
// {
// /* Get transformation matrix for nodes(vertices relative to bones) */
// aiMatrix4x4 tp1 = m_pScene->mRootNode->mTransformation;
// m_GlobalInverseTransform = aiMatrix4x4ToGlm(tp1);
// m_GlobalInverseTransform = glm::inverse(m_GlobalInverseTransform);
//
// ret = InitFromScene(m_pScene, fileName.data());
// }
// else
// {
// std::cout << "Error parsing : " << fileName.data() << " : " << m_Importer->GetErrorString() << std::endl;
// }
//
// /* Make sure the VAO is not changed from the outside */
// glBindVertexArray(0);
//
// return;
//}
//
//bool SkeletalModel::InitFromScene(const aiScene* pScene, const std::string& fileName)
//{
// /* Resize the mesh & texture vectors */
// m_Entries.resize(pScene->mNumMeshes);
// m_Textures.resize(pScene->mNumMaterials);
//
// std::vector<glm::vec3> Positions;
// std::vector<glm::vec3> Normals;
// std::vector<glm::vec2> TexCoords;
// std::vector<VertexBoneData> Bones;
// std::vector<unsigned int> Indices;
//
// unsigned int NumVertices = 0;
// unsigned int NumIndices = 0;
//
// /* Count the number of vertices and indices */
// for (unsigned int i = 0; i < m_Entries.size(); ++i)
// {
// m_Entries[i].m_materialIndex = pScene->mMeshes[i]->mMaterialIndex;
// m_Entries[i].m_numIndices = pScene->mMeshes[i]->mNumFaces * 3;
// m_Entries[i].m_baseVertex = NumVertices;
// m_Entries[i].m_baseIndex = NumIndices;
//
// NumVertices += pScene->mMeshes[i]->mNumVertices;
// NumIndices += m_Entries[i].m_numIndices;
// }
//
// // Reserve space in the vectors for the vertex attributes and indices
// Positions.reserve(NumVertices);
// Normals.reserve(NumVertices);
// TexCoords.reserve(NumVertices);
// Bones.resize(NumVertices);
// Indices.reserve(NumIndices);
//
// /* Initialize the meshes in the scene one by one */
// for (unsigned int i = 0; i < m_Entries.size(); ++i)
// {
// /* get mesh */
// const aiMesh* paiMesh = pScene->mMeshes[i];
// /* init the mesh */
// InitMesh(i, paiMesh, Positions, Normals, TexCoords, Bones, Indices);
// }
//
// /* init the material */
// if (!InitMaterials(pScene, fileName))
// return false;
//
// /* Generate and populate the buffers with vertex attributes and indices */
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[POS_VB]);
// glBufferData(GL_ARRAY_BUFFER, sizeof(Positions[0]) * Positions.size(), &Positions[0], GL_STATIC_DRAW);
// glEnableVertexAttribArray(POSITION_LOCATION);
// glVertexAttribPointer(POSITION_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, 0);
//
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[TEXCOORD_VB]);
// glBufferData(GL_ARRAY_BUFFER, sizeof(TexCoords[0]) * TexCoords.size(), &TexCoords[0], GL_STATIC_DRAW);
// glEnableVertexAttribArray(TEX_COORD_LOCATION);
// glVertexAttribPointer(TEX_COORD_LOCATION, 2, GL_FLOAT, GL_FALSE, 0, 0);
//
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[NORMAL_VB]);
// glBufferData(GL_ARRAY_BUFFER, sizeof(Normals[0]) * Normals.size(), &Normals[0], GL_STATIC_DRAW);
// glEnableVertexAttribArray(NORMAL_LOCATION);
// glVertexAttribPointer(NORMAL_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, 0);
//
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[BONE_VB]);
// glBufferData(GL_ARRAY_BUFFER, sizeof(Bones[0]) * Bones.size(), &Bones[0], GL_STATIC_DRAW);
//
// glEnableVertexAttribArray(BONE_ID_LOCATION);
// glVertexAttribIPointer(BONE_ID_LOCATION, 4, GL_INT, sizeof(VertexBoneData), (const GLvoid*)0);
//
// glEnableVertexAttribArray(BONE_WEIGHT_LOCATION);
// glVertexAttribPointer(BONE_WEIGHT_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(VertexBoneData), (const GLvoid*)16);
//
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Buffers[INDEX_BUFFER]);
// glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices[0]) * Indices.size(), &Indices[0], GL_STATIC_DRAW);
//
// if (glGetError() == GL_NO_ERROR)
// return true;
// else
// return false;
//}
//
//void SkeletalModel::InitMesh(unsigned int MeshIndex,
// const aiMesh* paiMesh,
// std::vector<glm::vec3>& Positions,
// std::vector<glm::vec3>& Normals,
// std::vector<glm::vec2>& TexCoords,
// std::vector<VertexBoneData>& Bones,
// std::vector<unsigned int>& Indices)
//{
// const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
//
// /* Populize the vertex attribute vectors */
// for (unsigned int i = 0; i < paiMesh->mNumVertices; ++i)
// {
// /* Get pos normal texCoord */
//
// const aiVector3D* pPos = &(paiMesh->mVertices[i]);
//
// const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D;
//
// /* store pos normal texCoord */
// Positions.push_back(glm::vec3(pPos->x, pPos->y, pPos->z));
//
// if (paiMesh->HasNormals())
// {
// const aiVector3D* pNormal = &(paiMesh->mNormals[i]);
// Normals.push_back(glm::vec3(-(pNormal->x), -(pNormal->y), -(pNormal->z)));
// }
// TexCoords.push_back(glm::vec2(pTexCoord->x, pTexCoord->y));
// }
//
// /* Load bones */
// LoadBones(MeshIndex, paiMesh, Bones);
//
// /* Populate the index buffer */
// for (unsigned int i = 0; i < paiMesh->mNumFaces; ++i)
// {
// const aiFace& Face = paiMesh->mFaces[i];
// /* if mNumIndices != 3 then worning */
// assert(Face.mNumIndices == 3);
// Indices.push_back(Face.mIndices[0]);
// Indices.push_back(Face.mIndices[1]);
// Indices.push_back(Face.mIndices[2]);
// }
//}
//
//void SkeletalModel::LoadBones(unsigned int MeshIndex, const aiMesh* pMesh, std::vector<VertexBoneData>& Bones)
//{
// /* Load bones one by one */
//
// for (unsigned int i = 0; i < pMesh->mNumBones; ++i)
// {
// unsigned int BoneIndex = 0;
// std::string BoneName(pMesh->mBones[i]->mName.data);
//
// if (m_BoneMapping.find(BoneName) == m_BoneMapping.end())
// {
// /* allocate an index for the new bone */
// BoneIndex = m_NumBones;
// m_NumBones++;
// BoneInfo bi;
// m_BoneInfo.push_back(bi);
//
// aiMatrix4x4 tp1 = pMesh->mBones[i]->mOffsetMatrix;
// m_BoneInfo[BoneIndex].BoneOffset = aiMatrix4x4ToGlm(tp1);
// m_BoneMapping[BoneName] = BoneIndex;
// }
// else
// {
// BoneIndex = m_BoneMapping[BoneName];
// }
//
// for (unsigned int j = 0; j < pMesh->mBones[i]->mNumWeights; ++j)
// {
// //std::cout << pMesh->mBones[i]->mWeights. << std::endl;
// unsigned int VertexID = m_Entries[MeshIndex].m_baseVertex + pMesh->mBones[i]->mWeights[j].mVertexId;
// float Weight = pMesh->mBones[i]->mWeights[j].mWeight;
// Bones[VertexID].AddBoneData(BoneIndex, Weight);
// }
// }
//}
//
//bool SkeletalModel::InitMaterials(const aiScene* pScene, const std::string& filename)
//{
// UNREFERENCED_PARAMETER(pScene);
// UNREFERENCED_PARAMETER(filename);
//
// //// Extract the directory part from the file name
// //std::string::size_type SlashIndex = Filename.find_last_of("/");
// //std::string Dir;
//
// //if (SlashIndex == std::string::npos) {
// // Dir = ".";
// //}
// //else if (SlashIndex == 0) {
// // Dir = "/";
// //}
// //else {
// // Dir = Filename.substr(0, SlashIndex);
// //}
//
// //bool ret = true;
//
// ///* Initialize the materials */
// //for (unsigned int i = 0; i < pScene->mNumMaterials; ++i)
// //{
// // _textures.resize(pScene->mNumMaterials);
// // /* Get the material */
// // const aiMaterial* pMaterial = pScene->mMaterials[i];
//
// // m_Textures[i] = 0;
//
// // if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0)
// // {
// // aiString Path;
//
// // if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS)
// // {
// // std::string p(Path.data);
//
// // if (p.substr(0, 2) == ".\\")
// // {
// // p = p.substr(2, p.size() - 2);
// // }
//
// // std::string FullPath = Dir + "/" + p;
//
// // _textures[i] = new Texture(_pOwnerEntity, _subModules, _primaryComponentSlots, FullPath.c_str());
//
// // if (!_textures[i]->LoadTexture())
// // {
// // printf("Failed to load texture at: %s\n", FullPath.c_str());
// // delete _textures[i];
// // _textures[i] = nullptr;
//
// // }
// // }
// // }
// //}
// //return ret;
//
// return false;
//}
//
//void SkeletalModel::render(GLuint shaderId)
//{
// UNREFERENCED_PARAMETER(shaderId);
//
// glBindVertexArray(m_VAO);
//
// for (unsigned int i = 0; i < m_Entries.size(); i++) {
//
// const unsigned int materialIndex = m_Entries[i].m_materialIndex;
//
// if (materialIndex < _textures.size() && _textures[materialIndex])
// {
// _textures[materialIndex]->UseTexture();
// }
//
// glDrawElementsBaseVertex(GL_TRIANGLES,
// m_Entries[i].m_numIndices,
// GL_UNSIGNED_INT,
// (void*)(sizeof(unsigned int) * m_Entries[i].m_baseIndex),
// m_Entries[i].m_baseVertex);
// }
//
// glBindVertexArray(0);
//}
//
//unsigned int SkeletalModel::FindPosition(float AnimationTime, const aiNodeAnim* pNodeAnim)
//{
// for (unsigned int i = 0; i < pNodeAnim->mNumPositionKeys - 1; i++)
// {
//
// if (AnimationTime < (float)pNodeAnim->mPositionKeys[i + 1].mTime) {
// return i;
// }
// }
//
// assert(0);
// return 0;
//}
//
//unsigned int SkeletalModel::FindRotation(float AnimationTime, const aiNodeAnim* pNodeAnim)
//{
// assert(pNodeAnim->mNumRotationKeys > 0);
//
// for (unsigned int i = 0; i < pNodeAnim->mNumRotationKeys - 1; i++) {
// if (AnimationTime < (float)pNodeAnim->mRotationKeys[i + 1].mTime) {
// return i;
// }
// }
//
// assert(0);
// return 0;
//}
//
//unsigned int SkeletalModel::FindScaling(float AnimationTime, const aiNodeAnim* pNodeAnim)
//{
// assert(pNodeAnim->mNumScalingKeys > 0);
//
// for (unsigned int i = 0; i < pNodeAnim->mNumScalingKeys - 1; i++) {
// if (AnimationTime < (float)pNodeAnim->mScalingKeys[i + 1].mTime) {
// return i;
// }
// }
//
// assert(0);
// return 0;
//}
//
//void SkeletalModel::CalcInterpolatedPosition(aiVector3D& Out, float AnimationTime, const aiNodeAnim* pNodeAnim)
//{
// if (pNodeAnim->mNumPositionKeys == 1) {
// Out = pNodeAnim->mPositionKeys[0].mValue;
// return;
// }
//
// unsigned int PositionIndex = FindPosition(AnimationTime, pNodeAnim);
// unsigned int NextPositionIndex = (PositionIndex + 1);
// assert(NextPositionIndex < pNodeAnim->mNumPositionKeys);
// float DeltaTime = (float)(pNodeAnim->mPositionKeys[NextPositionIndex].mTime - pNodeAnim->mPositionKeys[PositionIndex].mTime);
// float Factor = (AnimationTime - (float)pNodeAnim->mPositionKeys[PositionIndex].mTime) / DeltaTime;
// assert(Factor >= 0.0f && Factor <= 1.0f);
// const aiVector3D& Start = pNodeAnim->mPositionKeys[PositionIndex].mValue;
// const aiVector3D& End = pNodeAnim->mPositionKeys[NextPositionIndex].mValue;
// aiVector3D Delta = End - Start;
// Out = Start + Factor * Delta;
//}
//
//void SkeletalModel::CalcInterpolatedRotation(aiQuaternion& Out, float AnimationTime, const aiNodeAnim* pNodeAnim)
//{
// // we need at least two values to interpolate...
// if (pNodeAnim->mNumRotationKeys == 1) {
// Out = pNodeAnim->mRotationKeys[0].mValue;
// return;
// }
//
// unsigned int RotationIndex = FindRotation(AnimationTime, pNodeAnim);
// unsigned int NextRotationIndex = (RotationIndex + 1);
// assert(NextRotationIndex < pNodeAnim->mNumRotationKeys);
// float DeltaTime = (float)(pNodeAnim->mRotationKeys[NextRotationIndex].mTime - pNodeAnim->mRotationKeys[RotationIndex].mTime);
// float Factor = (AnimationTime - (float)pNodeAnim->mRotationKeys[RotationIndex].mTime) / DeltaTime;
// assert(Factor >= 0.0f && Factor <= 1.0f);
// const aiQuaternion& StartRotationQ = pNodeAnim->mRotationKeys[RotationIndex].mValue;
// const aiQuaternion& EndRotationQ = pNodeAnim->mRotationKeys[NextRotationIndex].mValue;
// aiQuaternion::Interpolate(Out, StartRotationQ, EndRotationQ, Factor);
// Out = Out.Normalize();
//}
//
//void SkeletalModel::CalcInterpolatedScaling(aiVector3D& Out, float AnimationTime, const aiNodeAnim* pNodeAnim)
//{
// if (pNodeAnim->mNumScalingKeys == 1) {
// Out = pNodeAnim->mScalingKeys[0].mValue;
// return;
// }
//
// unsigned int ScalingIndex = FindScaling(AnimationTime, pNodeAnim);
// unsigned int NextScalingIndex = (ScalingIndex + 1);
// assert(NextScalingIndex < pNodeAnim->mNumScalingKeys);
// float DeltaTime = (float)(pNodeAnim->mScalingKeys[NextScalingIndex].mTime - pNodeAnim->mScalingKeys[ScalingIndex].mTime);
// float Factor = (AnimationTime - (float)pNodeAnim->mScalingKeys[ScalingIndex].mTime) / DeltaTime;
// assert(Factor >= 0.0f && Factor <= 1.0f);
// const aiVector3D& Start = pNodeAnim->mScalingKeys[ScalingIndex].mValue;
// const aiVector3D& End = pNodeAnim->mScalingKeys[NextScalingIndex].mValue;
// aiVector3D Delta = End - Start;
// Out = Start + Factor * Delta;
//}
//
//void SkeletalModel::ReadNodeHeirarchy(float AnimationTime, const aiNode* pNode, const glm::mat4& ParentTransform)
//{
// std::string NodeName(pNode->mName.data);
//
// const aiAnimation* pAnimation = m_pScene->mAnimations[0];
//
// aiMatrix4x4 tp1 = pNode->mTransformation;
// glm::mat4 NodeTransformation = aiMatrix4x4ToGlm(tp1);
// const aiNodeAnim* pNodeAnim = FindNodeAnim(pAnimation, NodeName);
//
// if (pNodeAnim) {
// // Interpolate scaling and generate scaling transformation matrix
// aiVector3D Scaling;
// CalcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim);
// glm::mat4 ScalingM = std::move(glm::mat4(1.0f));
//
// ScalingM = glm::scale(ScalingM, glm::vec3(Scaling.x, Scaling.y, Scaling.z));
//
// // Interpolate rotation and generate rotation transformation matrix
// aiQuaternion RotationQ;
// CalcInterpolatedRotation(RotationQ, AnimationTime, pNodeAnim);
// aiMatrix3x3 tp = RotationQ.GetMatrix();
// glm::mat4 RotationM = aiMatrix3x3ToGlm(tp);
//
// // Interpolate translation and generate translation transformation matrix
// aiVector3D Translation;
//
// CalcInterpolatedPosition(Translation, AnimationTime, pNodeAnim);
// glm::mat4 TranslationM = std::move(glm::mat4(1.0f));
// TranslationM = glm::translate(TranslationM, glm::vec3(Translation.x, Translation.y, Translation.z));
//
// // Combine the above transformations
// NodeTransformation = TranslationM * RotationM *ScalingM;
// }
//
// glm::mat4 GlobalTransformation = ParentTransform * NodeTransformation;
//
// if (m_BoneMapping.find(NodeName) != m_BoneMapping.end()) {
// unsigned int BoneIndex = m_BoneMapping[NodeName];
// m_BoneInfo[BoneIndex].FinalTransformation = m_GlobalInverseTransform * GlobalTransformation * m_BoneInfo[BoneIndex].BoneOffset;
// }
//
// for (unsigned int i = 0; i < pNode->mNumChildren; i++) {
// ReadNodeHeirarchy(AnimationTime, pNode->mChildren[i], GlobalTransformation);
// }
//}
//
//void SkeletalModel::boneTransform(float timeInSeconds, std::vector<glm::mat4>& Transforms)
//{
// glm::mat4 Identity = std::move(glm::mat4(1.0f));
//
//
// /* The original code with the buggy animation duration */
// //animDuration = (float)m_pScene->mAnimations[0]->mDuration;
//
// /* Calc animation duration from last frame */
// unsigned int numPosKeys = m_pScene->mAnimations[0]->mChannels[0]->mNumPositionKeys;
// animDuration = m_pScene->mAnimations[0]->mChannels[0]->mPositionKeys[numPosKeys - 1].mTime;
//
// float TicksPerSecond = (float)(m_pScene->mAnimations[0]->mTicksPerSecond != 0 ? m_pScene->mAnimations[0]->mTicksPerSecond : 25.0f);
//
// float TimeInTicks = timeInSeconds * TicksPerSecond;
// float AnimationTime = static_cast<float>(fmod(TimeInTicks, animDuration));
//
// ReadNodeHeirarchy(AnimationTime, m_pScene->mRootNode, Identity);
//
// Transforms.resize(m_NumBones);
//
// for (unsigned int i = 0; i < m_NumBones; i++) {
// Transforms[i] = m_BoneInfo[i].FinalTransformation;
// }
//}
//
//const aiNodeAnim* SkeletalModel::FindNodeAnim(const aiAnimation* pAnimation, const std::string NodeName)
//{
// for (unsigned int i = 0; i < pAnimation->mNumChannels; i++) {
// const aiNodeAnim* pNodeAnim = pAnimation->mChannels[i];
//
// if (std::string(pNodeAnim->mNodeName.data) == NodeName) {
// return pNodeAnim;
// }
// }
//
// return NULL;
//}
| 33.685413 | 212 | 0.648406 | FrankMejzlik |
1e492915206c1c32a6f4f79efada46d6b27d8a8b | 193 | cpp | C++ | src/Lab2/main.cpp | viktormuzyka/ooop | 9d89d1f9884166a7fd6267bab231c6d9ac98c676 | [
"Apache-2.0"
] | 1 | 2021-10-04T17:42:42.000Z | 2021-10-04T17:42:42.000Z | src/Lab2/main.cpp | viktormuzyka/ooop | 9d89d1f9884166a7fd6267bab231c6d9ac98c676 | [
"Apache-2.0"
] | null | null | null | src/Lab2/main.cpp | viktormuzyka/ooop | 9d89d1f9884166a7fd6267bab231c6d9ac98c676 | [
"Apache-2.0"
] | null | null | null | #include <QtWidgets>
#include "texthook.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
AddressBook addressBook;
addressBook.show();
return app.exec();
}
| 14.846154 | 33 | 0.658031 | viktormuzyka |
1e4c56171378f5a6299614434f3a188bcc30deba | 13,108 | hpp | C++ | include/Newtonsoft/Json/Utilities/TypeExtensions.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Utilities/TypeExtensions.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Utilities/TypeExtensions.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: MemberTypes
struct MemberTypes;
// Forward declaring type: MemberInfo
class MemberInfo;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: Newtonsoft.Json.Utilities
namespace Newtonsoft::Json::Utilities {
// Forward declaring type: TypeExtensions
class TypeExtensions;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Newtonsoft::Json::Utilities::TypeExtensions);
DEFINE_IL2CPP_ARG_TYPE(::Newtonsoft::Json::Utilities::TypeExtensions*, "Newtonsoft.Json.Utilities", "TypeExtensions");
// Type namespace: Newtonsoft.Json.Utilities
namespace Newtonsoft::Json::Utilities {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Newtonsoft.Json.Utilities.TypeExtensions
// [TokenAttribute] Offset: FFFFFFFF
// [PreserveAttribute] Offset: 122B714
// [ExtensionAttribute] Offset: FFFFFFFF
class TypeExtensions : public ::Il2CppObject {
public:
// static public System.Reflection.MemberTypes MemberType(System.Reflection.MemberInfo memberInfo)
// Offset: 0x2039D68
static ::System::Reflection::MemberTypes MemberType(::System::Reflection::MemberInfo* memberInfo);
// static public System.Boolean ContainsGenericParameters(System.Type type)
// Offset: 0x204E008
static bool ContainsGenericParameters(::System::Type* type);
// static public System.Boolean IsInterface(System.Type type)
// Offset: 0x2041384
static bool IsInterface(::System::Type* type);
// static public System.Boolean IsGenericType(System.Type type)
// Offset: 0x204B21C
static bool IsGenericType(::System::Type* type);
// static public System.Boolean IsGenericTypeDefinition(System.Type type)
// Offset: 0x204139C
static bool IsGenericTypeDefinition(::System::Type* type);
// static public System.Type BaseType(System.Type type)
// Offset: 0x2039AFC
static ::System::Type* BaseType(::System::Type* type);
// static public System.Boolean IsEnum(System.Type type)
// Offset: 0x2040024
static bool IsEnum(::System::Type* type);
// static public System.Boolean IsClass(System.Type type)
// Offset: 0x204B714
static bool IsClass(::System::Type* type);
// static public System.Boolean IsSealed(System.Type type)
// Offset: 0x204E028
static bool IsSealed(::System::Type* type);
// static public System.Boolean IsAbstract(System.Type type)
// Offset: 0x20413BC
static bool IsAbstract(::System::Type* type);
// static public System.Boolean IsValueType(System.Type type)
// Offset: 0x204B074
static bool IsValueType(::System::Type* type);
// static public System.Boolean AssignableToTypeName(System.Type type, System.String fullTypeName, out System.Type match)
// Offset: 0x204E040
static bool AssignableToTypeName(::System::Type* type, ::StringW fullTypeName, ByRef<::System::Type*> match);
// static public System.Boolean AssignableToTypeName(System.Type type, System.String fullTypeName)
// Offset: 0x204E160
static bool AssignableToTypeName(::System::Type* type, ::StringW fullTypeName);
// static public System.Boolean ImplementInterface(System.Type type, System.Type interfaceType)
// Offset: 0x204E188
static bool ImplementInterface(::System::Type* type, ::System::Type* interfaceType);
}; // Newtonsoft.Json.Utilities.TypeExtensions
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::MemberType
// Il2CppName: MemberType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MemberTypes (*)(::System::Reflection::MemberInfo*)>(&Newtonsoft::Json::Utilities::TypeExtensions::MemberType)> {
static const MethodInfo* get() {
static auto* memberInfo = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "MemberType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{memberInfo});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::ContainsGenericParameters
// Il2CppName: ContainsGenericParameters
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::ContainsGenericParameters)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "ContainsGenericParameters", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsInterface
// Il2CppName: IsInterface
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsInterface)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsInterface", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsGenericType
// Il2CppName: IsGenericType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsGenericType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsGenericType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsGenericTypeDefinition
// Il2CppName: IsGenericTypeDefinition
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsGenericTypeDefinition)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsGenericTypeDefinition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::BaseType
// Il2CppName: BaseType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::BaseType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "BaseType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsEnum
// Il2CppName: IsEnum
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsEnum)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsEnum", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsClass
// Il2CppName: IsClass
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsClass)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsClass", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsSealed
// Il2CppName: IsSealed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsSealed)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsSealed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsAbstract
// Il2CppName: IsAbstract
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsAbstract)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsAbstract", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsValueType
// Il2CppName: IsValueType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsValueType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsValueType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName
// Il2CppName: AssignableToTypeName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::StringW, ByRef<::System::Type*>)>(&Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* fullTypeName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* match = &::il2cpp_utils::GetClassFromName("System", "Type")->this_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "AssignableToTypeName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, fullTypeName, match});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName
// Il2CppName: AssignableToTypeName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::StringW)>(&Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* fullTypeName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "AssignableToTypeName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, fullTypeName});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::ImplementInterface
// Il2CppName: ImplementInterface
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::ImplementInterface)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* interfaceType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "ImplementInterface", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, interfaceType});
}
};
| 60.12844 | 207 | 0.741303 | RedBrumbler |
1e4c8b0adf1d13acd4e8d6359ce133fdf65a2e0f | 5,127 | cc | C++ | src/internal/nb_http_request_factory.cc | rk0jima/baas-sdk-embedded | 2481a43ab114008e37966964d2032970cda2a1bf | [
"Apache-2.0"
] | null | null | null | src/internal/nb_http_request_factory.cc | rk0jima/baas-sdk-embedded | 2481a43ab114008e37966964d2032970cda2a1bf | [
"Apache-2.0"
] | null | null | null | src/internal/nb_http_request_factory.cc | rk0jima/baas-sdk-embedded | 2481a43ab114008e37966964d2032970cda2a1bf | [
"Apache-2.0"
] | 1 | 2022-01-31T23:30:04.000Z | 2022-01-31T23:30:04.000Z | /*
* Copyright (C) 2017 NEC Corporation
*/
#include "necbaas/internal/nb_http_request_factory.h"
#include <curlpp/cURLpp.hpp>
#include "necbaas/internal/nb_constants.h"
#include "necbaas/internal/nb_logger.h"
namespace necbaas {
using std::string;
using std::list;
using std::multimap;
NbHttpRequestFactory::NbHttpRequestFactory(const string &end_point_url, const string &tenant_id, const string &app_id,
const string &app_key, const string &session_token, const string &proxy)
: end_point_url_(end_point_url),
tenant_id_(tenant_id),
app_id_(app_id),
app_key_(app_key),
session_token_(session_token),
proxy_(proxy) {
CheckParameter();
}
NbHttpRequestFactory::~NbHttpRequestFactory() {}
NbHttpRequestFactory &NbHttpRequestFactory::Get(const string &api_uri) {
request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_GET;
path_ = api_uri;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::Post(const string &api_uri) {
request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_POST;
path_ = api_uri;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::Put(const string &api_uri) {
request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_PUT;
path_ = api_uri;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::Delete(const string &api_uri) {
request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_DELETE;
path_ = api_uri;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::AppendPath(const string &path) {
path_.append(path);
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::Params(const multimap<string, string> ¶ms) {
request_params_ = params;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::AppendParam(const string &key, const string &value) {
if (!key.empty() && !value.empty()) {
request_params_.insert(std::make_pair(key, value));
}
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::Headers(const multimap<string, string> &headers) {
headers_ = headers;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::AppendHeader(const string &key, const string &value) {
if (!key.empty() && !value.empty()) {
headers_.insert(std::make_pair(key, value));
}
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::Body(const string &body) {
body_ = body;
return *this;
}
NbHttpRequestFactory &NbHttpRequestFactory::SessionNone() {
session_none_ = true;
return *this;
}
NbHttpRequest NbHttpRequestFactory::Build() {
auto url_params = CreateRequestParams();
// end_point_url_の最後の'/'
if (*end_point_url_.rbegin() != '/') {
end_point_url_ += "/";
}
auto url = end_point_url_ + kPathApiVersion + "/" + tenant_id_ + path_ + url_params;
// Set common headers
headers_.insert(std::make_pair(kHeaderAppId, app_id_));
headers_.insert(std::make_pair(kHeaderAppKey, app_key_));
// User-Agent
if (headers_.count(kHeaderUserAgent) == 0) {
headers_.insert(std::make_pair(kHeaderUserAgent, kHeaderUserAgentDefault));
}
if (!session_none_ && !session_token_.empty()) {
headers_.insert(std::make_pair(kHeaderSessionToken, session_token_));
}
auto header_list = list<string>();
for (auto itor : headers_) {
if (!itor.first.empty() && !itor.second.empty()) {
auto line = itor.first + ": " + itor.second;
header_list.push_back(line);
}
}
return NbHttpRequest(url, request_method_, header_list, body_, proxy_);
}
NbResultCode NbHttpRequestFactory::GetError() const { return error_; }
bool NbHttpRequestFactory::IsError() const { return (error_ != NbResultCode::NB_OK); }
void NbHttpRequestFactory::CheckParameter() {
if (end_point_url_.empty()) {
NBLOG(ERROR) << "End point URL is empty.";
error_ = NbResultCode::NB_ERROR_ENDPOINT_URL;
} else if (tenant_id_.empty()) {
NBLOG(ERROR) << "Tenant ID is empty.";
error_ = NbResultCode::NB_ERROR_TENANT_ID;
} else if (app_id_.empty()) {
NBLOG(ERROR) << "App ID is empty.";
error_ = NbResultCode::NB_ERROR_APP_ID;
} else if (app_key_.empty()) {
NBLOG(ERROR) << "App Key is empty.";
error_ = NbResultCode::NB_ERROR_APP_KEY;
}
}
string NbHttpRequestFactory::CreateRequestParams() const {
string converted_params;
if (request_params_.empty()) {
return converted_params;
}
converted_params = "?";
string escaped_first;
string escaped_second;
for (auto itor = request_params_.begin(); itor != request_params_.end(); ++itor) {
if (!itor->first.empty() && !itor->second.empty()) {
escaped_first = curlpp::escape(itor->first);
escaped_second = curlpp::escape(itor->second);
converted_params += escaped_first + "=" + escaped_second + "&";
}
}
// remove an excess '&' or '?'
converted_params.erase(--converted_params.end());
return converted_params;
}
} // namespace necbaas
| 30.885542 | 118 | 0.679735 | rk0jima |
1e4d4524d0bdc15e17224e494ae463cd24fae58f | 4,046 | cpp | C++ | edbee-lib/edbee/util/simpleprofiler.cpp | UniSwarm/edbee-lib | b1f0b440d32f5a770877b11c6b24944af1131b91 | [
"BSD-2-Clause"
] | 445 | 2015-01-04T16:30:56.000Z | 2022-03-30T02:27:05.000Z | edbee-lib/edbee/util/simpleprofiler.cpp | UniSwarm/edbee-lib | b1f0b440d32f5a770877b11c6b24944af1131b91 | [
"BSD-2-Clause"
] | 305 | 2015-01-04T09:20:03.000Z | 2020-10-01T08:45:45.000Z | edbee-lib/edbee/util/simpleprofiler.cpp | UniSwarm/edbee-lib | b1f0b440d32f5a770877b11c6b24944af1131b91 | [
"BSD-2-Clause"
] | 49 | 2015-02-14T01:43:38.000Z | 2022-02-15T17:03:55.000Z | /**
* Copyright 2011-2012 - Reliable Bits Software by Blommers IT. All Rights Reserved.
* Author Rick Blommers
*/
#include "simpleprofiler.h"
#include <QDateTime>
#include "edbee/debug.h"
namespace edbee {
/// This method returns the profile instance
SimpleProfiler *SimpleProfiler::instance()
{
static SimpleProfiler profiler;
return &profiler;
}
/// the constructor for a profile stat issue
SimpleProfiler::ProfilerItem::ProfilerItem(const char *filename, int line, const char *function, const char* name )
: filename_(filename)
, line_(line)
, function_(function)
, name_(name)
, callCount_(0)
, duration_(0)
, childDuration_(0)
{
}
SimpleProfiler::SimpleProfiler()
{
}
/// destroy the stuff
SimpleProfiler::~SimpleProfiler()
{
qDeleteAll(statsMap_);
statsMap_.clear();
stack_.clear();
}
/// begin the profiling
void SimpleProfiler::begin(const char *file, int line, const char *function, const char* name )
{
// build the key
QString key = QStringLiteral("%1:%2").arg(file).arg(line);
// fetch or create the item
ProfilerItem *item = statsMap_.value(key,0);
if( !item ) {
item = new ProfilerItem(file,line,function,name);
statsMap_.insert(key,item);
}
ProfileStackItem stackItem = { item, QDateTime::currentMSecsSinceEpoch() };
stack_.push(stackItem);
}
/// ends profiling
void SimpleProfiler::end()
{
Q_ASSERT( stack_.size() > 0 );
ProfileStackItem stackItem = stack_.pop();
stackItem.item->incCallCount();
int duration = QDateTime::currentMSecsSinceEpoch() - stackItem.startTime;
stackItem.item->addDuration( duration );
if( !stack_.isEmpty() ) {
stack_.top().item->addChildDuration( duration );
}
}
static bool sortByDuration( const SimpleProfiler::ProfilerItem* a, const SimpleProfiler::ProfilerItem* b )
{
return b->durationWithoutChilds() < a->durationWithoutChilds();
}
/// This method dumps the results to the output
void SimpleProfiler::dumpResults()
{
QList<ProfilerItem*> items = statsMap_.values();
if( items.length() > 0 ) {
std::sort(items.begin(), items.end(), sortByDuration);
qlog_info() << "";
qlog_info() << "Profiler Results";
qlog_info() << "================";
qint64 totalDuration = 0;
int totalCallCount = 0;
int totalDurationWitoutChilds = 0;
foreach( ProfilerItem* item, items ) {
totalDuration += item->duration();
totalCallCount += item->callCount();
totalDurationWitoutChilds += item->durationWithoutChilds();
}
foreach( ProfilerItem* item, items ) {
double durationPercentage = totalDuration > 0 ? 100.0 * item->duration() / totalDuration : 100;
double callCountPercentage = totalCallCount > 0 ? 100.0 * item->callCount() / totalCallCount : 100;
double durationWithoutChildsPercenage = totalDurationWitoutChilds > 0 ? 100.0 * item->durationWithoutChilds() / totalDurationWitoutChilds : 100;
QString line = QStringLiteral("%1x(%2%) %3ms(%4%) %5ms(%6%) | %7:%8 %9")
.arg(item->callCount(),8).arg( callCountPercentage, 6, 'f', 2 )
.arg(item->duration(),6).arg( durationPercentage, 6, 'f', 2 )
.arg(item->durationWithoutChilds(), 6 ).arg( durationWithoutChildsPercenage, 6, 'f', 2 )
.arg(item->filename()).arg(item->line()).arg(item->name())
;
qlog_info() << line;
}
qlog_info() << "";
qlog_info() << "Total Duration: " << totalDuration << "ms";
qlog_info() << "Total Calls : " << totalCallCount;
qlog_info() << "Total Items : " << items.size() << "ms";
if( !stack_.isEmpty() ) {
qlog() << "** WARNING: The stack isn't empty!! ** ";
foreach( ProfileStackItem stackItem, stack_) {
qlog() << " * " << stackItem.item->function() << ":" << stackItem.item->line();
}
}
}
}
} // edbee
| 30.19403 | 156 | 0.615175 | UniSwarm |
1e4f66ab7dbfcb0454de91c05bcef29e7aa9b867 | 882 | cpp | C++ | implementations/ugene/src/libs_3rdparty/QSpec/testApp/mainwindow.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/libs_3rdparty/QSpec/testApp/mainwindow.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/libs_3rdparty/QSpec/testApp/mainwindow.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | #include "mainwindow.h"
#include "EventRecorderWidget.h"
#include "EventFilter.h"
#include <QEvent>
#include <QKeyEvent>
#include <QLineEdit>
#include <QGridLayout>
MainWindow* MainWindow::instance;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QGridLayout* l = new QGridLayout(this);
setLayout(l);
testLine = new QLineEdit(this);
testLine->setObjectName("testLine");
l->addWidget(testLine, 0, 0, 5, 5);
eventFilter = new EventFilter(this);
eventRecorderWidget = new EventRecorderWidget(this);
eventRecorderWidget->setObjectName("eventRecorder");
eventRecorderWidget->installEventFilter(eventFilter);
l->addWidget(eventRecorderWidget, 1, 0, 5, 5);
}
MainWindow::~MainWindow()
{
}
MainWindow* MainWindow::getInstance(){
if(instance == NULL){
instance = new MainWindow();
}
return instance;
}
| 21.512195 | 57 | 0.702948 | r-barnes |
1e4f8d152b59747f02b092029111b6e15d0f8bfa | 309 | cpp | C++ | sort/compare_sorts/selection_sort.cpp | chhanganivarun/DS | 13b9ed64a2bfd7fb443d99153568bf6261ae31c6 | [
"MIT"
] | 1 | 2018-01-26T07:49:05.000Z | 2018-01-26T07:49:05.000Z | sort/compare_sorts/selection_sort.cpp | chhanganivarun/DS | 13b9ed64a2bfd7fb443d99153568bf6261ae31c6 | [
"MIT"
] | null | null | null | sort/compare_sorts/selection_sort.cpp | chhanganivarun/DS | 13b9ed64a2bfd7fb443d99153568bf6261ae31c6 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,*a;
n=100000;
a=new int [n];
for(int i=0;i<n;i++)
a[i]=rand();
for(int i=0;i<n-1;i++)
{
int min=i;
for(int j=i+1;j<n;j++)
{
if(a[min]>a[j])
{
swap(min,j);
}
}
swap(a[min],a[i]);
}
cout<<"Sorted!\n";
return 0;
}
| 12.36 | 24 | 0.491909 | chhanganivarun |
1e50a1baa34895844921e60463f38fec98fc7304 | 1,569 | cc | C++ | palindrome-number.cc | yevka/leetcode | abc3150d25069545ed155eed2751d75159f55342 | [
"MIT"
] | null | null | null | palindrome-number.cc | yevka/leetcode | abc3150d25069545ed155eed2751d75159f55342 | [
"MIT"
] | null | null | null | palindrome-number.cc | yevka/leetcode | abc3150d25069545ed155eed2751d75159f55342 | [
"MIT"
] | null | null | null | // 9. Palindrome Number
// https://leetcode.com/problems/palindrome-number/
#include <gtest/gtest.h>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
} else if (x == 0) {
return true;
} else if (!(x % 10)) {
return false;
}
string str = to_string(x);
reverse(str.begin(), str.end());
int revert_x = atoi(str.c_str());
return x == revert_x;
}
};
class Solution2 {
public:
bool isPalindrome(int x) {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int y = 0;
while(x > y){
y = y * 10 + x % 10;
if (y == 0) {
return false;
}
x /= 10;
}
return (x == y || x == y / 10);
}
};
TEST(Solution, isPalindrome1) {
Solution solution;
ASSERT_TRUE(solution.isPalindrome(121));
}
TEST(Solution, isPalindrome2) {
Solution solution;
ASSERT_FALSE(solution.isPalindrome(-121));
}
TEST(Solution, isPalindrome3) {
Solution solution;
ASSERT_FALSE(solution.isPalindrome(123));
}
TEST(Solution, isPalindrome4) {
Solution solution;
ASSERT_FALSE(solution.isPalindrome(10));
}
TEST(Solution2, isPalindrome) {
Solution2 solution;
ASSERT_TRUE(solution.isPalindrome(121));
ASSERT_FALSE(solution.isPalindrome(-121));
ASSERT_FALSE(solution.isPalindrome(123));
ASSERT_FALSE(solution.isPalindrome(10));
}
| 21.493151 | 51 | 0.581899 | yevka |
1e5118ae1ac780f29b9251398b33faa0c77ea83b | 2,061 | cpp | C++ | src/samples/ExplodingObjects/Mesh.cpp | int-Frank/DgLib-deprecated | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | [
"MIT"
] | null | null | null | src/samples/ExplodingObjects/Mesh.cpp | int-Frank/DgLib-deprecated | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | [
"MIT"
] | null | null | null | src/samples/ExplodingObjects/Mesh.cpp | int-Frank/DgLib-deprecated | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | [
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include "Mesh.h"
#include "DgR3AABB.h"
typedef Dg::R3::AABB<float> AABB;
static void NormalizeData(std::vector<vec4> & a_points)
{
AABB aabb(a_points.begin(), a_points.end());
vec4 offset(-aabb.GetCenter().x(),
-aabb.GetCenter().y(),
-aabb.GetCenter().z(),
0.0f);
for (auto & p : a_points)
{
p += offset;
}
vec4 diag(aabb.Diagonal());
float max_hl = (diag[0] > diag[1]) ? diag[0] : diag[1];
if (diag[2] > max_hl) max_hl = diag[2];
float scaleFactor = 1.0f / max_hl;
for (auto & p : a_points)
{
p.x() *= scaleFactor;
p.y() *= scaleFactor;
p.z() *= scaleFactor;
}
}
bool Mesh::LoadOBJ(std::string const & a_fileName)
{
Clear();
std::ifstream ifs;
ifs.open(a_fileName);
if (!ifs.good())
{
std::cout << "Can't open data file: " << a_fileName;
return false;
}
struct Face
{
unsigned short v[3];
unsigned short vn[3];
};
std::string firstWord;
std::vector<vec4> v_list;
std::vector<vec4> vn_list;
std::vector<Face> f_list;
while (ifs >> firstWord)
{
if (firstWord == "v")
{
float vx = 0.0f;
float vy = 0.0f;
float vz = 0.0f;
ifs >> vx >> vy >> vz;
v_list.push_back(vec4(vx, vy, vz, 1.f));
}
else if (firstWord == "vn")
{
float vx = 0.0f;
float vy = 0.0f;
float vz = 0.0f;
ifs >> vx >> vy >> vz;
vn_list.push_back(vec4(vx, vy, vz, 0.f));
}
else if (firstWord == "f")
{
Face f;
char s = 0;
for (int i = 0; i < 3; ++i)
{
ifs >> f.v[i] >> s >> s >> f.vn[i];
--f.v[i];
--f.vn[i];
}
f_list.push_back(f);
}
ifs.ignore(2048, '\n');
}
NormalizeData(v_list);
for (auto const & face : f_list)
{
Facet f;
for (int i = 0; i < 3; ++i)
{
f.points[i] = v_list[face.v[i]];
f.normals[i] = vn_list[face.vn[i]];
}
m_facets.push_back(f);
}
return true;
}
void Mesh::Clear()
{
m_facets.clear();
} | 18.401786 | 57 | 0.512373 | int-Frank |
1e5167d00f1aa1f61b7c8a99933444f6579025e7 | 665 | cpp | C++ | Sorting-Searching/quicksort/testDriver.cpp | Alex0Blackwell/c-projects | eb5a4507603b8510abc18223fd99c454e8effc38 | [
"MIT"
] | 1 | 2020-12-07T03:00:52.000Z | 2020-12-07T03:00:52.000Z | Sorting-Searching/quicksort/testDriver.cpp | Alex0Blackwell/c-projects | eb5a4507603b8510abc18223fd99c454e8effc38 | [
"MIT"
] | 1 | 2020-10-02T06:27:48.000Z | 2020-10-02T06:27:48.000Z | Sorting-Searching/quicksort/testDriver.cpp | Alex0Blackwell/c-projects | eb5a4507603b8510abc18223fd99c454e8effc38 | [
"MIT"
] | 2 | 2020-10-02T06:16:11.000Z | 2020-10-27T15:05:25.000Z | #include <iostream>
#include <vector>
#include <assert.h>
#include "quicksort.hpp"
using namespace std;
int main(void) {
vector<int> arr1;
for(int i = 0; i < 100; ++i)
arr1.push_back(rand() % 100);
cout << "Array before:" << endl;
for(auto el : arr1)
cout << el << ", ";
cout << endl;
quicksort<int>(arr1);
cout << "Testing quicksort" << endl;
for(size_t i = 1; i < (size_t)arr1.size(); ++i)
assert(arr1[i-1] <= arr1[i]);
cout << "Array is sorted!" << endl;
cout << "Array after:" << endl;
for(auto el : arr1)
cout << el << ", ";
cout << endl;
cout << "Nice! Exited with status code 0." << endl;
return 0;
}
| 17.051282 | 53 | 0.557895 | Alex0Blackwell |
1e5169b8db08d00bca8008714c3541a9527bed92 | 1,647 | cc | C++ | aleyen.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | aleyen.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | aleyen.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <algorithm>
#include "numutils.hh"
#include "imgutils.hh"
#include "strutils.hh"
#include "partrait.hh"
using namespace std;
using namespace makemore;
double pld(double x0, double y0, double x1, double y1, double x2, double y2) {
double d = 0;
d = -((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1);
d /= sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
return d;
}
int main(int argc, char **argv) {
std::string srcdir = argv[1];
std::string dstdir = argv[2];
std::vector<std::string> srcimages;
struct dirent *de;
DIR *dp = opendir(srcdir.c_str());
assert(dp);
while ((de = readdir(dp))) {
if (*de->d_name == '.')
continue;
srcimages.push_back(de->d_name);
}
closedir(dp);
std::sort(srcimages.begin(), srcimages.end());
assert(srcimages.size());
for (auto srcfn : srcimages) {
Partrait par;
par.load(srcdir + "/" + srcfn);
if (!par.has_pose())
continue;
//assert(par.alpha);
Pose pose = par.get_pose();
par.set_tag("angle", pose.angle);
par.set_tag("stretch", pose.stretch);
par.set_tag("skew", pose.skew);
Partrait newpar(256, 256);
newpar.fill_gray();
newpar.set_pose(Pose::STANDARD);
//newpar.alpha = new uint8_t[256 * 256];
//assert(newpar.alpha);
par.warp(&newpar);
//memset(newpar.alpha, 0xFF, 256 * 256);
newpar.save(dstdir + "/" + srcfn);
fprintf(stderr, "aleyened %s/%s -> %s/%s\n", srcdir.c_str(), srcfn.c_str(), dstdir.c_str(), srcfn.c_str());
}
return 0;
}
| 22.561644 | 111 | 0.612022 | jdb19937 |
1e5290d32b146fb3fc13a9d7c49dc08d17013964 | 9,624 | cpp | C++ | rai/secure/http.cpp | gokoo/Raicoin | 494be83a1e29106d268f71e613fac1e4033a82f2 | [
"MIT"
] | 94 | 2019-09-25T05:57:44.000Z | 2021-12-30T09:08:06.000Z | rai/secure/http.cpp | lannuary12/Raicoin | b5d10726f79e233b46e14e6ec064fa20ece1bb15 | [
"MIT"
] | 4 | 2020-05-06T10:10:14.000Z | 2021-12-26T09:35:16.000Z | rai/secure/http.cpp | lannuary12/Raicoin | b5d10726f79e233b46e14e6ec064fa20ece1bb15 | [
"MIT"
] | 13 | 2019-09-25T05:57:52.000Z | 2022-02-24T02:09:03.000Z | #include <rai/secure/http.hpp>
#include <boost/property_tree/json_parser.hpp>
rai::HttpClient::HttpClient(boost::asio::io_service& service)
: service_(service),
used_(false),
resolver_(service),
ctx_(boost::asio::ssl::context::tlsv12_client)
{
}
std::shared_ptr<rai::HttpClient> rai::HttpClient::Shared()
{
return shared_from_this();
}
bool rai::HttpClient::CheckUpdateUsed()
{
std::lock_guard<std::mutex> lock(mutex_);
if (used_)
{
return true;
}
used_ = true;
return false;
}
rai::ErrorCode rai::HttpClient::Get(const rai::Url& url,
const rai::HttpCallback& callback)
{
IF_ERROR_RETURN(CheckUpdateUsed(), rai::ErrorCode::HTTP_CLIENT_USED);
url_ = url;
callback_ = callback;
IF_ERROR_RETURN(CheckUrl_(), rai::ErrorCode::INVALID_URL);
if (url_.protocol_ == "https")
{
IF_ERROR_RETURN(LoadCert_(), rai::ErrorCode::LOAD_CERT);
}
PrepareGetReq_();
Resolve();
return rai::ErrorCode::SUCCESS;
}
rai::ErrorCode rai::HttpClient::Post(const rai::Url& url,
const rai::Ptree& ptree,
const rai::HttpCallback& callback)
{
IF_ERROR_RETURN(CheckUpdateUsed(), rai::ErrorCode::HTTP_CLIENT_USED);
url_ = url;
callback_ = callback;
IF_ERROR_RETURN(CheckUrl_(), rai::ErrorCode::INVALID_URL);
if (url_.protocol_ == "https")
{
IF_ERROR_RETURN(LoadCert_(), rai::ErrorCode::LOAD_CERT);
}
PreparePostReq_(ptree);
Resolve();
return rai::ErrorCode::SUCCESS;
}
void rai::HttpClient::Resolve()
{
std::shared_ptr<rai::HttpClient> client(Shared());
boost::asio::ip::tcp::resolver::query query(url_.host_,
std::to_string(url_.port_));
resolver_.async_resolve(
query, [client](const boost::system::error_code& ec,
boost::asio::ip::tcp::resolver::iterator results) {
client->OnResolve(ec, results);
});
}
void rai::HttpClient::OnResolve(
const boost::system::error_code& ec,
boost::asio::ip::tcp::resolver::iterator results)
{
if (ec)
{
// log
std::cout << "Failed to resolve: " << ec.message() << std::endl;
Callback_(rai::ErrorCode::DNS_RESOLVE);
return;
}
std::shared_ptr<rai::HttpClient> client(Shared());
if (url_.protocol_ == "http")
{
socket_ = std::make_shared<boost::asio::ip::tcp::socket>(service_);
boost::asio::async_connect(
*socket_, results,
[client](const boost::system::error_code& ec,
boost::asio::ip::tcp::resolver::iterator iterator) {
client->OnConnect(ec);
});
}
else
{
ssl_stream_ = std::make_shared<
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(service_,
ctx_);
boost::asio::async_connect(
ssl_stream_->next_layer(), results,
[client](const boost::system::error_code& ec,
boost::asio::ip::tcp::resolver::iterator iterator) {
client->OnConnect(ec);
});
}
}
void rai::HttpClient::OnConnect(const boost::system::error_code& ec)
{
if (ec)
{
// log
std::cout << "Failed to connect: " << ec.message() << std::endl;
Callback_(rai::ErrorCode::TCP_CONNECT);
return;
}
if (url_.protocol_ == "https")
{
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(ssl_stream_->native_handle(),
url_.host_.c_str()))
{
// log
std::cout << "Failed to set SNI: " << url_.host_ << std::endl;
Callback_(rai::ErrorCode::SET_SSL_SNI);
return;
}
ssl_stream_->set_verify_mode(
boost::asio::ssl::verify_peer
| boost::asio::ssl::verify_fail_if_no_peer_cert);
ssl_stream_->set_verify_callback(
boost::asio::ssl::rfc2818_verification(url_.host_));
std::shared_ptr<rai::HttpClient> client(Shared());
ssl_stream_->async_handshake(
boost::asio::ssl::stream_base::client,
[client](const boost::system::error_code& ec) {
client->OnSslHandshake(ec);
});
}
else
{
Write();
}
}
void rai::HttpClient::OnSslHandshake(const boost::system::error_code& ec)
{
if (ec)
{
// log
std::cout << "Ssl handshake failed: " << ec.message() << std::endl;
Callback_(rai::ErrorCode::SSL_HANDSHAKE);
return;
}
Write();
}
void rai::HttpClient::Onwrite(const boost::system::error_code& ec, size_t size)
{
if (ec || size == 0)
{
// log
std::cout << "Failed to write stream: " << ec.message() << std::endl;
Callback_(rai::ErrorCode::WRITE_STREAM);
return;
}
Read();
}
void rai::HttpClient::OnRead(const boost::system::error_code& ec, size_t size)
{
if (ec)
{
// log
std::cout << "Failed to read stream: " << ec.message() << std::endl;
Callback_(rai::ErrorCode::STREAM);
return;
}
if (res_.result() != boost::beast::http::status::ok)
{
if (post_req_)
{
// log
std::cout << "Http post failed, status: "
<< static_cast<uint32_t>(res_.result()) << std::endl;
Callback_(rai::ErrorCode::HTTP_POST);
}
else
{
// log
std::cout << "Http get failed, status: "
<< static_cast<uint32_t>(res_.result()) << std::endl;
Callback_(rai::ErrorCode::HTTP_GET);
}
return;
}
Callback_(rai::ErrorCode::SUCCESS, res_.body());
if (url_.protocol_ == "https")
{
std::shared_ptr<rai::HttpClient> client(Shared());
ssl_stream_->async_shutdown(
[client](const boost::system::error_code&) {});
}
else
{
boost::system::error_code ignore;
socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
}
}
void rai::HttpClient::Write()
{
std::shared_ptr<rai::HttpClient> client(Shared());
if (url_.protocol_ == "https")
{
if (post_req_)
{
boost::beast::http::async_write(
*ssl_stream_, *post_req_,
[client](const boost::system::error_code& ec, size_t size) {
client->Onwrite(ec, size);
});
}
else
{
boost::beast::http::async_write(
*ssl_stream_, *get_req_,
[client](const boost::system::error_code& ec, size_t size) {
client->Onwrite(ec, size);
});
}
}
else
{
if (post_req_)
{
boost::beast::http::async_write(
*socket_, *post_req_,
[client](const boost::system::error_code& ec, size_t size) {
client->Onwrite(ec, size);
});
}
else
{
boost::beast::http::async_write(
*socket_, *get_req_,
[client](const boost::system::error_code& ec, size_t size) {
client->Onwrite(ec, size);
});
}
}
}
void rai::HttpClient::Read()
{
std::shared_ptr<rai::HttpClient> client(Shared());
if (url_.protocol_ == "https")
{
boost::beast::http::async_read(
*ssl_stream_, buffer_, res_,
[client](const boost::system::error_code& ec, size_t size) {
client->OnRead(ec, size);
});
}
else
{
boost::beast::http::async_read(
*socket_, buffer_, res_,
[client](const boost::system::error_code& ec, size_t size) {
client->OnRead(ec, size);
});
}
}
bool rai::HttpClient::CheckUrl_() const
{
if (!url_ || (url_.protocol_ != "http" && url_.protocol_ != "https"))
{
return true;
}
return false;
}
void rai::HttpClient::Callback_(rai::ErrorCode error_code,
const std::string& response)
{
if (callback_)
{
callback_(error_code, response);
}
}
bool rai::HttpClient::LoadCert_()
{
try
{
ctx_.load_verify_file("cacert.pem");
return false;
}
catch(...)
{
return true;
}
}
void rai::HttpClient::PrepareGetReq_()
{
get_req_ = std::make_shared<
boost::beast::http::request<boost::beast::http::empty_body>>();
get_req_->version(11);
get_req_->method(boost::beast::http::verb::get);
get_req_->target(url_.path_);
get_req_->insert(boost::beast::http::field::host, url_.host_);
}
void rai::HttpClient::PreparePostReq_(const rai::Ptree& ptree)
{
std::stringstream stream;
boost::property_tree::write_json(stream, ptree);
stream.flush();
post_req_ = std::make_shared<
boost::beast::http::request<boost::beast::http::string_body>>();
post_req_->method(boost::beast::http::verb::post);
post_req_->target(url_.path_);
post_req_->version(11);
post_req_->insert(boost::beast::http::field::host, url_.host_);
post_req_->insert(boost::beast::http::field::content_type,
"application/json");
post_req_->body() = stream.str();
post_req_->prepare_payload();
}
| 27.976744 | 79 | 0.543537 | gokoo |
1e550c2919b79c1008da21b51f158c6eaf004951 | 1,354 | hpp | C++ | sdk/core/azure-core/src/private/environment_log_level_listener.hpp | mikeharder/azure-sdk-for-cpp | da1451586a6ef50bac4e3dead9eba2c094c2d91a | [
"MIT"
] | null | null | null | sdk/core/azure-core/src/private/environment_log_level_listener.hpp | mikeharder/azure-sdk-for-cpp | da1451586a6ef50bac4e3dead9eba2c094c2d91a | [
"MIT"
] | null | null | null | sdk/core/azure-core/src/private/environment_log_level_listener.hpp | mikeharder/azure-sdk-for-cpp | da1451586a6ef50bac4e3dead9eba2c094c2d91a | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#pragma once
#include "azure/core/diagnostics/logger.hpp"
#if defined(AZ_PLATFORM_WINDOWS)
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
// This use of windows.h within the header is OK because the header is private and in source only.
#include <windows.h>
#endif
namespace Azure { namespace Core { namespace Diagnostics { namespace _detail {
class EnvironmentLogLevelListener final {
EnvironmentLogLevelListener() = delete;
~EnvironmentLogLevelListener() = delete;
public:
static Logger::Level GetLogLevel(Logger::Level defaultValue);
static std::function<void(Logger::Level level, std::string const& message)> GetLogListener();
};
#if (defined(WINAPI_PARTITION_DESKTOP) && !WINAPI_PARTITION_DESKTOP) // See azure/core/platform.hpp
// for explanation.
inline Logger::Level EnvironmentLogLevelListener::GetLogLevel(Logger::Level defaultValue)
{
return defaultValue;
}
inline std::function<void(Logger::Level level, std::string const& message)>
EnvironmentLogLevelListener::GetLogListener()
{
return nullptr;
}
#endif
}}}} // namespace Azure::Core::Diagnostics::_detail
| 30.088889 | 99 | 0.718612 | mikeharder |
1e55e496fcd2dcde8efd416f5637d07772fd25f0 | 975 | cpp | C++ | Kattis/leftandright.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | 3 | 2021-02-19T17:01:11.000Z | 2021-03-11T16:50:19.000Z | Kattis/leftandright.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | Kattis/leftandright.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | // greedy
// https://open.kattis.com/problems/leftandright
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define For(i, n) for (int i = 0; i < n; ++i)
#define Forcase int __t = 0; cin >> __t; while (__t--)
#define pb push_back
#define ll long long
#define ull unsigned long long
#define ar array
using namespace std;
using namespace __gnu_pbds;
template<class Type> using indexed_set=tree<Type,null_type,less<Type>,rb_tree_tag,tree_order_statistics_node_update>;
const int MOD = 1e9 + 7;
const int INF = 2147483647;
const ll IINF = 1e18;
const double eps = 1e-12;
int n;
string s;
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> s;
int prvR = -1, R = 0;
while (R < n) {
while (R < n && s[R] == 'L') R++;
cout << R + 1 << '\n';
For (i, R - prvR - 1) {
cout << R - i << '\n';
}
prvR = R;
R++;
}
return 0;
} | 22.674419 | 117 | 0.594872 | YourName0729 |
1e59fb4a980ca0cfe3893234273984ae20f53181 | 7,791 | cpp | C++ | gi/scfg/abc/scfg.cpp | agesmundo/FasterCubePruning | f80150140b5273fd1eb0dfb34bdd789c4cbd35e6 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 1 | 2019-06-03T00:44:01.000Z | 2019-06-03T00:44:01.000Z | gi/scfg/abc/scfg.cpp | jhclark/cdec | 237ddc67ffa61da310e19710f902d4771dc323c2 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | null | null | null | gi/scfg/abc/scfg.cpp | jhclark/cdec | 237ddc67ffa61da310e19710f902d4771dc323c2 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 1 | 2021-02-19T12:44:54.000Z | 2021-02-19T12:44:54.000Z | #include <iostream>
#include <fstream>
#include <boost/shared_ptr.hpp>
#include <boost/pointer_cast.hpp>
#include "lattice.h"
#include "tdict.h"
#include "agrammar.h"
#include "bottom_up_parser.h"
#include "hg.h"
#include "hg_intersect.h"
#include "../utils/ParamsArray.h"
using namespace std;
vector<string> src_corpus;
vector<string> tgt_corpus;
bool openParallelCorpora(string & input_filename){
ifstream input_file;
input_file.open(input_filename.c_str());
if (!input_file) {
cerr << "Cannot open input file " << input_filename << ". Exiting..." << endl;
return false;
}
int line =0;
while (!input_file.eof()) {
// get a line of source language data
// cerr<<"new line "<<ctr<<endl;
string str;
getline(input_file, str);
line++;
if (str.length()==0){
cerr<<" sentence number "<<line<<" is empty, skip the sentence\n";
continue;
}
string delimiters("|||");
vector<string> v = tokenize(str, delimiters);
if ( (v.size() != 2) and (v.size() != 3) ) {
cerr<<str<<endl;
cerr<<" source or target sentence is not found in sentence number "<<line<<" , skip the sentence\n";
continue;
}
src_corpus.push_back(v[0]);
tgt_corpus.push_back(v[1]);
}
return true;
}
typedef aTextGrammar aGrammar;
aGrammar * load_grammar(string & grammar_filename){
cerr<<"start_load_grammar "<<grammar_filename<<endl;
aGrammar * test = new aGrammar(grammar_filename);
return test;
}
Lattice convertSentenceToLattice(const string & str){
std::vector<WordID> vID;
TD::ConvertSentence(str , &vID);
Lattice lsentence;
lsentence.resize(vID.size());
for (int i=0; i<vID.size(); i++){
lsentence[i].push_back( LatticeArc(vID[i], 0.0, 1) );
}
// if(!lsentence.IsSentence())
// cout<<"not a sentence"<<endl;
return lsentence;
}
bool parseSentencePair(const string & goal_sym, const string & src, const string & tgt, GrammarPtr & g, Hypergraph &hg){
// cout<<" Start parse the sentence pairs\n"<<endl;
Lattice lsource = convertSentenceToLattice(src);
//parse the source sentence by the grammar
vector<GrammarPtr> grammars(1, g);
ExhaustiveBottomUpParser parser = ExhaustiveBottomUpParser(goal_sym, grammars);
if (!parser.Parse(lsource, &hg)){
cerr<<"source sentence is not parsed by the grammar!"<<endl;
return false;
}
//intersect the hg with the target sentence
Lattice ltarget = convertSentenceToLattice(tgt);
//forest.PrintGraphviz();
if (!HG::Intersect(ltarget, & hg)) return false;
SparseVector<double> reweight;
reweight.set_value(FD::Convert("MinusLogP"), -1 );
hg.Reweight(reweight);
return true;
}
int main(int argc, char** argv){
ParamsArray params(argc, argv);
params.setDescription("scfg models");
params.addConstraint("grammar_file", "grammar file (default ./grammar.pr )", true); // optional
params.addConstraint("input_file", "parallel input file (default ./parallel_corpora)", true); //optional
params.addConstraint("output_file", "grammar output file (default ./grammar_output)", true); //optional
params.addConstraint("goal_symbol", "top nonterminal symbol (default: X)", true); //optional
params.addConstraint("split", "split one nonterminal into 'split' nonterminals (default: 2)", true); //optional
params.addConstraint("prob_iters", "number of iterations (default: 10)", true); //optional
params.addConstraint("split_iters", "number of splitting iterations (default: 3)", true); //optional
params.addConstraint("alpha", "alpha (default: 0.1)", true); //optional
if (!params.runConstraints("scfg")) {
return 0;
}
cerr<<"get parametters\n\n\n";
string grammar_file = params.asString("grammar_file", "./grammar.pr");
string input_file = params.asString("input_file", "parallel_corpora");
string output_file = params.asString("output_file", "grammar_output");
string goal_sym = params.asString("goal_symbol", "X");
int max_split = atoi(params.asString("split", "2").c_str());
int prob_iters = atoi(params.asString("prob_iters", "2").c_str());
int split_iters = atoi(params.asString("split_iters", "1").c_str());
double alpha = atof(params.asString("alpha", ".001").c_str());
/////
cerr<<"grammar_file ="<<grammar_file<<endl;
cerr<<"input_file ="<< input_file<<endl;
cerr<<"output_file ="<< output_file<<endl;
cerr<<"goal_sym ="<< goal_sym<<endl;
cerr<<"max_split ="<< max_split<<endl;
cerr<<"prob_iters ="<< prob_iters<<endl;
cerr<<"split_iters ="<< split_iters<<endl;
cerr<<"alpha ="<< alpha<<endl;
//////////////////////////
cerr<<"\n\nLoad parallel corpus...\n";
if (! openParallelCorpora(input_file))
exit(1);
cerr<<"Load grammar file ...\n";
aGrammar * agrammar = load_grammar(grammar_file);
agrammar->SetGoalNT(goal_sym);
agrammar->setMaxSplit(max_split);
agrammar->set_alpha(alpha);
srand(123);
GrammarPtr g( agrammar);
Hypergraph hg;
int data_size = src_corpus.size();
int cnt_unparsed =0;
for (int i =0; i <split_iters; i++){
cerr<<"Split Nonterminals, iteration "<<(i+1)<<endl;
agrammar->PrintAllRules(output_file+".s" + itos(i+1));
agrammar->splitAllNonterminals();
//vector<string> src_corpus;
//vector<string> tgt_corpus;
for (int j=0; j<prob_iters; j++){
cerr<<"reset grammar score\n";
agrammar->ResetScore();
// cerr<<"done reset grammar score\n";
for (int k=0; k <data_size; k++){
string src = src_corpus[k];
string tgt = tgt_corpus[k];
cerr <<"parse sentence pair: "<<src<<" ||| "<<tgt<<endl;
if (! parseSentencePair(goal_sym, src, tgt, g, hg) ){
cerr<<"target sentence is not parsed by the grammar!\n";
//return 1;
cnt_unparsed++;
continue;
}
cerr<<"update edge posterior prob"<<endl;
boost::static_pointer_cast<aGrammar>(g)->UpdateHgProsteriorProb(hg);
hg.clear();
if (k%1000 ==0 ) cerr<<"sentences "<<k<<endl;
}
cerr<<"cnt_unparased="<<cnt_unparsed<<endl;
boost::static_pointer_cast<aGrammar>(g)->UpdateScore();
}
boost::static_pointer_cast<aGrammar>(g)->PrintAllRules(output_file+".e" + itos(i+1));
}
// // agrammar->ResetScore();
// // agrammar->UpdateScore();
// if (! parseSentencePair(goal_sym, src, tgt, g, hg) ){
// cerr<<"target sentence is not parsed by the grammar!\n";
// return 1;
// }
// // hg.PrintGraphviz();
// //hg.clear();
// agrammar->PrintAllRules();
// /*split grammar*/
// cout<<"split NTs\n";
// cerr<<"first of all write all nonterminals"<<endl;
// // agrammar->printAllNonterminals();
// cout<<"after split nonterminal"<<endl;
// agrammar->PrintAllRules();
// Hypergraph hg1;
// if (! parseSentencePair(goal_sym, src, tgt, g, hg1) ){
// cerr<<"target sentence is not parsed by the grammar!\n";
// return 1;
// }
// hg1.PrintGraphviz();
// agrammar->splitNonterminal(15);
// cout<<"after split nonterminal"<<TD::Convert(15)<<endl;
// agrammar->PrintAllRules();
/*load training corpus*/
/*for each sentence pair in training corpus*/
// forest.PrintGraphviz();
/*calculate expected count*/
}
| 28.02518 | 179 | 0.602747 | agesmundo |
1e5a29bcdb25a9e5b5625b701065f2c88c8ffead | 4,322 | cpp | C++ | test/unit-test/src/test-xml-001.cpp | solosTec/cyng | 3862a6b7a2b536d1f00fef20700e64170772dcff | [
"MIT"
] | null | null | null | test/unit-test/src/test-xml-001.cpp | solosTec/cyng | 3862a6b7a2b536d1f00fef20700e64170772dcff | [
"MIT"
] | null | null | null | test/unit-test/src/test-xml-001.cpp | solosTec/cyng | 3862a6b7a2b536d1f00fef20700e64170772dcff | [
"MIT"
] | null | null | null |
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Sylko Olzscher
*
*/
#include "test-xml-001.h"
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <cyng/xml.h>
#include <cyng/object.h>
#include <cyng/factory.h>
#include <cyng/io/serializer.h>
#include <boost/uuid/random_generator.hpp>
#include <boost/filesystem.hpp>
namespace cyng
{
bool test_xml_001()
{
#ifdef CYNG_PUGIXML_INSTALLED
const boost::filesystem::path tmp = boost::filesystem::temp_directory_path();
const boost::filesystem::path pwd = boost::filesystem::current_path();
boost::uuids::random_generator rgen;
//
// create an object tree
//
const auto conf = cyng::vector_factory({
cyng::tuple_factory(cyng::param_factory("log-dir", tmp.string())
, cyng::param_factory("log-level", "INFO")
, cyng::param_factory("tag", rgen())
, cyng::param_factory("generated", std::chrono::system_clock::now())
, cyng::param_factory("log-pushdata", false) // log file for each channel
, cyng::param_factory("output", cyng::vector_factory({ "DB", "XML", "LOG" })) // options are XML, JSON, DB
, cyng::param_factory("DB", cyng::tuple_factory(
cyng::param_factory("type", "SQLite"),
cyng::param_factory("file-name", (pwd / "store.database").string()),
cyng::param_factory("busy-timeout", 12), // seconds
cyng::param_factory("watchdog", 30), // for database connection
cyng::param_factory("pool-size", 1) // no pooling for SQLite
))
, cyng::param_factory("XML", cyng::tuple_factory(
cyng::param_factory("root-dir", (pwd / "xml").string()),
cyng::param_factory("root-name", "SML"),
cyng::param_factory("endcoding", "UTF-8")
))
, cyng::param_factory("JSON", cyng::tuple_factory(
cyng::param_factory("root-dir", (pwd / "json").string())
))
, cyng::param_factory("ABL", cyng::tuple_factory(
cyng::param_factory("root-dir", (pwd / "abl").string()),
cyng::param_factory("prefix", "smf")
))
, cyng::param_factory("BIN", cyng::tuple_factory(
cyng::param_factory("root-dir", (pwd / "sml").string()),
cyng::param_factory("prefix", "smf"),
cyng::param_factory("suffix", "sml")
))
, cyng::param_factory("LOG", cyng::tuple_factory(
cyng::param_factory("root-dir", (pwd / "log").string()),
cyng::param_factory("prefix", "smf")
))
, cyng::param_factory("ipt", cyng::vector_factory({
cyng::tuple_factory(
cyng::param_factory("host", "127.0.0.1"),
cyng::param_factory("service", "26862"),
cyng::param_factory("account", "data-store"),
cyng::param_factory("pwd", "to-define"),
cyng::param_factory("def-sk", "0102030405060708090001020304050607080900010203040506070809000001"), // scramble key
cyng::param_factory("scrambled", true),
cyng::param_factory("monitor", 57)), // seconds
cyng::tuple_factory(
cyng::param_factory("host", "127.0.0.1"),
cyng::param_factory("service", "26863"),
cyng::param_factory("account", "data-store"),
cyng::param_factory("pwd", "to-define"),
cyng::param_factory("def-sk", "0102030405060708090001020304050607080900010203040506070809000001"), // scramble key
cyng::param_factory("scrambled", false),
cyng::param_factory("monitor", 57))
}))
, cyng::param_factory("targets", cyng::vector_factory({ "data.sink.1", "data.sink.2" })) // list of targets
)
});
//std::cout << io::to_str(conf) << std::endl;
pugi::xml_document doc;
auto declarationNode = doc.append_child(pugi::node_declaration);
declarationNode.append_attribute("version") = "1.0";
declarationNode.append_attribute("encoding") = "UTF-8";
declarationNode.append_attribute("standalone") = "yes";
pugi::xml_node root = doc.append_child("test");
root.append_attribute("xmlns:xsi") = "w3.org/2001/XMLSchema-instance";
//
// serialize to XML
//
xml::write(root, make_object(conf));
const auto p = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("unit-test-%%%%-%%%%-%%%%-%%%%.xml");
if (doc.save_file(p.c_str(), PUGIXML_TEXT(" ")))
{
std::cout << p << std::endl;
doc.reset();
}
//
// deserialize from XML
//
object obj = xml::read_file(p.string());
//std::cout << io::to_str(obj) << std::endl;
#endif
return true;
}
}
| 35.138211 | 128 | 0.648542 | solosTec |
1e5b542f3fb95c2b36220a2c7a4b4310a6461bd8 | 2,609 | cpp | C++ | legacy/c3_trajectory_generator/src/waypoint_validity.cpp | DSsoto/SubjuGator | fb3861442399540e1dc4472af6e98a817a81e607 | [
"MIT"
] | null | null | null | legacy/c3_trajectory_generator/src/waypoint_validity.cpp | DSsoto/SubjuGator | fb3861442399540e1dc4472af6e98a817a81e607 | [
"MIT"
] | null | null | null | legacy/c3_trajectory_generator/src/waypoint_validity.cpp | DSsoto/SubjuGator | fb3861442399540e1dc4472af6e98a817a81e607 | [
"MIT"
] | null | null | null | #include "waypoint_validity.hpp"
// Point and sub_size must be relative to ogrid (IE, in ogrid-cell units)
bool WaypointValidity::check_if_hit(cv::Point center, cv::Size sub_size)
{
for (int x = center.x - sub_size.width / 2; x < center.x + sub_size.width / 2; ++x)
{
for (int y = center.y - sub_size.height / 2; y < center.y + sub_size.height / 2; ++y)
{
try
{
if (ogrid_map_->data.at(x + y * ogrid_map_->info.width) == (uchar)WAYPOINT_ERROR_TYPE::OCCUPIED)
{
return true;
}
}
catch (std::out_of_range &e)
{
return true;
}
}
}
return false;
}
void WaypointValidity::ogrid_callback(const nav_msgs::OccupancyGridConstPtr &ogrid_map)
{
this->ogrid_map_ = ogrid_map;
}
// Convert waypoint to be relative to ogrid, then do a series of checks (unknown, occupied, or above water).
// Returns a bool that represents if the move is safe, and an error
std::pair<bool, WAYPOINT_ERROR_TYPE> WaypointValidity::is_waypoint_valid(const geometry_msgs::Pose &waypoint,
bool do_waypoint_validation)
{
if (!do_waypoint_validation)
return std::make_pair(true, WAYPOINT_ERROR_TYPE::NOT_CHECKED);
if (waypoint.position.z > 0.2)
{
return std::make_pair(false, WAYPOINT_ERROR_TYPE::ABOVE_WATER);
}
if (!this->ogrid_map_)
{
return std::make_pair(false, WAYPOINT_ERROR_TYPE::NO_OGRID);
}
cv::Point where_sub = cv::Point(waypoint.position.x / ogrid_map_->info.resolution + ogrid_map_->info.width / 2,
waypoint.position.y / ogrid_map_->info.resolution + ogrid_map_->info.height / 2);
// Area we want to check around the sub
int sub_x = 1.5 / ogrid_map_->info.resolution;
int sub_y = 1.5 / ogrid_map_->info.resolution;
if (check_if_hit(where_sub, cv::Size(sub_x, sub_y)))
{
return std::make_pair(false, WAYPOINT_ERROR_TYPE::OCCUPIED);
}
try
{
if (ogrid_map_->data.at(where_sub.x + where_sub.y * ogrid_map_->info.width) == (uchar)WAYPOINT_ERROR_TYPE::UNKNOWN)
{
return std::make_pair(false, WAYPOINT_ERROR_TYPE::UNKNOWN);
}
}
catch (std::out_of_range &e)
{
return std::make_pair(false, WAYPOINT_ERROR_TYPE::OCCUPIED);
}
return std::make_pair(true, WAYPOINT_ERROR_TYPE::UNOCCUPIED);
}
WaypointValidity::WaypointValidity(ros::NodeHandle &nh)
{
nh_ = &nh;
sub_ = nh_->subscribe<nav_msgs::OccupancyGrid>("/ogrid_pointcloud/ogrid", 1,
boost::bind(&WaypointValidity::ogrid_callback, this, _1));
} | 33.448718 | 119 | 0.647374 | DSsoto |
1e5ebc48a00a599d8291db052ed3d7e7e52a941a | 1,526 | hpp | C++ | Nacro/SDK/FN_StatusWidget_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_StatusWidget_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_StatusWidget_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function StatusWidget.StatusWidget_C.UpdateLoginStatusText
struct UStatusWidget_C_UpdateLoginStatusText_Params
{
struct FText ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function StatusWidget.StatusWidget_C.SetStatusText
struct UStatusWidget_C_SetStatusText_Params
{
struct FText Status; // (Parm)
};
// Function StatusWidget.StatusWidget_C.SetTitleText
struct UStatusWidget_C_SetTitleText_Params
{
struct FText TitleText; // (Parm)
};
// Function StatusWidget.StatusWidget_C.Construct
struct UStatusWidget_C_Construct_Params
{
};
// Function StatusWidget.StatusWidget_C.Destruct
struct UStatusWidget_C_Destruct_Params
{
};
// Function StatusWidget.StatusWidget_C.ExecuteUbergraph_StatusWidget
struct UStatusWidget_C_ExecuteUbergraph_StatusWidget_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 27.25 | 152 | 0.537353 | Milxnor |
1e62875135ba024ee4b17d5d6d3fd54aa2cf01c3 | 7,128 | cpp | C++ | src/dtl/filter/model/calibration_data_test.cpp | peterboncz/bloomfilter-bsd | bae83545a091555e48b5495669c7adcb99fd2047 | [
"Apache-2.0",
"BSD-3-Clause"
] | 15 | 2018-08-26T15:31:49.000Z | 2022-01-28T06:28:33.000Z | lib/bsd/src/dtl/filter/model/calibration_data_test.cpp | tum-db/partitioned-filters | 56c20102715a442cbec9ecb732d41de15b31c828 | [
"MIT"
] | 1 | 2019-12-20T22:56:22.000Z | 2019-12-20T22:56:22.000Z | lib/bsd/src/dtl/filter/model/calibration_data_test.cpp | tum-db/partitioned-filters | 56c20102715a442cbec9ecb732d41de15b31c828 | [
"MIT"
] | 8 | 2018-10-02T09:15:29.000Z | 2021-12-29T15:45:42.000Z | #include "gtest/gtest.h"
#include <iostream>
#include <fstream>
#include <cstdio>
#include <dtl/dtl.hpp>
#include "dtl/filter/model/calibration_data.hpp"
#include "dtl/filter/model/timing.hpp"
using namespace dtl::filter::model;
//===----------------------------------------------------------------------===//
TEST(model_calibration_data, basic_persistence) {
const std::string filename = "/tmp/calibration_data";
std::remove(filename.c_str());
dtl::blocked_bloomfilter_config bbf_config_1;
bbf_config_1.k = 1;
dtl::blocked_bloomfilter_config bbf_config_2;
bbf_config_2.k = 2;
dtl::cuckoofilter::config cf_config_1;
cf_config_1.tags_per_bucket = 1;
dtl::cuckoofilter::config cf_config_2;
cf_config_1.tags_per_bucket = 2;
const std::vector<timing> delta_timings_1 = {{1,2}, {3,4}, {5,6}, {7,8}};
const std::vector<timing> delta_timings_2 = {{9,10}, {11,12}, {13,14}, {15,16}};
{
calibration_data cd(filename);
cd.set_cache_sizes({10,20,30});
ASSERT_EQ(10, cd.get_cache_size(1));
ASSERT_EQ(20, cd.get_cache_size(2));
ASSERT_EQ(30, cd.get_cache_size(3));
cd.set_filter_sizes({4,8,16,32});
ASSERT_EQ(4, cd.get_filter_size(1));
ASSERT_EQ(8, cd.get_filter_size(2));
ASSERT_EQ(16, cd.get_filter_size(3));
ASSERT_EQ(32, cd.get_filter_size(4));
ASSERT_EQ(4, cd.get_mem_levels());
cd.put_timings(bbf_config_1, delta_timings_1);
cd.put_timings(bbf_config_2, delta_timings_2);
cd.put_timings(cf_config_1, delta_timings_1);
cd.put_timings(cf_config_2, delta_timings_2);
auto actual_bbf_timings_1 = cd.get_timings(bbf_config_1);
ASSERT_EQ(delta_timings_1, actual_bbf_timings_1);
auto actual_bbf_timings_2 = cd.get_timings(bbf_config_2);
ASSERT_EQ(delta_timings_2, actual_bbf_timings_2);
auto actual_cf_timings_1 = cd.get_timings(cf_config_1);
ASSERT_EQ(delta_timings_1, actual_cf_timings_1);
auto actual_cf_timings_2 = cd.get_timings(cf_config_2);
ASSERT_EQ(delta_timings_1, actual_cf_timings_1);
// check, if tuning parameters exist
auto actual_bbf_tuning_1 = cd.get_tuning_params(bbf_config_1);
ASSERT_EQ(cd.get_null_tuning_params(), actual_bbf_tuning_1);
auto actual_bbf_tuning_2 = cd.get_tuning_params(bbf_config_2);
ASSERT_EQ(cd.get_null_tuning_params(), actual_bbf_tuning_2);
auto actual_cf_tuning_1 = cd.get_tuning_params(cf_config_1);
ASSERT_EQ(cd.get_null_tuning_params(), actual_cf_tuning_1);
auto actual_cf_tuning_2 = cd.get_tuning_params(cf_config_2);
ASSERT_EQ(cd.get_null_tuning_params(), actual_cf_tuning_2);
ASSERT_TRUE(cd.changed());
cd.persist();
}
{
calibration_data cd(filename);
ASSERT_EQ(4, cd.get_mem_levels());
ASSERT_EQ(10, cd.get_cache_size(1));
ASSERT_EQ(20, cd.get_cache_size(2));
ASSERT_EQ(30, cd.get_cache_size(3));
ASSERT_EQ(4, cd.get_filter_size(1));
ASSERT_EQ(8, cd.get_filter_size(2));
ASSERT_EQ(16, cd.get_filter_size(3));
ASSERT_EQ(32, cd.get_filter_size(4));
auto received_timings_1 = cd.get_timings(bbf_config_1);
ASSERT_EQ(delta_timings_1, received_timings_1);
auto received_timings_2 = cd.get_timings(bbf_config_2);
ASSERT_EQ(delta_timings_2, received_timings_2);
ASSERT_FALSE(cd.changed());
}
std::remove(filename.c_str());
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
TEST(model_calibration_data, add_config) {
const std::string filename = "/tmp/calibration_data";
std::remove(filename.c_str());
dtl::blocked_bloomfilter_config bbf_config_1;
bbf_config_1.k = 1;
dtl::blocked_bloomfilter_config bbf_config_2;
bbf_config_2.k = 2;
dtl::cuckoofilter::config cf_config_1;
cf_config_1.tags_per_bucket = 1;
dtl::cuckoofilter::config cf_config_2;
cf_config_1.tags_per_bucket = 2;
const std::vector<timing> delta_timings_1 = {{1,2}, {3,4}, {5,6}, {7,8}};
const std::vector<timing> delta_timings_2 = {{9,10}, {11,12}, {13,14}, {15,16}};
{
// create a config file
calibration_data cd(filename);
cd.set_cache_sizes({10,20,30});
cd.set_filter_sizes({4,8,16,32});
// put first config
cd.put_timings(bbf_config_1, delta_timings_1);
// write to file
cd.persist();
}
{
// re-open
calibration_data cd(filename);
// put second config
cd.put_timings(bbf_config_2, delta_timings_2);
// write to file
cd.persist();
}
{
// re-open
calibration_data cd(filename);
// check if first config exists
auto received_timings_1 = cd.get_timings(bbf_config_1);
ASSERT_EQ(delta_timings_1, received_timings_1);
// check if second config exists
auto received_timings_2 = cd.get_timings(bbf_config_2);
ASSERT_EQ(delta_timings_2, received_timings_2);
}
std::remove(filename.c_str());
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
TEST(model_calibration_data, update_config) {
const std::string filename = "/tmp/calibration_data";
std::remove(filename.c_str());
dtl::blocked_bloomfilter_config bbf_config_1;
bbf_config_1.k = 1;
dtl::blocked_bloomfilter_config bbf_config_2;
bbf_config_2.k = 2;
dtl::cuckoofilter::config cf_config_1;
cf_config_1.tags_per_bucket = 1;
dtl::cuckoofilter::config cf_config_2;
cf_config_1.tags_per_bucket = 2;
const std::vector<timing> delta_timings_1 = {{1,2}, {3,4}, {5,6}, {7,8}};
const std::vector<timing> delta_timings_2 = {{9,10}, {11,12}, {13,14}, {15,16}};
{
// create a config file
calibration_data cd(filename);
cd.set_cache_sizes({10,20,30});
cd.set_filter_sizes({4,8,16,32});
// put first config
cd.put_timings(bbf_config_1, delta_timings_1);
cd.put_timings(cf_config_1, delta_timings_1);
cd.put_tuning_params(bbf_config_1, tuning_params {2});
cd.put_tuning_params(cf_config_1, tuning_params {4});
// write to file
cd.persist();
}
{
// re-open
calibration_data cd(filename);
// update first config
cd.put_timings(bbf_config_1, delta_timings_2);
cd.put_timings(cf_config_1, delta_timings_2);
cd.put_tuning_params(bbf_config_1, tuning_params {4});
cd.put_tuning_params(cf_config_1, tuning_params {8});
// write to file
cd.persist();
}
{
// re-open
calibration_data cd(filename);
// check first config
auto received_timings_1 = cd.get_timings(bbf_config_1);
ASSERT_EQ(delta_timings_2, received_timings_1);
// check if second config exists
auto received_timings_2 = cd.get_timings(cf_config_1);
ASSERT_EQ(delta_timings_2, received_timings_2);
auto actual_tuning_params_1 = cd.get_tuning_params(bbf_config_1);
ASSERT_EQ(actual_tuning_params_1, tuning_params {4});
auto actual_tuning_params_2 = cd.get_tuning_params(cf_config_1);
ASSERT_EQ(actual_tuning_params_2, tuning_params {8});
}
std::remove(filename.c_str());
}
//===----------------------------------------------------------------------===//
| 31.126638 | 82 | 0.668771 | peterboncz |
1e63e8d76b3c16566d9249d90e4cb5652ae44268 | 8,651 | cc | C++ | text/text_buffer.cc | abarth/zi | 1cdd73a36c8d79d1e1c6fc7ff7195b0ad0b8214f | [
"0BSD"
] | 2 | 2016-09-20T15:26:39.000Z | 2021-08-13T08:20:43.000Z | text/text_buffer.cc | abarth/zi | 1cdd73a36c8d79d1e1c6fc7ff7195b0ad0b8214f | [
"0BSD"
] | null | null | null | text/text_buffer.cc | abarth/zi | 1cdd73a36c8d79d1e1c6fc7ff7195b0ad0b8214f | [
"0BSD"
] | null | null | null | // Copyright (c) 2016, Google Inc.
//
// 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.
#include "text/text_buffer.h"
#include <string.h>
#include <algorithm>
#include <utility>
#ifndef NDEBUG
#include <iostream>
#endif
namespace zi {
TextBuffer::TextBuffer() = default;
TextBuffer::TextBuffer(std::vector<char> text) : buffer_(std::move(text)) {}
TextBuffer::~TextBuffer() = default;
void TextBuffer::InsertCharacter(const TextPosition& position, char c) {
if (gap_start_ == gap_end_)
Expand(1);
MoveInsertionPointTo(position.offset());
buffer_[gap_start_++] = c;
// TODO(abarth): Consider the affinity when adjusting the TextBufferRanges.
DidInsert(1);
}
void TextBuffer::InsertText(const TextPosition& position, StringView text) {
const size_t length = text.length();
if (gap_start_ + length > gap_end_)
Expand(length);
MoveInsertionPointTo(position.offset());
memcpy(&buffer_[gap_start_], text.data(), length);
gap_start_ += length;
// TODO(abarth): Consider the affinity when adjusting the TextBufferRanges.
DidInsert(length);
}
void TextBuffer::InsertText(const TextPosition& position,
const std::string& text) {
InsertText(position, StringView(text));
}
void TextBuffer::DeleteCharacterAfter(size_t position) {
DeleteRange(TextBufferRange(position, position + 1));
}
void TextBuffer::DeleteRange(const TextBufferRange& range) {
const size_t size = this->size();
const size_t begin = std::min(range.start(), size);
const size_t end = std::min(range.end(), size);
if (begin == end)
return;
const size_t count = end - begin;
MoveInsertionPointTo(end);
gap_start_ -= count;
DidDelete(count);
DidMoveInsertionPointBackward();
}
void TextBuffer::MoveInsertionPointForward(size_t offset) {
size_t delta = std::min(offset, buffer_.size() - gap_end_);
memmove(&buffer_[gap_start_], &buffer_[gap_end_], delta);
gap_start_ += delta;
gap_end_ += delta;
DidMoveInsertionPointForward();
}
void TextBuffer::MoveInsertionPointBackward(size_t offset) {
size_t delta = std::min(offset, gap_start_);
gap_start_ -= delta;
gap_end_ -= delta;
memmove(&buffer_[gap_end_], &buffer_[gap_start_], delta);
DidMoveInsertionPointBackward();
}
void TextBuffer::MoveInsertionPointTo(size_t position) {
if (position > gap_start_)
MoveInsertionPointForward(position - gap_start_);
else if (position < gap_start_)
MoveInsertionPointBackward(gap_start_ - position);
}
size_t TextBuffer::Find(char c, size_t pos) {
if (pos < gap_start_) {
char* ptr = static_cast<char*>(memchr(&buffer_[pos], c, gap_start_ - pos));
if (ptr)
return ptr - data();
pos = gap_start_;
}
pos += gap_size();
if (pos < buffer_.size()) {
char* ptr =
static_cast<char*>(memchr(&buffer_[pos], c, buffer_.size() - pos));
if (ptr)
return ptr - data() - gap_size();
}
return std::string::npos;
}
size_t TextBuffer::RFind(char c, size_t pos) {
if (is_empty())
return std::string::npos;
pos = std::min(pos, size() - 1);
for (size_t i = 0; i <= pos; ++i) {
size_t probe = pos - i;
// TODO(abarth): Factor this loop so we don't have to test against gap_start
// in each iteration.
if (At(probe) == c)
return probe;
}
return std::string::npos;
}
std::string TextBuffer::ToString() const {
std::string result;
result.resize(size());
if (gap_start_ > 0)
result.replace(0, gap_start_, data(), gap_start_);
if (gap_end_ < buffer_.size()) {
const size_t tail_size = this->tail_size();
result.replace(gap_start_, tail_size, &buffer_[gap_end_], tail_size);
}
return result;
}
TextView TextBuffer::GetText() const {
const char* data = buffer_.data();
return TextView(StringView(data, data + gap_start_),
StringView(data + gap_end_, data + buffer_.size()));
}
TextView TextBuffer::GetTextForRange(TextBufferRange* range) const {
if (range->end() <= gap_start_) {
const char* begin = &buffer_[range->start()];
return TextView(StringView(begin, begin + range->length()));
} else if (range->start() >= gap_start_) {
const char* begin = &buffer_[range->start() + gap_size()];
// TODO(abarth): Should we handle the case where the range extends beyond
// the
// buffer?
return TextView(StringView(begin, begin + range->length()));
} else {
// The range crosses the gap.
const char* first_begin = &buffer_[range->start()];
const char* first_end = &buffer_[gap_start_];
const size_t first_length = first_end - first_begin;
const char* second_begin = &buffer_[gap_end_];
const char* second_end = second_begin + (range->length() - first_length);
return TextView(StringView(first_begin, first_end),
StringView(second_begin, second_end));
}
}
char TextBuffer::At(size_t offset) {
if (offset >= gap_start_)
offset += gap_size();
return buffer_[offset];
}
void TextBuffer::AddRange(TextBufferRange* range) {
if (range->end() <= gap_start_)
before_gap_.push(range);
else if (range->start() >= gap_start_)
after_gap_.push(range);
else
across_gap_.push_back(range);
}
void TextBuffer::RemoveRange(TextBufferRange* range) {
RemoveRanges(&range, &range);
}
#ifndef NDEBUG
static void DebugDumpTextBufferRangeVector(
const std::vector<TextBufferRange*>& ranges) {
for (auto& range : ranges) {
std::cout << "begin=" << range->start() << " end=" << range->end()
<< std::endl;
}
}
void TextBuffer::DebugDumpRanges() {
std::cout << "gap_begin=" << gap_start_ << " gap_end=" << gap_end_
<< " size=" << buffer_.size() << std::endl;
std::cout << "== Before gap ==" << std::endl;
DebugDumpTextBufferRangeVector(before_gap_.debug_container());
std::cout << "== Across gap ==" << std::endl;
DebugDumpTextBufferRangeVector(across_gap_);
std::cout << "== After gap ==" << std::endl;
DebugDumpTextBufferRangeVector(after_gap_.debug_container());
}
#endif
void TextBuffer::Expand(size_t required_gap_size) {
size_t existing_gap = gap_size();
if (existing_gap >= required_gap_size)
return;
size_t min_size = buffer_.size() - existing_gap + required_gap_size;
std::vector<char> new_buffer(min_size * 1.5 + 1);
if (gap_start_ > 0)
memcpy(&new_buffer[0], data(), gap_start_);
if (gap_end_ < buffer_.size()) {
const size_t tail_size = this->tail_size();
memcpy(&new_buffer[new_buffer.size() - tail_size],
&buffer_[buffer_.size() - tail_size], tail_size);
}
gap_end_ += new_buffer.size() - buffer_.size();
buffer_.swap(new_buffer);
}
void TextBuffer::DidInsert(size_t count) {
for (auto& range : across_gap_)
range->PushBack(count);
after_gap_.ShiftForward(count);
}
void TextBuffer::DidDelete(size_t count) {
std::vector<TextBufferRange*> displaced;
while (!before_gap_.empty()) {
TextBufferRange* range = before_gap_.top();
if (range->end() <= gap_start_)
break;
before_gap_.pop();
displaced.push_back(range);
range->PopBack(range->end() - gap_start_);
}
AddRanges(displaced.begin(), displaced.end());
for (auto& range : across_gap_)
range->PopBack(count);
after_gap_.ShiftBackward(count);
}
void TextBuffer::DidMoveInsertionPointForward() {
std::vector<TextBufferRange*> displaced;
across_gap_.swap(displaced);
while (!after_gap_.empty()) {
TextBufferRange* range = after_gap_.top();
if (range->start() >= gap_start_)
break;
after_gap_.pop();
displaced.push_back(range);
}
AddRanges(displaced.begin(), displaced.end());
}
void TextBuffer::DidMoveInsertionPointBackward() {
std::vector<TextBufferRange*> displaced;
across_gap_.swap(displaced);
while (!before_gap_.empty()) {
TextBufferRange* range = before_gap_.top();
if (range->end() <= gap_start_)
break;
before_gap_.pop();
displaced.push_back(range);
}
AddRanges(displaced.begin(), displaced.end());
}
} // namespace zi
| 31.118705 | 80 | 0.684776 | abarth |
1e65a32b91642689bffc2adbd6ca65e625e1c876 | 1,753 | hpp | C++ | Stats/ReservoirSampler.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 108 | 2020-10-01T17:12:40.000Z | 2022-03-30T09:18:03.000Z | Stats/ReservoirSampler.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 94 | 2020-10-03T13:40:30.000Z | 2022-03-30T09:18:00.000Z | Stats/ReservoirSampler.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 17 | 2020-10-29T13:27:59.000Z | 2022-03-18T13:05:03.000Z | #ifndef STATS_RESERVOIRSAMPLER_HPP
#define STATS_RESERVOIRSAMPLER_HPP
#include"Util/vector_emplace_back.hpp"
#include<cstdint>
#include<random>
#include<vector>
namespace Stats {
/** class ReservoirSampler<Sample, Weight>
*
* @brief selects a number of samples, biased by
* weight (higher weight items are more likely to
* be selected).
*
* @desc Implements A-Chao.
*/
template< typename Sample
, typename Weight = double
>
class ReservoirSampler {
private:
std::size_t max_selected;
std::vector<Sample> selected;
Weight wsum;
public:
ReservoirSampler() : max_selected(1) { }
explicit
ReservoirSampler(std::size_t max_selected_
) : max_selected(max_selected_) { }
ReservoirSampler(ReservoirSampler&&) =default;
ReservoirSampler(ReservoirSampler const&) =default;
void clear() { selected.clear(); }
void clear(std::size_t max_selected_) {
selected.clear();
max_selected = max_selected_;
}
template<typename Rand>
void add(Sample s, Weight w, Rand& r) {
/* Should not happen. */
if (max_selected == 0)
return;
if (selected.size() == 0)
wsum = w;
else
wsum += w;
if (selected.size() < max_selected) {
Util::vector_emplace_back( selected
, std::move(s)
);
return;
}
auto distw = std::uniform_real_distribution<Weight>(
0, 1
);
auto p = w / wsum;
auto j = distw(r);
if (j <= p) {
/* Randomly replace an existing selection. */
auto disti
= std::uniform_int_distribution<std::size_t>(
0, selected.size() - 1
);
auto i = disti(r);
selected[i] = std::move(s);
}
}
std::vector<Sample> const& get() const { return selected; }
std::vector<Sample> finalize()&& {
return std::move(selected);
}
};
}
#endif /* STATS_RESERVOIRSAMPLER_HPP */
| 20.623529 | 60 | 0.673702 | 3nprob |
1e6cf705100563897a92ad607cf604b6c0e5dc6d | 6,521 | cpp | C++ | dmengine/utils/dmzonehelper.cpp | damao1222/dmengine | 09ab62c043a520f8f6b15eb8790c7ee56c006931 | [
"Apache-2.0"
] | null | null | null | dmengine/utils/dmzonehelper.cpp | damao1222/dmengine | 09ab62c043a520f8f6b15eb8790c7ee56c006931 | [
"Apache-2.0"
] | null | null | null | dmengine/utils/dmzonehelper.cpp | damao1222/dmengine | 09ab62c043a520f8f6b15eb8790c7ee56c006931 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2012 Xiongfa Li
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "dmzonehelper.h"
#include "dmdebug.h"
DM_BEGIN_NAMESPACE
class ZoneHelperPrivate
{
public:
ZoneHelperPrivate();
dint mWidth;
dint mHeight;
dint mOffsetX;
dint mOffsetY;
dint mRow;
dint mColumn;
dint mZoneWidth;
dint mZoneHeight;
dint mZoneSize;
};
ZoneHelperPrivate::ZoneHelperPrivate():
mWidth(0),
mHeight(0),
mOffsetX(0),
mOffsetY(0),
mRow(0),
mColumn(0),
mZoneWidth(0),
mZoneHeight(0),
mZoneSize(0)
{
}
ZoneHelper::ZoneHelper():
C_D(ZoneHelper)
{
}
ZoneHelper::~ZoneHelper()
{
D_D(ZoneHelper);
}
void ZoneHelper::setSize(dint nWidth, dint nHeigh)
{
if (nWidth <= 0 || nHeigh <= 0)
return ;
if (pdm->mWidth != nWidth)
{
pdm->mWidth = nWidth;
}
if (pdm->mHeight != nHeigh)
{
pdm->mHeight = nHeigh;
}
}
void ZoneHelper::setSize(const Size &size)
{
pdm->mWidth = size.width();
pdm->mHeight = size.height();
}
void ZoneHelper::getSize(dint &nWidth, dint &nHeigh) const
{
nWidth = pdm->mWidth;
nHeigh = pdm->mHeight;
}
Size ZoneHelper::getSize() const
{
return Size(pdm->mWidth, pdm->mHeight);
}
void ZoneHelper::setOffset(dint nX, dint nY)
{
if (pdm->mOffsetX != nX)
{
pdm->mOffsetX = nX;
}
if (pdm->mOffsetY != nY)
{
pdm->mOffsetY = nY;
}
}
void ZoneHelper::getOffset(dint &nX, dint &nY)
{
nX = pdm->mOffsetX;
nY = pdm->mOffsetY;
}
void ZoneHelper::setZoneSize(dint nWidth, dint nHeigh)
{
if (nWidth <= 0 || nHeigh <= 0)
return ;
if (pdm->mZoneWidth != nWidth)
{
pdm->mZoneWidth = nWidth;
if (pdm->mWidth > 0)
{
pdm->mColumn = pdm->mWidth / pdm->mZoneWidth;
}
}
if (pdm->mZoneHeight != nHeigh)
{
pdm->mZoneHeight = nHeigh;
if (pdm->mHeight > 0)
{
pdm->mRow = pdm->mHeight / pdm->mZoneHeight;
}
}
}
void ZoneHelper::setZoneSize(const Size &size)
{
setZoneSize(size.width(), size.height());
}
void ZoneHelper::getZoneSize(dint &nWidth, dint &nHeigh) const
{
nWidth = pdm->mZoneWidth;
nHeigh = pdm->mZoneHeight;
}
Size ZoneHelper::getZoneSize() const
{
return Size(pdm->mZoneWidth, pdm->mZoneHeight);
}
void ZoneHelper::setRow(dint nRow)
{
if (nRow <= 0)
return ;
if (pdm->mRow != nRow)
{
pdm->mRow = nRow;
}
if (pdm->mHeight == 0)
{
DMDEBUG("height need be set at first!");
return ;
}
pdm->mZoneHeight = pdm->mHeight / pdm->mRow;
if (pdm->mColumn != 0)
{
pdm->mZoneSize = pdm->mRow * pdm->mColumn;
}
}
void ZoneHelper::setColumn(dint nColumn)
{
if (nColumn <= 0)
return ;
if (pdm->mColumn != nColumn)
{
pdm->mColumn = nColumn;
}
if (pdm->mWidth == 0)
{
DMDEBUG("width need be set at first!");
return ;
}
pdm->mZoneWidth = pdm->mWidth / pdm->mColumn;
if (pdm->mRow != 0)
{
pdm->mZoneSize = pdm->mRow * pdm->mColumn;
}
}
dint ZoneHelper::getCount() const
{
return pdm->mZoneSize;
}
Rect ZoneHelper::hitTestRect(dint nX, dint nY) const
{
if (pdm->mZoneWidth <= 0 || pdm->mZoneHeight <= 0)
{
DMDEBUG("Zone size is 0, call setZoneSize first");
return Rect();
}
dint x = ((nX-pdm->mOffsetX) / pdm->mZoneWidth)*pdm->mZoneWidth;
dint y = ((nY-pdm->mOffsetY) / pdm->mZoneHeight)*pdm->mZoneHeight;
return Rect(x+pdm->mOffsetX, y+pdm->mOffsetY, pdm->mZoneWidth, pdm->mZoneHeight);
}
dint ZoneHelper::hitTestIndex(dint nX, dint nY) const
{
if (pdm->mZoneWidth <= 0 || pdm->mZoneHeight <= 0)
{
DMDEBUG("Zone size is 0, call setZoneSize first");
return -1;
}
dint column = (nX-pdm->mOffsetX) / pdm->mZoneWidth;
dint row = (nY-pdm->mOffsetY) / pdm->mZoneHeight;
return (row*pdm->mColumn+column);
}
Rect ZoneHelper::fromIndex(dint index) const
{
if (pdm->mZoneWidth <= 0 || pdm->mZoneHeight <= 0)
{
DMDEBUG("Zone size is 0, call setZoneSize first");
return Rect();
}
dint row = index / pdm->mColumn;
dint column = index % pdm->mColumn;
return Rect(column*pdm->mZoneWidth+pdm->mOffsetX, \
row*pdm->mZoneHeight+pdm->mOffsetY, \
pdm->mZoneWidth, pdm->mZoneHeight);
}
dbool ZoneHelper::isValid() const
{
return (pdm->mWidth>0&&pdm->mHeight>0&&pdm->mZoneWidth>0&&pdm->mZoneHeight>0);
//return pdm->mZoneSize > 0;
}
ZoneHelper &ZoneHelper::operator=(const ZoneHelper &other)
{
this->pdm->mWidth = other.pdm->mWidth;
this->pdm->mHeight = other.pdm->mHeight;
this->pdm->mOffsetX = other.pdm->mOffsetX;
this->pdm->mOffsetY = other.pdm->mOffsetY;
this->pdm->mRow = other.pdm->mRow;
this->pdm->mColumn = other.pdm->mColumn;
this->pdm->mZoneWidth = other.pdm->mZoneWidth;
this->pdm->mZoneHeight = other.pdm->mZoneHeight;
this->pdm->mZoneSize = other.pdm->mZoneSize;
return (*this);
}
DM_END_NAMESPACE | 24.062731 | 754 | 0.636712 | damao1222 |
1e6d00cf7194038426023c237d038f6f9018ff34 | 2,671 | hpp | C++ | src/Domain/ElementIndex.hpp | osheamonn/spectre | 4a3332c61d749d83c161ea1c2ea014a937fd5dd8 | [
"MIT"
] | null | null | null | src/Domain/ElementIndex.hpp | osheamonn/spectre | 4a3332c61d749d83c161ea1c2ea014a937fd5dd8 | [
"MIT"
] | null | null | null | src/Domain/ElementIndex.hpp | osheamonn/spectre | 4a3332c61d749d83c161ea1c2ea014a937fd5dd8 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Defines class ElementIndex.
#pragma once
#include <array>
#include <cstddef>
#include <functional>
#include <iosfwd>
#include "Utilities/ConstantExpressions.hpp"
/// \cond
template <size_t>
struct ElementId;
/// \endcond
struct SegmentId;
namespace ElementIndex_detail {
constexpr size_t block_id_bits = 7;
constexpr size_t refinement_bits = 5;
constexpr size_t max_refinement_level = 20;
static_assert(block_id_bits + refinement_bits + max_refinement_level ==
8 * sizeof(int),
"Bit representation requires padding or is too large");
static_assert(two_to_the(refinement_bits) >= max_refinement_level,
"Not enough bits to represent all refinement levels");
} // namespace ElementIndex_detail
class SegmentIndex {
public:
SegmentIndex() = default;
SegmentIndex(size_t block_id, const SegmentId& segment_id) noexcept;
size_t block_id() const noexcept { return block_id_; }
size_t index() const noexcept { return index_; }
size_t refinement_level() const noexcept { return refinement_level_; }
private:
unsigned block_id_ : ElementIndex_detail::block_id_bits;
unsigned refinement_level_ : ElementIndex_detail::refinement_bits;
unsigned index_ : ElementIndex_detail::max_refinement_level;
};
template <size_t VolumeDim>
std::ostream& operator<<(std::ostream& s, const SegmentIndex& index) noexcept;
/// \ingroup ParallelGroup
/// A class for indexing a Charm array by Element.
template <size_t VolumeDim>
class ElementIndex {
public:
ElementIndex() = default;
// clang-tidy: mark explicit: we want to allow conversion
ElementIndex(const ElementId<VolumeDim>& id) noexcept; // NOLINT
size_t block_id() const noexcept { return segments_[0].block_id(); }
const std::array<SegmentIndex, VolumeDim>& segments() const noexcept {
return segments_;
}
private:
std::array<SegmentIndex, VolumeDim> segments_;
};
template <size_t VolumeDim>
bool operator==(const ElementIndex<VolumeDim>& a,
const ElementIndex<VolumeDim>& b) noexcept;
template <size_t VolumeDim>
bool operator!=(const ElementIndex<VolumeDim>& a,
const ElementIndex<VolumeDim>& b) noexcept;
template <size_t VolumeDim>
size_t hash_value(const ElementIndex<VolumeDim>& index) noexcept;
namespace std {
template <size_t VolumeDim>
struct hash<ElementIndex<VolumeDim>> {
size_t operator()(const ElementIndex<VolumeDim>& x) const noexcept;
};
} // namespace std
template <size_t VolumeDim>
std::ostream& operator<<(std::ostream& s,
const ElementIndex<VolumeDim>& index) noexcept;
| 30.701149 | 78 | 0.7383 | osheamonn |
1e6e82cca00613fe75de13ca5b8ed198da177878 | 4,415 | cpp | C++ | tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_IconView.cpp | ILW000/SDL_gui | 2c916fb73fa5b469cecb91b674032e2b624f0b9b | [
"MIT"
] | 243 | 2015-12-30T00:33:06.000Z | 2022-03-22T20:37:41.000Z | tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_IconView.cpp | ILW000/SDL_gui | 2c916fb73fa5b469cecb91b674032e2b624f0b9b | [
"MIT"
] | 13 | 2019-02-09T17:05:57.000Z | 2021-12-23T18:10:17.000Z | tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_IconView.cpp | ILW000/SDL_gui | 2c916fb73fa5b469cecb91b674032e2b624f0b9b | [
"MIT"
] | 53 | 2016-01-06T23:49:36.000Z | 2022-03-15T15:47:33.000Z | //
// GUI_IconView.cpp
// GUI_TextView
//
// Created by Panutat Tejasen on 12/1/2562 BE.
// Copyright © 2562 Jimmy Software Co., Ltd. All rights reserved.
//
#include "GUI_IconView.h"
#include "GUI_Fonts.h"
#include "skgui.h"
#include "include/core/SkSurface.h"
#include "include/core/SkImage.h"
#include "include/core/SkPaint.h"
GUI_IconView *GUI_IconView::create( GUI_View *parent, uint16_t unicode, const char *fontname, int fontsize, int x, int y, int width, int height,
std::function<bool(SDL_Event* ev)>userEventHandler ) {
return new GUI_IconView(parent, unicode, fontname, fontsize, x, y, width, height, userEventHandler );
}
GUI_IconView::GUI_IconView(GUI_View *parent, uint16_t unicode, const char *fontname, int fontsize, int x, int y, int width, int height,
std::function<bool(SDL_Event* ev)>userEventHandler) :
GUI_TextView(parent, NULL, fontname, fontsize, x, y, width, height, userEventHandler )
{
mouseReceive = false;
setIcon(unicode);
}
GUI_IconView::~GUI_IconView() {
}
void GUI_IconView::updateContent() {
// SDL_Texture *texture = createTextureFormUnicode( icon );
// if (texture == NULL){
// GUI_Log("Could not create icon texture\n");
// return;
// }
// image.setTexture(texture);
auto img = createImageFromUnicode( icon );
if(img==NULL){
GUI_Log("Could not create icon image\n");
return;
}
image.setImage(img);
updateSize();
if( parent ) {
parent->updateLayout();
}
else {
updateLayout();
}
}
void GUI_IconView::setIcon( uint16_t unicode ) {
icon = unicode;
updateContent();
}
//SDL_Texture* GUI_IconView::createTextureFormUnicode(Uint16 unicode, SDL_Rect* rect) {
//// if (font) {
//// SDL_Surface* surf = TTF_RenderGlyph_Blended(font, unicode, cWhite);
//// SDL_Texture *tex = SDL_CreateTextureFromSurface(GUI_renderer, surf);
////
//// if (rect != NULL) {
//// rect->x = rect->y = 0;
//// rect->w = surf->w;
//// rect->h = surf->h;
//// }
////
//// SDL_FreeSurface(surf);
//// return tex;
//// }
//
// return NULL;
//}
static void sk_release_direct_surface_storage(void* pixels, void* context){
if (pixels == context) {
SkDebugf("expected release context\n");
}
sk_free(pixels);
}
static sk_sp<SkSurface> MakeRasterDirectReleaseProc(int w, int h){
SkImageInfo imageInfo = SkImageInfo::Make(w, h, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kUnpremul_SkAlphaType);
size_t pixelLen = w * h * 4; // // it's 8888, so 4 bytes per pixel
void* pixelPtr = sk_malloc_throw(pixelLen); //sk_malloc_canfail(pixelLen);
if(pixelPtr){
sk_sp<SkSurface> surface(SkSurface::MakeRasterDirectReleaseProc(imageInfo, pixelPtr, w*4,
sk_release_direct_surface_storage, pixelPtr));
return surface;
}
return nullptr;
}
sk_sp<SkImage> GUI_IconView::createImageFromUnicode(Uint16 unicode, GUI_Rect* rect){
SkUnichar c = unicode;
uint16_t g = font.unicharToGlyph(c);
SkPath path;
font.getPath(g, &path);
SkRect bounds = path.getBounds();
if(rect){
rect->x = bounds.x();
rect->y = bounds.y();
rect->w = bounds.width();
rect->h = bounds.height();
}
auto surface = MakeRasterDirectReleaseProc(bounds.width(), bounds.height());
auto canvas = surface->getCanvas();
canvas->translate(-bounds.x(), -bounds.y());
SkPaint p;
canvas->clear(cClear);
canvas->drawPath(path, p);
canvas->flush();
return surface->makeImageSnapshot();
}
bool GUI_IconView::eventHandler(SDL_Event*event) {
switch (event->type) {
case GUI_FontChanged:
{
std::string fn;
fn = _fontName;
int fs = _fontSize;
if( fs == 0 ) {
fs = GUI_GetUIIconFontSize();
}
std::string fontPath = std::string("fonts/")+fn;
font = GUI_Fonts::getFont(fn, fs);
updateContent();
updateSize();
break;
}
default:
{
return GUI_ImageView::eventHandler(event);
}
}
return false;
}
| 29.238411 | 144 | 0.591846 | ILW000 |
1e6ef06b32dd37d7a572de735ba700ce3ff1bea6 | 1,595 | cpp | C++ | Chapitre 8 - Avec Assimp/PetitMoteur3D/TurtleGo.cpp | KeikakuB/grand-turtle-racing | b9a19ac1d9056ff582a63e2a5e4782b6fdc4d53b | [
"Apache-2.0"
] | null | null | null | Chapitre 8 - Avec Assimp/PetitMoteur3D/TurtleGo.cpp | KeikakuB/grand-turtle-racing | b9a19ac1d9056ff582a63e2a5e4782b6fdc4d53b | [
"Apache-2.0"
] | null | null | null | Chapitre 8 - Avec Assimp/PetitMoteur3D/TurtleGo.cpp | KeikakuB/grand-turtle-racing | b9a19ac1d9056ff582a63e2a5e4782b6fdc4d53b | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "TurtleGo.h"
#include "IPoseComponentInterface.h"
#include "SimulationComponentBase.h"
#include "HealthComponent.h"
#include "MeshRenderComponent.h"
#include "CelMeshRenderComponent.h"
#include "LambdaUpdateComponent.h"
#include "ISimulationManager.h"
#include "TurtleUpdateComponent.h"
#include "Ids.h"
#include "CollisionTypes.h"
#include "IGameLogicManager.h"
using namespace physx;
namespace PM3D
{
TurtleGo::TurtleGo()
{
}
void TurtleGo::OnSpawn(const physx::PxTransform& pose)
{
auto logic_manager = Game<IGameLogicManager>();
if ( logic_manager )
{
logic_manager->SetTurtlePose(pose);
}
auto simulationComponent = AddComponent<DynamicSimulationComponent>();
simulationComponent->SetTransform(pose);
auto &pxActor = simulationComponent->pxActor();
physx_material_ = physx::unique_ptr<PxMaterial>{
Game<ISimulationManager>()->physics().createMaterial(1.0f, 1.0f, 0.1f)
};
PxVec3 block_size{ 30, 30, 10 };
PxShape *actorShape = pxActor.createShape(PxBoxGeometry(block_size / 2), *physx_material_, PxTransform{ 0, 0, 0 });
PxFilterData filterData;
filterData.word0 = CollisionTypes::kPlayer;
filterData.word1 = CollisionTypes::kTerrain | CollisionTypes::kObstacle;
actorShape->setSimulationFilterData(filterData);
PxRigidBodyExt::updateMassAndInertia(pxActor, 10, &PxVec3{ 0, 0, -15 });
AddComponent<HealthComponent>(2000);
AddComponent<TurtleUpdateComponent>();
AddComponent<CelMeshRenderComponent>(ids::models::kTurtle)->SetLodOptimizability(false);
}
} | 30.673077 | 119 | 0.737931 | KeikakuB |
1e74d16d3ad55a9ac60c20a3ae075e55c5a07370 | 11,327 | cc | C++ | test/ttre.cc | jahan-addison/ttre | e79eff9b45ccfc7d661df5cb36c2f792a38e08d5 | [
"Apache-2.0"
] | null | null | null | test/ttre.cc | jahan-addison/ttre | e79eff9b45ccfc7d661df5cb36c2f792a38e08d5 | [
"Apache-2.0"
] | null | null | null | test/ttre.cc | jahan-addison/ttre | e79eff9b45ccfc7d661df5cb36c2f792a38e08d5 | [
"Apache-2.0"
] | null | null | null | #include <test/catch.h>
#include <ttre/ttre.h>
#include <iostream>
using namespace ttre;
struct NFA_Fixture
{
NFA nfa;
NFA_Fixture(NFA_Fixture const&) = delete;
explicit NFA_Fixture(std::string_view str) : nfa(util::construct_NFA_from_regular_expression(str))
{};
};
Edge::Node assert_and_get_state_exists_by_id(std::set<Edge::Node> const& items, unsigned short id)
{
auto search = std::ranges::find_if(items.begin(), items.end(),
[&id](Edge::Node const& search) -> bool {
return search->id == id;
});
if (search == items.end())
WARN("id " << id << " not found");
REQUIRE(search != items.end());
return *search;
}
TEST_CASE("ttre::util::epsilon_closure : overload 1 : kleene star case 1")
{
auto fixture_1 = NFA_Fixture("a*bb");
auto test = util::epsilon_closure(fixture_1.nfa, fixture_1.nfa.start);
CHECK(test.size() == 1);
assert_and_get_state_exists_by_id(test, 2);
test = util::epsilon_closure(fixture_1.nfa, *test.begin());
CHECK(test.size() == 2);
test = util::epsilon_closure(fixture_1.nfa, assert_and_get_state_exists_by_id(fixture_1.nfa.states, 2));
CHECK(test.size() == 2);
assert_and_get_state_exists_by_id(test, 4);
assert_and_get_state_exists_by_id(test, 0);
}
TEST_CASE("ttre::util::epsilon_closure : overload 1 : kleene star case 2")
{
auto fixture_1 = NFA_Fixture("a*");
auto test = util::epsilon_closure(fixture_1.nfa, fixture_1.nfa.start);
CHECK(test.size() == 3);
assert_and_get_state_exists_by_id(test, 3);
assert_and_get_state_exists_by_id(test, 1);
assert_and_get_state_exists_by_id(test, 1);
}
TEST_CASE("ttre::util::epsilon_closure : overload 1 : character case")
{
auto fixture_1 = NFA_Fixture("a");
auto test = util::epsilon_closure(fixture_1.nfa, fixture_1.nfa.start);
CHECK(test.size() == 1);
}
TEST_CASE("ttre::util::epsilon_closure : overload 1 : union case 1")
{
auto fixture_1 = NFA_Fixture("a|b");
auto test = util::epsilon_closure(fixture_1.nfa, fixture_1.nfa.start);
CHECK(test.size() == 2);
assert_and_get_state_exists_by_id(test, 5);
assert_and_get_state_exists_by_id(test, 2);
}
TEST_CASE("ttre::util::epsilon_closure : overload 1 : union case 2")
{
auto fixture_1 = NFA_Fixture("a*|b");
auto test = util::epsilon_closure(fixture_1.nfa, fixture_1.nfa.start);
CHECK(test.size() == 3);
assert_and_get_state_exists_by_id(test, 4);
assert_and_get_state_exists_by_id(test, 7);
assert_and_get_state_exists_by_id(test, 5);
}
TEST_CASE("ttre::util::epsilon_closure : overload 1 : concatenation case")
{
auto fixture_1 = NFA_Fixture("aaa");
auto test = util::epsilon_closure(fixture_1.nfa, fixture_1.nfa.start);
CHECK(test.size() == 1);
}
TEST_CASE("ttre::util::epsilon_closure : overload 2 : case 1")
{
auto fixture_1 = NFA_Fixture("a*bb");
std::set<Edge::Node> states = {
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 0),
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 1),
};
auto test = util::epsilon_closure(fixture_1.nfa, states);
CHECK(test.size() == 2);
assert_and_get_state_exists_by_id(test, 0);
}
TEST_CASE("ttre::util::epsilon_closure : overload 2 : case 2")
{
auto fixture_1 = NFA_Fixture("a*|bb");
std::set<Edge::Node> states = {
fixture_1.nfa.start,
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 5),
};
auto test = util::epsilon_closure(fixture_1.nfa, states);
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 12);
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 4);
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 7);
assert_and_get_state_exists_by_id(fixture_1.nfa.states, 5);
}
TEST_CASE("ttre::util::transition : union case 1")
{
auto fixture_1 = NFA_Fixture("(ab)|cde");
auto states = util::transition(fixture_1.nfa, fixture_1.nfa.states, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 5);
assert_and_get_state_exists_by_id(states, 4);
states = util::transition(fixture_1.nfa, states, 'b');
CHECK(states.size() == 1);
assert_and_get_state_exists_by_id(states, 14);
states = util::transition(fixture_1.nfa, fixture_1.nfa.states, 'c');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 10);
assert_and_get_state_exists_by_id(states, 9);
states = util::transition(fixture_1.nfa, states, 'd');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 11);
assert_and_get_state_exists_by_id(states, 12);
states = util::transition(fixture_1.nfa, states, 'e');
CHECK(states.size() == 1);
assert_and_get_state_exists_by_id(states, 14);
}
TEST_CASE("ttre::util::transition : union case 2")
{
auto fixture_1 = NFA_Fixture("ab|aaa");
auto states = util::transition(fixture_1.nfa, fixture_1.nfa.states, 'a');
states = util::transition(fixture_1.nfa, fixture_1.nfa.states, 'b');
CHECK(states.size() == 1);
assert_and_get_state_exists_by_id(states, 14);
states = util::transition(fixture_1.nfa, fixture_1.nfa.states, 'a');
states = util::transition(fixture_1.nfa, states, 'a');
states = util::transition(fixture_1.nfa, states, 'a');
CHECK(states.size() == 1);
assert_and_get_state_exists_by_id(states, 14);
}
TEST_CASE("ttre::util::transition : union case 3")
{
// auto fixture_1 = NFA_Fixture("ab*");
// auto states = util::transition(fixture_1.nfa, fixture_1.nfa.states, 'a');
// states = util::transition(fixture_1.nfa, states, 'b');
}
TEST_CASE("ttre::util::transition : kleene star case 1")
{
auto fixture_1 = NFA_Fixture("(acab)*");
auto states = util::transition(fixture_1.nfa, {fixture_1.nfa.start}, 'b');
CHECK(states.size() == 0);
states = util::transition(fixture_1.nfa, {fixture_1.nfa.start}, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 2);
assert_and_get_state_exists_by_id(states, 3);
auto test = util::transition(fixture_1.nfa, states, 'b');
CHECK(test.size() == 0);
states = util::transition(fixture_1.nfa, states, 'c');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 4);
assert_and_get_state_exists_by_id(states, 5);
states = util::transition(fixture_1.nfa, states, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 6);
assert_and_get_state_exists_by_id(states, 7);
states = util::transition(fixture_1.nfa, states, 'b');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 7);
assert_and_get_state_exists_by_id(states, 0);
// test the cyclic edge of the transition graph
states = util::transition(fixture_1.nfa, states, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 2);
assert_and_get_state_exists_by_id(states, 3);
}
TEST_CASE("ttre::util::transition : concatenation case")
{
auto fixture_1 = NFA_Fixture("aaaa*");
auto states = util::transition(fixture_1.nfa, {fixture_1.nfa.start}, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 2);
assert_and_get_state_exists_by_id(states, 3);
states = util::transition(fixture_1.nfa, states, 'a');
auto cyclic = assert_and_get_state_exists_by_id(fixture_1.nfa.states, 5);
states = util::transition(fixture_1.nfa, {cyclic}, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 5);
assert_and_get_state_exists_by_id(states, 7);
}
TEST_CASE("ttre::util::transition : strong case")
{
auto fixture_1 = NFA_Fixture("(ab)*|cd|abc");
auto states = util::transition(fixture_1.nfa, {fixture_1.nfa.states}, 'a');
CHECK(states.size() == 4);
assert_and_get_state_exists_by_id(states, 24);
assert_and_get_state_exists_by_id(states, 8);
assert_and_get_state_exists_by_id(states, 6);
assert_and_get_state_exists_by_id(states, 25);
auto states_1 = util::transition(fixture_1.nfa, states, 'b');
CHECK(states_1.size() == 4);
// cyclic edges:
assert_and_get_state_exists_by_id(states_1, 8);
assert_and_get_state_exists_by_id(states_1, 9);
// "c"
assert_and_get_state_exists_by_id(states_1, 27);
assert_and_get_state_exists_by_id(states_1, 26);
states = util::transition(fixture_1.nfa, states_1, 'c');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 28);
assert_and_get_state_exists_by_id(states, 29);
states = util::transition(fixture_1.nfa, {fixture_1.nfa.states}, 'c');
CHECK(states.size() == 4);
assert_and_get_state_exists_by_id(states, 15);
assert_and_get_state_exists_by_id(states, 16);
assert_and_get_state_exists_by_id(states, 29);
assert_and_get_state_exists_by_id(states, 28);
states = util::transition(fixture_1.nfa, states, 'd');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 17);
assert_and_get_state_exists_by_id(states, 29);
}
// TEST_CASE("ttre::util::transition : kleene star case 2")
// {
// auto fixture_1 = NFA_Fixture("(ac)*bb");
// auto states = util::transition(fixture_1.nfa, {fixture_1.nfa.states}, 'a');
// util::print_NFA(fixture_1.nfa, "(ac)*bb");
// util::print_states(states);
// CHECK(states.size() == 2);
// assert_and_get_state_exists_by_id(states, 2);
// assert_and_get_state_exists_by_id(states, 3);
// states = util::transition(fixture_1.nfa, states, 'c');
// assert_and_get_state_exists_by_id(states, 0); // the cyclic edge
// assert_and_get_state_exists_by_id(states, 3);
// states = util::transition(fixture_1.nfa, {assert_and_get_state_exists_by_id(fixture_1.nfa.states, 4)}, 'b');
// CHECK(states.size() == 1);
// assert_and_get_state_exists_by_id(states, 7);
// states = util::transition(fixture_1.nfa, states, 'b');
// CHECK(states.size() == 1);
// assert_and_get_state_exists_by_id(states, 7);
// }
TEST_CASE("ttre::util::transition : kleene star case 3")
{
auto fixture_1 = NFA_Fixture("aac*bb");
auto states = util::transition(fixture_1.nfa, {fixture_1.nfa.states}, 'a');
CHECK(states.size() == 3);
assert_and_get_state_exists_by_id(states, 2);
assert_and_get_state_exists_by_id(states, 3);
assert_and_get_state_exists_by_id(states, 6);
states = util::transition(fixture_1.nfa, states, 'a');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 6);
assert_and_get_state_exists_by_id(states, 3);
states = util::transition(fixture_1.nfa, states, 'c');
CHECK(states.size() == 2);
assert_and_get_state_exists_by_id(states, 6);
assert_and_get_state_exists_by_id(states, 3);
states = util::transition(fixture_1.nfa, {assert_and_get_state_exists_by_id(fixture_1.nfa.states, 6)}, 'b');
CHECK(states.size() == 1);
assert_and_get_state_exists_by_id(states, 9);
states = util::transition(fixture_1.nfa, states, 'b');
CHECK(states.size() == 1);
assert_and_get_state_exists_by_id(states, 9);
}
TEST_CASE("ttre::match")
{
//print<"abc|aaa">();
//std::cout << std::boolalpha << " " << match<"abc|aaa">("abc");
print<"abc|def">();
CHECK(match<"abc|aaa">("abc") == true);
}
| 34.11747 | 115 | 0.690651 | jahan-addison |
1e7621afd0524730fc90776b57a2d30426f3b883 | 2,392 | cpp | C++ | src/test/entity.t.cpp | bkentel/boken-old | 8967856be5f283989d0c10843bcb739728423152 | [
"MIT"
] | null | null | null | src/test/entity.t.cpp | bkentel/boken-old | 8967856be5f283989d0c10843bcb739728423152 | [
"MIT"
] | null | null | null | src/test/entity.t.cpp | bkentel/boken-old | 8967856be5f283989d0c10843bcb739728423152 | [
"MIT"
] | 1 | 2020-04-11T12:20:00.000Z | 2020-04-11T12:20:00.000Z | #if !defined(BK_NO_TESTS)
#include "catch.hpp"
#include "entity.hpp"
#include "entity_def.hpp"
#include <algorithm>
#include <array>
#include <vector>
TEST_CASE("property_set") {
using namespace boken;
enum class test_enum {
a, b, c, d, e
};
property_set<test_enum, char> properties;
REQUIRE(properties.size() == 0u);
REQUIRE(properties.empty());
REQUIRE(properties.begin() == properties.end());
REQUIRE(5 == properties.add_or_update_properties({
{test_enum::e, 'e'}
, {test_enum::d, 'd'}
, {test_enum::c, 'c'}
, {test_enum::b, 'b'}
, {test_enum::a, 'a'}
}));
REQUIRE(properties.size() == 5u);
REQUIRE(!properties.empty());
REQUIRE(std::distance(properties.begin(), properties.end()) == 5);
REQUIRE(properties.value_or(test_enum::a, '\0') == 'a');
REQUIRE(properties.value_or(test_enum::b, '\0') == 'b');
REQUIRE(properties.value_or(test_enum::c, '\0') == 'c');
REQUIRE(properties.value_or(test_enum::d, '\0') == 'd');
REQUIRE(properties.value_or(test_enum::e, '\0') == 'e');
SECTION("remove values") {
auto size = properties.size();
auto const remove = [&](test_enum const e) {
return properties.has_property(e)
&& properties.remove_property(e)
&& (properties.size() == --size)
&& (properties.value_or(e, '\0') == '\0');
};
REQUIRE(remove(test_enum::a));
REQUIRE(remove(test_enum::d));
REQUIRE(remove(test_enum::b));
REQUIRE(remove(test_enum::e));
REQUIRE(remove(test_enum::c));
REQUIRE(properties.empty());
REQUIRE(properties.size() == 0);
}
SECTION("insert duplicates") {
REQUIRE(0 == properties.add_or_update_properties({
{test_enum::e, 'f'}
, {test_enum::d, 'e'}
, {test_enum::c, 'd'}
, {test_enum::b, 'c'}
, {test_enum::a, 'b'}
}));
REQUIRE(properties.size() == 5u);
REQUIRE(properties.value_or(test_enum::a, '\0') == 'b');
REQUIRE(properties.value_or(test_enum::b, '\0') == 'c');
REQUIRE(properties.value_or(test_enum::c, '\0') == 'd');
REQUIRE(properties.value_or(test_enum::d, '\0') == 'e');
REQUIRE(properties.value_or(test_enum::e, '\0') == 'f');
}
}
#endif // !defined(BK_NO_TESTS)
| 28.819277 | 70 | 0.559783 | bkentel |
1e764c80fcbaf1ef35c4c59ca1b9429c98484065 | 661 | cc | C++ | solved/two-sum.cc | vizee/leetcode | 26c44eee5dd1fcb84fa697db650b01732a6ce79e | [
"MIT"
] | null | null | null | solved/two-sum.cc | vizee/leetcode | 26c44eee5dd1fcb84fa697db650b01732a6ce79e | [
"MIT"
] | null | null | null | solved/two-sum.cc | vizee/leetcode | 26c44eee5dd1fcb84fa697db650b01732a6ce79e | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> m(nums);
sort(m.begin(), m.end());
vector<int> r;
for (size_t i = 0; i < nums.size() && r.empty(); i++) {
auto v = target - nums[i];
auto p = lower_bound(m.begin(), m.end(), v);
if (v != *p) {
continue;
}
for (auto j = 0; j < nums.size(); j++) {
if (nums[j] == v && j != i) {
r.push_back(i);
r.push_back(j);
break;
}
}
}
return r;
}
};
| 27.541667 | 63 | 0.361573 | vizee |
1e76b079caf308566d7d86d2051496dd595b7f41 | 954 | cpp | C++ | source/vec2.cpp | Snoopyxxel/programmiersprachen-aufgabenblatt-2 | 3fb4cd58296e951cfe48ae88796b23961082de94 | [
"MIT"
] | null | null | null | source/vec2.cpp | Snoopyxxel/programmiersprachen-aufgabenblatt-2 | 3fb4cd58296e951cfe48ae88796b23961082de94 | [
"MIT"
] | null | null | null | source/vec2.cpp | Snoopyxxel/programmiersprachen-aufgabenblatt-2 | 3fb4cd58296e951cfe48ae88796b23961082de94 | [
"MIT"
] | null | null | null | #include "vec2.hpp"
Vec2 &Vec2::operator+=(Vec2 const &v) {
this->x = this->x + v.x;
this->y = this->y + v.y;
return *this;
}
Vec2 &Vec2::operator-=(Vec2 const &v) {
this->x = this->x - v.x;
this->y = this->y - v.y;
return *this;
}
Vec2 &Vec2::operator*=(float s) {
this->x = this->x * s;
this->y = this->y * s;
return *this;
}
Vec2 &Vec2::operator/=(float s) {
this->x = this->x / s;
this->y = this->y / s;
return *this;
}
Vec2 operator+(Vec2 const &u, Vec2 const &v) {
Vec2 erg{u.x + v.x, u.y + v.y};
return erg;
}
Vec2 operator-(Vec2 const &u, Vec2 const &v) {
Vec2 erg{u.x - v.x, u.y - v.y};
return erg;
}
Vec2 operator*(Vec2 const &v, float s){
Vec2 erg{v.x * s, v.y * s};
return erg;
}
Vec2 operator/(Vec2 const &v, float s) {
Vec2 erg{v.x / s, v.y / s};
return erg;
}
Vec2 operator*(float s, Vec2 const &v) {
Vec2 erg{v.x * s, v.y * s};
return erg;
} | 19.08 | 46 | 0.528302 | Snoopyxxel |
1e7affc602bb94009091605f7cbbe0a8d7d48ec9 | 71 | cpp | C++ | extensions/nsplugin/src/npwin.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 18 | 2018-02-16T16:57:26.000Z | 2022-02-10T21:23:47.000Z | extensions/nsplugin/src/npwin.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 2 | 2018-08-12T12:46:38.000Z | 2020-06-19T16:30:06.000Z | extensions/nsplugin/src/npwin.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 7 | 2018-06-22T01:17:58.000Z | 2021-09-02T21:05:28.000Z | #error "This file is provided by Netscape. Please see documentation."
| 35.5 | 70 | 0.774648 | sandsmark |
1e8284b1de226497a3f68e2aee7a299a29c50ad5 | 405 | cpp | C++ | Battleships/Source/Core/Input/FInput.cpp | RodrigoHolztrattner/Battleships | cf3e9c8a4a40f52aee41a7b9baaac5a406365a06 | [
"MIT"
] | 3 | 2018-04-09T13:01:07.000Z | 2021-03-18T12:28:48.000Z | Battleships/Source/Core/Input/FInput.cpp | RodrigoHolztrattner/Battleships | cf3e9c8a4a40f52aee41a7b9baaac5a406365a06 | [
"MIT"
] | null | null | null | Battleships/Source/Core/Input/FInput.cpp | RodrigoHolztrattner/Battleships | cf3e9c8a4a40f52aee41a7b9baaac5a406365a06 | [
"MIT"
] | 1 | 2021-03-18T12:28:50.000Z | 2021-03-18T12:28:50.000Z | ///////////////////////////////////////////////////////////////////////////////
// Filename: FInput.cpp
///////////////////////////////////////////////////////////////////////////////
#include "FInput.h"
FInput::FInput()
{
}
FInput::FInput(const FInput& other)
{
}
FInput::~FInput()
{
}
////////////
// GLOBAL //
////////////
// Declare the message array
TArray<InputMessage> FInput::m_InputMessages; | 17.608696 | 79 | 0.37037 | RodrigoHolztrattner |
1e8292c55a655b1215ac7812dbf6636205efee25 | 132 | cpp | C++ | Source/Event/twEventArgs.cpp | microqq/TwinkleGraphics | e3975dc6dad5b6b8d5db1d54e30e815072db162e | [
"MIT"
] | null | null | null | Source/Event/twEventArgs.cpp | microqq/TwinkleGraphics | e3975dc6dad5b6b8d5db1d54e30e815072db162e | [
"MIT"
] | 1 | 2020-07-03T03:13:39.000Z | 2020-07-03T03:13:39.000Z | Source/Event/twEventArgs.cpp | microqq/TwinkleGraphics | e3975dc6dad5b6b8d5db1d54e30e815072db162e | [
"MIT"
] | null | null | null | #include "twEventArgs.h"
namespace TwinkleGraphics
{
BaseEventArgs::~BaseEventArgs() {}
} // namespace TwinkleGraphics
| 16.5 | 39 | 0.704545 | microqq |
1e843fbe9d97b9986b55625d9d73c48da627b571 | 3,207 | hxx | C++ | OCC/opencascade-7.2.0/x64/debug/inc/BRepExtrema_TriangleSet.hxx | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 2 | 2020-02-21T01:04:35.000Z | 2020-02-21T03:35:37.000Z | OCC/opencascade-7.2.0/x64/debug/inc/BRepExtrema_TriangleSet.hxx | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | OCC/opencascade-7.2.0/x64/debug/inc/BRepExtrema_TriangleSet.hxx | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2021-11-21T13:03:26.000Z | 2021-11-21T13:03:26.000Z | // Created on: 2014-10-20
// Created by: Denis BOGOLEPOV
// Copyright (c) 2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepExtrema_TriangleSet_HeaderFile
#define _BRepExtrema_TriangleSet_HeaderFile
#include <TopoDS_Face.hxx>
#include <BVH_PrimitiveSet3d.hxx>
//! List of shapes and their IDs for collision detection.
typedef NCollection_Vector<TopoDS_Face> BRepExtrema_ShapeList;
//! Triangle set corresponding to specific face.
class BRepExtrema_TriangleSet : public BVH_PrimitiveSet3d
{
public:
//! Creates empty triangle set.
Standard_EXPORT BRepExtrema_TriangleSet();
//! Creates triangle set from the given face.
Standard_EXPORT BRepExtrema_TriangleSet (const BRepExtrema_ShapeList& theFaces);
//! Releases resources of triangle set.
Standard_EXPORT ~BRepExtrema_TriangleSet();
public: //! @name methods implementing BVH set interface
//! Returns total number of triangles.
Standard_EXPORT Standard_Integer Size() const Standard_OVERRIDE;
//! Returns AABB of the given triangle.
Standard_EXPORT BVH_Box<Standard_Real, 3> Box (const Standard_Integer theIndex) const Standard_OVERRIDE;
//! Make inherited method Box() visible to avoid CLang warning
using BVH_PrimitiveSet3d::Box;
//! Returns centroid position along specified axis.
Standard_EXPORT Standard_Real Center (const Standard_Integer theIndex, const Standard_Integer theAxis) const Standard_OVERRIDE;
//! Swaps indices of two specified triangles.
Standard_EXPORT void Swap (const Standard_Integer theIndex1, const Standard_Integer theIndex2) Standard_OVERRIDE;
public:
//! Clears triangle set data.
Standard_EXPORT void Clear();
//! Initializes triangle set.
Standard_EXPORT Standard_Boolean Init (const BRepExtrema_ShapeList& theFaces);
//! Returns vertices of the given triangle.
Standard_EXPORT void GetVertices (const Standard_Integer theIndex,
BVH_Vec3d& theVertex1,
BVH_Vec3d& theVertex2,
BVH_Vec3d& theVertex3) const;
//! Returns face ID of the given triangle.
Standard_EXPORT Standard_Integer GetFaceID (const Standard_Integer theIndex) const;
protected:
//! Array of vertex indices.
BVH_Array4i myTriangles;
//! Array of vertex UV params.
BVH_Array2d myVertUVArray;
//! Array of vertex coordinates.
BVH_Array3d myVertexArray;
public:
DEFINE_STANDARD_RTTIEXT(BRepExtrema_TriangleSet, BVH_PrimitiveSet3d)
};
DEFINE_STANDARD_HANDLE(BRepExtrema_TriangleSet, BVH_PrimitiveSet3d)
#endif // _BRepExtrema_TriangleSet_HeaderFile
| 34.483871 | 129 | 0.757406 | jiaguobing |
1e8551759b0584a07ea62c464dc5c9ff7a83042c | 1,954 | cc | C++ | policies/DIF/RMT/MaxQueue/ReadRateReducer/ReadRateReducer.cc | AthirahJohar/RINASIM | 70b0d83e243b0d4d6949efcd36d5dc4ead94356c | [
"MIT"
] | null | null | null | policies/DIF/RMT/MaxQueue/ReadRateReducer/ReadRateReducer.cc | AthirahJohar/RINASIM | 70b0d83e243b0d4d6949efcd36d5dc4ead94356c | [
"MIT"
] | null | null | null | policies/DIF/RMT/MaxQueue/ReadRateReducer/ReadRateReducer.cc | AthirahJohar/RINASIM | 70b0d83e243b0d4d6949efcd36d5dc4ead94356c | [
"MIT"
] | null | null | null | //
// Copyright © 2014 - 2015 PRISTINE Consortium (http://ict-pristine.eu)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <ReadRateReducer.h>
Define_Module(ReadRateReducer);
void ReadRateReducer::onPolicyInit()
{
fwd = check_and_cast<IntPDUForwarding*>
(getModuleByPath("^.pduForwardingPolicy"));
}
bool ReadRateReducer::run(RMTQueue* queue)
{
if (queue->getLength() >= queue->getMaxLength())
{
if (queue->getType() == RMTQueue::OUTPUT)
{
const PDU* pdu = dynamic_cast<const PDU*>(queue->getLastPDU());
// this isn't optimal, but there doesn't seem to be a better way to
// get output->input port mapping in connection-less forwarding
RMTPorts inputPorts = fwd->lookup(pdu);
if (!inputPorts.front()->hasBlockedInput())
{ // block read from the input port
inputPorts.front()->blockInput();
}
}
}
return false;
}
void ReadRateReducer::onQueueLengthDrop(RMTQueue* queue)
{
const PDU* pdu = dynamic_cast<const PDU*>(queue->getLastPDU());
RMTPorts inputPorts = fwd->lookup(pdu);
if (inputPorts.front()->hasBlockedInput())
{ // the output buffers are keeping up again, continue receiving on input
inputPorts.front()->unblockInput();
}
}
| 32.032787 | 79 | 0.670931 | AthirahJohar |
1e89ac184ae18ab37f7863155401aed4bbce92f5 | 56,756 | cc | C++ | chrome/browser/extensions/extension_toolbar_model_unittest.cc | sunjc53yy/chromium | 049b380040949089c2a6e447b0cd0ac3c4ece38e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/extension_toolbar_model_unittest.cc | sunjc53yy/chromium | 049b380040949089c2a6e447b0cd0ac3c4ece38e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/extension_toolbar_model_unittest.cc | sunjc53yy/chromium | 049b380040949089c2a6e447b0cd0ac3c4ece38e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "chrome/browser/extensions/extension_action_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/extensions/extension_toolbar_model_factory.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/test_extension_dir.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "components/crx_file/id_util.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/value_builder.h"
#if defined(USE_AURA)
#include "ui/aura/env.h"
#endif
namespace extensions {
namespace {
// A helper class to create test web contents (tabs) for unit tests, without
// inheriting from RenderViewTestHarness. Can create web contents, and will
// clean up after itself upon destruction. Owns all created web contents.
// A few notes:
// - Works well allocated on the stack, because it should be destroyed before
// associated browser context.
// - Doesn't play nice with web contents created any other way (because of
// the implementation of RenderViewHostTestEnabler). But if you are creating
// web contents already, what do you need this for? ;)
// - This will call aura::Env::Create/DeleteInstance(), because that's needed
// for web contents. Nothing else should call it first. (This could be
// tweaked by passing in a flag, if there's need.)
// TODO(devlin): Look around and see if this class is needed elsewhere; if so,
// move it there and expand the API a bit (methods to, e.g., delete/close a
// web contents, access existing web contents, etc).
class TestWebContentsFactory {
public:
TestWebContentsFactory();
~TestWebContentsFactory();
// Creates a new WebContents with the given |context|, and returns it.
content::WebContents* CreateWebContents(content::BrowserContext* context);
private:
// The test factory (and friends) for creating test web contents.
scoped_ptr<content::RenderViewHostTestEnabler> rvh_enabler_;
// The vector of web contents that this class created.
ScopedVector<content::WebContents> web_contents_;
DISALLOW_COPY_AND_ASSIGN(TestWebContentsFactory);
};
TestWebContentsFactory::TestWebContentsFactory()
: rvh_enabler_(new content::RenderViewHostTestEnabler()) {
#if defined(USE_AURA)
aura::Env::CreateInstance(true);
#endif
}
TestWebContentsFactory::~TestWebContentsFactory() {
web_contents_.clear();
// Let any posted tasks for web contents deletion run.
base::RunLoop().RunUntilIdle();
rvh_enabler_.reset();
// Let any posted tasks for RenderProcess/ViewHost deletion run.
base::RunLoop().RunUntilIdle();
#if defined(USE_AURA)
aura::Env::DeleteInstance();
#endif
}
content::WebContents* TestWebContentsFactory::CreateWebContents(
content::BrowserContext* context) {
scoped_ptr<content::WebContents> web_contents(
content::WebContentsTester::CreateTestWebContents(context, nullptr));
DCHECK(web_contents);
web_contents_.push_back(web_contents.release());
return web_contents_.back();
}
// Creates a new ExtensionToolbarModel for the given |context|.
KeyedService* BuildToolbarModel(content::BrowserContext* context) {
return new ExtensionToolbarModel(Profile::FromBrowserContext(context),
ExtensionPrefs::Get(context));
}
// Given a |profile|, assigns the testing keyed service function to
// BuildToolbarModel() and uses it to create and initialize a new
// ExtensionToolbarModel.
// |wait_for_ready| indicates whether or not to post the ExtensionSystem's
// ready task.
ExtensionToolbarModel* CreateToolbarModelForProfile(Profile* profile,
bool wait_for_ready) {
ExtensionToolbarModel* model = ExtensionToolbarModel::Get(profile);
if (model)
return model;
// No existing model means it's a new profile (since we, by default, don't
// create the ToolbarModel in testing).
ExtensionToolbarModelFactory::GetInstance()->SetTestingFactory(
profile, &BuildToolbarModel);
model = ExtensionToolbarModel::Get(profile);
if (wait_for_ready) {
// Fake the extension system ready signal.
// HACK ALERT! In production, the ready task on ExtensionSystem (and most
// everything else on it, too) is shared between incognito and normal
// profiles, but a TestExtensionSystem doesn't have the concept of "shared".
// Because of this, we have to set any new profile's TestExtensionSystem's
// ready task, too.
static_cast<TestExtensionSystem*>(ExtensionSystem::Get(profile))->
SetReady();
// Run tasks posted to TestExtensionSystem.
base::RunLoop().RunUntilIdle();
}
return model;
}
// Create an extension. If |action_key| is non-NULL, it should point to either
// kBrowserAction or kPageAction, and the extension will have the associated
// action.
scoped_refptr<const Extension> GetActionExtension(const std::string& name,
const char* action_key) {
DictionaryBuilder manifest;
manifest.Set("name", name)
.Set("description", "An extension")
.Set("manifest_version", 2)
.Set("version", "1.0.0");
if (action_key)
manifest.Set(action_key, DictionaryBuilder().Pass());
return ExtensionBuilder().SetManifest(manifest.Pass())
.SetID(crx_file::id_util::GenerateId(name))
.Build();
}
// A simple observer that tracks the number of times certain events occur.
class ExtensionToolbarModelTestObserver
: public ExtensionToolbarModel::Observer {
public:
explicit ExtensionToolbarModelTestObserver(ExtensionToolbarModel* model);
~ExtensionToolbarModelTestObserver() override;
size_t inserted_count() const { return inserted_count_; }
size_t removed_count() const { return removed_count_; }
size_t moved_count() const { return moved_count_; }
int highlight_mode_count() const { return highlight_mode_count_; }
size_t initialized_count() const { return initialized_count_; }
size_t reorder_count() const { return reorder_count_; }
private:
// ExtensionToolbarModel::Observer:
void ToolbarExtensionAdded(const Extension* extension, int index) override {
++inserted_count_;
}
void ToolbarExtensionRemoved(const Extension* extension) override {
++removed_count_;
}
void ToolbarExtensionMoved(const Extension* extension, int index) override {
++moved_count_;
}
void ToolbarExtensionUpdated(const Extension* extension) override {}
bool ShowExtensionActionPopup(const Extension* extension,
bool grant_active_tab) override {
return false;
}
void ToolbarVisibleCountChanged() override {}
void ToolbarHighlightModeChanged(bool is_highlighting) override {
// Add one if highlighting, subtract one if not.
highlight_mode_count_ += is_highlighting ? 1 : -1;
}
void OnToolbarModelInitialized() override { ++initialized_count_; }
void OnToolbarReorderNecessary(content::WebContents* web_contents) override {
++reorder_count_;
}
Browser* GetBrowser() override { return NULL; }
ExtensionToolbarModel* model_;
size_t inserted_count_;
size_t removed_count_;
size_t moved_count_;
// Int because it could become negative (if something goes wrong).
int highlight_mode_count_;
size_t initialized_count_;
size_t reorder_count_;
};
ExtensionToolbarModelTestObserver::ExtensionToolbarModelTestObserver(
ExtensionToolbarModel* model) : model_(model),
inserted_count_(0),
removed_count_(0),
moved_count_(0),
highlight_mode_count_(0),
initialized_count_(0),
reorder_count_(0) {
model_->AddObserver(this);
}
ExtensionToolbarModelTestObserver::~ExtensionToolbarModelTestObserver() {
model_->RemoveObserver(this);
}
} // namespace
class ExtensionToolbarModelUnitTest : public ExtensionServiceTestBase {
protected:
// Initialize the ExtensionService, ExtensionToolbarModel, and
// ExtensionSystem.
void Init();
void TearDown() override;
// Adds or removes the given |extension| and verify success.
testing::AssertionResult AddExtension(
const scoped_refptr<const Extension>& extension) WARN_UNUSED_RESULT;
testing::AssertionResult RemoveExtension(
const scoped_refptr<const Extension>& extension) WARN_UNUSED_RESULT;
// Adds three extensions, all with browser actions.
testing::AssertionResult AddBrowserActionExtensions() WARN_UNUSED_RESULT;
// Adds three extensions, one each for browser action, page action, and no
// action, and are added in that order.
testing::AssertionResult AddActionExtensions() WARN_UNUSED_RESULT;
// Returns the extension at the given index in the toolbar model, or NULL
// if one does not exist.
// If |model| is specified, it is used. Otherwise, this defaults to
// |toolbar_model_|.
const Extension* GetExtensionAtIndex(
size_t index, const ExtensionToolbarModel* model) const;
const Extension* GetExtensionAtIndex(size_t index) const;
ExtensionToolbarModel* toolbar_model() { return toolbar_model_; }
const ExtensionToolbarModelTestObserver* observer() const {
return model_observer_.get();
}
size_t num_toolbar_items() const {
return toolbar_model_->toolbar_items().size();
}
const Extension* browser_action_a() const { return browser_action_a_.get(); }
const Extension* browser_action_b() const { return browser_action_b_.get(); }
const Extension* browser_action_c() const { return browser_action_c_.get(); }
const Extension* browser_action() const {
return browser_action_extension_.get();
}
const Extension* page_action() const { return page_action_extension_.get(); }
const Extension* no_action() const { return no_action_extension_.get(); }
private:
// Verifies that all extensions in |extensions| are added successfully.
testing::AssertionResult AddAndVerifyExtensions(
const ExtensionList& extensions);
// The toolbar model associated with the testing profile.
ExtensionToolbarModel* toolbar_model_;
// The test observer to track events. Must come after toolbar_model_ so that
// it is destroyed and removes itself as an observer first.
scoped_ptr<ExtensionToolbarModelTestObserver> model_observer_;
// Sample extensions with only browser actions.
scoped_refptr<const Extension> browser_action_a_;
scoped_refptr<const Extension> browser_action_b_;
scoped_refptr<const Extension> browser_action_c_;
// Sample extensions with different kinds of actions.
scoped_refptr<const Extension> browser_action_extension_;
scoped_refptr<const Extension> page_action_extension_;
scoped_refptr<const Extension> no_action_extension_;
};
void ExtensionToolbarModelUnitTest::Init() {
InitializeEmptyExtensionService();
toolbar_model_ = CreateToolbarModelForProfile(profile(), true);
model_observer_.reset(new ExtensionToolbarModelTestObserver(toolbar_model_));
}
void ExtensionToolbarModelUnitTest::TearDown() {
model_observer_.reset();
ExtensionServiceTestBase::TearDown();
}
testing::AssertionResult ExtensionToolbarModelUnitTest::AddExtension(
const scoped_refptr<const Extension>& extension) {
if (registry()->enabled_extensions().GetByID(extension->id())) {
return testing::AssertionFailure() << "Extension " << extension->name() <<
" already installed!";
}
service()->AddExtension(extension.get());
if (!registry()->enabled_extensions().GetByID(extension->id())) {
return testing::AssertionFailure() << "Failed to install extension: " <<
extension->name();
}
return testing::AssertionSuccess();
}
testing::AssertionResult ExtensionToolbarModelUnitTest::RemoveExtension(
const scoped_refptr<const Extension>& extension) {
if (!registry()->enabled_extensions().GetByID(extension->id())) {
return testing::AssertionFailure() << "Extension " << extension->name() <<
" not installed!";
}
service()->UnloadExtension(extension->id(),
UnloadedExtensionInfo::REASON_DISABLE);
if (registry()->enabled_extensions().GetByID(extension->id())) {
return testing::AssertionFailure() << "Failed to unload extension: " <<
extension->name();
}
return testing::AssertionSuccess();
}
testing::AssertionResult ExtensionToolbarModelUnitTest::AddActionExtensions() {
browser_action_extension_ =
GetActionExtension("browser_action", manifest_keys::kBrowserAction);
page_action_extension_ =
GetActionExtension("page_action", manifest_keys::kPageAction);
no_action_extension_ = GetActionExtension("no_action", NULL);
ExtensionList extensions;
extensions.push_back(browser_action_extension_);
extensions.push_back(page_action_extension_);
extensions.push_back(no_action_extension_);
return AddAndVerifyExtensions(extensions);
}
testing::AssertionResult
ExtensionToolbarModelUnitTest::AddBrowserActionExtensions() {
browser_action_a_ =
GetActionExtension("browser_actionA", manifest_keys::kBrowserAction);
browser_action_b_ =
GetActionExtension("browser_actionB", manifest_keys::kBrowserAction);
browser_action_c_ =
GetActionExtension("browser_actionC", manifest_keys::kBrowserAction);
ExtensionList extensions;
extensions.push_back(browser_action_a_);
extensions.push_back(browser_action_b_);
extensions.push_back(browser_action_c_);
return AddAndVerifyExtensions(extensions);
}
const Extension* ExtensionToolbarModelUnitTest::GetExtensionAtIndex(
size_t index, const ExtensionToolbarModel* model) const {
return index < model->toolbar_items().size()
? model->toolbar_items()[index].get()
: NULL;
}
const Extension* ExtensionToolbarModelUnitTest::GetExtensionAtIndex(
size_t index) const {
return GetExtensionAtIndex(index, toolbar_model_);
}
testing::AssertionResult ExtensionToolbarModelUnitTest::AddAndVerifyExtensions(
const ExtensionList& extensions) {
for (ExtensionList::const_iterator iter = extensions.begin();
iter != extensions.end(); ++iter) {
if (!AddExtension(*iter)) {
return testing::AssertionFailure() << "Failed to install extension: " <<
(*iter)->name();
}
}
return testing::AssertionSuccess();
}
// A basic test for extensions with browser actions showing up in the toolbar.
TEST_F(ExtensionToolbarModelUnitTest, BasicExtensionToolbarModelTest) {
Init();
// Load an extension with no browser action.
scoped_refptr<const Extension> extension1 =
GetActionExtension("no_action", NULL);
ASSERT_TRUE(AddExtension(extension1));
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0u, observer()->inserted_count());
EXPECT_EQ(0u, num_toolbar_items());
EXPECT_EQ(NULL, GetExtensionAtIndex(0u));
// Load an extension with a browser action.
scoped_refptr<const Extension> extension2 =
GetActionExtension("browser_action", manifest_keys::kBrowserAction);
ASSERT_TRUE(AddExtension(extension2));
// We should now find our extension in the model.
EXPECT_EQ(1u, observer()->inserted_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(extension2.get(), GetExtensionAtIndex(0u));
// Should be a no-op, but still fires the events.
toolbar_model()->MoveExtensionIcon(extension2->id(), 0);
EXPECT_EQ(1u, observer()->moved_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(extension2.get(), GetExtensionAtIndex(0u));
// Remove the extension and verify.
ASSERT_TRUE(RemoveExtension(extension2));
EXPECT_EQ(1u, observer()->removed_count());
EXPECT_EQ(0u, num_toolbar_items());
EXPECT_EQ(NULL, GetExtensionAtIndex(0u));
}
// Test various different reorderings, removals, and reinsertions.
TEST_F(ExtensionToolbarModelUnitTest, ExtensionToolbarReorderAndReinsert) {
Init();
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
// Verify the three extensions are in the model in the proper order.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
// Order is now A, B, C. Let's put C first.
toolbar_model()->MoveExtensionIcon(browser_action_c()->id(), 0);
EXPECT_EQ(1u, observer()->moved_count());
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(2u));
// Order is now C, A, B. Let's put A last.
toolbar_model()->MoveExtensionIcon(browser_action_a()->id(), 2);
EXPECT_EQ(2u, observer()->moved_count());
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(2u));
// Order is now C, B, A. Let's remove B.
ASSERT_TRUE(RemoveExtension(browser_action_b()));
EXPECT_EQ(1u, observer()->removed_count());
EXPECT_EQ(2u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(1u));
// Load extension B again.
ASSERT_TRUE(AddExtension(browser_action_b()));
// Extension B loaded again.
EXPECT_EQ(4u, observer()->inserted_count());
EXPECT_EQ(3u, num_toolbar_items());
// Make sure it gets its old spot in the list.
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
// Unload B again.
ASSERT_TRUE(RemoveExtension(browser_action_b()));
EXPECT_EQ(2u, observer()->removed_count());
EXPECT_EQ(2u, num_toolbar_items());
// Order is now C, A. Flip it.
toolbar_model()->MoveExtensionIcon(browser_action_a()->id(), 0);
EXPECT_EQ(3u, observer()->moved_count());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
// Move A to the location it already occupies.
toolbar_model()->MoveExtensionIcon(browser_action_a()->id(), 0);
EXPECT_EQ(4u, observer()->moved_count());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
// Order is now A, C. Remove C.
ASSERT_TRUE(RemoveExtension(browser_action_c()));
EXPECT_EQ(3u, observer()->removed_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
// Load extension C again.
ASSERT_TRUE(AddExtension(browser_action_c()));
// Extension C loaded again.
EXPECT_EQ(5u, observer()->inserted_count());
EXPECT_EQ(2u, num_toolbar_items());
// Make sure it gets its old spot in the list (at the very end).
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
}
// Test that order persists after unloading and disabling, but not across
// uninstallation.
TEST_F(ExtensionToolbarModelUnitTest,
ExtensionToolbarUnloadDisableAndUninstall) {
Init();
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
// Verify the three extensions are in the model in the proper order: A, B, C.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
// Unload B, then C, then A, and then reload C, then A, then B.
ASSERT_TRUE(RemoveExtension(browser_action_b()));
ASSERT_TRUE(RemoveExtension(browser_action_c()));
ASSERT_TRUE(RemoveExtension(browser_action_a()));
EXPECT_EQ(0u, num_toolbar_items()); // Sanity check: all gone?
ASSERT_TRUE(AddExtension(browser_action_c()));
ASSERT_TRUE(AddExtension(browser_action_a()));
ASSERT_TRUE(AddExtension(browser_action_b()));
EXPECT_EQ(3u, num_toolbar_items()); // Sanity check: all back?
EXPECT_EQ(0u, observer()->moved_count());
// Even though we unloaded and reloaded in a different order, the original
// order (A, B, C) should be preserved.
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
// Disabling extensions should also preserve order.
service()->DisableExtension(browser_action_b()->id(),
Extension::DISABLE_USER_ACTION);
service()->DisableExtension(browser_action_c()->id(),
Extension::DISABLE_USER_ACTION);
service()->DisableExtension(browser_action_a()->id(),
Extension::DISABLE_USER_ACTION);
service()->EnableExtension(browser_action_c()->id());
service()->EnableExtension(browser_action_a()->id());
service()->EnableExtension(browser_action_b()->id());
// Make sure we still get the original A, B, C order.
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
// Move browser_action_b() to be first.
toolbar_model()->MoveExtensionIcon(browser_action_b()->id(), 0);
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(0u));
// Uninstall Extension B.
service()->UninstallExtension(browser_action_b()->id(),
UNINSTALL_REASON_FOR_TESTING,
base::Bind(&base::DoNothing),
NULL); // Ignore error.
// List contains only A and C now. Validate that.
EXPECT_EQ(2u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
ASSERT_TRUE(AddExtension(browser_action_b()));
// Make sure Extension B is _not_ first (its old position should have been
// forgotten at uninstall time). Order should be A, C, B.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(2u));
}
TEST_F(ExtensionToolbarModelUnitTest, ReorderOnPrefChange) {
Init();
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
EXPECT_EQ(3u, num_toolbar_items());
// Change the value of the toolbar preference.
ExtensionIdList new_order;
new_order.push_back(browser_action_c()->id());
new_order.push_back(browser_action_b()->id());
ExtensionPrefs::Get(profile())->SetToolbarOrder(new_order);
// Verify order is changed.
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(2u));
}
TEST_F(ExtensionToolbarModelUnitTest, ExtensionToolbarHighlightMode) {
Init();
EXPECT_FALSE(toolbar_model()->HighlightExtensions(ExtensionIdList()));
EXPECT_EQ(0, observer()->highlight_mode_count());
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
EXPECT_EQ(3u, num_toolbar_items());
// Highlight one extension.
ExtensionIdList extension_ids;
extension_ids.push_back(browser_action_b()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_EQ(1, observer()->highlight_mode_count());
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(0u));
// Stop highlighting.
toolbar_model()->StopHighlighting();
EXPECT_EQ(0, observer()->highlight_mode_count());
EXPECT_FALSE(toolbar_model()->is_highlighting());
// Verify that the extensions are back to normal.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
// Call stop highlighting a second time (shouldn't be notified).
toolbar_model()->StopHighlighting();
EXPECT_EQ(0, observer()->highlight_mode_count());
EXPECT_FALSE(toolbar_model()->is_highlighting());
// Highlight all extensions.
extension_ids.clear();
extension_ids.push_back(browser_action_a()->id());
extension_ids.push_back(browser_action_b()->id());
extension_ids.push_back(browser_action_c()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_EQ(1, observer()->highlight_mode_count());
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
// Highlight only extension b (shrink the highlight list).
extension_ids.clear();
extension_ids.push_back(browser_action_b()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_EQ(2, observer()->highlight_mode_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(0u));
// Highlight extensions a and b (grow the highlight list).
extension_ids.clear();
extension_ids.push_back(browser_action_a()->id());
extension_ids.push_back(browser_action_b()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_EQ(3, observer()->highlight_mode_count());
EXPECT_EQ(2u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
// Highlight no extensions (empty the highlight list).
extension_ids.clear();
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_EQ(2, observer()->highlight_mode_count());
EXPECT_FALSE(toolbar_model()->is_highlighting());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
}
TEST_F(ExtensionToolbarModelUnitTest, ExtensionToolbarHighlightModeRemove) {
Init();
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
EXPECT_EQ(3u, num_toolbar_items());
// Highlight two of the extensions.
ExtensionIdList extension_ids;
extension_ids.push_back(browser_action_a()->id());
extension_ids.push_back(browser_action_b()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1, observer()->highlight_mode_count());
EXPECT_EQ(2u, num_toolbar_items());
// Disable one of them - only one should remain highlighted.
service()->DisableExtension(browser_action_a()->id(),
Extension::DISABLE_USER_ACTION);
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(0u));
// Uninstall the remaining highlighted extension. This should result in
// highlight mode exiting.
service()->UninstallExtension(browser_action_b()->id(),
UNINSTALL_REASON_FOR_TESTING,
base::Bind(&base::DoNothing),
NULL); // Ignore error.
EXPECT_FALSE(toolbar_model()->is_highlighting());
EXPECT_EQ(0, observer()->highlight_mode_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
// Test that removing an unhighlighted extension still works.
// Reinstall extension b, and then highlight extension c.
ASSERT_TRUE(AddExtension(browser_action_b()));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
extension_ids.clear();
extension_ids.push_back(browser_action_c()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_EQ(1, observer()->highlight_mode_count());
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
// Uninstalling b should not have visible impact.
service()->UninstallExtension(browser_action_b()->id(),
UNINSTALL_REASON_FOR_TESTING,
base::Bind(&base::DoNothing),
NULL); // Ignore error.
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1, observer()->highlight_mode_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
// When we stop, only extension c should remain.
toolbar_model()->StopHighlighting();
EXPECT_FALSE(toolbar_model()->is_highlighting());
EXPECT_EQ(0, observer()->highlight_mode_count());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u));
}
TEST_F(ExtensionToolbarModelUnitTest, ExtensionToolbarHighlightModeAdd) {
Init();
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
EXPECT_EQ(3u, num_toolbar_items());
// Remove one (down to two).
ASSERT_TRUE(RemoveExtension(browser_action_c()));
// Highlight one of the two extensions.
ExtensionIdList extension_ids;
extension_ids.push_back(browser_action_a()->id());
toolbar_model()->HighlightExtensions(extension_ids);
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
// Adding a new extension should have no visible effect.
ASSERT_TRUE(AddExtension(browser_action_c()));
EXPECT_TRUE(toolbar_model()->is_highlighting());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
// When we stop highlighting, we should see the new extension show up.
toolbar_model()->StopHighlighting();
EXPECT_FALSE(toolbar_model()->is_highlighting());
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
}
// Test that the extension toolbar maintains the proper size, even after a pref
// change.
TEST_F(ExtensionToolbarModelUnitTest, ExtensionToolbarSizeAfterPrefChange) {
Init();
// Add the three browser action extensions.
ASSERT_TRUE(AddBrowserActionExtensions());
EXPECT_EQ(3u, num_toolbar_items());
// Should be at max size.
EXPECT_TRUE(toolbar_model()->all_icons_visible());
EXPECT_EQ(num_toolbar_items(), toolbar_model()->visible_icon_count());
toolbar_model()->OnExtensionToolbarPrefChange();
// Should still be at max size.
EXPECT_TRUE(toolbar_model()->all_icons_visible());
EXPECT_EQ(num_toolbar_items(), toolbar_model()->visible_icon_count());
}
// Test that, in the absence of the extension-action-redesign switch, the
// model only contains extensions with browser actions.
TEST_F(ExtensionToolbarModelUnitTest, TestToolbarExtensionTypesNoSwitch) {
Init();
ASSERT_TRUE(AddActionExtensions());
EXPECT_EQ(1u, num_toolbar_items());
EXPECT_EQ(browser_action(), GetExtensionAtIndex(0u));
}
// Test that, with the extension-action-redesign switch, the model contains
// all types of extensions, except those which should not be displayed on the
// toolbar (like component extensions).
TEST_F(ExtensionToolbarModelUnitTest, TestToolbarExtensionTypesSwitch) {
FeatureSwitch::ScopedOverride enable_redesign(
FeatureSwitch::extension_action_redesign(), true);
Init();
ASSERT_TRUE(AddActionExtensions());
// With the switch on, extensions with page actions and no action should also
// be displayed in the toolbar.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action(), GetExtensionAtIndex(0u));
EXPECT_EQ(page_action(), GetExtensionAtIndex(1u));
EXPECT_EQ(no_action(), GetExtensionAtIndex(2u));
}
// Test that hiding actions on the toolbar results in their removal from the
// model when the redesign switch is not enabled.
TEST_F(ExtensionToolbarModelUnitTest,
ExtensionToolbarActionsVisibilityNoSwitch) {
Init();
ASSERT_TRUE(AddBrowserActionExtensions());
// Sanity check: Order should start as A B C.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
// By default, all actions should be visible.
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, browser_action_a()->id()));
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, browser_action_b()->id()));
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, browser_action_c()->id()));
// Hiding an action should result in its removal from the toolbar.
ExtensionActionAPI::SetBrowserActionVisibility(
prefs, browser_action_b()->id(), false);
EXPECT_FALSE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, browser_action_b()->id()));
// Thus, there should now only be two items on the toolbar - A and C.
EXPECT_EQ(2u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
// Resetting the visibility to 'true' should result in the extension being
// added back at its original position.
ExtensionActionAPI::SetBrowserActionVisibility(
prefs, browser_action_b()->id(), true);
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, browser_action_b()->id()));
// So the toolbar order should be A B C.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2u));
}
TEST_F(ExtensionToolbarModelUnitTest, ExtensionToolbarIncognitoModeTest) {
Init();
ASSERT_TRUE(AddBrowserActionExtensions());
// Give two extensions incognito access.
// Note: We use ExtensionPrefs::SetIsIncognitoEnabled instead of
// util::SetIsIncognitoEnabled because the latter tries to reload the
// extension, which requries a filepath associated with the extension (and,
// for this test, reloading the extension is irrelevant to us).
ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile());
extension_prefs->SetIsIncognitoEnabled(browser_action_b()->id(), true);
extension_prefs->SetIsIncognitoEnabled(browser_action_c()->id(), true);
util::SetIsIncognitoEnabled(browser_action_b()->id(), profile(), true);
util::SetIsIncognitoEnabled(browser_action_c()->id(), profile(), true);
// Move C to the second index.
toolbar_model()->MoveExtensionIcon(browser_action_c()->id(), 1u);
// Set visible count to 2 so that c is overflowed. State is A C [B].
toolbar_model()->SetVisibleIconCount(2);
EXPECT_EQ(1u, observer()->moved_count());
// Get an incognito profile and toolbar.
ExtensionToolbarModel* incognito_model =
CreateToolbarModelForProfile(profile()->GetOffTheRecordProfile(), true);
ExtensionToolbarModelTestObserver incognito_observer(incognito_model);
EXPECT_EQ(0u, incognito_observer.moved_count());
// We should have two items, C and B, and the order should be preserved from
// the original model.
EXPECT_EQ(2u, incognito_model->toolbar_items().size());
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(0u, incognito_model));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1u, incognito_model));
// Extensions in the overflow menu in the regular toolbar should remain in
// overflow in the incognito toolbar. So, we should have C [B].
EXPECT_EQ(1u, incognito_model->visible_icon_count());
// The regular model should still have two icons visible.
EXPECT_EQ(2u, toolbar_model()->visible_icon_count());
// Changing the incognito model size should not affect the regular model.
incognito_model->SetVisibleIconCount(0);
EXPECT_EQ(0u, incognito_model->visible_icon_count());
EXPECT_EQ(2u, toolbar_model()->visible_icon_count());
// Expanding the incognito model to 2 should register as "all icons"
// since it is all of the incognito-enabled extensions.
incognito_model->SetVisibleIconCount(2u);
EXPECT_EQ(2u, incognito_model->visible_icon_count());
EXPECT_TRUE(incognito_model->all_icons_visible());
// Moving icons in the incognito toolbar should not affect the regular
// toolbar. Incognito currently has C B...
incognito_model->MoveExtensionIcon(browser_action_b()->id(), 0u);
// So now it should be B C...
EXPECT_EQ(1u, incognito_observer.moved_count());
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(0u, incognito_model));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u, incognito_model));
// ... and the regular toolbar should be unaffected.
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0u));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1u));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(2u));
// Similarly, the observer for the regular model should not have received
// any updates.
EXPECT_EQ(1u, observer()->moved_count());
// And performing moves on the regular model should have no effect on the
// incognito model or its observers.
toolbar_model()->MoveExtensionIcon(browser_action_c()->id(), 2u);
EXPECT_EQ(2u, observer()->moved_count());
EXPECT_EQ(1u, incognito_observer.moved_count());
}
// Test that enabling extensions incognito with an active incognito profile
// works.
TEST_F(ExtensionToolbarModelUnitTest,
ExtensionToolbarIncognitoEnableExtension) {
Init();
const char* kManifest =
"{"
" \"name\": \"%s\","
" \"version\": \"1.0\","
" \"manifest_version\": 2,"
" \"browser_action\": {}"
"}";
// For this test, we need to have "real" extension files, because we need to
// be able to reload them during the incognito process. Since the toolbar
// needs to be notified of the reload, we need it this time (as opposed to
// above, where we simply set the prefs before the incognito bar was
// created.
TestExtensionDir dir1;
dir1.WriteManifest(base::StringPrintf(kManifest, "incognito1"));
TestExtensionDir dir2;
dir2.WriteManifest(base::StringPrintf(kManifest, "incognito2"));
TestExtensionDir* dirs[] = { &dir1, &dir2 };
const Extension* extensions[] = { nullptr, nullptr };
for (size_t i = 0; i < arraysize(dirs); ++i) {
// The extension id will be calculated from the file path; we need this to
// wait for the extension to load.
base::FilePath path_for_id =
base::MakeAbsoluteFilePath(dirs[i]->unpacked_path());
std::string id = crx_file::id_util::GenerateIdForPath(path_for_id);
TestExtensionRegistryObserver observer(registry(), id);
UnpackedInstaller::Create(service())->Load(dirs[i]->unpacked_path());
observer.WaitForExtensionLoaded();
extensions[i] = registry()->enabled_extensions().GetByID(id);
ASSERT_TRUE(extensions[i]);
}
// For readability, alias to A and B. Since we'll be reloading these
// extensions, we also can't rely on pointers.
std::string extension_a = extensions[0]->id();
std::string extension_b = extensions[1]->id();
// The first model should have both extensions visible.
EXPECT_EQ(2u, toolbar_model()->toolbar_items().size());
EXPECT_EQ(extension_a, GetExtensionAtIndex(0)->id());
EXPECT_EQ(extension_b, GetExtensionAtIndex(1)->id());
// Set the model to only show one extension, so the order is A [B].
toolbar_model()->SetVisibleIconCount(1u);
// Get an incognito profile and toolbar.
ExtensionToolbarModel* incognito_model =
CreateToolbarModelForProfile(profile()->GetOffTheRecordProfile(), true);
ExtensionToolbarModelTestObserver incognito_observer(incognito_model);
// Right now, no extensions are enabled in incognito mode.
EXPECT_EQ(0u, incognito_model->toolbar_items().size());
// Set extension b (which is overflowed) to be enabled in incognito. This
// results in b reloading, so wait for it.
{
TestExtensionRegistryObserver observer(registry(), extension_b);
util::SetIsIncognitoEnabled(extension_b, profile(), true);
observer.WaitForExtensionLoaded();
}
// Now, we should have one icon in the incognito bar. But, since B is
// overflowed in the main bar, it shouldn't be visible.
EXPECT_EQ(1u, incognito_model->toolbar_items().size());
EXPECT_EQ(extension_b, GetExtensionAtIndex(0u, incognito_model)->id());
EXPECT_EQ(0u, incognito_model->visible_icon_count());
// Also enable extension a for incognito (again, wait for the reload).
{
TestExtensionRegistryObserver observer(registry(), extension_a);
util::SetIsIncognitoEnabled(extension_a, profile(), true);
observer.WaitForExtensionLoaded();
}
// Now, both extensions should be enabled in incognito mode. In addition, the
// incognito toolbar should have expanded to show extension a (since it isn't
// overflowed in the main bar).
EXPECT_EQ(2u, incognito_model->toolbar_items().size());
EXPECT_EQ(extension_a, GetExtensionAtIndex(0u, incognito_model)->id());
EXPECT_EQ(extension_b, GetExtensionAtIndex(1u, incognito_model)->id());
EXPECT_EQ(1u, incognito_model->visible_icon_count());
}
// Test that hiding actions on the toolbar results in sending them to the
// overflow menu when the redesign switch is enabled.
TEST_F(ExtensionToolbarModelUnitTest,
ExtensionToolbarActionsVisibilityWithSwitch) {
FeatureSwitch::ScopedOverride enable_redesign(
FeatureSwitch::extension_action_redesign(), true);
Init();
// We choose to use all types of extensions here, since the misnamed
// BrowserActionVisibility is now for toolbar visibility.
ASSERT_TRUE(AddActionExtensions());
// For readability, alias extensions A B C.
const Extension* extension_a = browser_action();
const Extension* extension_b = page_action();
const Extension* extension_c = no_action();
// Sanity check: Order should start as A B C, with all three visible.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_TRUE(toolbar_model()->all_icons_visible());
EXPECT_EQ(extension_a, GetExtensionAtIndex(0u));
EXPECT_EQ(extension_b, GetExtensionAtIndex(1u));
EXPECT_EQ(extension_c, GetExtensionAtIndex(2u));
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
// By default, all actions should be visible.
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, extension_a->id()));
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, extension_c->id()));
EXPECT_TRUE(ExtensionActionAPI::GetBrowserActionVisibility(
prefs, extension_b->id()));
// Hiding an action should result in it being sent to the overflow menu.
ExtensionActionAPI::SetBrowserActionVisibility(
prefs, extension_b->id(), false);
// Thus, the order should be A C B, with B in the overflow.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(2u, toolbar_model()->visible_icon_count());
EXPECT_EQ(extension_a, GetExtensionAtIndex(0u));
EXPECT_EQ(extension_c, GetExtensionAtIndex(1u));
EXPECT_EQ(extension_b, GetExtensionAtIndex(2u));
// Hiding an extension's action should result in it being sent to the overflow
// as well, but as the _first_ extension in the overflow.
ExtensionActionAPI::SetBrowserActionVisibility(
prefs, extension_a->id(), false);
// Thus, the order should be C A B, with A and B in the overflow.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(1u, toolbar_model()->visible_icon_count());
EXPECT_EQ(extension_c, GetExtensionAtIndex(0u));
EXPECT_EQ(extension_a, GetExtensionAtIndex(1u));
EXPECT_EQ(extension_b, GetExtensionAtIndex(2u));
// Resetting A's visibility to true should send it back to the visible icons
// (and should grow visible icons by 1), but it should be added to the end of
// the visible icon list (not to its original position).
ExtensionActionAPI::SetBrowserActionVisibility(
prefs, extension_a->id(), true);
// So order is C A B, with only B in the overflow.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_EQ(2u, toolbar_model()->visible_icon_count());
EXPECT_EQ(extension_c, GetExtensionAtIndex(0u));
EXPECT_EQ(extension_a, GetExtensionAtIndex(1u));
EXPECT_EQ(extension_b, GetExtensionAtIndex(2u));
// Resetting B to be visible should make the order C A B, with no overflow.
ExtensionActionAPI::SetBrowserActionVisibility(
prefs, extension_b->id(), true);
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_TRUE(toolbar_model()->all_icons_visible());
EXPECT_EQ(extension_c, GetExtensionAtIndex(0u));
EXPECT_EQ(extension_a, GetExtensionAtIndex(1u));
EXPECT_EQ(extension_b, GetExtensionAtIndex(2u));
}
// Test that toolbar actions can pop themselves out of overflow if they want
// to act on a given web contents.
TEST_F(ExtensionToolbarModelUnitTest, ToolbarActionsPopOutToAct) {
// Extensions popping themselves out to act is part of the toolbar redesign,
// and hidden behind a flag.
FeatureSwitch::ScopedOverride enable_redesign(
FeatureSwitch::extension_action_redesign(), true);
Init();
TestWebContentsFactory web_contents_factory;
ASSERT_TRUE(AddActionExtensions());
// We should start in the order of "browser action" "page action" "no action"
// and have all extensions visible.
EXPECT_EQ(3u, num_toolbar_items());
EXPECT_TRUE(toolbar_model()->all_icons_visible());
EXPECT_EQ(browser_action(), GetExtensionAtIndex(0u));
EXPECT_EQ(page_action(), GetExtensionAtIndex(1u));
EXPECT_EQ(no_action(), GetExtensionAtIndex(2u));
// Shrink the model to only show one action, and move the page action to the
// end.
toolbar_model()->SetVisibleIconCount(1);
toolbar_model()->MoveExtensionIcon(page_action()->id(), 2u);
// Quickly verify that the move/visible count worked.
EXPECT_EQ(1u, toolbar_model()->visible_icon_count());
EXPECT_EQ(browser_action(), GetExtensionAtIndex(0u));
EXPECT_EQ(no_action(), GetExtensionAtIndex(1u));
EXPECT_EQ(page_action(), GetExtensionAtIndex(2u));
// Create two test web contents, and a session tab helper for each. We need
// a session tab helper, since we rely on tab ids.
content::WebContents* web_contents =
web_contents_factory.CreateWebContents(profile());
ASSERT_TRUE(web_contents);
SessionTabHelper::CreateForWebContents(web_contents);
content::WebContents* second_web_contents =
web_contents_factory.CreateWebContents(profile());
ASSERT_TRUE(second_web_contents);
SessionTabHelper::CreateForWebContents(second_web_contents);
// Find the tab ids, ensure that the two web contents have different ids, and
// verify that neither is -1 (invalid).
int tab_id = SessionTabHelper::IdForTab(web_contents);
int second_tab_id = SessionTabHelper::IdForTab(second_web_contents);
EXPECT_NE(tab_id, second_tab_id);
EXPECT_NE(-1, second_tab_id);
EXPECT_NE(-1, tab_id);
// First, check the model order for the first tab. Since we haven't changed
// anything (i.e., no extensions want to act), this should be the same as we
// left it: "browser action", "no action", "page action", with only one
// visible.
ExtensionList tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(browser_action(), tab_order[0]);
EXPECT_EQ(no_action(), tab_order[1]);
EXPECT_EQ(page_action(), tab_order[2]);
EXPECT_EQ(1u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
// And we should have no notifications to reorder the toolbar.
EXPECT_EQ(0u, observer()->reorder_count());
// Make "page action" want to act by making it's page action visible on the
// first tab, and notify the API of the change.
ExtensionActionManager* action_manager =
ExtensionActionManager::Get(profile());
ExtensionAction* action = action_manager->GetExtensionAction(*page_action());
ASSERT_TRUE(action);
action->SetIsVisible(tab_id, true);
ExtensionActionAPI* extension_action_api = ExtensionActionAPI::Get(profile());
extension_action_api->NotifyChange(action, web_contents, profile());
// This should result in "page action" being popped out of the overflow menu.
// This has two visible effects:
// - page action should move to the second index (the one right after the last
// originally-visible).
// - The visible count should increase by one (so page action is visible).
tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(browser_action(), tab_order[0]);
EXPECT_EQ(page_action(), tab_order[1]);
EXPECT_EQ(no_action(), tab_order[2]);
EXPECT_EQ(2u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
// We should also have been told to reorder the toolbar.
EXPECT_EQ(1u, observer()->reorder_count());
// This should not have any effect on the second tab, which should still have
// the original order and visible count.
tab_order = toolbar_model()->GetItemOrderForTab(second_web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(browser_action(), tab_order[0]);
EXPECT_EQ(no_action(), tab_order[1]);
EXPECT_EQ(page_action(), tab_order[2]);
EXPECT_EQ(1u,
toolbar_model()->GetVisibleIconCountForTab(second_web_contents));
// Now, set the action to be hidden again, and notify of the change.
action->SetIsVisible(tab_id, false);
extension_action_api->NotifyChange(action, web_contents, profile());
// The order and visible count should return to normal (the page action should
// move back to its original index in overflow). So, order should be "browser
// action", "no action", "page action".
tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(browser_action(), tab_order[0]);
EXPECT_EQ(no_action(), tab_order[1]);
EXPECT_EQ(page_action(), tab_order[2]);
EXPECT_EQ(1u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
// This should also result in a reorder.
EXPECT_EQ(2u, observer()->reorder_count());
// Move page action to the first index (so it's naturally visible), and make
// it want to act.
toolbar_model()->MoveExtensionIcon(page_action()->id(), 0u);
action->SetIsVisible(tab_id, true);
extension_action_api->NotifyChange(action, web_contents, profile());
// Since the action is already visible, this should have no effect - the order
// and visible count should remain unchanged. Order is "page action", "browser
// action", "no action".
tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(page_action(), tab_order[0]);
EXPECT_EQ(browser_action(), tab_order[1]);
EXPECT_EQ(no_action(), tab_order[2]);
EXPECT_EQ(1u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
// We should still be able to increase the size of the model, and to move the
// page action.
toolbar_model()->SetVisibleIconCount(2);
toolbar_model()->MoveExtensionIcon(page_action()->id(), 1u);
tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(browser_action(), tab_order[0]);
EXPECT_EQ(page_action(), tab_order[1]);
EXPECT_EQ(no_action(), tab_order[2]);
EXPECT_EQ(2u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
// Neither of the above operations should have precipitated a reorder.
EXPECT_EQ(2u, observer()->reorder_count());
// If we moved the page action, the move should remain in effect even after
// the action no longer wants to act.
action->SetIsVisible(tab_id, false);
extension_action_api->NotifyChange(action, web_contents, profile());
tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(browser_action(), tab_order[0]);
EXPECT_EQ(page_action(), tab_order[1]);
EXPECT_EQ(no_action(), tab_order[2]);
EXPECT_EQ(2u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
// The above change should *not* require a reorder, because the extension is
// in a new, visible spot and doesn't need to change its position.
EXPECT_EQ(2u, observer()->reorder_count());
// Test the edge case of having no icons visible.
toolbar_model()->SetVisibleIconCount(0);
EXPECT_EQ(0u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
action->SetIsVisible(tab_id, true);
extension_action_api->NotifyChange(action, web_contents, profile());
tab_order = toolbar_model()->GetItemOrderForTab(web_contents);
ASSERT_EQ(3u, tab_order.size());
EXPECT_EQ(page_action(), tab_order[0]);
EXPECT_EQ(browser_action(), tab_order[1]);
EXPECT_EQ(no_action(), tab_order[2]);
EXPECT_EQ(1u, toolbar_model()->GetVisibleIconCountForTab(web_contents));
EXPECT_EQ(3u, observer()->reorder_count());
}
// Test that observers receive no Added notifications until after the
// ExtensionSystem has initialized.
TEST_F(ExtensionToolbarModelUnitTest, ModelWaitsForExtensionSystemReady) {
InitializeEmptyExtensionService();
ExtensionToolbarModel* toolbar_model =
CreateToolbarModelForProfile(profile(), false);
ExtensionToolbarModelTestObserver model_observer(toolbar_model);
EXPECT_TRUE(AddBrowserActionExtensions());
// Since the model hasn't been initialized (the ExtensionSystem::ready task
// hasn't been run), there should be no insertion notifications.
EXPECT_EQ(0u, model_observer.inserted_count());
EXPECT_EQ(0u, model_observer.initialized_count());
EXPECT_FALSE(toolbar_model->extensions_initialized());
// Run the ready task.
static_cast<TestExtensionSystem*>(ExtensionSystem::Get(profile()))->
SetReady();
// Run tasks posted to TestExtensionSystem.
base::RunLoop().RunUntilIdle();
// We should still have no insertions, but should have an initialized count.
EXPECT_TRUE(toolbar_model->extensions_initialized());
EXPECT_EQ(0u, model_observer.inserted_count());
EXPECT_EQ(1u, model_observer.initialized_count());
}
// Check that the toolbar model correctly clears and reorders when it detects
// a preference change.
TEST_F(ExtensionToolbarModelUnitTest, ToolbarModelPrefChange) {
Init();
ASSERT_TRUE(AddBrowserActionExtensions());
// We should start in the basic A B C order.
ASSERT_TRUE(browser_action_a());
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(0));
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(1));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(2));
// Record the difference between the inserted and removed counts. The actual
// value of the counts is not important, but we need to be sure that if we
// call to remove any, we also add them back.
size_t inserted_and_removed_difference =
observer()->inserted_count() - observer()->removed_count();
// Assign a new order, B C A, and write it in the prefs.
ExtensionIdList new_order;
new_order.push_back(browser_action_b()->id());
new_order.push_back(browser_action_c()->id());
new_order.push_back(browser_action_a()->id());
ExtensionPrefs::Get(profile())->SetToolbarOrder(new_order);
// Ensure everything has time to run.
base::RunLoop().RunUntilIdle();
// The new order should be reflected in the model.
EXPECT_EQ(browser_action_b(), GetExtensionAtIndex(0));
EXPECT_EQ(browser_action_c(), GetExtensionAtIndex(1));
EXPECT_EQ(browser_action_a(), GetExtensionAtIndex(2));
EXPECT_EQ(inserted_and_removed_difference,
observer()->inserted_count() - observer()->removed_count());
}
} // namespace extensions
| 42.010363 | 80 | 0.741825 | sunjc53yy |
1e8e50bb3b335fc3322f15192af4708fb4b0ad89 | 3,729 | cc | C++ | chromeos/network/system_token_cert_db_storage.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromeos/network/system_token_cert_db_storage.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromeos/network/system_token_cert_db_storage.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // 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 "chromeos/network/system_token_cert_db_storage.h"
#include "base/callback.h"
#include "base/callback_list.h"
#include "base/check_op.h"
#include "base/location.h"
#include "base/observer_list.h"
#include "base/observer_list_types.h"
#include "base/sequence_checker.h"
#include "base/timer/timer.h"
#include "net/cert/nss_cert_database.h"
namespace chromeos {
namespace {
// Owned ChromeBrowserMainPartsChromeos.
SystemTokenCertDbStorage* g_system_token_cert_db_storage = nullptr;
} // namespace
// static
constexpr base::TimeDelta SystemTokenCertDbStorage::kMaxCertDbRetrievalDelay;
// static
void SystemTokenCertDbStorage::Initialize() {
DCHECK_EQ(g_system_token_cert_db_storage, nullptr);
g_system_token_cert_db_storage = new SystemTokenCertDbStorage();
}
// static
void SystemTokenCertDbStorage::Shutdown() {
DCHECK_NE(g_system_token_cert_db_storage, nullptr);
delete g_system_token_cert_db_storage;
g_system_token_cert_db_storage = nullptr;
}
// static
SystemTokenCertDbStorage* SystemTokenCertDbStorage::Get() {
return g_system_token_cert_db_storage;
}
void SystemTokenCertDbStorage::SetDatabase(
net::NSSCertDatabase* system_token_cert_database) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(system_token_cert_database_, nullptr);
system_token_cert_database_ = std::move(system_token_cert_database);
system_token_cert_db_retrieval_timer_.Stop();
get_system_token_cert_db_callback_list_.Notify(system_token_cert_database_);
}
void SystemTokenCertDbStorage::ResetDatabase() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
system_token_cert_database_ = nullptr;
// If any consumer asks for the database between now and when
// SystemTokenCertDbStorage is destroyed, respond with a failure.
system_token_cert_db_retrieval_failed_ = true;
// Notify observers that the SystemTokenCertDbStorage and the
// NSSCertDatabase it provides can not be used anymore.
for (auto& observer : g_system_token_cert_db_storage->observers_)
observer.OnSystemTokenCertDbDestroyed();
}
void SystemTokenCertDbStorage::GetDatabase(GetDatabaseCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(callback);
if (system_token_cert_database_) {
std::move(callback).Run(system_token_cert_database_);
} else if (system_token_cert_db_retrieval_failed_) {
std::move(callback).Run(/*nss_cert_database=*/nullptr);
} else {
get_system_token_cert_db_callback_list_.AddUnsafe(std::move(callback));
if (!system_token_cert_db_retrieval_timer_.IsRunning()) {
system_token_cert_db_retrieval_timer_.Start(
FROM_HERE, kMaxCertDbRetrievalDelay, /*receiver=*/this,
&SystemTokenCertDbStorage::OnSystemTokenDbRetrievalTimeout);
}
}
}
void SystemTokenCertDbStorage::AddObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
observers_.AddObserver(observer);
}
void SystemTokenCertDbStorage::RemoveObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
observers_.RemoveObserver(observer);
}
SystemTokenCertDbStorage::SystemTokenCertDbStorage() = default;
SystemTokenCertDbStorage::~SystemTokenCertDbStorage() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void SystemTokenCertDbStorage::OnSystemTokenDbRetrievalTimeout() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
system_token_cert_db_retrieval_failed_ = true;
get_system_token_cert_db_callback_list_.Notify(
/*nss_cert_database=*/nullptr);
}
} // namespace chromeos
| 31.601695 | 78 | 0.806919 | iridium-browser |
1e93a83db9ced0290c839ab25269b3e5d8da514a | 1,387 | cpp | C++ | WixApp/WixApp.prj/PathUnits.cpp | rrvt/WixApp | f72724f74d4d7eb8153646424f78823def9b7e35 | [
"MIT"
] | null | null | null | WixApp/WixApp.prj/PathUnits.cpp | rrvt/WixApp | f72724f74d4d7eb8153646424f78823def9b7e35 | [
"MIT"
] | null | null | null | WixApp/WixApp.prj/PathUnits.cpp | rrvt/WixApp | f72724f74d4d7eb8153646424f78823def9b7e35 | [
"MIT"
] | 1 | 2020-02-25T09:11:37.000Z | 2020-02-25T09:11:37.000Z | // Parse a path into an array
#include "stdafx.h"
#include "PathUnits.h"
PathUnits& PathUnits::operator= (String& path) {
parse(path); return *this;
}
// disect the path to a file into bite size chunks, mostly directories (e.g. D:\, \abc\, etc.)
void PathUnits::parse(const String& path) {
String t = path;
int end;
units.clear();
while ((end = t.find(_T('\\'))) > 0) {units += t.substr(0, end); t = t.substr(end+1);}
}
PathUnits::operator String() {
int n = units.end();
int i;
tempPath.clear();
for (i = 0; i < n; i++) tempPath += units[i] + _T('\\');
return tempPath;
}
PathUnits& PathUnits::copy(PathUnits& p) {
int n = units.end();
int j;
tempPath = p.tempPath;
for (j = 0; j < n; j++) units[j] = p.units[j];
return *this;
}
#if 0
PathUnits::operator CString() {
static String s = *this; return s.str();
//8static CString cs = s.str(); return cs;
}
bool PathUnits::relativePath(PathUnits& pathUnit, String& rel) {
int i;
int j;
rel.clear();
if (nUnits <= 0 || pathUnit.nUnits <= 0) return false;
for (i = 0; i < nUnits && i < pathUnit.nUnits; i++) if (units[i] != pathUnit.units[i]) break;
if (!i) return false;
if (i >= pathUnit.nUnits) return true;
for (j = i; j < nUnits; j++) rel += "..\\";
for (j = i; j < pathUnit.nUnits; j++) rel += pathUnit.units[j] + "\\";
return true;
}
#endif
| 17.556962 | 95 | 0.583994 | rrvt |
1e97e094a4450e5b378b3458af5a5c08b41020a3 | 2,107 | cpp | C++ | Days 111 - 120/Day 112/FindLowestCommonAncestor.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 111 - 120/Day 112/FindLowestCommonAncestor.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 111 - 120/Day 112/FindLowestCommonAncestor.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
struct Node
{
char value;
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
std::shared_ptr<Node> parent = nullptr;
explicit Node(char value, const std::shared_ptr<Node>& left = nullptr, const std::shared_ptr<Node>& right = nullptr) noexcept
: value(value), left(left), right(right)
{ }
};
unsigned int GetNodeDepth(const std::shared_ptr<Node>& node) noexcept
{
if (node == nullptr)
{
return 0;
}
return GetNodeDepth(node->parent) + 1;
}
std::shared_ptr<Node> GetLowestCommonAncestor(const std::shared_ptr<Node>& nodeA, const std::shared_ptr<Node>& nodeB) noexcept
{
if (nodeA == nullptr || nodeB == nullptr)
{
return nullptr;
}
const unsigned int nodeADepth = GetNodeDepth(nodeA);
const unsigned int nodeBDepth = GetNodeDepth(nodeB);
const auto[minDepth, maxDepth] = std::minmax(nodeADepth, nodeBDepth);
auto[deeperNode, shallowerNode] = nodeADepth > nodeBDepth ? std::make_pair(nodeA, nodeB) : std::make_pair(nodeB, nodeA);
for (unsigned int i = 0; i < maxDepth - minDepth; i++)
{
deeperNode = deeperNode->parent;
}
while (deeperNode != nullptr && shallowerNode != nullptr)
{
if (deeperNode == shallowerNode)
{
return deeperNode;
}
deeperNode = deeperNode->parent;
shallowerNode = shallowerNode->parent;
}
return nullptr;
}
int main(int argc, char* argv[])
{
const auto nodeG = std::make_shared<Node>('g');
const auto nodeF = std::make_shared<Node>('f');
const auto nodeE = std::make_shared<Node>('e');
const auto nodeD = std::make_shared<Node>('d', nodeF, nodeG);
nodeF->parent = nodeD;
nodeG->parent = nodeD;
const auto nodeC = std::make_shared<Node>('c', nodeD, nodeE);
nodeD->parent = nodeC;
nodeE->parent = nodeC;
const auto nodeB = std::make_shared<Node>('b');
const auto nodeA = std::make_shared<Node>('a', nodeB, nodeC);
nodeB->parent = nodeA;
nodeC->parent = nodeA;
std::cout << GetLowestCommonAncestor(nodeB, nodeE)->value << "\n";
std::cout << GetLowestCommonAncestor(nodeE, nodeF)->value << "\n";
std::cin.get();
return 0;
} | 23.674157 | 126 | 0.689606 | LucidSigma |
1e9a4dd9b0f311d1cb53610d769f4c5248e2ce82 | 11,974 | cpp | C++ | Tools/ModelConverter/ModelConverter/ObjModelLoader.cpp | AnkurSheel/RoutePlanner | a50b6ccb735db42ff4e5b2f4c87e710819c4564b | [
"CC-BY-4.0"
] | null | null | null | Tools/ModelConverter/ModelConverter/ObjModelLoader.cpp | AnkurSheel/RoutePlanner | a50b6ccb735db42ff4e5b2f4c87e710819c4564b | [
"CC-BY-4.0"
] | null | null | null | Tools/ModelConverter/ModelConverter/ObjModelLoader.cpp | AnkurSheel/RoutePlanner | a50b6ccb735db42ff4e5b2f4c87e710819c4564b | [
"CC-BY-4.0"
] | null | null | null | // *************************************************************************
// ObjModelLoader version: 1.0 Ankur Sheel date: 2012/10/29
// ------------------------------------------------------------------------
//
// ------------------------------------------------------------------------
// Copyright (C) 2008 - All Rights Reserved
// *************************************************************************
//
// *************************************************************************
#include "stdafx.h"
#include "ObjModelLoader.h"
#include "Optional.h"
#include "Vector3.h"
#include "FileInput.hxx"
#include "FileOutput.hxx"
using namespace Graphics;
using namespace Base;
using namespace Utilities;
using namespace std;
// *************************************************************************
cObjModelLoader::cObjModelLoader()
: m_vBoundingBoxMaxPos(-MaxFloat, -MaxFloat, -MaxFloat)
, m_vBoundingBoxMinPos(MaxFloat, MaxFloat, MaxFloat)
{
}
// *************************************************************************
cObjModelLoader::~cObjModelLoader()
{
m_MaterialsMap.clear();
}
// *************************************************************************
void cObjModelLoader::ConvertObjFile(const Base::cString & strObjFile,
const Base::cString & strOutputFile)
{
LoadObjFile(strObjFile);
BuildVertexAndIndexData();
WriteSPDOFile(strOutputFile);
m_MaterialsMap.clear();
}
// *************************************************************************
void cObjModelLoader::LoadObjFile(const Base::cString & strObjFile)
{
shared_ptr<IFileInput> pObjFile = shared_ptr<IFileInput>(IFileInput::CreateInputFile());
if(pObjFile->Open(strObjFile, std::ios_base::in))
{
cString strLine;
vector<cString> vtokens;
int iCurrentSubset = -1;
int iStartIndexNo = 0;
do
{
strLine = pObjFile->ReadLine();
if(!strLine.IsEmpty())
{
if (strLine[0] == '#')
{
continue;
}
strLine.TrimBoth();
if(!strLine.IsEmpty())
{
vtokens.clear();
strLine.Tokenize(' ', vtokens);
// vertices
if (vtokens[0] == "v")
{
float x = GetFloatValue(vtokens[1]);
float y = GetFloatValue(vtokens[2]);
float z = GetFloatValue(vtokens[3]);
// invert z coordinate vertice
//z = z * -1.0f;
m_vVertexPositions.push_back(cVector3(x, y, z));
}
else if(vtokens[0] == "vt")
{
float u = GetFloatValue(vtokens[1]);
float v = GetFloatValue(vtokens[2]);
float w = 0.0f;
if (vtokens.size() == 4)
{
w = GetFloatValue(vtokens[3]);
}
m_vVertexTexCoordinates.push_back(cVector3(u, v, w));
}
// faces/triangles
else if (vtokens[0] == "f")
{
m_vObjSubset[iCurrentSubset].vFaces.push_back(ParseFaceInfo(vtokens[1]));
m_vObjSubset[iCurrentSubset].vFaces.push_back(ParseFaceInfo(vtokens[2]));
m_vObjSubset[iCurrentSubset].vFaces.push_back(ParseFaceInfo(vtokens[3]));
iStartIndexNo += 3;
}
else if (vtokens[0] == "mtllib")
{
LoadMaterialFile(vtokens[1]);
}
else if (vtokens[0] == "usemtl")
{
MaterialMap::const_iterator curr = m_MaterialsMap.find(vtokens[1]);
if (curr != m_MaterialsMap.end())
{
iCurrentSubset++;
stObjSubsetData subset;
subset.diffuseColor = curr->second.Diffuse;
subset.iStartIndexNo = iStartIndexNo;
subset.strDiffuseTextureFilename = curr->second.strDiffuseTextureFilename;
m_vObjSubset.push_back(subset);
}
}
}
}
}
while(!pObjFile->IsEOF() || !strLine.IsEmpty());
pObjFile->Close();
}
}
// *************************************************************************
void cObjModelLoader::LoadMaterialFile(const Base::cString & strMaterialFile)
{
shared_ptr<IFileInput> pMtlFile = shared_ptr<IFileInput>(IFileInput::CreateInputFile());
if(pMtlFile->Open(strMaterialFile, std::ios_base::in))
{
cString strLine;
vector<cString> vtokens;
cString strCurrentMaterialName;
do
{
strLine = pMtlFile->ReadLine();
if(!strLine.IsEmpty())
{
if (strLine[0] == '#')
{
continue;
}
strLine.TrimBoth();
if(!strLine.IsEmpty())
{
vtokens.clear();
strLine.Tokenize(' ', vtokens);
// vertices
if (vtokens[0] == "newmtl")
{
stMaterial material;
strCurrentMaterialName = vtokens[1];
material.strMatName = strCurrentMaterialName;
m_MaterialsMap.insert(std::make_pair(strCurrentMaterialName, material));
}
else if (vtokens[0] == "Kd")
{
MaterialMap::iterator curr = m_MaterialsMap.find(strCurrentMaterialName);
if (curr != m_MaterialsMap.end())
{
float r = GetFloatValue(vtokens[1]);
float g = GetFloatValue(vtokens[2]);
float b = GetFloatValue(vtokens[3]);
(curr->second).Diffuse = cColor(r, g, b, 1.0f);
}
}
else if (vtokens[0] == "map_Kd")
{
MaterialMap::iterator curr = m_MaterialsMap.find(strCurrentMaterialName);
if (curr != m_MaterialsMap.end())
{
(curr->second).strDiffuseTextureFilename = vtokens[1];
}
}
}
}
}
while(!pMtlFile->IsEOF() || !strLine.IsEmpty());
pMtlFile->Close();
}
}
// *************************************************************************
stObjFaceInfo cObjModelLoader::ParseFaceInfo(const Base::cString & strFaceVal)
{
stObjFaceInfo faceInfo;
vector<cString> vtokens;
strFaceVal.Tokenize('/', vtokens);
for (unsigned int i = 0; i<vtokens.size();i++)
{
int iVal = GetIntValue(vtokens[i]) - 1;
if (i == 0)
{
faceInfo.iPosIndex = iVal;
}
else if (i == 1)
{
faceInfo.iTexCoordIndex = iVal;
}
}
return faceInfo;
}
// *************************************************************************
void cObjModelLoader::BuildVertexAndIndexData()
{
m_iTotalIndices = 0;
int totalVerts = 0;
vector<stObjFaceInfo> vVertexIndex;
for(unsigned int i=0; i< m_vObjSubset.size(); i++)
{
stObjSubsetData objSubset = m_vObjSubset[i];
stSPDOSubsetData subsetData;
subsetData.diffuseColor = objSubset.diffuseColor;
subsetData.iStartIndexNo = objSubset.iStartIndexNo;
subsetData.strDiffuseTextureFilename = objSubset.strDiffuseTextureFilename;
for(unsigned int j = 0; j < objSubset.vFaces.size(); j++)
{
stObjFaceInfo faceInfo = objSubset.vFaces[j];
bool vertAlreadyExists = false;
if(totalVerts >= 3)
{
for(int iCheck = 0; iCheck < totalVerts; iCheck++)
{
if(!vertAlreadyExists && faceInfo.iPosIndex == vVertexIndex[iCheck].iPosIndex
&& faceInfo.iTexCoordIndex == vVertexIndex[iCheck].iTexCoordIndex)
{
subsetData.vIndexData.push_back(iCheck); //Set index for this vertex
vertAlreadyExists = true; //If we've made it here, the vertex already exists
break;
}
}
}
//If this vertex is not already in our vertex arrays, put it there
if(!vertAlreadyExists)
{
vVertexIndex.push_back(faceInfo);
subsetData.vIndexData.push_back(totalVerts); //Set index for this vertex
stSPDOVertexData spdoVertexData;
spdoVertexData.vPos = m_vVertexPositions[faceInfo.iPosIndex];
if (m_vVertexTexCoordinates.empty())
{
spdoVertexData.vTex = cVector3::Zero();
}
else
{
spdoVertexData.vTex = m_vVertexTexCoordinates[faceInfo.iTexCoordIndex];
}
m_vVertexData.push_back(spdoVertexData);
totalVerts++; //We created a new vertex
// get the bounding box min pos
subsetData.vBoundingBoxMinPos.x = min(subsetData.vBoundingBoxMinPos.x, spdoVertexData.vPos.x);
subsetData.vBoundingBoxMinPos.y = min(subsetData.vBoundingBoxMinPos.y, spdoVertexData.vPos.y);
subsetData.vBoundingBoxMinPos.z = min(subsetData.vBoundingBoxMinPos.z, spdoVertexData.vPos.z);
// get the bounding box max pos
subsetData.vBoundingBoxMaxPos.x = max(subsetData.vBoundingBoxMaxPos.x, spdoVertexData.vPos.x);
subsetData.vBoundingBoxMaxPos.y = max(subsetData.vBoundingBoxMaxPos.y, spdoVertexData.vPos.y);
subsetData.vBoundingBoxMaxPos.z = max(subsetData.vBoundingBoxMaxPos.z, spdoVertexData.vPos.z);
}
m_iTotalIndices++;
}
m_vSubsetData.push_back(subsetData);
}
for(unsigned int i=0; i< m_vSubsetData.size(); i++)
{
m_vBoundingBoxMinPos.x = min(m_vBoundingBoxMinPos.x, m_vSubsetData[i].vBoundingBoxMinPos.x);
m_vBoundingBoxMinPos.y = min(m_vBoundingBoxMinPos.y, m_vSubsetData[i].vBoundingBoxMinPos.y);
m_vBoundingBoxMinPos.z = min(m_vBoundingBoxMinPos.z, m_vSubsetData[i].vBoundingBoxMinPos.z);
// get the bounding box max pos
m_vBoundingBoxMaxPos.x = max(m_vBoundingBoxMaxPos.x, m_vSubsetData[i].vBoundingBoxMaxPos.x);
m_vBoundingBoxMaxPos.y = max(m_vBoundingBoxMaxPos.y, m_vSubsetData[i].vBoundingBoxMaxPos.y);
m_vBoundingBoxMaxPos.z = max(m_vBoundingBoxMaxPos.z, m_vSubsetData[i].vBoundingBoxMaxPos.z);
}
}
// *************************************************************************
void cObjModelLoader::WriteSPDOFile(const cString & strOutputFile)
{
shared_ptr<IFileOutput> pOutputFile = shared_ptr<IFileOutput>(IFileOutput::CreateOutputFile());
if(pOutputFile->Open(strOutputFile, std::ios_base::out))
{
pOutputFile->WriteLine(cString(100, "VertexCount %d\n\n", m_vVertexData.size()));
for (unsigned int i=0; i<m_vVertexData.size(); i++)
{
pOutputFile->WriteLine(cString(100, "v %0.2f %0.2f %0.2f %0.2f %0.2f %0.2f\n",
m_vVertexData[i].vPos.x, m_vVertexData[i].vPos.y, m_vVertexData[i].vPos.z,
m_vVertexData[i].vTex.x, m_vVertexData[i].vTex.y, m_vVertexData[i].vTex.z));
}
pOutputFile->WriteLine(cString(100, "\nTotalIndexCount %d\n\n", m_iTotalIndices));
for(unsigned int i=0; i< m_vSubsetData.size(); i++)
{
for(unsigned int j=0; j<m_vSubsetData[i].vIndexData.size();)
{
pOutputFile->WriteLine("t ");
pOutputFile->WriteLine(cString(100, "%d ", m_vSubsetData[i].vIndexData[j++]));
pOutputFile->WriteLine(cString(100, "%d ", m_vSubsetData[i].vIndexData[j++]));
pOutputFile->WriteLine(cString(100, "%d\n", m_vSubsetData[i].vIndexData[j++]));
}
}
pOutputFile->WriteLine(cString(100, "\nBBMin %0.2f %0.2f %0.2f\n",
m_vBoundingBoxMinPos.x, m_vBoundingBoxMinPos.y, m_vBoundingBoxMinPos.z));
pOutputFile->WriteLine(cString(100, "BBMax %0.2f %0.2f %0.2f\n",
m_vBoundingBoxMaxPos.x, m_vBoundingBoxMaxPos.y, m_vBoundingBoxMaxPos.z));
for(unsigned int i=0; i< m_vSubsetData.size(); i++)
{
pOutputFile->WriteLine(cString(100, "\nSubset %d\n\n", i));
pOutputFile->WriteLine(cString(100, "startindex %d\n", m_vSubsetData[i].iStartIndexNo));
pOutputFile->WriteLine(cString(100, "indexcount %d\n", m_vSubsetData[i].vIndexData.size()));
pOutputFile->WriteLine(cString(100, "SBBMin %0.2f %0.2f %0.2f\n",
m_vSubsetData[i].vBoundingBoxMinPos.x, m_vSubsetData[i].vBoundingBoxMinPos.y,
m_vSubsetData[i].vBoundingBoxMinPos.z));
pOutputFile->WriteLine(cString(100, "SBBMax %0.2f %0.2f %0.2f\n",
m_vSubsetData[i].vBoundingBoxMaxPos.x, m_vSubsetData[i].vBoundingBoxMaxPos.y,
m_vSubsetData[i].vBoundingBoxMaxPos.z));
pOutputFile->WriteLine(cString(100, "diffusecolor %d %d %d %d\n",
m_vSubsetData[i].diffuseColor.m_iRed, m_vSubsetData[i].diffuseColor.m_iBlue,
m_vSubsetData[i].diffuseColor.m_iGreen, m_vSubsetData[i].diffuseColor.m_iAlpha));
if (!m_vSubsetData[i].strDiffuseTextureFilename.IsEmpty())
{
pOutputFile->WriteLine("dTex " + m_vSubsetData[i].strDiffuseTextureFilename + "\n");
}
}
pOutputFile->Close();
}
}
// *************************************************************************
float cObjModelLoader::GetFloatValue(const cString & strVal)
{
tOptional<float> val = strVal.ToFloat();
if (val.IsValid())
{
return *val;
}
return 0;
}
// *************************************************************************
int cObjModelLoader::GetIntValue(const Base::cString & strVal)
{
tOptional<int> val = strVal.ToInt();
if (val.IsValid())
{
return *val;
}
return 0;
}
| 31.761273 | 98 | 0.618423 | AnkurSheel |
1e9fd884fed24bdc6d07825d9b30cbffa3d5ebbd | 5,102 | cpp | C++ | grpc/cpp-cubic/cubic_client.cpp | tumarsal/sdk-cubic | ce366b032e4401bd796599b5c2cdce7e6f280649 | [
"Apache-2.0"
] | 1 | 2020-01-08T15:10:21.000Z | 2020-01-08T15:10:21.000Z | grpc/cpp-cubic/cubic_client.cpp | iZIVer/sdk-cubic | 12c0f20c50b777c2a9f00cf881fa492bdd00e3cc | [
"Apache-2.0"
] | null | null | null | grpc/cpp-cubic/cubic_client.cpp | iZIVer/sdk-cubic | 12c0f20c50b777c2a9f00cf881fa492bdd00e3cc | [
"Apache-2.0"
] | null | null | null | // Copyright (2019) Cobalt Speech and Language, Inc.
#include "cubic_client.h"
#include <chrono>
#include <grpc/grpc.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include "cubic.grpc.pb.h"
#include "cubic_exception.h"
CubicClient::CubicClient(const std::string &url, bool secureConnection) :
mCubicVersion(""),
mServerVersion(""),
mTimeout(30000)
{
// Quick runtime check to verify that the user has linked against
// a version of protobuf that is compatible with the version used
// to generate the c++ files.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Setup credentials
std::shared_ptr<grpc::ChannelCredentials> creds;
if(secureConnection)
creds = grpc::SslCredentials(grpc::SslCredentialsOptions());
else
creds = grpc::InsecureChannelCredentials();
// Create the channel and stub
std::unique_ptr<cobaltspeech::cubic::Cubic::Stub> tmpStub =
cobaltspeech::cubic::Cubic::NewStub(grpc::CreateChannel(url, creds));
mStub.swap(tmpStub);
}
CubicClient::~CubicClient()
{}
const std::string& CubicClient::cubicVersion()
{
// Check if we have it cached.
if(mCubicVersion.empty())
this->requestVersion();
return mCubicVersion;
}
const std::string& CubicClient::serverVersion()
{
// Check if we have it cached.
if(mServerVersion.empty())
this->requestVersion();
return mServerVersion;
}
std::vector<CubicModel> CubicClient::listModels()
{
// Check if we have already cached the models
if(mModels.empty())
{
// If it is not cached, make the gRPC request.
grpc::ClientContext ctx;
cobaltspeech::cubic::ListModelsRequest request;
cobaltspeech::cubic::ListModelsResponse response;
this->setContextDeadline(ctx);
grpc::Status status = mStub->ListModels(&ctx, request, &response);
if(!status.ok())
throw CubicException(status);
// Cache the models.
for(int i=0; i < response.models_size(); i++)
{
CubicModel model(response.models(i));
mModels.push_back(model);
}
}
return mModels;
}
cobaltspeech::cubic::RecognitionResponse
CubicClient::recognize(const cobaltspeech::cubic::RecognitionConfig &config,
const char* audioData, size_t sizeInBytes)
{
// Setup the request
cobaltspeech::cubic::RecognizeRequest request;
request.mutable_audio()->set_data(audioData, sizeInBytes);
request.mutable_config()->CopyFrom(config);
// Setup the context and make the request
cobaltspeech::cubic::RecognitionResponse response;
grpc::ClientContext ctx;
this->setContextDeadline(ctx);
grpc::Status status = mStub->Recognize(&ctx, request, &response);
if(!status.ok())
throw CubicException(status);
return response;
}
CubicRecognizerStream CubicClient::streamingRecognize(
const cobaltspeech::cubic::RecognitionConfig &config)
{
// We need the context to exist for as long as the stream,
// so we are creating it as a managed pointer.
std::shared_ptr<grpc::ClientContext> ctx(new grpc::ClientContext);
this->setContextDeadline(*ctx);
// Create the grpc reader/writer.
std::shared_ptr<grpc::ClientReaderWriter<cobaltspeech::cubic::StreamingRecognizeRequest,
cobaltspeech::cubic::RecognitionResponse>>
readerWriter(mStub->StreamingRecognize(ctx.get()));
// Send the first message (the recognizer config) to Cubic. We must
// do this before we can send any audio data.
cobaltspeech::cubic::StreamingRecognizeRequest request;
request.mutable_config()->CopyFrom(config);
if(!readerWriter->Write(request))
throw CubicException("couldn't send recognizer config to Cubic");
return CubicRecognizerStream(readerWriter, ctx);
}
void CubicClient::setRequestTimeout(unsigned int milliseconds)
{
mTimeout = milliseconds;
}
CubicClient::CubicClient(const CubicClient &)
{
// Do nothing. This copy constructor is intentionally private
// and does nothing because we don't want to copy client objects.
}
CubicClient& CubicClient::operator=(const CubicClient &)
{
// Do nothing. The assignment operator is intentionally private
// and does nothing because we don't want to copy client objects.
return *this;
}
void CubicClient::setContextDeadline(grpc::ClientContext &ctx)
{
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(mTimeout);
ctx.set_deadline(deadline);
}
void CubicClient::requestVersion()
{
grpc::ClientContext ctx;
google::protobuf::Empty request;
cobaltspeech::cubic::VersionResponse response;
this->setContextDeadline(ctx);
grpc::Status status = mStub->Version(&ctx, request, &response);
if(!status.ok())
throw CubicException(status);
mCubicVersion = response.cubic();
mServerVersion = response.server();
}
| 30.011765 | 92 | 0.688554 | tumarsal |
1ea035b4bde24e1a106dc28294b70b982f388b2c | 271 | cpp | C++ | chp3/excercises/excercise3-3.cpp | justinePrasad/PPC2nd | fc28c10dace8b46bd35abc9b62d1f56577035c19 | [
"MIT"
] | null | null | null | chp3/excercises/excercise3-3.cpp | justinePrasad/PPC2nd | fc28c10dace8b46bd35abc9b62d1f56577035c19 | [
"MIT"
] | null | null | null | chp3/excercises/excercise3-3.cpp | justinePrasad/PPC2nd | fc28c10dace8b46bd35abc9b62d1f56577035c19 | [
"MIT"
] | null | null | null | #include "../../../../std_lib_facilities.h"
//header file from Programming-_Principles_and_Practice_Using_Cpp
int main()
{
//some key words are reserved, and identifier can't start with numbers
char 3 = 'a';
int double = 0;
char int = '1';
char send = 'a';
}
| 22.583333 | 71 | 0.667897 | justinePrasad |
1ea163bf62c68060c7610c9b5a74ff0303f65543 | 527 | cpp | C++ | real.cpp | yuantailing/2-center | d9d7408bfda30626160ae569ee36b8f5a5ebe38e | [
"MIT"
] | null | null | null | real.cpp | yuantailing/2-center | d9d7408bfda30626160ae569ee36b8f5a5ebe38e | [
"MIT"
] | null | null | null | real.cpp | yuantailing/2-center | d9d7408bfda30626160ae569ee36b8f5a5ebe38e | [
"MIT"
] | null | null | null | #include "real.h"
BoundingBox BoundingBox::from_vector(std::vector<Coord> const &S) {
BoundingBox bb;
if (S.empty()) {
bb.xmin = bb.xmax = bb.ymin = bb.ymax = Real(0);
} else {
bb.xmin = bb.xmax = S.front().x;
bb.ymin = bb.ymax = S.front().y;
}
for (Coord const &coord: S) {
bb.xmin = std::min(bb.xmin, coord.x);
bb.xmax = std::max(bb.xmax, coord.x);
bb.ymin = std::min(bb.ymin, coord.y);
bb.ymax = std::max(bb.ymax, coord.y);
}
return bb;
}
| 27.736842 | 67 | 0.531309 | yuantailing |
1ea4281e5b8799f25917b3d74078c39dd9924a9c | 1,069 | hpp | C++ | Electro/src/Renderer/Renderer2D.hpp | SurgeTechnologies/Electro | 8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394 | [
"MIT"
] | 21 | 2021-08-30T15:30:22.000Z | 2022-02-09T14:05:36.000Z | Electro/src/Renderer/Renderer2D.hpp | SurgeTechnologies/Electro | 8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394 | [
"MIT"
] | null | null | null | Electro/src/Renderer/Renderer2D.hpp | SurgeTechnologies/Electro | 8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394 | [
"MIT"
] | null | null | null | // ELECTRO ENGINE
// Copyright(c) 2021 - Electro Team - All rights reserved
#pragma once
#include "Core/Base.hpp"
#include "Math/BoundingBox.hpp"
#include "Renderer/Camera/EditorCamera.hpp"
#include "Scene/Components.hpp"
#include "Scene/SceneCamera.hpp"
namespace Electro
{
class Renderer2D
{
public:
static void Init();
static void Shutdown();
static void BeginScene(const EditorCamera& camera);
static void BeginScene(const glm::mat4& viewProjection);
static void EndScene();
static void Flush();
static void SubmitLine(const glm::vec3& p1, const glm::vec3& p2, const glm::vec4& color = { 1.0f, 1.0f, 1.0f, 1.0f });
static void SubmitAABB(const BoundingBox& aabb, const glm::mat4& transform, const glm::vec4& color = { 1.0f, 1.0f, 1.0f, 1.0f });
static void SubmitAABB(glm::vec4* corners, const glm::mat4& transform, const glm::vec4& color = { 1.0f, 1.0f, 1.0f, 1.0f });
private:
static void StartBatch();
static void NextBatch();
};
}
| 34.483871 | 137 | 0.638915 | SurgeTechnologies |
1ea5dc5fec27d2447a909e202a959efea15592ee | 761 | hpp | C++ | Framework/Common/include/MemoryManager.hpp | Quanwei1992/RTR | cd4e6e056de2bd0ec7ee993b06975508a561b0d6 | [
"MIT"
] | 3 | 2021-03-30T09:02:56.000Z | 2022-03-16T05:43:21.000Z | Framework/Common/include/MemoryManager.hpp | Quanwei1992/RTR | cd4e6e056de2bd0ec7ee993b06975508a561b0d6 | [
"MIT"
] | null | null | null | Framework/Common/include/MemoryManager.hpp | Quanwei1992/RTR | cd4e6e056de2bd0ec7ee993b06975508a561b0d6 | [
"MIT"
] | null | null | null | #pragma once
#include <new>
#include "IRuntimeModule.hpp"
#include "Allocator.hpp"
RTR_BEGIN_NAMESPACE
class MemoryManager : implements IRuntimeModule
{
public:
template<class T, typename... Arguments>
T* New(Arguments... parameters)
{
return new (Allocate(sizeof(T))) T(parameters...);
}
template<class T>
void Delete(T* p)
{
p->~T();
Free(p, sizeof(T));
}
public:
virtual ~MemoryManager() {}
virtual int Initialize();
virtual void Finalize();
virtual void Tick();
void* Allocate(size_t size);
void* Allocate(size_t size, size_t alignment);
void Free(void* p, size_t size);
private:
static size_t* m_pBlockSizeLookup;
static Allocator* m_pAllocators;
private:
static Allocator* LookUpAllocator(size_t size);
};
RTR_END_NAMESPACE | 18.560976 | 52 | 0.722733 | Quanwei1992 |
1ea6eb36eabefc34b6b5f9f90572fec59af660fb | 9,506 | cpp | C++ | GPU2/lib/gpunb.avx.cpp | JamesAPetts/NBODY6df | bc1d1d765a7a0608f2fcc650e31a20e50ff4ada7 | [
"MIT"
] | 4 | 2017-03-04T07:30:10.000Z | 2020-02-06T01:50:38.000Z | GPU2/lib/gpunb.avx.cpp | JamesAPetts/NBODY6df | bc1d1d765a7a0608f2fcc650e31a20e50ff4ada7 | [
"MIT"
] | 1 | 2018-03-15T15:03:18.000Z | 2018-03-26T16:20:11.000Z | GPU2/lib/gpunb.avx.cpp | JamesAPetts/NBODY6df | bc1d1d765a7a0608f2fcc650e31a20e50ff4ada7 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cassert>
#define TMAX 8 // maximum number of threads
#if 1
#include <omp.h>
#else
static inline int omp_get_num_threads(){return 1;}
static inline int omp_get_thread_num() {return 0;}
#endif
#define PROFILE
#ifdef PROFILE
#include <sys/time.h>
static double get_wtime(){
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + 1.e-6 * tv.tv_usec;
}
#else
static double get_wtime(){
return 0.0;
}
#endif
static double time_send, time_grav;
static long long numInter;
template <class T>
struct myvector{
size_t num;
T *val;
myvector() : num(0), val(NULL) {}
~myvector(){
delete [] val;
val = NULL;
}
void clear(){
num = 0;
}
void reserve(size_t count){
val = new T[count];
}
void free(){
delete [] val;
val = NULL;
}
void push_back(const T &t){
val[num++] = t;
}
size_t size() const {
return num;
}
T &operator[](int i){
return val[i];
}
const T &operator[](int i) const{
return val[i];
}
};
typedef float v4sf __attribute__ ((vector_size(16)));
typedef float v8sf __attribute__ ((vector_size(32)));
typedef double v2df __attribute__ ((vector_size(16)));
typedef double v4df __attribute__ ((vector_size(32)));
#define REP4(x) {x, x, x, x}
#define REP8(x) {x, x, x, x, x, x, x, x}
static inline v8sf v8sf_rsqrt(const v8sf x){
v8sf y = __builtin_ia32_rsqrtps256(x);
return ((v8sf)REP8(-0.5f) * y) * (x*y*y + (v8sf)REP8(-3.0f));
}
static v4sf *jparr1; // {x, y, z, m}
static v4sf *jparr2; // {vx, vy, vz, pad}
static myvector<int> nblist[TMAX][4];
static int nbody, nbodymax;
static void *amalloc64(size_t n){
void *ptr;
(void)posix_memalign(&ptr, 64, n);
assert(ptr);
return ptr;
}
void GPUNB_open(int nbmax){
time_send = time_grav = 0.0;
numInter = 0;
nbodymax = nbmax;
jparr1 = (v4sf *)amalloc64(sizeof(v4sf) * (nbmax+3));
jparr2 = (v4sf *)amalloc64(sizeof(v4sf) * (nbmax+3));
int numCPU = -1;
#pragma omp parallel
{
int nth = omp_get_num_threads();
assert(nth <= TMAX);
int tid = omp_get_thread_num();
for(int v=0; v<4; v++){
nblist[tid][v].reserve(nbmax);
}
if(tid == 0) numCPU = omp_get_num_threads();
}
#ifdef PROFILE
fprintf(stderr, "***********************\n");
fprintf(stderr, "Initializing NBODY6/AVX library\n");
fprintf(stderr, "#threads = %d\n", numCPU);
fprintf(stderr, "***********************\n");
#endif
}
void GPUNB_close(){
free(jparr1); jparr1 = NULL;
free(jparr2); jparr2 = NULL;
#pragma omp parallel
{
int tid = omp_get_thread_num();
for(int v=0; v<4; v++){
nblist[tid][v].free();
}
}
nbodymax = 0;
#ifdef PROFILE
fprintf(stderr, "***********************\n");
fprintf(stderr, "Closed NBODY6/AVX library\n");
fprintf(stderr, "time send : %f sec\n", time_send);
fprintf(stderr, "time grav : %f sec\n", time_grav);
fprintf(stderr, "%f Gflops (gravity part only)\n", 60.e-9 * numInter / time_grav);
fprintf(stderr, "***********************\n");
#endif
}
void GPUNB_send(
int nj,
double mj[],
double xj[][3],
double vj[][3])
{
time_send -= get_wtime();
nbody = nj;
assert(nbody <= nbodymax);
#pragma omp parallel for
for(int j=0; j<nj; j++){
const v4df jp1 = {xj[j][0], xj[j][1], xj[j][2], mj[j]};
const v4df jp2 = {vj[j][0], vj[j][1], vj[j][2], 0.0 };
jparr1[j] = __builtin_ia32_cvtpd2ps256(jp1);
jparr2[j] = __builtin_ia32_cvtpd2ps256(jp2);
}
if(nj%2){ // padding
jparr1[nj] = (v4sf){255.0f, 255.0f, 255.0f, 0.0f};
jparr2[nj] = (v4sf){0.0f, 0.0f, 0.0f, 0.0f};
nbody++;
}
time_send += get_wtime();
}
static inline v8sf gen_i_particle(double x, double y, double z, double w){
const v4df vd = {x, y, z, w};
const v4sf vs = __builtin_ia32_cvtpd2ps256(vd);
v8sf ret = REP8(0.0f);
ret = __builtin_ia32_vinsertf128_ps256(ret, vs, 0);
ret = __builtin_ia32_vinsertf128_ps256(ret, vs, 1);
return ret;
}
static inline void reduce_force(const v8sf f8, double &x, double &y, double &z, double &w){
const v4sf fh = __builtin_ia32_vextractf128_ps256(f8, 0);
const v4sf fl = __builtin_ia32_vextractf128_ps256(f8, 1);
const v4df fsum = __builtin_ia32_cvtps2pd256(fh)
+ __builtin_ia32_cvtps2pd256(fl);
const v2df xy = __builtin_ia32_vextractf128_pd256(fsum, 0);
const v2df zw = __builtin_ia32_vextractf128_pd256(fsum, 1);
x = __builtin_ia32_vec_ext_v2df(xy, 0);
y = __builtin_ia32_vec_ext_v2df(xy, 1);
z = __builtin_ia32_vec_ext_v2df(zw, 0);
w = __builtin_ia32_vec_ext_v2df(zw, 1);
}
void GPUNB_regf(
int ni,
double h2d[],
double dtr[],
double xid[][3],
double vid[][3],
double acc[][3],
double jrk[][3],
double pot[],
int lmax,
int nbmax,
int *listbase)
{
time_grav -= get_wtime();
numInter += ni * nbody;
#pragma omp parallel for
for(int i=0; i<ni; i+=4){
int tid = omp_get_thread_num();
nblist[tid][0].clear();
nblist[tid][1].clear();
nblist[tid][2].clear();
nblist[tid][3].clear();
int nii = (ni-i < 4) ? ni-i : 4;
const v8sf xi = gen_i_particle(xid[i+0][0], xid[i+1][0], xid[i+2][0], xid[i+3][0]);
const v8sf yi = gen_i_particle(xid[i+0][1], xid[i+1][1], xid[i+2][1], xid[i+3][1]);
const v8sf zi = gen_i_particle(xid[i+0][2], xid[i+1][2], xid[i+2][2], xid[i+3][2]);
const v8sf vxi = gen_i_particle(vid[i+0][0], vid[i+1][0], vid[i+2][0], vid[i+3][0]);
const v8sf vyi = gen_i_particle(vid[i+0][1], vid[i+1][1], vid[i+2][1], vid[i+3][1]);
const v8sf vzi = gen_i_particle(vid[i+0][2], vid[i+1][2], vid[i+2][2], vid[i+3][2]);
static const v8sf h2mask[5] = {
{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0},
{1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0},
{1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0},
{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0},
};
const v8sf h2i = gen_i_particle(h2d[i+0], h2d[i+1], h2d[i+2], h2d[i+3]) * h2mask[nii];
const v8sf dtri = gen_i_particle(dtr[i+0], dtr[i+1], dtr[i+2], dtr[i+3]);
v8sf Ax = REP8(0.0f);
v8sf Ay = REP8(0.0f);
v8sf Az = REP8(0.0f);
v8sf Jx = REP8(0.0f);
v8sf Jy = REP8(0.0f);
v8sf Jz = REP8(0.0f);
v8sf poti = REP8(0.0f);
const v4sf *jpp1 = jparr1;
const v4sf *jpp2 = jparr2;
const int nj = ::nbody;
for(int j=0; j<nj; j+=2){
const v8sf jp1 = *(v8sf *)(jpp1 + j);
const v8sf jp2 = *(v8sf *)(jpp2 + j);
const v8sf xj = __builtin_ia32_shufps256(jp1, jp1, 0x00);
const v8sf yj = __builtin_ia32_shufps256(jp1, jp1, 0x55);
const v8sf zj = __builtin_ia32_shufps256(jp1, jp1, 0xaa);
const v8sf mj = __builtin_ia32_shufps256(jp1, jp1, 0xff);
const v8sf vxj = __builtin_ia32_shufps256(jp2, jp2, 0x00);
const v8sf vyj = __builtin_ia32_shufps256(jp2, jp2, 0x55);
const v8sf vzj = __builtin_ia32_shufps256(jp2, jp2, 0xaa);
const v8sf dx = xj - xi;
const v8sf dy = yj - yi;
const v8sf dz = zj - zi;
const v8sf dvx = vxj - vxi;
const v8sf dvy = vyj - vyi;
const v8sf dvz = vzj - vzi;
const v8sf dxp = dx + dtri * dvx;
const v8sf dyp = dy + dtri * dvy;
const v8sf dzp = dz + dtri * dvz;
const v8sf r2 = dx*dx + dy*dy + dz*dz;
v8sf rv = dx*dvx + dy*dvy + dz*dvz;
const v8sf r2p = dxp*dxp + dyp*dyp + dzp*dzp;
const v8sf r2min = __builtin_ia32_minps256(r2, r2p);
const v8sf mask = __builtin_ia32_cmpps256(r2min, h2i, 17); // 17 : less-than ordered quiet
const int bits = __builtin_ia32_movmskps256(mask);
if(bits){
//if(bits & 0x0f){
if (bits&1) nblist[tid][0].push_back(j);
if (bits&2) nblist[tid][1].push_back(j);
if (bits&4) nblist[tid][2].push_back(j);
if (bits&8) nblist[tid][3].push_back(j);
//}
//if(bits & 0xf0){
if (bits&0x10) nblist[tid][0].push_back(j+1);
if (bits&0x20) nblist[tid][1].push_back(j+1);
if (bits&0x40) nblist[tid][2].push_back(j+1);
if (bits&0x80) nblist[tid][3].push_back(j+1);
//}
}
v8sf rinv1 = v8sf_rsqrt(r2);
rinv1 = __builtin_ia32_andnps256(mask, rinv1);
const v8sf rinv2 = rinv1 * rinv1;
rinv1 *= mj;
poti += rinv1;
const v8sf rinv3 = rinv1 * rinv2;
rv *= (v8sf)REP8(-3.0f) * rinv2;
Ax += rinv3 * dx;
Ay += rinv3 * dy;
Az += rinv3 * dz;
Jx += rinv3 * (dvx + rv * dx);
Jy += rinv3 * (dvy + rv * dy);
Jz += rinv3 * (dvz + rv * dz);
}
reduce_force(Ax, acc[i+0][0], acc[i+1][0], acc[i+2][0], acc[i+3][0]);
reduce_force(Ay, acc[i+0][1], acc[i+1][1], acc[i+2][1], acc[i+3][1]);
reduce_force(Az, acc[i+0][2], acc[i+1][2], acc[i+2][2], acc[i+3][2]);
reduce_force(Jx, jrk[i+0][0], jrk[i+1][0], jrk[i+2][0], jrk[i+3][0]);
reduce_force(Jy, jrk[i+0][1], jrk[i+1][1], jrk[i+2][1], jrk[i+3][1]);
reduce_force(Jz, jrk[i+0][2], jrk[i+1][2], jrk[i+2][2], jrk[i+3][2]);
reduce_force(poti, pot[i+0], pot[i+1], pot[i+2], pot[i+3]);
for(int ii=0; ii<nii; ii++){
const int nnb = nblist[tid][ii].size();
int *nnbp = listbase + lmax * (i+ii);
int *nblistp = nnbp + 1;
if(nnb > nbmax){
*nnbp = -1;
}else{
*nnbp = nnb;
for(int k=0; k<nnb; k++){
nblistp[k] = nblist[tid][ii][k];
}
}
}
}
time_grav += get_wtime();
}
extern "C" {
void gpunb_open_( int *nbmax){
GPUNB_open(*nbmax);
}
void gpunb_close_(){
GPUNB_close();
}
void gpunb_send_(
int *nj,
double mj[],
double xj[][3],
double vj[][3]){
GPUNB_send(*nj, mj, xj, vj);
}
void gpunb_regf_(
int *ni,
double h2[],
double dtr[],
double xi[][3],
double vi[][3],
double acc[][3],
double jrk[][3],
double pot[],
int *lmax,
int *nbmax,
int *list){ // list[][lmax]
GPUNB_regf(*ni, h2, dtr, xi, vi, acc, jrk, pot, *lmax, *nbmax, list);
}
}
| 27.082621 | 93 | 0.60425 | JamesAPetts |
1ea792ea9ff20e3010f12071447fcef0c4815418 | 2,565 | hh | C++ | include/seastar/coroutine/maybe_yield.hh | bigo-sg/seastar | 64a9499ee01c66f19dc45a9cd4f0d84c45eb1b7d | [
"Apache-2.0"
] | 6,526 | 2015-09-22T16:47:59.000Z | 2022-03-31T07:31:07.000Z | include/seastar/coroutine/maybe_yield.hh | bigo-sg/seastar | 64a9499ee01c66f19dc45a9cd4f0d84c45eb1b7d | [
"Apache-2.0"
] | 925 | 2015-09-23T13:52:53.000Z | 2022-03-31T21:33:25.000Z | include/seastar/coroutine/maybe_yield.hh | bigo-sg/seastar | 64a9499ee01c66f19dc45a9cd4f0d84c45eb1b7d | [
"Apache-2.0"
] | 1,473 | 2015-09-22T23:19:04.000Z | 2022-03-31T21:09:00.000Z | /*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2021-present ScyllaDB
*/
#pragma once
#include <concepts>
#include <type_traits>
#include <seastar/core/coroutine.hh>
namespace seastar::coroutine {
namespace internal {
struct maybe_yield_awaiter final : task {
using coroutine_handle_t = SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<void>;
coroutine_handle_t when_ready;
task* main_coroutine_task;
bool await_ready() const {
return !need_preempt();
}
template <typename T>
void await_suspend(SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<T> h) {
when_ready = h;
main_coroutine_task = &h.promise(); // for waiting_task()
schedule(this);
}
void await_resume() {
}
virtual void run_and_dispose() noexcept override {
when_ready.resume();
// No need to delete, this is allocated on the coroutine frame
}
virtual task* waiting_task() noexcept override {
return main_coroutine_task;
}
};
}
/// Preempt if the current task quota expired.
///
/// `maybe_yield()` can be used to break a long computation in a
/// coroutine and allow the reactor to preempt its execution. This
/// allows other tasks to gain access to the CPU. If the task quota
/// did not expire, the coroutine continues execution.
///
/// It should be used in long loops that do not contain other `co_await`
/// calls.
///
/// Example
///
/// ```
/// seastar::future<int> long_loop(int n) {
/// float acc = 0;
/// for (int i = 0; i < n; ++i) {
/// acc += std::sin(float(i));
/// co_await seastar::coroutine::maybe_yield();
/// }
/// co_return acc;
/// }
/// ```
class [[nodiscard("must co_await an maybe_yield() object")]] maybe_yield {
public:
auto operator co_await() { return internal::maybe_yield_awaiter(); }
};
}
| 27.880435 | 92 | 0.682261 | bigo-sg |
1eaaa5b8e1ac79039309ae700e87476bf818f8d4 | 8,875 | cpp | C++ | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Data/Data.cpp | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Data/Data.cpp | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | null | null | null | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Data/Data.cpp | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "precompiled.h"
#include "Data.h"
#include <AzCore/Component/EntityBus.h>
#include <AzCore/Math/VectorFloat.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Serialization/SerializeContext.h>
namespace DataCpp
{
using namespace ScriptCanvas;
using namespace ScriptCanvas::Data;
AZ_INLINE AZStd::pair<bool, Type> FromAZTypeHelper(const AZ::Uuid& type)
{
if (type.IsNull())
{
return { true, Type::Invalid() };
}
else if (IsAABB(type))
{
return { true, Type::AABB() };
}
else if (IsBoolean(type))
{
return { true, Type::Boolean() };
}
else if (IsColor(type))
{
return { true, Type::Color() };
}
else if (IsCRC(type))
{
return { true, Type::CRC() };
}
else if (IsEntityID(type))
{
return { true, Type::EntityID() };
}
else if (IsMatrix3x3(type))
{
return { true, Type::Matrix3x3() };
}
else if (IsMatrix4x4(type))
{
return { true, Type::Matrix4x4() };
}
else if (IsNumber(type))
{
return { true, Type::Number() };
}
else if (IsOBB(type))
{
return { true, Type::OBB() };
}
else if (IsPlane(type))
{
return { true, Type::Plane() };
}
else if (IsRotation(type))
{
return { true, Type::Rotation() };
}
else if (IsString(type))
{
return { true, Type::String() };
}
else if (IsTransform(type))
{
return { true, Type::Transform() };
}
else if (IsVector2(type))
{
return { true, Type::Vector2() };
}
else if (IsVector3(type))
{
return { true, Type::Vector3() };
}
else if (IsVector4(type))
{
return { true, Type::Vector4() };
}
else
{
return { false, Type::Invalid() };
}
}
AZ_INLINE AZStd::pair<bool, Type> FromBehaviorContextTypeHelper(const AZ::Uuid& type)
{
if (type.IsNull())
{
return { true, Type::Invalid() };
}
else if (IsBoolean(type))
{
return { true, Type::Boolean() };
}
else if (IsEntityID(type))
{
return { true, Type::EntityID() };
}
else if (IsNumber(type))
{
return { true, Type::Number() };
}
else if (IsString(type))
{
return { true, Type::String() };
}
else
{
return { false, Type::Invalid() };
}
}
AZ_INLINE const char* GetBehaviorClassName(const AZ::Uuid& typeID)
{
const AZ::BehaviorClass* behaviorClass = AZ::BehaviorContextHelper::GetClass(typeID);
return behaviorClass ? behaviorClass->m_name.c_str() : "Invalid";
}
AZ_INLINE bool IsSupportedBehaviorContextObject(const AZ::Uuid& typeID)
{
return AZ::BehaviorContextHelper::GetClass(typeID) != nullptr;
}
}
namespace ScriptCanvas
{
namespace Data
{
Type FromAZType(const AZ::Uuid& type)
{
AZStd::pair<bool, Type> help = DataCpp::FromAZTypeHelper(type);
return help.first ? help.second : Type::BehaviorContextObject(type);
}
Type FromAZTypeChecked(const AZ::Uuid& type)
{
AZStd::pair<bool, Type> help = DataCpp::FromAZTypeHelper(type);
return help.first
? help.second
: DataCpp::IsSupportedBehaviorContextObject(type)
? Type::BehaviorContextObject(type)
: Type::Invalid();
}
Type FromBehaviorContextType(const AZ::Uuid& type)
{
AZStd::pair<bool, Type> help = DataCpp::FromBehaviorContextTypeHelper(type);
return help.first ? help.second : Type::BehaviorContextObject(type);
}
Type FromBehaviorContextTypeChecked(const AZ::Uuid& type)
{
AZStd::pair<bool, Type> help = DataCpp::FromBehaviorContextTypeHelper(type);
return help.first
? help.second
: DataCpp::IsSupportedBehaviorContextObject(type)
? Type::BehaviorContextObject(type)
: Type::Invalid();
}
const char* GetName(const Type& type)
{
switch (type.GetType())
{
case eType::AABB:
return eTraits<eType::AABB>::s_traits.GetName();
case eType::BehaviorContextObject:
return DataCpp::GetBehaviorClassName(type.GetAZType());
case eType::Boolean:
return eTraits<eType::Boolean>::s_traits.GetName();
case eType::Color:
return eTraits<eType::Color>::s_traits.GetName();
case eType::CRC:
return eTraits<eType::CRC>::s_traits.GetName();
case eType::EntityID:
return eTraits<eType::EntityID>::s_traits.GetName();
case eType::Invalid:
return "Invalid";
case eType::Matrix3x3:
return eTraits<eType::Matrix3x3>::s_traits.GetName();
case eType::Matrix4x4:
return eTraits<eType::Matrix4x4>::s_traits.GetName();
case eType::Number:
return eTraits<eType::Number>::s_traits.GetName();
case eType::OBB:
return eTraits<eType::OBB>::s_traits.GetName();
case eType::Plane:
return eTraits<eType::Plane>::s_traits.GetName();
case eType::Rotation:
return eTraits<eType::Rotation>::s_traits.GetName();
case eType::String:
return eTraits<eType::String>::s_traits.GetName();
case eType::Transform:
return eTraits<eType::Transform>::s_traits.GetName();
case eType::Vector2:
return eTraits<eType::Vector2>::s_traits.GetName();
case eType::Vector3:
return eTraits<eType::Vector3>::s_traits.GetName();
case eType::Vector4:
return eTraits<eType::Vector4>::s_traits.GetName();
default:
AZ_Assert(false, "Invalid type!");
return "Invalid";
}
}
const char* GetBehaviorContextName(const AZ::Uuid& azType)
{
const Type& type = ScriptCanvas::Data::FromAZType(azType);
switch (type.GetType())
{
case eType::Boolean:
return eTraits<eType::Boolean>::s_traits.GetName();
case eType::EntityID:
return eTraits<eType::EntityID>::s_traits.GetName();
case eType::Invalid:
return "Invalid";
case eType::Number:
return eTraits<eType::Number>::s_traits.GetName();
case eType::String:
return eTraits<eType::String>::s_traits.GetName();
case eType::AABB:
case eType::BehaviorContextObject:
case eType::Color:
case eType::CRC:
case eType::Matrix3x3:
case eType::Matrix4x4:
case eType::OBB:
case eType::Plane:
case eType::Rotation:
case eType::Transform:
case eType::Vector3:
case eType::Vector2:
case eType::Vector4:
default:
return DataCpp::GetBehaviorClassName(azType);
}
}
void Type::Reflect(AZ::ReflectContext* reflection)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<Type>()
->Version(1)
->Field("m_type", &Type::m_type)
->Field("m_azType", &Type::m_azType)
->Field("m_independentType", &Type::m_independentType)
;
}
}
}
} | 30.084746 | 104 | 0.523606 | horvay |
1eacd9e8ec30384638a6a74970d6f1c2c329c251 | 9,773 | hxx | C++ | main/forms/source/component/GroupManager.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/forms/source/component/GroupManager.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/forms/source/component/GroupManager.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _FRM_GROUPMANAGER_HXX_
#define _FRM_GROUPMANAGER_HXX_
#include <com/sun/star/sdbc/XRowSet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/container/XContainer.hpp>
#include <comphelper/stl_types.hxx>
#include <cppuhelper/implbase2.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/types.hxx>
using namespace comphelper;
/*========================================================================
Funktionsweise GroupManager:
Der GroupManager horcht an der starform, ob FormComponents eingefuegt oder entfernt
werden. Zusaetzlich horcht er bei den FormComponents an den Properties
"Name" und "TabIndex". Mit diesen Infos aktualisiert er seine Gruppen.
Der GroupManager verwaltet eine Gruppe, in der alle Controls nach TabIndex
geordnet sind, und ein Array von Gruppen, in dem jede FormComponent noch
einmal einer Gruppe dem Namen nach zugeordnet wird.
Die einzelnen Gruppen werden ueber eine Map aktiviert, wenn sie mehr als
ein Element besitzen.
Die Gruppen verwalten intern die FormComponents in zwei Arrays. In dem
GroupCompArray werden die Components nach TabIndex und Einfuegepostion
sortiert. Da auf dieses Array ueber die FormComponent zugegriffen
wird, gibt es noch das GroupCompAccessArray, in dem die FormComponents
nach ihrer Speicheradresse sortiert sind. Jedes Element des
GroupCompAccessArrays ist mit einem Element des GroupCompArrays verpointert.
========================================================================*/
//.........................................................................
namespace frm
{
//.........................................................................
//========================================================================
template <class ELEMENT, class LESS_COMPARE>
sal_Int32 insert_sorted(::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, const LESS_COMPARE& _rCompareOp)
{
typename ::std::vector<ELEMENT>::iterator aInsertPos = lower_bound(
_rArray.begin(),
_rArray.end(),
_rNewElement,
_rCompareOp
);
aInsertPos = _rArray.insert(aInsertPos, _rNewElement);
return aInsertPos - _rArray.begin();
}
template <class ELEMENT, class LESS_COMPARE>
sal_Bool seek_entry(const ::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, sal_Int32& nPos, const LESS_COMPARE& _rCompareOp)
{
typename ::std::vector<ELEMENT>::const_iterator aExistentPos = lower_bound(
_rArray.begin(),
_rArray.end(),
_rNewElement,
_rCompareOp
);
if ((aExistentPos != _rArray.end()) && (*aExistentPos == _rNewElement))
{ // we have a valid "lower or equal" element and it's really "equal"
nPos = aExistentPos - _rArray.begin();
return sal_True;
}
nPos = -1;
return sal_False;
}
//========================================================================
class OGroupComp
{
::rtl::OUString m_aName;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xComponent;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> m_xControlModel;
sal_Int32 m_nPos;
sal_Int16 m_nTabIndex;
friend class OGroupCompLess;
public:
OGroupComp(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, sal_Int32 nInsertPos );
OGroupComp(const OGroupComp& _rSource);
OGroupComp();
sal_Bool operator==( const OGroupComp& rComp ) const;
inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
inline const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>& GetControlModel() const { return m_xControlModel; }
sal_Int32 GetPos() const { return m_nPos; }
sal_Int16 GetTabIndex() const { return m_nTabIndex; }
::rtl::OUString GetName() const { return m_aName; }
};
DECLARE_STL_VECTOR(OGroupComp, OGroupCompArr);
//========================================================================
class OGroupComp;
class OGroupCompAcc
{
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xComponent;
OGroupComp m_aGroupComp;
friend class OGroupCompAccLess;
public:
OGroupCompAcc(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, const OGroupComp& _rGroupComp );
sal_Bool operator==( const OGroupCompAcc& rCompAcc ) const;
inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
const OGroupComp& GetGroupComponent() const { return m_aGroupComp; }
};
DECLARE_STL_VECTOR(OGroupCompAcc, OGroupCompAccArr);
//========================================================================
class OGroup
{
OGroupCompArr m_aCompArray;
OGroupCompAccArr m_aCompAccArray;
::rtl::OUString m_aGroupName;
sal_uInt16 m_nInsertPos; // Die Einfugeposition der GroupComps wird von der Gruppe bestimmt.
friend class OGroupLess;
public:
OGroup( const ::rtl::OUString& rGroupName );
#ifdef DBG_UTIL
OGroup( const OGroup& _rSource ); // just to ensure the DBG_CTOR call
#endif
virtual ~OGroup();
sal_Bool operator==( const OGroup& rGroup ) const;
::rtl::OUString GetGroupName() const { return m_aGroupName; }
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > GetControlModels() const;
void InsertComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void RemoveComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
sal_uInt16 Count() const { return sal::static_int_cast< sal_uInt16 >(m_aCompArray.size()); }
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetObject( sal_uInt16 nP ) const
{ return m_aCompArray[nP].GetComponent(); }
};
DECLARE_STL_USTRINGACCESS_MAP(OGroup, OGroupArr);
DECLARE_STL_VECTOR(OGroupArr::iterator, OActiveGroups);
//========================================================================
class OGroupManager : public ::cppu::WeakImplHelper2< ::com::sun::star::beans::XPropertyChangeListener, ::com::sun::star::container::XContainerListener>
{
OGroup* m_pCompGroup; // Alle Components nach TabIndizes sortiert
OGroupArr m_aGroupArr; // Alle Components nach Gruppen sortiert
OActiveGroups m_aActiveGroupMap; // In dieser Map werden die Indizes aller Gruppen gehalten,
// die mehr als 1 Element haben
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >
m_xContainer;
// Helper functions
void InsertElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void RemoveElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void removeFromGroupMap(const ::rtl::OUString& _sGroupName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xSet);
public:
OGroupManager(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _rxContainer);
virtual ~OGroupManager();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::beans::XPropertyChangeListener
virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::container::XContainerListener
virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
// Other functions
sal_Int32 getGroupCount();
void getGroup(sal_Int32 nGroup, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup, ::rtl::OUString& Name);
void getGroupByName(const ::rtl::OUString& Name, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > getControlModels();
};
//.........................................................................
} // namespace frm
//.........................................................................
#endif // _FRM_GROUPMANAGER_HXX_
| 43.435556 | 173 | 0.671237 | Grosskopf |
1eace8ab8944f394274dd8a1ebc2f9c66bece4c9 | 2,097 | cpp | C++ | src/option/Options.cpp | agxmaster/polarphp | 31012ff7e6c0f72ee587546c296b06013c98cf9a | [
"PHP-3.01"
] | 1,083 | 2018-05-26T09:12:13.000Z | 2022-02-14T00:13:01.000Z | src/option/Options.cpp | agxmaster/polarphp | 31012ff7e6c0f72ee587546c296b06013c98cf9a | [
"PHP-3.01"
] | 27 | 2018-08-25T07:28:25.000Z | 2021-05-06T06:31:09.000Z | src/option/Options.cpp | agxmaster/polarphp | 31012ff7e6c0f72ee587546c296b06013c98cf9a | [
"PHP-3.01"
] | 78 | 2018-08-28T02:43:09.000Z | 2020-11-21T15:45:24.000Z | //===--- Options.cpp - Option info & table --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2019/12/02.
#include "polarphp/option/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
namespace polar::options {
using namespace llvm::opt;
#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "polarphp/option/OptionsDef.h"
#undef PREFIX
static const OptTable::Info sg_infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES) \
{PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS, VALUES},
#include "polarphp/option/OptionsDef.h"
#undef OPTION
};
namespace {
class PolarphpOptTable : public OptTable
{
public:
PolarphpOptTable()
: OptTable(sg_infoTable)
{}
};
} // end anonymous namespace
} // polar::options
namespace polar {
using namespace llvm::opt;
using polar::options::PolarphpOptTable;
std::unique_ptr<OptTable> create_polarphp_opt_table()
{
return std::unique_ptr<OptTable>(new PolarphpOptTable());
}
} // polar
| 31.298507 | 85 | 0.668574 | agxmaster |
1eae03a6503fdb6ac21b41d940a53dc91558f605 | 5,349 | cpp | C++ | types/DatetimeIntervalType.cpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | types/DatetimeIntervalType.cpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | types/DatetimeIntervalType.cpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include "types/DatetimeIntervalType.hpp"
#include <cinttypes>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <string>
#include "types/IntervalLit.hpp"
#include "types/IntervalParser.hpp"
#include "types/NullCoercibilityCheckMacro.hpp"
#include "types/Type.hpp"
#include "types/TypeID.hpp"
#include "types/TypedValue.hpp"
#include "utility/CheckSnprintf.hpp"
#include "glog/logging.h"
// NetBSD's libc has snprintf, but it doesn't show up in the std namespace for
// C++.
#ifndef __NetBSD__
using std::snprintf;
#endif
namespace quickstep {
bool DatetimeIntervalType::isCoercibleFrom(const Type &original_type) const {
QUICKSTEP_NULL_COERCIBILITY_CHECK();
return (original_type.getTypeID() == kDatetimeInterval);
}
bool DatetimeIntervalType::isSafelyCoercibleFrom(const Type &original_type) const {
QUICKSTEP_NULL_COERCIBILITY_CHECK();
return (original_type.getTypeID() == kDatetimeInterval);
}
std::string DatetimeIntervalType::printValueToString(const TypedValue &value) const {
DCHECK(!value.isNull());
std::int64_t subseconds = value.getLiteral<DatetimeIntervalLit>().interval_ticks;
const bool negative_interval = subseconds < 0;
if (negative_interval) {
subseconds = -subseconds;
}
std::int64_t seconds = subseconds / DatetimeIntervalLit::kTicksPerSecond;
subseconds -= seconds * DatetimeIntervalLit::kTicksPerSecond;
const std::int64_t days = seconds / (24 * 60 * 60);
seconds -= days * (24 * 60 * 60);
char interval_buf[DatetimeIntervalLit::kPrintingChars + 1];
std::size_t chars_written = 0;
int snprintf_result = 0;
if (negative_interval) {
interval_buf[0] = '-';
interval_buf[1] = '\0';
++chars_written;
}
if (days != 0) {
snprintf_result = snprintf(interval_buf + chars_written,
sizeof(interval_buf) - chars_written,
"%" PRId64,
days);
CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written);
if (days == 1) {
snprintf_result = snprintf(interval_buf + chars_written,
sizeof(interval_buf) - chars_written,
" day ");
} else {
snprintf_result = snprintf(interval_buf + chars_written,
sizeof(interval_buf) - chars_written,
" days ");
}
CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written);
}
int hours = seconds / (60 * 60);
int minutes = (seconds - hours * (60 * 60)) / 60;
int seconds_remainder = seconds - (60 * hours + minutes) * 60;
snprintf_result = snprintf(interval_buf + chars_written,
sizeof(interval_buf) - chars_written,
"%02d:%02d:%02d",
hours, minutes, seconds_remainder);
CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written);
if (subseconds != 0) {
snprintf_result = snprintf(interval_buf + chars_written,
sizeof(interval_buf) - chars_written,
".%06" PRId64,
subseconds);
CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written);
}
return std::string(interval_buf);
}
void DatetimeIntervalType::printValueToFile(const TypedValue &value,
FILE *file,
const int padding) const {
// We simply re-use the logic from printValueToString(), as trying to do
// padding on-the fly with so many different fields is too much of a hassle.
std::fprintf(file, "%*s", padding, printValueToString(value).c_str());
}
bool DatetimeIntervalType::parseValueFromString(const std::string &value_string,
TypedValue *value) const {
// Try simple-format parse first.
std::int64_t count;
std::string units;
DatetimeIntervalLit literal;
if (IntervalParser::ParseSimpleFormatFieldsFromCombinedStringNoExtraWhitespace(
value_string, &count, &units)
&& IntervalParser::ParseDatetimeIntervalSimpleFormat(count, units, &literal)) {
*value = TypedValue(literal);
return true;
}
// Try complex format.
if (IntervalParser::ParseDatetimeIntervalComplexFormat(value_string, &literal)) {
*value = TypedValue(literal);
return true;
}
return false;
}
} // namespace quickstep
| 34.509677 | 85 | 0.662554 | Hacker0912 |
1eaf1b8ff68afb95fda02bbd880a3ad700be65c4 | 939 | cpp | C++ | test/unit/math/mix/fun/inv_Phi_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/mix/fun/inv_Phi_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/mix/fun/inv_Phi_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, invPhi) {
auto f = [](const auto& x1) { return stan::math::inv_Phi(x1); };
stan::test::expect_common_unary_vectorized(f);
stan::test::expect_unary_vectorized(f, 0.02425, 0.97575); // breakpoints
stan::test::expect_unary_vectorized(f, -100.25, -2, 0.01, 0.1, 0.98, 0.5,
2.0);
}
TEST(mathMixMatFun, invPhi_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_args;
auto f = [](const auto& x1) {
using stan::math::inv_Phi;
return inv_Phi(x1);
};
std::vector<double> com_args = common_args();
std::vector<double> args{0.02425, 0.97575, -2, 0.1, 0.5, 2.0};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
| 33.535714 | 75 | 0.635783 | LaudateCorpus1 |
1eb2a72e9061eea16eb8bd0959a0a5efe8208bc7 | 2,606 | cpp | C++ | sort/mergesort.cpp | thebenhurley/Cplusplus-Examples | 918d7d4b6389f23d79be0cbdadb6a8710c91460f | [
"MIT"
] | null | null | null | sort/mergesort.cpp | thebenhurley/Cplusplus-Examples | 918d7d4b6389f23d79be0cbdadb6a8710c91460f | [
"MIT"
] | null | null | null | sort/mergesort.cpp | thebenhurley/Cplusplus-Examples | 918d7d4b6389f23d79be0cbdadb6a8710c91460f | [
"MIT"
] | null | null | null | // Benjamin Hurley
// mergesort.cpp
#include <iostream>
using namespace std;
void mergeSort(int[], int, int);
void merge(int[], int, int, int);
void printArray(int[], int);
int main()
{
// For this example, we will use an array and
// populate it with random numbers each time
const int count = 20;
srand (time(NULL));
// example array
int arr[count];
// even though we know the size already, we can
// practice solving for the size
int arr_size = sizeof(arr)/sizeof(arr[0]);
// fill array with random numbers 1-100
for (int i = 0; i < count; i++) {
arr[i] = (rand() % 100 + 1);
}
cout << "Given unosrted array is: ";
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
cout << "Sorted array is: ";
printArray(arr, arr_size);
return 0;
}
// Step 1 of 2: Break in half and sort halves.
void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int mid = left + (right - left)/2;
// Sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge them together
merge(arr, left, mid, right);
}
}
// Step 2 of 2: Merge sorted halves back together
void merge(int arr[], int left, int mid, int right)
{
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// create temp arrays
int L[n1], R[n2];
// copy data into temp arrays
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1+ j];
// Merge the temp arrays back into the original array
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = left; // Initial index of merged subarray
// merge lowest of two into originial array
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[] (if any)
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[] (if any)
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
} | 21.716667 | 57 | 0.495012 | thebenhurley |
1eb2f13ae930cbaf908e6b8db779752e5186e23d | 1,918 | cpp | C++ | lib/popnn/codelets/LossCrossEntropyTransform.cpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | 95 | 2020-07-06T17:11:23.000Z | 2022-03-12T14:42:28.000Z | lib/popnn/codelets/LossCrossEntropyTransform.cpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | null | null | null | lib/popnn/codelets/LossCrossEntropyTransform.cpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | 14 | 2020-07-15T12:32:57.000Z | 2022-01-26T14:58:45.000Z | // Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#include "poplar/AvailableVTypes.h"
#include "poplibs_support/ExternalCodelet.hpp"
#include "popops/EncodingConstants.hpp"
#include <cmath>
#include <poplar/HalfFloat.hpp>
#include <poplar/Vertex.hpp>
#ifdef VECTOR_AVAIL_SCALED_PTR32
static constexpr auto PTR_ALIGN32 = poplar::VectorLayout::SCALED_PTR32;
#else
static constexpr auto PTR_ALIGN32 = poplar::VectorLayout::ONE_PTR;
#endif
using namespace poplar;
static constexpr auto SCALED_PTR32 = poplar::VectorLayout::SCALED_PTR32;
namespace popnn {
template <typename FPType> class LossCrossEntropyTransform : public Vertex {
public:
LossCrossEntropyTransform();
Input<Vector<FPType, PTR_ALIGN32, 4>> probs;
Input<Vector<FPType, PTR_ALIGN32, 4>> expected;
Output<Vector<FPType, PTR_ALIGN32, 4>> deltas;
Output<Vector<FPType, PTR_ALIGN32, 4>> transformed;
const unsigned short size;
Input<FPType> deltasScale;
Input<FPType> modelOutputScaling;
IS_EXTERNAL_CODELET(true);
bool compute() {
float eps =
std::is_same<FPType, float>() ? EPS_LOG_N_FLOAT : EPS_LOG_N_HALF;
const FPType scale = *deltasScale / *modelOutputScaling;
const FPType logModelOutputScaling =
FPType(log(float(*modelOutputScaling)));
for (std::size_t i = 0; i < size; i++) {
FPType expect = expected[i];
FPType actual = probs[i];
// Returned deltas are scaled by deltasScale to
// maintain accuracy (actual is already assumed to be scaled by
// modelOutputScaling)
deltas[i] = scale * (actual - expect * (*modelOutputScaling));
// Returned transformed is adjusted to no longer be scaled
transformed[i] =
-expect * (FPType(log(float(actual) + eps)) - logModelOutputScaling);
}
return true;
}
};
template class LossCrossEntropyTransform<float>;
template class LossCrossEntropyTransform<half>;
} // namespace popnn
| 31.966667 | 79 | 0.72732 | graphcore |
1eb59372bc2629eaffc9801aaae0d2013a79d85f | 4,933 | cc | C++ | sys/sde/main.cc | cwolsen7905/UbixOS | 2f6063103347a8e8c369aacdd1399911bb4a4776 | [
"BSD-3-Clause"
] | null | null | null | sys/sde/main.cc | cwolsen7905/UbixOS | 2f6063103347a8e8c369aacdd1399911bb4a4776 | [
"BSD-3-Clause"
] | null | null | null | sys/sde/main.cc | cwolsen7905/UbixOS | 2f6063103347a8e8c369aacdd1399911bb4a4776 | [
"BSD-3-Clause"
] | null | null | null | /*-
* Copyright (c) 2002-2018 The UbixOS Project.
* All rights reserved.
*
* This was developed by Christopher W. Olsen for the UbixOS Project.
*
* 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, the following disclaimer and the list of authors.
* 2) Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions, the following disclaimer and the list of authors in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the UbixOS Project nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 <ubixos/sched.h>
//#include <lib/kprintf.h>
//#include <vmm/paging.h>
//#include <lib/bioscall.h>
extern "C" {
#include <lib/kprintf.h>
#include <ubixos/vitals.h>
#include <ubixos/exec.h>
#include <vmm/vmm.h>
#include <lib/kmalloc.h>
}
#include <sde/sde.h>
#include <objgfx40/objgfx40.h>
#include <sde/ogDisplay_UbixOS.h>
#include <objgfx40/ogFont.h>
void sdeTestThread();
extern "C" void sdeThread();
void sdeThread() {
ogSurface *screen = new ogDisplay_UbixOS();
struct sdeWindows *tmp = 0x0;
ogSurface *buf = 0x0;
ogBitFont * font = new ogBitFont();
font->Load("/var/fonts/ROM8X14.DPF", 0);
font->SetFGColor(255, 255, 255, 255);
font->SetBGColor(0, 0, 0, 255);
printOff = 0x1;
screen->ogCreate(800, 600, OG_PIXFMT_24BPP);
//screen->ogClear(screen->ogPack(122, 140, 163));
//screen->ogClear(screen->ogPack(0x66, 0xE0, 0xFF));
screen->ogClear(screen->ogPack(0x92, 0xA8, 0xD1));
systemVitals->screen = screen;
systemVitals->font = font;
ogprintOff = (int) 0x0;
screen->ogSetAntiAliasing(false);
execThread(&sdeTestThread, 0x2000, 0x0);
//ogSurface::RawLine(100, 100, 200, 200, 0xDEADBEEF)
//screen->RawLine(100, 100, 200, 200, 0xDEADBEEF);
//font->PutChar(*screen, 100, 100, 'A' - 2);
//font->PutChar(*screen, 100, 120, 'a');
while (1) {
for (tmp = windows; tmp; tmp = tmp->next) {
switch (tmp->status) {
case registerWindow:
kprintf("buf->buffer 0x%X, buf->bSize: 0x%X", buf->buffer, buf->bSize);
buf = (ogSurface *) tmp->buf;
buf->buffer = (void *) vmm_mapFromTask(tmp->pid, buf->buffer, buf->bSize);
if (buf->buffer == 0x0) {
kprintf("Error: buf->buffer\n");
while (1)
asm("nop");
}
kprintf("buf->lineOfs 0x%X, buf->lSize: 0x%X", buf->lineOfs, buf->lSize);
buf->lineOfs = (uInt32 *) vmm_mapFromTask(tmp->pid, buf->lineOfs, buf->lSize);
if (buf->lineOfs == 0x0) {
kprintf("Error: buf->lineOfs\n");
while (1)
;
}
tmp->status = windowReady;
//kprintf("Window Registered!\n");
break;
case drawWindow:
buf = (ogSurface *) tmp->buf;
screen->ogCopyBuf(screen->ogGetMaxX() - buf->ogGetMaxX(), screen->ogGetMaxY() - buf->ogGetMaxY(), *buf, 0, 0, buf->ogGetMaxX(), buf->ogGetMaxY());
tmp->status = windowReady;
kprintf("Draw Window Routines Here: %i-%i\n", buf->ogGetMaxX(), buf->ogGetMaxY());
break;
case killWindow:
//kprintf("Killed Window\n");
if (tmp->next != 0x0) {
tmp->next->prev = tmp->prev;
if (tmp->prev != 0x0)
tmp->prev->next = tmp->next;
}
else if (tmp->prev != 0x0) {
tmp->prev->next = tmp->next;
if (tmp->next != 0x0)
tmp->next->prev = tmp->prev;
}
else {
windows = 0x0;
}
vmm_unmapPages(buf->buffer, buf->bSize, VMM_KEEP);
vmm_unmapPages(buf->lineOfs, buf->lSize, VMM_KEEP);
kfree(tmp);
tmp = 0x0;
break;
default:
sched_yield();
break;
}
}
}
}
| 34.256944 | 156 | 0.627205 | cwolsen7905 |
1eb647e9b129c2db4e4a42f67b32ebda8f344b55 | 2,251 | cc | C++ | test_uuid.cc | pallas/libuuidpp | abe53378e5317aca4e3d569fce86ef987e133520 | [
"Zlib"
] | null | null | null | test_uuid.cc | pallas/libuuidpp | abe53378e5317aca4e3d569fce86ef987e133520 | [
"Zlib"
] | null | null | null | test_uuid.cc | pallas/libuuidpp | abe53378e5317aca4e3d569fce86ef987e133520 | [
"Zlib"
] | null | null | null | #include "uuidpp.h"
#include <lace/hash.h>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <vector>
int main(int argc, char* argv[]) {
for (int i = 0 ; i < argc ; ++i) {
uuid u;
std::stringstream(argv[i]) >> u;
std::cout
<< (bool)u << '\t'
<< argv[i] << '\t'
<< u << '\t'
<< (u.temporal() ? u.time() : 0) << '\t'
<< lace::hash(u)
<< std::endl;
}
for(auto const & l : std::vector<const char *>{"@dns", "@url", "@oid", "@x500"}) {
const uuid u(l);
std::cout
<< u << '\t'
<< (u.temporal() ? u.time() : 0) << '\t'
<< lace::hash(u)
<< std::endl;
}
assert(uuid("@dns") == uuid("@dns"));
assert(uuid("@dns") != uuid("@url"));
assert(uuid("@dns") < uuid("@url"));
assert(uuid("@url") > uuid("@dns"));
assert(uuid("@dns") == uuid::dns);
assert(uuid("@url") == uuid::url);
assert(uuid("@oid") == uuid::oid);
assert(uuid("@x500") == uuid::x500);
{
const uuid u(uuid::type_t::random);
assert(!u.temporal());
std::cout
<< u << '\t'
<< (u.temporal() ? u.time() : 0) << '\t'
<< lace::hash(u)
<< std::endl;
}
{
const uuid u(uuid::type_t::time);
assert(u.temporal());
std::cout
<< u << '\t'
<< (u.temporal() ? u.time() : 0) << '\t'
<< lace::hash(u)
<< std::endl;
}
{
const uuid u(uuid("@oid"), "oh hai");
std::cout
<< u << '\t'
<< (u.temporal() ? u.time() : 0) << '\t'
<< lace::hash(u)
<< std::endl;
assert(0 == uuid(true).sha1(uuid("@oid"), "oh hai").cmp(u));
assert(u == uuid(true).sha1(uuid("@oid"), "oh hai"));
assert(0 != uuid(true).md5(uuid("@oid"), "oh hai").cmp(u));
assert(u != uuid(true).md5(uuid("@oid"), "oh hai"));
}
assert(lace::hash(uuid(uuid("@oid"), "oh hai")) == lace::hash(uuid(uuid("@oid"), "oh hai")));
assert(lace::hash(uuid(uuid("@oid"), "oh hai")) != lace::hash(uuid(uuid("@oid"), "meh no")));
return EXIT_SUCCESS;
}
| 30.013333 | 97 | 0.423812 | pallas |
1eb736b63d326eeb8bde768f6f921e034555a25f | 16,466 | cpp | C++ | Source/RenderPostProcess.cpp | marcussvensson92/vulkan_testbed | 6cfbee9fd5fb245f10c1d5694812eda6232b9a6c | [
"MIT"
] | 10 | 2020-03-26T08:51:29.000Z | 2021-08-17T07:43:12.000Z | Source/RenderPostProcess.cpp | marcussvensson92/vulkan_testbed | 6cfbee9fd5fb245f10c1d5694812eda6232b9a6c | [
"MIT"
] | null | null | null | Source/RenderPostProcess.cpp | marcussvensson92/vulkan_testbed | 6cfbee9fd5fb245f10c1d5694812eda6232b9a6c | [
"MIT"
] | null | null | null | #include "RenderPostProcess.h"
#include "VkUtil.h"
void RenderPostProcess::Create(const RenderContext& rc)
{
// Temporal Blend
{
VkDescriptorSetLayoutBinding set_layout_bindings[] =
{
{ 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
};
VkDescriptorSetLayoutCreateInfo set_layout_info = {};
set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
set_layout_info.bindingCount = static_cast<uint32_t>(sizeof(set_layout_bindings) / sizeof(*set_layout_bindings));
set_layout_info.pBindings = set_layout_bindings;
VK(vkCreateDescriptorSetLayout(Vk.Device, &set_layout_info, NULL, &m_TemporalBlendDescriptorSetLayout));
VkPipelineLayoutCreateInfo pipeline_layout_info = {};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.setLayoutCount = 1;
pipeline_layout_info.pSetLayouts = &m_TemporalBlendDescriptorSetLayout;
VK(vkCreatePipelineLayout(Vk.Device, &pipeline_layout_info, NULL, &m_TemporalBlendPipelineLayout));
}
// Temporal Resolve
{
VkDescriptorSetLayoutBinding set_layout_bindings[] =
{
{ 0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
{ 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL },
};
VkDescriptorSetLayoutCreateInfo set_layout_info = {};
set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
set_layout_info.bindingCount = static_cast<uint32_t>(sizeof(set_layout_bindings) / sizeof(*set_layout_bindings));
set_layout_info.pBindings = set_layout_bindings;
VK(vkCreateDescriptorSetLayout(Vk.Device, &set_layout_info, NULL, &m_TemporalResolveDescriptorSetLayout));
VkPipelineLayoutCreateInfo pipeline_layout_info = {};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.setLayoutCount = 1;
pipeline_layout_info.pSetLayouts = &m_TemporalResolveDescriptorSetLayout;
VK(vkCreatePipelineLayout(Vk.Device, &pipeline_layout_info, NULL, &m_TemporalResolvePipelineLayout));
}
// Tone Mapping
{
VkDescriptorSetLayoutBinding set_layout_bindings[] =
{
{ 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL },
{ 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL },
{ 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL },
{ 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL },
};
VkDescriptorSetLayoutCreateInfo set_layout_info = {};
set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
set_layout_info.bindingCount = static_cast<uint32_t>(sizeof(set_layout_bindings) / sizeof(*set_layout_bindings));
set_layout_info.pBindings = set_layout_bindings;
VK(vkCreateDescriptorSetLayout(Vk.Device, &set_layout_info, NULL, &m_ToneMappingDescriptorSetLayout));
VkPipelineLayoutCreateInfo pipeline_layout_info = {};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.setLayoutCount = 1;
pipeline_layout_info.pSetLayouts = &m_ToneMappingDescriptorSetLayout;
VK(vkCreatePipelineLayout(Vk.Device, &pipeline_layout_info, NULL, &m_ToneMappingPipelineLayout));
}
m_LuxoDoubleChecker = VkTextureLoadEXR("../Assets/Textures/LuxoDoubleChecker.exr");
CreatePipelines(rc);
CreateResolutionDependentResources(rc);
}
void RenderPostProcess::Destroy()
{
DestroyResolutionDependentResources();
DestroyPipelines();
VkTextureDestroy(m_LuxoDoubleChecker);
vkDestroyPipelineLayout(Vk.Device, m_TemporalBlendPipelineLayout, NULL);
vkDestroyDescriptorSetLayout(Vk.Device, m_TemporalBlendDescriptorSetLayout, NULL);
vkDestroyPipelineLayout(Vk.Device, m_TemporalResolvePipelineLayout, NULL);
vkDestroyDescriptorSetLayout(Vk.Device, m_TemporalResolveDescriptorSetLayout, NULL);
vkDestroyPipelineLayout(Vk.Device, m_ToneMappingPipelineLayout, NULL);
vkDestroyDescriptorSetLayout(Vk.Device, m_ToneMappingDescriptorSetLayout, NULL);
}
void RenderPostProcess::CreatePipelines(const RenderContext& rc)
{
// Temporal Blend
{
VkUtilCreateComputePipelineParams pipeline_params;
pipeline_params.PipelineLayout = m_TemporalBlendPipelineLayout;
pipeline_params.ComputeShaderFilepath = "../Assets/Shaders/PostProcessTemporalBlend.comp";
m_TemporalBlendPipeline = VkUtilCreateComputePipeline(pipeline_params);
}
// Temporal Resolve
{
VkUtilCreateComputePipelineParams pipeline_params;
pipeline_params.PipelineLayout = m_TemporalResolvePipelineLayout;
pipeline_params.ComputeShaderFilepath = "../Assets/Shaders/PostProcessTemporalResolve.comp";
m_TemporalResolvePipeline = VkUtilCreateComputePipeline(pipeline_params);
}
// Tone Mapping
{
VkUtilCreateGraphicsPipelineParams pipeline_params;
pipeline_params.PipelineLayout = m_ToneMappingPipelineLayout;
pipeline_params.RenderPass = rc.BackBufferRenderPass;
pipeline_params.VertexShaderFilepath = "../Assets/Shaders/PostProcessToneMapping.vert";
pipeline_params.FragmentShaderFilepath = "../Assets/Shaders/PostProcessToneMapping.frag";
pipeline_params.BlendAttachmentStates = { VkUtilGetDefaultBlendAttachmentState() };
m_ToneMappingPipeline = VkUtilCreateGraphicsPipeline(pipeline_params);
}
}
void RenderPostProcess::DestroyPipelines()
{
vkDestroyPipeline(Vk.Device, m_TemporalBlendPipeline, NULL);
vkDestroyPipeline(Vk.Device, m_TemporalResolvePipeline, NULL);
vkDestroyPipeline(Vk.Device, m_ToneMappingPipeline, NULL);
}
void RenderPostProcess::CreateResolutionDependentResources(const RenderContext& rc)
{
VkTextureCreateParams temporal_texture_params;
temporal_texture_params.Type = VK_IMAGE_TYPE_2D;
temporal_texture_params.ViewType = VK_IMAGE_VIEW_TYPE_2D;
temporal_texture_params.Width = rc.Width;
temporal_texture_params.Height = rc.Height;
temporal_texture_params.Format = VK_FORMAT_R16G16B16A16_SFLOAT;
temporal_texture_params.Usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
temporal_texture_params.InitialLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
m_TemporalTextures[0] = VkTextureCreate(temporal_texture_params);
m_TemporalTextures[1] = VkTextureCreate(temporal_texture_params);
}
void RenderPostProcess::DestroyResolutionDependentResources()
{
VkTextureDestroy(m_TemporalTextures[0]);
VkTextureDestroy(m_TemporalTextures[1]);
}
void RenderPostProcess::RecreatePipelines(const RenderContext& rc)
{
DestroyPipelines();
CreatePipelines(rc);
}
void RenderPostProcess::RecreateResolutionDependentResources(const RenderContext& rc)
{
DestroyResolutionDependentResources();
CreateResolutionDependentResources(rc);
}
void RenderPostProcess::Jitter(RenderContext& rc)
{
glm::vec2 jitter = glm::vec2(0.0f, 0.0f);
if (m_TemporalAAEnable && !rc.DebugEnable)
{
const float halton_23[8][2] =
{
{ 0.0f / 8.0f, 0.0f / 9.0f }, { 4.0f / 8.0f, 3.0f / 9.0f },
{ 2.0f / 8.0f, 6.0f / 9.0f }, { 6.0f / 8.0f, 1.0f / 9.0f },
{ 1.0f / 8.0f, 4.0f / 9.0f }, { 5.0f / 8.0f, 7.0f / 9.0f },
{ 3.0f / 8.0f, 2.0f / 9.0f }, { 7.0f / 8.0f, 5.0f / 9.0f },
};
jitter.x = halton_23[rc.FrameCounter % 8][0] / static_cast<float>(rc.Width);
jitter.y = halton_23[rc.FrameCounter % 8][1] / static_cast<float>(rc.Height);
}
rc.CameraCurr.Jitter(jitter);
}
void RenderPostProcess::Draw(const RenderContext& rc, VkCommandBuffer cmd)
{
if (m_TemporalAAEnable && !rc.DebugEnable)
{
VkPushLabel(cmd, "Post Process TAA");
VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
VkUtilImageBarrier(cmd, rc.DepthTexture.Image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT);
VkUtilImageBarrier(cmd, m_TemporalTextures[rc.FrameCounter & 1].Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT);
// Temporal Blend
{
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalBlendPipeline);
static uint32_t last_frame = ~0U;
const bool is_hist_valid = last_frame == rc.FrameCounter;
last_frame = rc.FrameCounter + 1;
struct Constants
{
uint32_t IsHistValid;
float Exposure;
};
VkAllocation constants_allocation = VkAllocateUploadBuffer(sizeof(Constants));
Constants* constants = reinterpret_cast<Constants*>(constants_allocation.Data);
constants->IsHistValid = is_hist_valid;
constants->Exposure = std::exp2f(m_Exposure);
VkDescriptorSet set = VkCreateDescriptorSetForCurrentFrame(m_TemporalBlendDescriptorSetLayout,
{
{ 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, constants_allocation.Buffer, constants_allocation.Offset, sizeof(Constants) },
{ 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, m_TemporalTextures[rc.FrameCounter & 1].ImageView, VK_IMAGE_LAYOUT_GENERAL, VK_NULL_HANDLE },
{ 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.ColorTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp },
{ 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.DepthTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp },
{ 4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.MotionTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp },
{ 5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, m_TemporalTextures[(rc.FrameCounter + 1) & 1].ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.LinearClamp },
});
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalBlendPipelineLayout, 0, 1, &set, 0, NULL);
vkCmdDispatch(cmd, (rc.Width + 7) / 8, (rc.Height + 7) / 8, 1);
}
VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT);
VkUtilImageBarrier(cmd, rc.DepthTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT);
VkUtilImageBarrier(cmd, m_TemporalTextures[rc.FrameCounter & 1].Image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
// Temporal Resolve
{
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalResolvePipeline);
VkDescriptorSet set = VkCreateDescriptorSetForCurrentFrame(m_TemporalResolveDescriptorSetLayout,
{
{ 0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, rc.ColorTexture.ImageView, VK_IMAGE_LAYOUT_GENERAL, VK_NULL_HANDLE },
{ 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, m_TemporalTextures[rc.FrameCounter & 1].ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp },
});
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalResolvePipelineLayout, 0, 1, &set, 0, NULL);
vkCmdDispatch(cmd, (rc.Width + 7) / 8, (rc.Height + 7) / 8, 1);
}
VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
VkPopLabel(cmd);
}
else
{
VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
}
VkUtilImageBarrier(cmd, rc.UiTexture.Image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
{
VkPushLabel(cmd, "Post Process Tone Mapping");
VkRenderPassBeginInfo render_pass_info = {};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_info.renderPass = rc.BackBufferRenderPass;
render_pass_info.framebuffer = rc.BackBufferFramebuffers[Vk.SwapchainImageIndex];
render_pass_info.renderArea.offset = { 0, 0 };
render_pass_info.renderArea.extent = { rc.Width, rc.Height };
vkCmdBeginRenderPass(cmd, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = { 0.0f, 0.0f, static_cast<float>(rc.Width), static_cast<float>(rc.Height), 0.0f, 1.0f };
VkRect2D scissor = { { 0, 0 }, { rc.Width, rc.Height } };
vkCmdSetViewport(cmd, 0, 1, &viewport);
vkCmdSetScissor(cmd, 0, 1, &scissor);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_ToneMappingPipeline);
struct Constants
{
float Exposure;
float Saturation;
float Contrast;
float Gamma;
float GamutExpansion;
uint32_t DebugEnable;
uint32_t ViewLuxoDoubleChecker;
int32_t DisplayMode;
int32_t DisplayMapping;
int32_t DisplayMappingAux;
uint32_t DisplayMappingSplitScreen;
int32_t DisplayMappingSplitScreenOffset;
float HdrDisplayLuminanceMin;
float HdrDisplayLuminanceMax;
float SdrWhiteLevel;
float ACESMidPoint;
float BT2390MidPoint;
};
VkAllocation constants_allocation = VkAllocateUploadBuffer(sizeof(Constants));
Constants* constants = reinterpret_cast<Constants*>(constants_allocation.Data);
constants->Exposure = std::exp2f(m_Exposure);
constants->Saturation = m_Saturation;
constants->Contrast = m_Contrast;
constants->Gamma = m_Gamma;
constants->GamutExpansion = m_GamutExpansion;
constants->DebugEnable = rc.DebugEnable;
constants->ViewLuxoDoubleChecker = m_ViewLuxoDoubleChecker;
constants->DisplayMode = static_cast<int32_t>(Vk.DisplayMode);
constants->DisplayMapping = m_DisplayMapping;
constants->DisplayMappingAux = m_DisplayMappingAux;
constants->DisplayMappingSplitScreen = m_DisplayMappingSplitScreen;
constants->DisplayMappingSplitScreenOffset = static_cast<int32_t>((m_DisplayMappingSplitScreenOffset * 0.5f + 0.5f) * static_cast<float>(rc.Width) + 0.5f);
constants->HdrDisplayLuminanceMin = m_HdrDisplayLuminanceMin;
constants->HdrDisplayLuminanceMax = m_HdrDisplayLuminanceMax;
constants->SdrWhiteLevel = m_SdrWhiteLevel;
constants->ACESMidPoint = m_ACESMidPoint;
constants->BT2390MidPoint = m_BT2390MidPoint;
VkDescriptorSet set = VkCreateDescriptorSetForCurrentFrame(m_ToneMappingDescriptorSetLayout,
{
{ 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, constants_allocation.Buffer, constants_allocation.Offset, sizeof(Constants) },
{ 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.ColorTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp },
{ 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.UiTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp },
{ 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, m_LuxoDoubleChecker.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.LinearClamp },
});
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_ToneMappingPipelineLayout, 0, 1, &set, 0, NULL);
vkCmdDraw(cmd, 3, 1, 0, 0);
vkCmdEndRenderPass(cmd);
VkPopLabel(cmd);
}
VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
VkUtilImageBarrier(cmd, rc.UiTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT);
} | 50.048632 | 187 | 0.760658 | marcussvensson92 |
1eb81b1f1b3072768ab983093acb96909760b317 | 602 | cpp | C++ | Zerojudge/d784.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 9 | 2017-10-08T16:22:03.000Z | 2021-08-20T09:32:17.000Z | Zerojudge/d784.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | null | null | null | Zerojudge/d784.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 2 | 2018-01-15T16:35:44.000Z | 2019-03-21T18:30:04.000Z | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n,t;
cin>>n;
for(int i=1;i<=n;++i)
{
cin>>t;
vector<int>k(t);
for(int j=0;j<t;++j)
{
cin>>k[j];
}
int x=k[0];
for(int j=0;j<t;++j)
{
int sum=k[j];
if(sum>x)x=sum;
for(int l=j+1;l<t;++l)
{
sum+=k[l];
if(sum>x)x=sum;
}
}
cout<<x<<endl;
}
return 0;
}
| 17.705882 | 35 | 0.345515 | w181496 |
1ebd6205d62e4fc78451abe0258f37cd5e258e76 | 3,214 | hpp | C++ | tools/Vitis-AI-Library/xmodel_image/include/vitis/ai/json_object_visitor.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 1 | 2022-02-17T22:13:23.000Z | 2022-02-17T22:13:23.000Z | tools/Vitis-AI-Library/xmodel_image/include/vitis/ai/json_object_visitor.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | tools/Vitis-AI-Library/xmodel_image/include/vitis/ai/json_object_visitor.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <glog/logging.h>
#include <json-c/json.h>
#include <string>
#include <vector>
namespace vitis {
namespace ai {
class JsonObjectVisitor {
public:
explicit JsonObjectVisitor(const json_object* json) : json_{json} {};
virtual ~JsonObjectVisitor() = default;
JsonObjectVisitor(const JsonObjectVisitor& other) = default;
JsonObjectVisitor& operator=(const JsonObjectVisitor& rhs) = default;
public:
void visit(bool& value);
void visit(int& value);
void visit(float& value);
void visit(std::string& value);
template <typename T>
void visit(T& x);
template <typename T>
void visit(std::vector<T>& value);
JsonObjectVisitor operator[](const char* field);
private:
const json_object* json_;
};
inline void JsonObjectVisitor::visit(bool& value) {
CHECK(json_object_is_type(json_, json_type_boolean))
<< "not a boolean type! json="
<< json_object_to_json_string(const_cast<json_object*>(json_));
auto v1 = json_object_get_boolean(json_);
value = (bool)v1;
}
inline void JsonObjectVisitor::visit(int& value) {
CHECK(json_object_is_type(json_, json_type_int))
<< "not a int type! json="
<< json_object_to_json_string(const_cast<json_object*>(json_));
value = json_object_get_int(json_);
}
inline void JsonObjectVisitor::visit(float& value) {
CHECK(json_object_is_type(json_, json_type_double))
<< "not a double type! json="
<< json_object_to_json_string(const_cast<json_object*>(json_));
auto v1 = json_object_get_double(json_);
value = (float)v1;
}
inline void JsonObjectVisitor::visit(std::string& value) {
CHECK(json_object_is_type(json_, json_type_string))
<< "not a string type! json="
<< json_object_to_json_string(const_cast<json_object*>(json_));
value = json_object_get_string(const_cast<json_object*>(json_));
}
inline JsonObjectVisitor JsonObjectVisitor::operator[](const char* field) {
return JsonObjectVisitor(json_object_object_get(json_, field));
}
template <typename T>
inline void JsonObjectVisitor::visit(T& x) {
x.VisitAttrs(*this);
}
template <typename T>
inline void JsonObjectVisitor::visit(std::vector<T>& value) {
CHECK(json_object_is_type(json_, json_type_array))
<< "not a array type! json="
<< json_object_to_json_string(const_cast<json_object*>(json_));
auto size = json_object_array_length(json_);
value.reserve(size);
for (decltype(size) idx = 0; idx < size; ++idx) {
auto elt = JsonObjectVisitor(json_object_array_get_idx(json_, idx));
T res;
elt.visit(res);
value.emplace_back(res);
}
}
} // namespace ai
} // namespace vitis
| 32.14 | 75 | 0.725264 | hito0512 |
362e6be5c66fb14c40a43df7a169f81cfd20bbf1 | 143 | cpp | C++ | tests/cluecode/data/ics/oprofile-libpp/xml_utils.cpp | s4-2/scancode-toolkit | 8931b42e2630b94d0cabc834dfb3c16f01f82321 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1,511 | 2015-07-01T15:29:03.000Z | 2022-03-30T13:40:05.000Z | tests/cluecode/data/ics/oprofile-libpp/xml_utils.cpp | s4-2/scancode-toolkit | 8931b42e2630b94d0cabc834dfb3c16f01f82321 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2,695 | 2015-07-01T16:01:35.000Z | 2022-03-31T19:17:44.000Z | tests/cluecode/data/ics/oprofile-libpp/xml_utils.cpp | s4-2/scancode-toolkit | 8931b42e2630b94d0cabc834dfb3c16f01f82321 | [
"Apache-2.0",
"CC-BY-4.0"
] | 540 | 2015-07-01T15:08:19.000Z | 2022-03-31T12:13:11.000Z | * @file xml_utils.cpp
* utility routines for generating XML
*
* @remark Copyright 2006 OProfile authors
* @remark Read the file COPYING
* | 23.833333 | 42 | 0.734266 | s4-2 |
363167a52cf18dd689b96ab152f4f57dc47d86ab | 2,778 | cpp | C++ | cpp/test/serialize_test.cpp | deHasara/cylon | f5e31a1191d6a30c0a8c5778a7db4a07c5802da8 | [
"Apache-2.0"
] | 229 | 2020-07-01T14:05:10.000Z | 2022-03-25T12:26:58.000Z | cpp/test/serialize_test.cpp | deHasara/cylon | f5e31a1191d6a30c0a8c5778a7db4a07c5802da8 | [
"Apache-2.0"
] | 261 | 2020-06-30T23:23:15.000Z | 2022-03-16T09:55:40.000Z | cpp/test/serialize_test.cpp | deHasara/cylon | f5e31a1191d6a30c0a8c5778a7db4a07c5802da8 | [
"Apache-2.0"
] | 36 | 2020-06-30T23:14:52.000Z | 2022-03-03T02:37:09.000Z | /*
* 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 "common/test_header.hpp"
#include "cylon/serialize/table_serialize.hpp"
#include "cylon/arrow/arrow_buffer.hpp"
namespace cylon {
namespace test {
TEST_CASE("serialize table", "[serialization]") {
auto schema = arrow::schema({
{field("_", arrow::boolean())},
{field("a", arrow::uint32())},
{field("b", arrow::float64())},
{field("c", arrow::utf8())},
});
auto in_table = TableFromJSON(schema, {R"([{"_": true, "a": null, "b": 5, "c": "1"},
{"_": false, "a": 1, "b": 3, "c": "12"},
{"_": true, "a": 3, "b": null, "c": "123"},
{"_": null, "a": null, "b": null, "c": null},
{"_": true, "a": 2, "b": 5, "c": "1234"},
{"_": false, "a": 1, "b": 5, "c": null}
])"});
for (const auto &atable: {in_table, in_table->Slice(3)}) {
SECTION(atable.get() == in_table.get() ? "without offset" : "with offset") {
auto table = std::make_shared<Table>(ctx, atable);
std::shared_ptr<TableSerializer> ser;
CHECK_CYLON_STATUS(CylonTableSerializer::Make(table, &ser));
// table serializer only has pointers to data. To emulate gather/ all gather behavior, create a
// vector of arrow buffers.
std::vector<std::shared_ptr<Buffer>> buffers;
buffers.reserve(ser->getNumberOfBuffers());
const auto &data_buffers = ser->getDataBuffers();
const auto &buffer_sizes = ser->getBufferSizes();
for (int i = 0; i < ser->getNumberOfBuffers(); i++) {
arrow::BufferBuilder builder;
REQUIRE(builder.Append(data_buffers[i], buffer_sizes[i]).ok());
buffers.push_back(std::make_shared<ArrowBuffer>(builder.Finish().ValueOrDie()));
}
std::shared_ptr<Table> output;
CHECK_CYLON_STATUS(DeserializeTable(ctx, schema, buffers, buffer_sizes, &output));
CHECK_ARROW_EQUAL(atable, output->get_table());
}
}
}
}
} | 42.090909 | 101 | 0.553276 | deHasara |
36316a3b79ae7b9f2ed8ae598fe157e8ce6308e3 | 49 | cpp | C++ | closed/Intel/code/bert-99/pytorch-cpu/csrc/bert_model.cpp | ctuning/inference_results_v1.1 | d9176eca28fcf6d7a05ccb97994362a76a1eb5ab | [
"Apache-2.0"
] | 12 | 2021-09-23T08:05:57.000Z | 2022-03-21T03:52:11.000Z | closed/Intel/code/bert-99/pytorch-cpu/csrc/bert_model.cpp | ctuning/inference_results_v1.1 | d9176eca28fcf6d7a05ccb97994362a76a1eb5ab | [
"Apache-2.0"
] | 11 | 2021-09-23T20:34:06.000Z | 2022-01-22T07:58:02.000Z | closed/Intel/code/bert-99/pytorch-cpu/csrc/bert_model.cpp | ctuning/inference_results_v1.1 | d9176eca28fcf6d7a05ccb97994362a76a1eb5ab | [
"Apache-2.0"
] | 16 | 2021-09-23T20:26:38.000Z | 2022-03-09T12:59:56.000Z | #include "bert_model.hpp"
namespace models {
}
| 8.166667 | 25 | 0.714286 | ctuning |
3634a29f1e422c725b1208ef3498411f5340c4d1 | 17,816 | cc | C++ | cvmfs/cache_transport.cc | traylenator/cvmfs | c7873bf3d1586524b2c7988eb219cea065ceffbc | [
"BSD-3-Clause"
] | null | null | null | cvmfs/cache_transport.cc | traylenator/cvmfs | c7873bf3d1586524b2c7988eb219cea065ceffbc | [
"BSD-3-Clause"
] | null | null | null | cvmfs/cache_transport.cc | traylenator/cvmfs | c7873bf3d1586524b2c7988eb219cea065ceffbc | [
"BSD-3-Clause"
] | null | null | null | /**
* This file is part of the CernVM File System.
*/
#include "cvmfs_config.h"
#include "cache_transport.h"
#include <alloca.h>
#include <errno.h>
#include <sys/socket.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include "hash.h"
#include "logging.h"
#include "smalloc.h"
#include "util/posix.h"
// TODO(jblomer): Check for possible starvation of plugin by dying clients
// (blocking read). Probably only relevant for TCP sockets.
using namespace std; // NOLINT
const char *CacheTransport::kEnvReadyNotifyFd =
"__CVMFS_CACHE_EXTERNAL_PIPE_READY__";
/**
* Called on the sender side to wrap a message into a MsgRpc message for wire
* transfer.
*/
cvmfs::MsgRpc *CacheTransport::Frame::GetMsgRpc() {
assert(msg_typed_ != NULL);
if (!is_wrapped_)
WrapMsg();
return &msg_rpc_;
}
/**
* Called on the receiving end of an RPC to extract the actual message from the
* MsgRpc.
*/
google::protobuf::MessageLite *CacheTransport::Frame::GetMsgTyped() {
assert(msg_rpc_.IsInitialized());
if (msg_typed_ == NULL)
UnwrapMsg();
return msg_typed_;
}
CacheTransport::Frame::Frame()
: owns_msg_typed_(false)
, msg_typed_(NULL)
, attachment_(NULL)
, att_size_(0)
, is_wrapped_(false)
, is_msg_out_of_band_(false)
{ }
CacheTransport::Frame::Frame(google::protobuf::MessageLite *m)
: owns_msg_typed_(false)
, msg_typed_(m)
, attachment_(NULL)
, att_size_(0)
, is_wrapped_(false)
, is_msg_out_of_band_(false)
{ }
CacheTransport::Frame::~Frame() {
Reset(0);
}
bool CacheTransport::Frame::IsMsgOutOfBand() {
assert(msg_rpc_.IsInitialized());
if (msg_typed_ == NULL)
UnwrapMsg();
return is_msg_out_of_band_;
}
void CacheTransport::Frame::MergeFrom(const Frame &other) {
msg_rpc_.CheckTypeAndMergeFrom(other.msg_rpc_);
owns_msg_typed_ = true;
if (other.att_size_ > 0) {
assert(att_size_ >= other.att_size_);
memcpy(attachment_, other.attachment_, other.att_size_);
att_size_ = other.att_size_;
}
}
bool CacheTransport::Frame::ParseMsgRpc(void *buffer, uint32_t size) {
bool retval = msg_rpc_.ParseFromArray(buffer, size);
if (!retval)
return false;
// Cleanup typed message when Frame leaves scope
owns_msg_typed_ = true;
return true;
}
void CacheTransport::Frame::Release() {
if (owns_msg_typed_)
return;
msg_rpc_.release_msg_refcount_req();
msg_rpc_.release_msg_refcount_reply();
msg_rpc_.release_msg_read_req();
msg_rpc_.release_msg_read_reply();
msg_rpc_.release_msg_object_info_req();
msg_rpc_.release_msg_object_info_reply();
msg_rpc_.release_msg_store_req();
msg_rpc_.release_msg_store_abort_req();
msg_rpc_.release_msg_store_reply();
msg_rpc_.release_msg_handshake();
msg_rpc_.release_msg_handshake_ack();
msg_rpc_.release_msg_quit();
msg_rpc_.release_msg_ioctl();
msg_rpc_.release_msg_info_req();
msg_rpc_.release_msg_info_reply();
msg_rpc_.release_msg_shrink_req();
msg_rpc_.release_msg_shrink_reply();
msg_rpc_.release_msg_list_req();
msg_rpc_.release_msg_list_reply();
msg_rpc_.release_msg_detach();
msg_rpc_.release_msg_breadcrumb_store_req();
msg_rpc_.release_msg_breadcrumb_load_req();
msg_rpc_.release_msg_breadcrumb_reply();
}
void CacheTransport::Frame::Reset(uint32_t original_att_size) {
msg_typed_ = NULL;
att_size_ = original_att_size;
is_wrapped_ = false;
is_msg_out_of_band_ = false;
Release();
msg_rpc_.Clear();
owns_msg_typed_ = false;
}
void CacheTransport::Frame::WrapMsg() {
if (msg_typed_->GetTypeName() == "cvmfs.MsgHandshake") {
msg_rpc_.set_allocated_msg_handshake(
reinterpret_cast<cvmfs::MsgHandshake *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgHandshakeAck") {
msg_rpc_.set_allocated_msg_handshake_ack(
reinterpret_cast<cvmfs::MsgHandshakeAck *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgQuit") {
msg_rpc_.set_allocated_msg_quit(
reinterpret_cast<cvmfs::MsgQuit *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgIoctl") {
msg_rpc_.set_allocated_msg_ioctl(
reinterpret_cast<cvmfs::MsgIoctl *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgRefcountReq") {
msg_rpc_.set_allocated_msg_refcount_req(
reinterpret_cast<cvmfs::MsgRefcountReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgRefcountReply") {
msg_rpc_.set_allocated_msg_refcount_reply(
reinterpret_cast<cvmfs::MsgRefcountReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgObjectInfoReq") {
msg_rpc_.set_allocated_msg_object_info_req(
reinterpret_cast<cvmfs::MsgObjectInfoReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgObjectInfoReply") {
msg_rpc_.set_allocated_msg_object_info_reply(
reinterpret_cast<cvmfs::MsgObjectInfoReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgReadReq") {
msg_rpc_.set_allocated_msg_read_req(
reinterpret_cast<cvmfs::MsgReadReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgReadReply") {
msg_rpc_.set_allocated_msg_read_reply(
reinterpret_cast<cvmfs::MsgReadReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgStoreReq") {
msg_rpc_.set_allocated_msg_store_req(
reinterpret_cast<cvmfs::MsgStoreReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgStoreAbortReq") {
msg_rpc_.set_allocated_msg_store_abort_req(
reinterpret_cast<cvmfs::MsgStoreAbortReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgStoreReply") {
msg_rpc_.set_allocated_msg_store_reply(
reinterpret_cast<cvmfs::MsgStoreReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgInfoReq") {
msg_rpc_.set_allocated_msg_info_req(
reinterpret_cast<cvmfs::MsgInfoReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgInfoReply") {
msg_rpc_.set_allocated_msg_info_reply(
reinterpret_cast<cvmfs::MsgInfoReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgShrinkReq") {
msg_rpc_.set_allocated_msg_shrink_req(
reinterpret_cast<cvmfs::MsgShrinkReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgShrinkReply") {
msg_rpc_.set_allocated_msg_shrink_reply(
reinterpret_cast<cvmfs::MsgShrinkReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgListReq") {
msg_rpc_.set_allocated_msg_list_req(
reinterpret_cast<cvmfs::MsgListReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgListReply") {
msg_rpc_.set_allocated_msg_list_reply(
reinterpret_cast<cvmfs::MsgListReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgBreadcrumbStoreReq") {
msg_rpc_.set_allocated_msg_breadcrumb_store_req(
reinterpret_cast<cvmfs::MsgBreadcrumbStoreReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgBreadcrumbLoadReq") {
msg_rpc_.set_allocated_msg_breadcrumb_load_req(
reinterpret_cast<cvmfs::MsgBreadcrumbLoadReq *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgBreadcrumbReply") {
msg_rpc_.set_allocated_msg_breadcrumb_reply(
reinterpret_cast<cvmfs::MsgBreadcrumbReply *>(msg_typed_));
} else if (msg_typed_->GetTypeName() == "cvmfs.MsgDetach") {
msg_rpc_.set_allocated_msg_detach(
reinterpret_cast<cvmfs::MsgDetach *>(msg_typed_));
is_msg_out_of_band_ = true;
} else {
// Unexpected message type, should never happen
abort();
}
is_wrapped_ = true;
}
void CacheTransport::Frame::UnwrapMsg() {
if (msg_rpc_.has_msg_handshake()) {
msg_typed_ = msg_rpc_.mutable_msg_handshake();
} else if (msg_rpc_.has_msg_handshake_ack()) {
msg_typed_ = msg_rpc_.mutable_msg_handshake_ack();
} else if (msg_rpc_.has_msg_quit()) {
msg_typed_ = msg_rpc_.mutable_msg_quit();
} else if (msg_rpc_.has_msg_ioctl()) {
msg_typed_ = msg_rpc_.mutable_msg_ioctl();
} else if (msg_rpc_.has_msg_refcount_req()) {
msg_typed_ = msg_rpc_.mutable_msg_refcount_req();
} else if (msg_rpc_.has_msg_refcount_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_refcount_reply();
} else if (msg_rpc_.has_msg_object_info_req()) {
msg_typed_ = msg_rpc_.mutable_msg_object_info_req();
} else if (msg_rpc_.has_msg_object_info_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_object_info_reply();
} else if (msg_rpc_.has_msg_read_req()) {
msg_typed_ = msg_rpc_.mutable_msg_read_req();
} else if (msg_rpc_.has_msg_read_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_read_reply();
} else if (msg_rpc_.has_msg_store_req()) {
msg_typed_ = msg_rpc_.mutable_msg_store_req();
} else if (msg_rpc_.has_msg_store_abort_req()) {
msg_typed_ = msg_rpc_.mutable_msg_store_abort_req();
} else if (msg_rpc_.has_msg_store_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_store_reply();
} else if (msg_rpc_.has_msg_info_req()) {
msg_typed_ = msg_rpc_.mutable_msg_info_req();
} else if (msg_rpc_.has_msg_info_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_info_reply();
} else if (msg_rpc_.has_msg_shrink_req()) {
msg_typed_ = msg_rpc_.mutable_msg_shrink_req();
} else if (msg_rpc_.has_msg_shrink_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_shrink_reply();
} else if (msg_rpc_.has_msg_list_req()) {
msg_typed_ = msg_rpc_.mutable_msg_list_req();
} else if (msg_rpc_.has_msg_list_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_list_reply();
} else if (msg_rpc_.has_msg_breadcrumb_store_req()) {
msg_typed_ = msg_rpc_.mutable_msg_breadcrumb_store_req();
} else if (msg_rpc_.has_msg_breadcrumb_load_req()) {
msg_typed_ = msg_rpc_.mutable_msg_breadcrumb_load_req();
} else if (msg_rpc_.has_msg_breadcrumb_reply()) {
msg_typed_ = msg_rpc_.mutable_msg_breadcrumb_reply();
} else if (msg_rpc_.has_msg_detach()) {
msg_typed_ = msg_rpc_.mutable_msg_detach();
is_msg_out_of_band_ = true;
} else {
// Unexpected message type, should never happen
abort();
}
}
//------------------------------------------------------------------------------
CacheTransport::CacheTransport(int fd_connection)
: fd_connection_(fd_connection)
, flags_(0)
{
assert(fd_connection_ >= 0);
}
CacheTransport::CacheTransport(int fd_connection, uint32_t flags)
: fd_connection_(fd_connection)
, flags_(flags)
{
assert(fd_connection_ >= 0);
}
void CacheTransport::FillMsgHash(
const shash::Any &hash,
cvmfs::MsgHash *msg_hash)
{
switch (hash.algorithm) {
case shash::kSha1:
msg_hash->set_algorithm(cvmfs::HASH_SHA1);
break;
case shash::kRmd160:
msg_hash->set_algorithm(cvmfs::HASH_RIPEMD160);
break;
case shash::kShake128:
msg_hash->set_algorithm(cvmfs::HASH_SHAKE128);
break;
default:
abort();
}
msg_hash->set_digest(hash.digest, shash::kDigestSizes[hash.algorithm]);
}
void CacheTransport::FillObjectType(
CacheManager::ObjectType object_type,
cvmfs::EnumObjectType *wire_type)
{
switch (object_type) {
case CacheManager::kTypeRegular:
// TODO(jblomer): "pinned" should mean a permanently open fd
case CacheManager::kTypePinned:
*wire_type = cvmfs::OBJECT_REGULAR;
break;
case CacheManager::kTypeCatalog:
*wire_type = cvmfs::OBJECT_CATALOG;
break;
case CacheManager::kTypeVolatile:
*wire_type = cvmfs::OBJECT_VOLATILE;
break;
default:
abort();
}
}
bool CacheTransport::ParseMsgHash(
const cvmfs::MsgHash &msg_hash,
shash::Any *hash)
{
switch (msg_hash.algorithm()) {
case cvmfs::HASH_SHA1:
hash->algorithm = shash::kSha1;
break;
case cvmfs::HASH_RIPEMD160:
hash->algorithm = shash::kRmd160;
break;
case cvmfs::HASH_SHAKE128:
hash->algorithm = shash::kShake128;
break;
default:
return false;
}
const unsigned digest_size = shash::kDigestSizes[hash->algorithm];
if (msg_hash.digest().length() != digest_size)
return false;
memcpy(hash->digest, msg_hash.digest().data(), digest_size);
return true;
}
bool CacheTransport::ParseObjectType(
cvmfs::EnumObjectType wire_type,
CacheManager::ObjectType *object_type)
{
switch (wire_type) {
case cvmfs::OBJECT_REGULAR:
*object_type = CacheManager::kTypeRegular;
return true;
case cvmfs::OBJECT_CATALOG:
*object_type = CacheManager::kTypeCatalog;
return true;
case cvmfs::OBJECT_VOLATILE:
*object_type = CacheManager::kTypeVolatile;
return true;
default:
return false;
}
}
bool CacheTransport::RecvFrame(CacheTransport::Frame *frame) {
uint32_t size;
bool has_attachment;
bool retval = RecvHeader(&size, &has_attachment);
if (!retval)
return false;
void *buffer;
if (size <= kMaxStackAlloc)
buffer = alloca(size);
else
buffer = smalloc(size);
ssize_t nbytes = SafeRead(fd_connection_, buffer, size);
if ((nbytes < 0) || (static_cast<uint32_t>(nbytes) != size)) {
if (size > kMaxStackAlloc) { free(buffer); }
return false;
}
uint32_t msg_size = size;
if (has_attachment) {
if (size < 2) {
// kMaxStackAlloc is > 2 (of course!) but we'll leave the condition here
// for consistency.
if (size > kMaxStackAlloc) { free(buffer); }
return false;
}
msg_size = (*reinterpret_cast<unsigned char *>(buffer)) +
((*(reinterpret_cast<unsigned char *>(buffer) + 1)) << 8);
if ((msg_size + kInnerHeaderSize) > size) {
if (size > kMaxStackAlloc) { free(buffer); }
return false;
}
}
void *ptr_msg = has_attachment
? (reinterpret_cast<char *>(buffer) + kInnerHeaderSize)
: buffer;
retval = frame->ParseMsgRpc(ptr_msg, msg_size);
if (!retval) {
if (size > kMaxStackAlloc) { free(buffer); }
return false;
}
if (has_attachment) {
uint32_t attachment_size = size - (msg_size + kInnerHeaderSize);
if (frame->att_size() < attachment_size) {
if (size > kMaxStackAlloc) { free(buffer); }
return false;
}
void *ptr_attachment =
reinterpret_cast<char *>(buffer) + kInnerHeaderSize + msg_size;
memcpy(frame->attachment(), ptr_attachment, attachment_size);
frame->set_att_size(attachment_size);
} else {
frame->set_att_size(0);
}
if (size > kMaxStackAlloc) { free(buffer); }
return true;
}
bool CacheTransport::RecvHeader(uint32_t *size, bool *has_attachment) {
unsigned char header[kHeaderSize];
ssize_t nbytes = SafeRead(fd_connection_, header, kHeaderSize);
if ((nbytes < 0) || (static_cast<unsigned>(nbytes) != kHeaderSize))
return false;
if ((header[0] & (~kFlagHasAttachment)) != kWireProtocolVersion)
return false;
*has_attachment = header[0] & kFlagHasAttachment;
*size = header[1] + (header[2] << 8) + (header[3] << 16);
return (*size > 0) && (*size <= kMaxMsgSize);
}
void CacheTransport::SendData(
void *message,
uint32_t msg_size,
void *attachment,
uint32_t att_size)
{
uint32_t total_size =
msg_size + att_size + ((att_size > 0) ? kInnerHeaderSize : 0);
assert(total_size > 0);
assert(total_size <= kMaxMsgSize);
LogCvmfs(kLogCache, kLogDebug,
"sending message of size %u to cache transport", total_size);
unsigned char header[kHeaderSize];
header[0] = kWireProtocolVersion | ((att_size == 0) ? 0 : kFlagHasAttachment);
header[1] = (total_size & 0x000000FF);
header[2] = (total_size & 0x0000FF00) >> 8;
header[3] = (total_size & 0x00FF0000) >> 16;
// Only transferred if an attachment is present. Otherwise the overall size
// is also the size of the protobuf message.
unsigned char inner_header[kInnerHeaderSize];
struct iovec iov[4];
iov[0].iov_base = header;
iov[0].iov_len = kHeaderSize;
if (att_size > 0) {
inner_header[0] = (msg_size & 0x000000FF);
inner_header[1] = (msg_size & 0x0000FF00) >> 8;
iov[1].iov_base = inner_header;
iov[1].iov_len = kInnerHeaderSize;
iov[2].iov_base = message;
iov[2].iov_len = msg_size;
iov[3].iov_base = attachment;
iov[3].iov_len = att_size;
} else {
iov[1].iov_base = message;
iov[1].iov_len = msg_size;
}
if (flags_ & kFlagSendNonBlocking) {
SendNonBlocking(iov, (att_size == 0) ? 2 : 4);
return;
}
bool retval = SafeWriteV(fd_connection_, iov, (att_size == 0) ? 2 : 4);
if (!retval && !(flags_ & kFlagSendIgnoreFailure)) {
LogCvmfs(kLogCache, kLogSyslogErr | kLogDebug,
"failed to write to external cache transport (%d), aborting",
errno);
abort();
}
}
void CacheTransport::SendNonBlocking(struct iovec *iov, unsigned iovcnt) {
assert(iovcnt > 0);
unsigned total_size = 0;
for (unsigned i = 0; i < iovcnt; ++i)
total_size += iov[i].iov_len;
unsigned char *buffer = reinterpret_cast<unsigned char *>(alloca(total_size));
unsigned pos = 0;
for (unsigned i = 0; i < iovcnt; ++i) {
memcpy(buffer + pos, iov[i].iov_base, iov[i].iov_len);
pos += iov[i].iov_len;
}
int retval = send(fd_connection_, buffer, total_size, MSG_DONTWAIT);
if (retval < 0) {
assert(errno != EMSGSIZE);
if (!(flags_ & kFlagSendIgnoreFailure)) {
LogCvmfs(kLogCache, kLogSyslogErr | kLogDebug,
"failed to write to external cache transport (%d), aborting",
errno);
abort();
}
}
}
void CacheTransport::SendFrame(CacheTransport::Frame *frame) {
cvmfs::MsgRpc *msg_rpc = frame->GetMsgRpc();
int32_t size = msg_rpc->ByteSize();
assert(size > 0);
#ifdef __APPLE__
void *buffer = smalloc(size);
#else
void *buffer = alloca(size);
#endif
bool retval = msg_rpc->SerializeToArray(buffer, size);
assert(retval);
SendData(buffer, size, frame->attachment(), frame->att_size());
#ifdef __APPLE__
free(buffer);
#endif
}
| 31.871199 | 80 | 0.699315 | traylenator |
3636bbb95cf966a10468d9162c765ac31eeb6d49 | 6,418 | cc | C++ | Testbed/src/cache/evictionStrategies/rand/RANDCache.cc | leowangx2013/Proactive-Caching-ACDC | a510960d11bd3a5514b65bd3c6bd471e08e2b727 | [
"Apache-2.0"
] | null | null | null | Testbed/src/cache/evictionStrategies/rand/RANDCache.cc | leowangx2013/Proactive-Caching-ACDC | a510960d11bd3a5514b65bd3c6bd471e08e2b727 | [
"Apache-2.0"
] | null | null | null | Testbed/src/cache/evictionStrategies/rand/RANDCache.cc | leowangx2013/Proactive-Caching-ACDC | a510960d11bd3a5514b65bd3c6bd471e08e2b727 | [
"Apache-2.0"
] | null | null | null | //
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
/* @file RANDCache.cc
* @author Johannes Pfannmüller, Christian Koch
* @date
* @version 1.0
*
* @brief Implements the Random Cache Eviction Strategy
*
* @section DESCRIPTION
*
* This Class is responsible for managing the storage with the behaviour of the RAND
* Eviction Strategy
*
*/
#include "RANDCache.h"
#include <algorithm>
/*
* @brief Creates a new RANDCache for caching functionalities
* @param parameters the parameters for this eviction strategy
* @param size The desired Size of this Cache
* @param storageAlterations a vector of pairs of double value representing storage alterations
* @param storageAlterationStrategy the strategy used when altering the size of the storage
* @return A pointer to this class
*/
RANDCache::RANDCache(std::vector<std::string>* parameters, long long size,
std::vector<std::pair<double, double>>* storageAlterations,
std::string storageAlterationStrategy) {
// TODO Auto-generated constructor stub
this->parameters = parameters;
setSize(size);
expandStrat = storageAlterationStrategy;
this->storageAlterations = storageAlterations;
if (storageAlterations->size() > 0) {
expanded = false;
} else {
expanded = true;
}
}
RANDCache::~RANDCache() {
delete storageAlterations;
}
/**
* @brief executes periodic events
*
* periodic events can regularily check on something
*/
void RANDCache::periodicEvents() {
}
/**
* @brief deletes video segment from the storage of the cache
*
* @param id the video id of the video segment that has to be deleted
*/
void RANDCache::deleteSegment(std::string id) {
int freedSize = container[id]->getSize();
delete container[id];
container.erase(id);
keyList.erase(std::remove(keyList.begin(), keyList.end(), id),
keyList.end());
cacheSize = cacheSize - freedSize;
writeOperation++;
}
/**
* @brief resets the cache hit and miss
*
* resets the values we use for tracking the performance of the caching strategy.
* Also triggers the storage alteration if any exist
*/
void RANDCache::resetRates() {
this->readOperation = 0;
this->writeOperation = 0;
if (!expanded
and (omnetpp::simTime().dbl() > storageAlterations->begin()->first)) {
alterCacheSize(storageAlterations->begin()->second);
storageAlterations->erase(storageAlterations->begin());
if (storageAlterations->size() == 0) {
expanded = true;
}
}
}
/**
* @brief Inserts a video segment into the Cache
*
* A segment is inserted into the cache following the RAND algorithm
* @param *pkg A VideoSegment
*/
void RANDCache::insertIntoCache(VideoSegment *pkg) {
std::string keyBuilder = pkg->getVideoId()
+ std::to_string(pkg->getSegmentId());
while (cacheSize > maxCacheSize - pkg->getSize()) {
int random = rand() % container.size();
std::string toRemove = keyList[random];
delete container[toRemove];
container.erase(toRemove);
std::vector<std::string>::iterator nth = keyList.begin() + random;
keyList.erase(nth);
}
container[keyBuilder] = pkg;
keyList.push_back(keyBuilder);
cacheSize = cacheSize + pkg->getSize();
writeOperation++;
}
/**
* @brief Checks if the requested segment is already in the Cache
* @param rqst a segment request
* @return A bool Value, indicating whether the Cache contains the segment or not
*/
bool RANDCache::contains(SegmentRequest *rqst) {
readOperation++;
std::string keyBuilder = rqst->getVideoId()
+ std::to_string(rqst->getSegmentId());
if (container.find(keyBuilder) == container.end())
return false;
else
return true;
}
/**
* @brief alters the cache size
*
* a function that alters the maximum size of the cache to a given double value
*
* @param newCacheSize a double value representing the new size of the cache
*/
void RANDCache::alterCacheSize(double newCacheSize) {
maxCacheSize = newCacheSize;
}
/**
* @brief Retrieves the video segment from the Cache. This should only be executed, if contains returns true.
* @param rqst A segment request
*
* The video segment is returned and we call rearrangeCache.
* @return The video segment that fullfills the segment request
*
*/
VideoSegment* RANDCache::retrieveSegment(SegmentRequest *rqst) {
readOperation++;
std::string keyBuilder = rqst->getVideoId()
+ std::to_string(rqst->getSegmentId());
return container[keyBuilder]->dup();
}
/**
* @brief Get the size of the cache
* @return Returns an integer Value describing the size of the cache
*/
long long RANDCache::getSize() {
return this->cacheSize;
}
void RANDCache::clearCache() {
for (auto i : container) {
delete i.second;
}
}
/**
* @brief returns the write operations
*
* Returns the amount of write operations performed since the last reset of the rates
* @return an Integer Value representing the amount of write operations performed
*/
int RANDCache::getWriteOperations() {
return this->writeOperation;
}
/**
* @brief returns the read operations
*
* Returns the amount of read operations performed since the last reset of the rates
* @return an Integer Value representing the amount of read operations performed
*/
int RANDCache::getReadOperations() {
return this->readOperation;
}
/**
* @brief Sets the size of the Cache
* @param size An Integer Value
*/
void RANDCache::setSize(long long size) {
cacheSize = size;
}
/*
* @brief rearranges the cache on hit in the RAND manner
*
* with RAND nothing happenes here
* @param pkg the video segment that triggered the rearrangement
*/
void RANDCache::rearrangeCache(VideoSegment *pkg) {
}
| 31.615764 | 109 | 0.698348 | leowangx2013 |
363770ab09e526264f2742970ecdf824ce8b648c | 1,941 | cpp | C++ | hackathon/Levy/refinement/refinement.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/Levy/refinement/refinement.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/Levy/refinement/refinement.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /* refinement.cpp
* This is a test plugin, you can use it as a demo.
* 2019-6-24 : by YourName
*/
#include "v3d_message.h"
#include <vector>
#include "refinement.h"
#include "n_class.h"
#include <fstream>
using namespace std;
Q_EXPORT_PLUGIN2(refine_swc, TestPlugin);
QStringList TestPlugin::menulist() const
{
return QStringList()
<<tr("menu1")
<<tr("menu2")
<<tr("about");
}
QStringList TestPlugin::funclist() const
{
return QStringList()
<<tr("func1")
<<tr("func2")
<<tr("help");
}
void TestPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)
{
if (menu_name == tr("menu1"))
{
v3d_msg("To be implemented.");
}
else if (menu_name == tr("menu2"))
{
v3d_msg("To be implemented.");
}
else
{
v3d_msg(tr("This is a test plugin, you can use it as a demo.. "
"Developed by YourName, 2021-10-19"));
}
}
bool TestPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent)
{
vector<char*> infiles, inparas, outfiles;
if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p);
if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p);
if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p);
if(func_name==tr("refine"))
{
NeuronTree nt1=readSWC_file(infiles[0]);
QString braindir= infiles[1];
SwcTree a;
a.initialize(nt1);
NeuronTree refinetree = a.refine_swc_by_gd(braindir,callback);
QString eswcfile = (outfiles.size()>=1) ? outfiles[0] : "";
writeESWC_file(eswcfile,refinetree);
}
else if (func_name == tr("help"))
{
cout<<"usage:"<<endl;
cout<<"v3d -x refine_swc -f func2 -i [file_swc] [brain_path] -o [txt_file]"<<endl;
}
else return false;
return true;
}
| 25.207792 | 160 | 0.613086 | zzhmark |
363accbb170ed8254e97d335d205d9e269152404 | 1,123 | cpp | C++ | sdl2/uMario/uNext/Flag.cpp | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | 2 | 2021-02-09T11:29:38.000Z | 2021-08-06T10:37:17.000Z | cpp/mario/src/Flag.cpp | SergiiSharpov/tcpp | b5d3840b6b5bedc736b617a22fe779ceba90ac6f | [
"MIT"
] | null | null | null | cpp/mario/src/Flag.cpp | SergiiSharpov/tcpp | b5d3840b6b5bedc736b617a22fe779ceba90ac6f | [
"MIT"
] | null | null | null | #include "Flag.h"
#include "Core.h"
/* ******************************************** */
Flag::Flag(int iXPos, int iYPos) {
this->iXPos = iXPos;
this->iYPos = iYPos;
this->iYTextPos = CCFG::GAME_HEIGHT - 3*32;
this->iPoints = -1;
this->iBlockID = CCore::getMap()->getLevelType() == 4 || CCore::getMap()->getLevelType() == 3 ? 168 : 42;
this->castleFlagExtraXPos = this->castleFlagY = 0;
}
Flag::~Flag(void) {
}
/* ******************************************** */
void Flag::Update() {
iYPos += 4;
iYTextPos -= 4;
}
void Flag::UpdateCastleFlag() {
if(castleFlagY <= 56)
castleFlagY += 2;
}
void Flag::Draw(SDL_Renderer* rR, CIMG* iIMG) {
iIMG->Draw(rR, (int)(iXPos + CCore::getMap()->getXPos()), iYPos);
if(iPoints > 0) {
CCFG::getText()->Draw(rR, std::to_string(iPoints), (int)(iXPos + CCore::getMap()->getXPos() + 42), iYTextPos - 22, 8, 16);
}
}
void Flag::DrawCastleFlag(SDL_Renderer* rR, CIMG* iIMG) {
iIMG->Draw(rR, (int)(iXPos + CCore::getMap()->getXPos() + castleFlagExtraXPos + 7*32 - 14), CCFG::GAME_HEIGHT + 14 - 6*32 - castleFlagY);
}
/* ******************************************** */ | 24.413043 | 138 | 0.54675 | pdpdds |
363b719a89e96fc067ef52cfd74d8b1c0e8f6aa8 | 6,572 | cc | C++ | deps/cld/internal/generated_entities.cc | nornagon/paulcbetts-cld-prebuilt | ad2cb3a76b3cf75de4ebb2a4cee3b05b84c07253 | [
"Apache-2.0"
] | 1 | 2017-12-11T07:53:29.000Z | 2017-12-11T07:53:29.000Z | deps/cld/internal/generated_entities.cc | nornagon/paulcbetts-cld-prebuilt | ad2cb3a76b3cf75de4ebb2a4cee3b05b84c07253 | [
"Apache-2.0"
] | 1 | 2019-04-06T17:33:10.000Z | 2019-11-19T20:13:14.000Z | deps/cld/internal/generated_entities.cc | nornagon/paulcbetts-cld-prebuilt | ad2cb3a76b3cf75de4ebb2a4cee3b05b84c07253 | [
"Apache-2.0"
] | 2 | 2019-04-06T04:27:40.000Z | 2019-09-18T21:22:02.000Z | // Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// generated_entities.cc
// Machine generated. Do Not Edit.
//
// Declarations for HTML entities recognized by CLD2
//
#include "generated_ulscript.h" // for CharIntPair
namespace CLD2 {
// Alphabetical order for binary search
extern const int kNameToEntitySize = 265;
extern const CharIntPair kNameToEntity[kNameToEntitySize] = {
{"AElig", 198},
{"AMP", 38},
{"Aacute", 193},
{"Acirc", 194},
{"Agrave", 192},
{"Alpha", 913},
{"Aring", 197},
{"Atilde", 195},
{"Auml", 196},
{"Beta", 914},
{"Ccaron", 268},
{"Ccedil", 199},
{"Chi", 935},
{"Dagger", 8225},
{"Delta", 916},
{"ETH", 208},
{"Eacute", 201},
{"Ecaron", 282},
{"Ecirc", 202},
{"Egrave", 200},
{"Epsilon", 917},
{"Eta", 919},
{"Euml", 203},
{"GT", 62},
{"Gamma", 915},
{"Iacute", 205},
{"Icirc", 206},
{"Igrave", 204},
{"Iota", 921},
{"Iuml", 207},
{"Kappa", 922},
{"LT", 60},
{"Lambda", 923},
{"Mu", 924},
{"Ntilde", 209},
{"Nu", 925},
{"OElig", 338},
{"Oacute", 211},
{"Ocirc", 212},
{"Ograve", 210},
{"Omega", 937},
{"Omicron", 927},
{"Oslash", 216},
{"Otilde", 213},
{"Ouml", 214},
{"Phi", 934},
{"Pi", 928},
{"Prime", 8243},
{"Psi", 936},
{"QUOT", 34},
{"Rcaron", 344},
{"Rho", 929},
{"Scaron", 352},
{"Sigma", 931},
{"THORN", 222},
{"Tau", 932},
{"Theta", 920},
{"Uacute", 218},
{"Ucirc", 219},
{"Ugrave", 217},
{"Upsilon", 933},
{"Uuml", 220},
{"Xi", 926},
{"Yacute", 221},
{"Yuml", 376},
{"Zeta", 918},
{"aacute", 225},
{"acirc", 226},
{"acute", 180},
{"aelig", 230},
{"agrave", 224},
{"alefsym", 8501},
{"alpha", 945},
{"amp", 38},
{"and", 8743},
{"ang", 8736},
{"apos", 39},
{"aring", 229},
{"asymp", 8776},
{"atilde", 227},
{"auml", 228},
{"bdquo", 8222},
{"beta", 946},
{"brvbar", 166},
{"bull", 8226},
{"cap", 8745},
{"ccaron", 269},
{"ccedil", 231},
{"cedil", 184},
{"cent", 162},
{"chi", 967},
{"circ", 710},
{"clubs", 9827},
{"cong", 8773},
{"copy", 169},
{"crarr", 8629},
{"cup", 8746},
{"curren", 164},
{"dArr", 8659},
{"dagger", 8224},
{"darr", 8595},
{"deg", 176},
{"delta", 948},
{"diams", 9830},
{"divide", 247},
{"eacute", 233},
{"ecaron", 283},
{"ecirc", 234},
{"egrave", 232},
{"emdash", 8212},
{"empty", 8709},
{"emsp", 8195},
{"endash", 8211},
{"ensp", 8194},
{"epsilon", 949},
{"equiv", 8801},
{"eta", 951},
{"eth", 240},
{"euml", 235},
{"euro", 8364},
{"exist", 8707},
{"fnof", 402},
{"forall", 8704},
{"frac12", 189},
{"frac14", 188},
{"frac34", 190},
{"frasl", 8260},
{"gamma", 947},
{"ge", 8805},
{"gt", 62},
{"hArr", 8660},
{"harr", 8596},
{"hearts", 9829},
{"hellip", 8230},
{"iacute", 237},
{"icirc", 238},
{"iexcl", 161},
{"igrave", 236},
{"image", 8465},
{"infin", 8734},
{"int", 8747},
{"iota", 953},
{"iquest", 191},
{"isin", 8712},
{"iuml", 239},
{"kappa", 954},
{"lArr", 8656},
{"lambda", 955},
{"lang", 9001},
{"laquo", 171},
{"larr", 8592},
{"lceil", 8968},
{"ldquo", 8220},
{"le", 8804},
{"lfloor", 8970},
{"lowast", 8727},
{"loz", 9674},
{"lrm", 8206},
{"lsaquo", 8249},
{"lsquo", 8216},
{"lt", 60},
{"macr", 175},
{"mdash", 8212},
{"micro", 181},
{"middot", 183},
{"minus", 8722},
{"mu", 956},
{"nabla", 8711},
{"nbsp", 160},
{"ndash", 8211},
{"ne", 8800},
{"ni", 8715},
{"not", 172},
{"notin", 8713},
{"nsub", 8836},
{"ntilde", 241},
{"nu", 957},
{"oacute", 243},
{"ocirc", 244},
{"oelig", 339},
{"ograve", 242},
{"oline", 8254},
{"omega", 969},
{"omicron", 959},
{"oplus", 8853},
{"or", 8744},
{"ordf", 170},
{"ordm", 186},
{"oslash", 248},
{"otilde", 245},
{"otimes", 8855},
{"ouml", 246},
{"para", 182},
{"part", 8706},
{"permil", 8240},
{"perp", 8869},
{"phi", 966},
{"pi", 960},
{"piv", 982},
{"plusmn", 177},
{"pound", 163},
{"prime", 8242},
{"prod", 8719},
{"prop", 8733},
{"psi", 968},
{"quot", 34},
{"rArr", 8658},
{"radic", 8730},
{"rang", 9002},
{"raquo", 187},
{"rarr", 8594},
{"rcaron", 345},
{"rceil", 8969},
{"rdquo", 8221},
{"real", 8476},
{"reg", 174},
{"rfloor", 8971},
{"rho", 961},
{"rlm", 8207},
{"rsaquo", 8250},
{"rsquo", 8217},
{"sbquo", 8218},
{"scaron", 353},
{"sdot", 8901},
{"sect", 167},
{"shy", 173},
{"sigma", 963},
{"sigmaf", 962},
{"sim", 8764},
{"spades", 9824},
{"sub", 8834},
{"sube", 8838},
{"sum", 8721},
{"sup", 8835},
{"sup1", 185},
{"sup2", 178},
{"sup3", 179},
{"supe", 8839},
{"szlig", 223},
{"tau", 964},
{"there4", 8756},
{"theta", 952},
{"thetasym", 977},
{"thinsp", 8201},
{"thorn", 254},
{"tilde", 732},
{"times", 215},
{"trade", 8482},
{"uArr", 8657},
{"uacute", 250},
{"uarr", 8593},
{"ucirc", 251},
{"ugrave", 249},
{"uml", 168},
{"upsih", 978},
{"upsilon", 965},
{"uuml", 252},
{"weierp", 8472},
{"xi", 958},
{"yacute", 253},
{"yen", 165},
{"yuml", 255},
{"zeta", 950},
{"zwj", 8205},
{"zwnj", 8204},
};
} // namespace CLD2
| 22.277966 | 76 | 0.431223 | nornagon |
363c6be9f1034dba41ec9906c1ebaa2e2f85f5c3 | 5,438 | cpp | C++ | oneflow/core/intrusive/dss_test.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2022-03-14T11:17:56.000Z | 2022-03-14T11:17:56.000Z | oneflow/core/intrusive/dss_test.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | null | null | null | oneflow/core/intrusive/dss_test.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2021-12-15T02:14:49.000Z | 2021-12-15T02:14:49.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "gtest/gtest.h"
#include "oneflow/core/intrusive/dss.h"
#include "oneflow/core/common/util.h"
namespace oneflow {
namespace {
struct Foo {
DSS_BEGIN(DSS_GET_FIELD_COUNTER(), Foo);
int x;
int y;
int* z;
DSS_DEFINE_FIELD(DSS_GET_FIELD_COUNTER(), "demo dss", int, x);
DSS_DEFINE_FIELD(DSS_GET_FIELD_COUNTER(), "demo dss", int, y);
DSS_DEFINE_FIELD(DSS_GET_FIELD_COUNTER(), "demo dss", int*, z);
DSS_END(DSS_GET_FIELD_COUNTER(), "demo dss", Foo);
};
struct Bar {
DSS_BEGIN(DSS_GET_FIELD_COUNTER(), Foo);
DSS_END(DSS_GET_FIELD_COUNTER(), "demo dss", Bar);
};
template<typename T>
struct IsPointer {
static const bool value = std::is_pointer<T>::value;
};
template<typename T>
struct RemovePointer {
using type = typename std::remove_pointer<T>::type;
};
template<typename T>
struct IsScalar {
static const bool value =
std::is_arithmetic<T>::value || std::is_enum<T>::value || std::is_same<T, std::string>::value;
};
template<int field_counter, typename WalkCtxType, typename FieldType>
struct DumpFieldName {
static void Call(WalkCtxType* ctx, FieldType* field, const char* field_name) {
ctx->emplace_back(field_name);
}
};
TEST(DSS, walk_field) {
Foo foo;
std::vector<std::string> field_names;
foo.__WalkVerboseField__<DumpFieldName>(&field_names);
ASSERT_EQ(field_names.size(), 3);
ASSERT_TRUE(field_names[0] == "x");
ASSERT_TRUE(field_names[1] == "y");
ASSERT_TRUE(field_names[2] == "z");
}
template<bool is_pointer>
struct PushBackPtrFieldName {
template<typename WalkCtxType>
static void Call(WalkCtxType* ctx, const char* field_name) {}
};
template<>
struct PushBackPtrFieldName<true> {
template<typename WalkCtxType>
static void Call(WalkCtxType* ctx, const char* field_name) {
ctx->emplace_back(field_name);
}
};
template<int field_counter, typename WalkCtxType, typename FieldType>
struct FilterPointerFieldName {
static void Call(WalkCtxType* ctx, FieldType* field, const char* field_name) {
PushBackPtrFieldName<std::is_pointer<FieldType>::value>::Call(ctx, field_name);
}
};
template<int field_counter, typename WalkCtxType, typename FieldType>
struct FilterPointerFieldNameUntil {
static bool Call(WalkCtxType* ctx, FieldType* field) {
return true;
PushBackPtrFieldName<std::is_pointer<FieldType>::value>::Call(ctx, "");
}
};
TEST(DSS, filter_field) {
Foo foo;
std::vector<std::string> field_names;
foo.__WalkVerboseField__<FilterPointerFieldName>(&field_names);
ASSERT_EQ(field_names.size(), 1);
ASSERT_TRUE(field_names[0] == "z");
}
TEST(DSS, filter_field_until) {
Foo foo;
std::vector<std::string> field_names;
ASSERT_TRUE(foo.__WalkFieldUntil__<FilterPointerFieldNameUntil>(&field_names));
ASSERT_TRUE(field_names.empty());
}
#define DSS_DEFINE_TEST_UNION_FIELD(field_counter) \
DSS_DEFINE_FIELD(field_counter, "demo dss", UnionField, union_field); \
DSS_DEFINE_UNION_FIELD_VISITOR(field_counter, union_case, \
OF_PP_MAKE_TUPLE_SEQ(int32_t, x, 1) \
OF_PP_MAKE_TUPLE_SEQ(int64_t, y, 2));
struct TestDssUnion {
DSS_BEGIN(DSS_GET_FIELD_COUNTER(), TestDssUnion);
public:
struct UnionField {
int32_t union_case;
union {
int32_t x;
int64_t y;
};
} union_field;
DSS_DEFINE_TEST_UNION_FIELD(DSS_GET_FIELD_COUNTER());
DSS_END(DSS_GET_FIELD_COUNTER(), "demo dss", TestDssUnion);
};
template<typename StructT, int field_counter, typename WalkCtxType, typename FieldType,
bool is_oneof_field>
struct StaticDumpFieldName {
static void Call(WalkCtxType* ctx, const char* field_name, const char* oneof_name) {
ctx->emplace_back(field_name);
ctx->emplace_back(oneof_name);
}
};
TEST(DSS, union_field) {
TestDssUnion foo;
foo.union_field.union_case = 0;
{
std::vector<std::string> field_names;
foo.__WalkVerboseField__<DumpFieldName>(&field_names);
ASSERT_EQ(field_names.size(), 0);
}
foo.union_field.union_case = 1;
{
std::vector<std::string> field_names;
foo.__WalkVerboseField__<DumpFieldName>(&field_names);
ASSERT_EQ(field_names.size(), 1);
ASSERT_EQ(field_names.at(0), "x");
}
foo.union_field.union_case = 2;
{
std::vector<std::string> field_names;
foo.__WalkVerboseField__<DumpFieldName>(&field_names);
ASSERT_EQ(field_names.size(), 1);
ASSERT_EQ(field_names.at(0), "y");
}
}
TEST(DSS, static_verbose_field) {
std::vector<std::string> field_names;
TestDssUnion::__WalkStaticVerboseField__<StaticDumpFieldName>(&field_names);
ASSERT_EQ(field_names.size(), 4);
ASSERT_EQ(field_names.at(0), "x");
ASSERT_EQ(field_names.at(1), "union_field");
ASSERT_EQ(field_names.at(2), "y");
ASSERT_EQ(field_names.at(3), "union_field");
}
} // namespace
} // namespace oneflow
| 28.925532 | 100 | 0.719566 | L-Net-1992 |
36411c8aef9c82ac93cfc0a34bfc2167f302d526 | 743 | cpp | C++ | cf1656B.cpp | yonghuatang/codeforces | 7e1268443e14b001049ef854d2b230f1449d5a2d | [
"MIT"
] | null | null | null | cf1656B.cpp | yonghuatang/codeforces | 7e1268443e14b001049ef854d2b230f1449d5a2d | [
"MIT"
] | null | null | null | cf1656B.cpp | yonghuatang/codeforces | 7e1268443e14b001049ef854d2b230f1449d5a2d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
for (int tc=1; tc<=t; tc++) {
int n, k;
cin >> n >> k;
vector<int> v(n, 0);
bool valid = false;
for (int i=0; i<n; i++) {
cin >> v[i];
}
set<int> s(v.begin(), v.end());
bool ok = false;
// for (int i=0; i<n; i++) {
// if (s.count(v[i] + k)) {
// ok = true;
// break;
// }
// }
for (auto it=s.begin(); it!=s.end(); it++) {
if (s.count((*it)+k)) {
ok = true;
break;
}
}
cout << (ok ? "YES" : "NO") << endl;
}
return 0;
} | 23.21875 | 52 | 0.325707 | yonghuatang |